"""Unit tests for the Spotify model.""" import base64 from unittest.mock import MagicMock import pytest import requests from artist.models import spotify @pytest.fixture def spotify_client_credentials(): """Spotify client credentials in {id}:{secret} format.""" return 'spotify:credentials' @pytest.fixture def spotify_access_token(): """A temporary access token returned by Spotify.""" return 'spotify_access_token' @pytest.fixture def mock_successful_access_token_call(mocker, spotify_access_token): """Mock the Spotify access token api call to return an access token.""" spotify_response = MagicMock() spotify_response.json = MagicMock( return_value={'access_token': spotify_access_token} ) mocker.patch.object(requests, 'post').return_value = spotify_response return spotify_response @pytest.fixture def mock_unsuccessful_access_token_call(mocker): """Mock the Spotify access token api call to not return an access token.""" spotify_response = MagicMock() spotify_response.json = MagicMock(return_value={}) mocker.patch.object(requests, 'post').return_value = spotify_response def test_get_access_token( mocker, spotify_access_token, spotify_client_credentials, mock_successful_access_token_call ): """Test getting an access token.""" mocker.patch.object(base64, 'b64encode').return_value = bytes( spotify_client_credentials, 'utf-8' ) access_token = spotify.get_access_token() requests.post.assert_called_with( 'https://accounts.spotify.com/api/token', data={'grant_type': 'client_credentials'}, headers={ 'Authorization': 'Basic {}'.format(spotify_client_credentials) } ) assert access_token == spotify_access_token def test_get_access_token_failure( mocker, spotify_client_credentials, mock_unsuccessful_access_token_call ): """Test being unable to get an access_token.""" access_token = spotify.get_access_token() assert access_token is None def test_search(mocker, mock_successful_access_token_call): """Test searching returns a list of results.""" spotify_response = MagicMock() spotify_response.json = MagicMock(return_value={ 'artists': { 'href': 'do not include this', 'items': [1, 2, 3] } }) mocker.patch.object(requests, 'get').return_value = spotify_response response = spotify.search('test', 'artist') assert response.status == 200 assert response.message == { 'items': [1, 2, 3] } def test_search_failure(mock_unsuccessful_access_token_call): """Test searching when an access token is not available.""" response = spotify.search('test', 'artist') assert response.status == 401