"""Tests for Spotify connector.""" import importlib from flexmock import flexmock import pytest import requests import spotipy from spotipy import oauth2 as spotipy_oauth2 from availability import config from availability import exceptions from availability.connectors.stores import spotify UPC = '819224018247' COUNTRIES = ['USA', 'UK'] @pytest.mark.parametrize( 'exc_cls, expected_exc_cls', [ (requests.exceptions.ConnectionError, exceptions.StoreRequestError), (ValueError, exceptions.StoreRequestError), ] ) def test_query_store_request_exception(exc_cls, expected_exc_cls): """Test exception in requests.get() while querying remote store.""" exc_args = ('foo', 'bar') (flexmock(spotipy.Spotify) .should_receive('search') .and_raise(exc_cls(*exc_args)) .once()) with pytest.raises(expected_exc_cls) as exc_info: spotify.query_store(UPC, COUNTRIES) original_exc = exc_info.value.args[0] assert type(original_exc) is exc_cls assert original_exc.args == exc_args def test_query_store_request_no_auth(): """Test successful remote store query without auth.""" expected_response = dict(foo='bar') flexmock(config).should_receive('SPOTIFY_CLIENT_ID').and_return(None) flexmock(config).should_receive('SPOTIFY_CLIENT_SECRET').and_return(None) (flexmock(spotipy.Spotify) .should_receive('search') .and_return(expected_response) .once()) (flexmock(spotipy_oauth2) .should_receive('SpotifyClientCredentials') .never()) assert expected_response == spotify.query_store(UPC, COUNTRIES) def test_query_store_request_auth(): """Test successful remote store query with auth.""" expected_response = dict(foo='bar') client_id = 'baz' client_secret = 'qux' flexmock(config).should_receive('SPOTIFY_CLIENT_ID').and_return(client_id) flexmock(config).should_receive('SPOTIFY_CLIENT_SECRET').and_return( client_secret) (flexmock(spotipy.Spotify) .should_receive('search') .and_return(expected_response) .once()) (flexmock(spotipy_oauth2) .should_receive('SpotifyClientCredentials') .with_args(client_id=client_id, client_secret=client_secret) .and_return() .once()) assert expected_response == spotify.query_store(UPC, COUNTRIES) def test_query_store_called_with_the_market_param(mocker): """Assert search called with market parameter.""" config.SPOTIFY_CLIENT_ID = None config.SPOTIFY_CLIENT_SECRET = None mock_search = mocker.patch( 'availability.connectors.stores.spotify.spotipy.Spotify.search') spotify.query_store('test', 'US') mock_search.assert_called_with(q='upc:test', type='album', market='US') def teardown_function(): """Teardown function that reloads config after every test case.""" importlib.reload(config)