Renamed the auth parameter of Spotify.__init__ to access_token for better clarity.

Removed the `client_credentials_manager` and `oauth_manager` parameters because they are redundant.

Replaced the `set_auth` and `auth_manager` properties with standard attributes.

Removed the following deprecated methods from `Spotify`:
* `playlist_tracks`
* `user_playlist`
* `user_playlist_tracks`
* `user_playlist_change_details`
* `user_playlist_unfollow`
* `user_playlist_add_tracks`
* `user_playlist_replace_tracks`
* `user_playlist_reorder_tracks`
* `user_playlist_remove_all_occurrences_of_tracks`
* `user_playlist_remove_specific_occurrences_of_tracks`
* `user_playlist_follow_playlist`
* `user_playlist_is_following`

Removed the deprecated `as_dict` parameter from the `get_access_token` method of `SpotifyOAuth` and `SpotifyPKCE`.

Removed the deprecated `get_cached_token` and `_save_token_info` methods of `SpotifyOAuth` and `SpotifyPKCE`.

Removed `SpotifyImplicitGrant`.

Removed `prompt_for_user_token`.
This commit is contained in:
Peter-Schorn committed 2021-04-14 12:40:08 -05:00
1 parent b6c3961d5f
commit bd80181816
35 files changed
+227 -1132

No files matched your search

+8 -9
View File
@@ -58,7 +58,8 @@ class AuthTestSpotipy(unittest.TestCase):
@classmethod
def setUpClass(self):
self.spotify = Spotify(
client_credentials_manager=SpotifyClientCredentials())
auth_manager=SpotifyClientCredentials()
)
self.spotify.trace = False
def test_audio_analysis(self):
@@ -232,9 +233,9 @@ class AuthTestSpotipy(unittest.TestCase):
self.assertTrue(found)
def test_search_timeout(self):
client_credentials_manager = SpotifyClientCredentials()
auth_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(requests_timeout=0.01,
client_credentials_manager=client_credentials_manager)
auth_manager=auth_manager)
# depending on the timing or bandwidth, this raises a timeout or connection error"
self.assertRaises((requests.exceptions.Timeout, requests.exceptions.ConnectionError),
@@ -242,17 +243,15 @@ class AuthTestSpotipy(unittest.TestCase):
def test_max_retries_reached_get(self):
spotify_no_retry = Spotify(
client_credentials_manager=SpotifyClientCredentials(),
auth_manager=SpotifyClientCredentials(),
retries=0)
i = 0
while i < 100:
for i in range(100):
try:
spotify_no_retry.search(q='foo')
except SpotifyException as e:
self.assertIsInstance(e, SpotifyException)
self.assertEqual(e.http_status, 429)
return
i += 1
self.fail()
def test_album_search(self):
@@ -350,7 +349,7 @@ class AuthTestSpotipy(unittest.TestCase):
sess = requests.Session()
sess.headers["user-agent"] = "spotipy-test"
with_custom_session = spotipy.Spotify(
client_credentials_manager=SpotifyClientCredentials(),
auth_manager=SpotifyClientCredentials(),
requests_session=sess)
self.assertTrue(
with_custom_session.user(
@@ -359,7 +358,7 @@ class AuthTestSpotipy(unittest.TestCase):
def test_force_no_requests_session(self):
with_no_session = spotipy.Spotify(
client_credentials_manager=SpotifyClientCredentials(),
auth_manager=SpotifyClientCredentials(),
requests_session=False)
self.assertNotIsInstance(with_no_session._session, requests.Session)
user = with_no_session.user(user="akx")
+29 -70
View File
@@ -2,15 +2,30 @@ import os
from spotipy import (
CLIENT_CREDS_ENV_VARS as CCEV,
prompt_for_user_token,
Spotify,
SpotifyException,
SpotifyImplicitGrant,
SpotifyPKCE
SpotifyOAuth,
SpotifyPKCE,
CacheFileHandler
)
import unittest
from tests import helpers
def _make_spotify(scopes=None, retries=None):
retries = retries or Spotify.max_retries
auth_manager = SpotifyOAuth(
scope=scopes,
cache_handler=CacheFileHandler()
)
spotify = Spotify(
auth_manager=auth_manager,
retries=retries
)
return spotify
class SpotipyPlaylistApiTest(unittest.TestCase):
@classmethod
@@ -48,10 +63,10 @@ class SpotipyPlaylistApiTest(unittest.TestCase):
'user-read-playback-state'
)
token = prompt_for_user_token(cls.username, scope=scope)
cls.spotify = _make_spotify(scopes=scope)
cls.spotify_no_retry = _make_spotify(scopes=scope, retries=0)
cls.spotify = Spotify(auth=token)
cls.spotify_no_retry = Spotify(auth=token, retries=0)
cls.new_playlist_name = 'spotipy-playlist-test'
cls.new_playlist = helpers.get_spotify_playlist(
cls.spotify, cls.new_playlist_name, cls.username) or \
@@ -119,8 +134,7 @@ class SpotipyPlaylistApiTest(unittest.TestCase):
self.assertEqual(pl["tracks"]["total"], 0)
def test_max_retries_reached_post(self):
i = 0
while i < 500:
for i in range(500):
try:
self.spotify_no_retry.playlist_change_details(
self.new_playlist['id'], description="test")
@@ -128,7 +142,6 @@ class SpotipyPlaylistApiTest(unittest.TestCase):
self.assertIsInstance(e, SpotifyException)
self.assertEqual(e.http_status, 429)
return
i += 1
self.fail()
def test_playlist_add_items(self):
@@ -188,17 +201,6 @@ class SpotipyPlaylistApiTest(unittest.TestCase):
return
self.fail()
def test_deprecated_starred(self):
pl = self.spotify.user_playlist(self.username)
self.assertTrue(pl["tracks"] is None)
self.assertTrue(pl["owner"] is None)
def test_deprecated_user_playlist(self):
# Test without user due to change from
# https://developer.spotify.com/community/news/2018/06/12/changes-to-playlist-uris/
pl = self.spotify.user_playlist(None, self.new_playlist['id'])
self.assertEqual(pl["tracks"]["total"], 0)
class SpotipyLibraryApiTests(unittest.TestCase):
@classmethod
@@ -227,10 +229,7 @@ class SpotipyLibraryApiTests(unittest.TestCase):
'ugc-image-upload '
'user-read-playback-state'
)
token = prompt_for_user_token(cls.username, scope=scope)
cls.spotify = Spotify(auth=token)
cls.spotify = _make_spotify(scopes=scope)
def test_track_bad_id(self):
with self.assertRaises(SpotifyException):
@@ -305,9 +304,7 @@ class SpotipyUserApiTests(unittest.TestCase):
'user-read-playback-state'
)
token = prompt_for_user_token(cls.username, scope=scope)
cls.spotify = Spotify(auth=token)
cls.spotify = _make_spotify(scopes=scope)
def test_basic_user_profile(self):
user = self.spotify.user(self.username)
@@ -335,9 +332,7 @@ class SpotipyUserApiTests(unittest.TestCase):
class SpotipyBrowseApiTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
username = os.getenv(CCEV['client_username'])
token = prompt_for_user_token(username)
cls.spotify = Spotify(auth=token)
cls.spotify = _make_spotify()
def test_category(self):
response = self.spotify.category('rock')
@@ -383,9 +378,7 @@ class SpotipyFollowApiTests(unittest.TestCase):
'user-read-playback-state'
)
token = prompt_for_user_token(cls.username, scope=scope)
cls.spotify = Spotify(auth=token)
cls.spotify = _make_spotify(scopes=scope)
def test_current_user_follows(self):
response = self.spotify.current_user_followed_artists()
@@ -438,9 +431,7 @@ class SpotipyPlayerApiTests(unittest.TestCase):
'user-read-playback-state'
)
token = prompt_for_user_token(cls.username, scope=scope)
cls.spotify = Spotify(auth=token)
cls.spotify = _make_spotify(scopes=scope)
def test_devices(self):
# No devices playing by default
@@ -454,39 +445,6 @@ class SpotipyPlayerApiTests(unittest.TestCase):
# not much more to test if account is inactive and has no recently played tracks
class SpotipyImplicitGrantTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
scope = (
'user-follow-read '
'user-follow-modify '
)
auth_manager = SpotifyImplicitGrant(scope=scope,
cache_path=".cache-implicittest")
cls.spotify = Spotify(auth_manager=auth_manager)
def test_user_follows_and_unfollows_artist(self):
# Initially follows 1 artist
current_user_followed_artists = self.spotify.current_user_followed_artists()[
'artists']['total']
# Follow 2 more artists
artists = ["6DPYiyq5kWVQS4RGwxzPC7", "0NbfKEOTQCcwd6o7wSDOHI"]
self.spotify.user_follow_artists(artists)
res = self.spotify.current_user_followed_artists()
self.assertEqual(res['artists']['total'], current_user_followed_artists + len(artists))
# Unfollow these 2 artists
self.spotify.user_unfollow_artists(artists)
res = self.spotify.current_user_followed_artists()
self.assertEqual(res['artists']['total'], current_user_followed_artists)
def test_current_user(self):
c_user = self.spotify.current_user()
user = self.spotify.user(c_user['id'])
self.assertEqual(c_user['display_name'], user['display_name'])
class SpotifyPKCETests(unittest.TestCase):
@classmethod
@@ -495,7 +453,8 @@ class SpotifyPKCETests(unittest.TestCase):
'user-follow-read '
'user-follow-modify '
)
auth_manager = SpotifyPKCE(scope=scope, cache_path=".cache-pkcetest")
cache_handler = CacheFileHandler(cache_path=".cache-pkcetest")
auth_manager = SpotifyPKCE(scope=scope, cache_handler=cache_handler)
cls.spotify = Spotify(auth_manager=auth_manager)
def test_user_follows_and_unfollows_artist(self):
+20 -184
View File
@@ -5,10 +5,11 @@ import unittest
import six.moves.urllib.parse as urllibparse
from spotipy import SpotifyOAuth, SpotifyImplicitGrant, SpotifyPKCE
from spotipy.cache_handler import MemoryCacheHandler
from spotipy import SpotifyOAuth, SpotifyPKCE
from spotipy.cache_handler import CacheHandler
from spotipy.oauth2 import SpotifyClientCredentials, SpotifyOauthError
from spotipy.oauth2 import SpotifyStateError
from spotipy import CacheFileHandler
try:
import unittest.mock as mock
@@ -43,10 +44,6 @@ def _make_oauth(*args, **kwargs):
return SpotifyOAuth("CLID", "CLISEC", "REDIR", "STATE", *args, **kwargs)
def _make_implicitgrantauth(*args, **kwargs):
return SpotifyImplicitGrant("CLID", "REDIR", "STATE", *args, **kwargs)
def _make_pkceauth(*args, **kwargs):
return SpotifyPKCE("CLID", "REDIR", "STATE", *args, **kwargs)
@@ -65,13 +62,12 @@ class OAuthCacheTest(unittest.TestCase):
opener.return_value = _token_file(json.dumps(tok, ensure_ascii=False))
is_token_expired.return_value = False
spot = _make_oauth(scope, path)
cache_handler = CacheFileHandler(cache_path=path)
spot = _make_oauth(scope, cache_handler=cache_handler)
cached_tok = spot.validate_token(spot.cache_handler.get_cached_token())
cached_tok_legacy = spot.get_cached_token()
opener.assert_called_with(path)
self.assertIsNotNone(cached_tok)
self.assertIsNotNone(cached_tok_legacy)
self.assertEqual(refresh_access_token.call_count, 0)
@patch.multiple(SpotifyOAuth,
@@ -88,7 +84,8 @@ class OAuthCacheTest(unittest.TestCase):
opener.return_value = token_file
refresh_access_token.return_value = fresh_tok
spot = _make_oauth(scope, path)
cache_handler = CacheFileHandler(cache_path=path)
spot = _make_oauth(scope, cache_handler=cache_handler)
spot.validate_token(spot.cache_handler.get_cached_token())
is_token_expired.assert_called_with(expired_tok)
@@ -108,7 +105,9 @@ class OAuthCacheTest(unittest.TestCase):
opener.return_value = _token_file(json.dumps(tok, ensure_ascii=False))
is_token_expired.return_value = False
spot = _make_oauth(requested_scope, path)
cache_handler = CacheFileHandler(cache_path=path)
spot = _make_oauth(requested_scope, cache_handler=cache_handler)
cached_tok = spot.validate_token(spot.cache_handler.get_cached_token())
opener.assert_called_with(path)
@@ -124,27 +123,13 @@ class OAuthCacheTest(unittest.TestCase):
fi = _fake_file()
opener.return_value = fi
spot = SpotifyOAuth("CLID", "CLISEC", "REDIR", "STATE", scope, path)
cache_handler = CacheFileHandler(cache_path=path)
spot = SpotifyOAuth("CLID", "CLISEC", "REDIR", "STATE", scope, cache_handler=cache_handler)
spot.cache_handler.save_token_to_cache(tok)
opener.assert_called_with(path, 'w')
self.assertTrue(fi.write.called)
@patch('spotipy.cache_handler.open', create=True)
def test_saves_to_cache_path_legacy(self, opener):
scope = "playlist-modify-private"
path = ".cache-username"
tok = _make_fake_token(1, 1, scope)
fi = _fake_file()
opener.return_value = fi
spot = SpotifyOAuth("CLID", "CLISEC", "REDIR", "STATE", scope, path)
spot._save_token_info(tok)
opener.assert_called_with(path, 'w')
self.assertTrue(fi.write.called)
def test_cache_handler(self):
scope = "playlist-modify-private"
tok = _make_fake_token(1, 1, scope)
@@ -248,142 +233,6 @@ class TestSpotifyClientCredentials(unittest.TestCase):
oauth.get_access_token()
self.assertEqual(error.exception.error, 'invalid_client')
class ImplicitGrantCacheTest(unittest.TestCase):
@patch.object(SpotifyImplicitGrant, "is_token_expired", DEFAULT)
@patch('spotipy.cache_handler.open', create=True)
def test_gets_from_cache_path(self, opener, is_token_expired):
scope = "playlist-modify-private"
path = ".cache-username"
tok = _make_fake_token(1, 1, scope)
opener.return_value = _token_file(json.dumps(tok, ensure_ascii=False))
is_token_expired.return_value = False
spot = _make_implicitgrantauth(scope, path)
cached_tok = spot.cache_handler.get_cached_token()
cached_tok_legacy = spot.get_cached_token()
opener.assert_called_with(path)
self.assertIsNotNone(cached_tok)
self.assertIsNotNone(cached_tok_legacy)
@patch.object(SpotifyImplicitGrant, "is_token_expired", DEFAULT)
@patch('spotipy.cache_handler.open', create=True)
def test_expired_token_returns_none(self, opener, is_token_expired):
scope = "playlist-modify-private"
path = ".cache-username"
expired_tok = _make_fake_token(0, None, scope)
token_file = _token_file(json.dumps(expired_tok, ensure_ascii=False))
opener.return_value = token_file
spot = _make_implicitgrantauth(scope, path)
cached_tok = spot.validate_token(spot.cache_handler.get_cached_token())
is_token_expired.assert_called_with(expired_tok)
opener.assert_any_call(path)
self.assertIsNone(cached_tok)
@patch.object(SpotifyImplicitGrant, "is_token_expired", DEFAULT)
@patch('spotipy.cache_handler.open', create=True)
def test_badly_scoped_token_bails(self, opener, is_token_expired):
token_scope = "playlist-modify-public"
requested_scope = "playlist-modify-private"
path = ".cache-username"
tok = _make_fake_token(1, 1, token_scope)
opener.return_value = _token_file(json.dumps(tok, ensure_ascii=False))
is_token_expired.return_value = False
spot = _make_implicitgrantauth(requested_scope, path)
cached_tok = spot.validate_token(spot.cache_handler.get_cached_token())
opener.assert_called_with(path)
self.assertIsNone(cached_tok)
@patch('spotipy.cache_handler.open', create=True)
def test_saves_to_cache_path(self, opener):
scope = "playlist-modify-private"
path = ".cache-username"
tok = _make_fake_token(1, 1, scope)
fi = _fake_file()
opener.return_value = fi
spot = SpotifyImplicitGrant("CLID", "REDIR", "STATE", scope, path)
spot.cache_handler.save_token_to_cache(tok)
opener.assert_called_with(path, 'w')
self.assertTrue(fi.write.called)
@patch('spotipy.cache_handler.open', create=True)
def test_saves_to_cache_path_legacy(self, opener):
scope = "playlist-modify-private"
path = ".cache-username"
tok = _make_fake_token(1, 1, scope)
fi = _fake_file()
opener.return_value = fi
spot = SpotifyImplicitGrant("CLID", "REDIR", "STATE", scope, path)
spot._save_token_info(tok)
opener.assert_called_with(path, 'w')
self.assertTrue(fi.write.called)
class TestSpotifyImplicitGrant(unittest.TestCase):
def test_get_authorize_url_doesnt_pass_state_by_default(self):
auth = SpotifyImplicitGrant("CLID", "REDIR")
url = auth.get_authorize_url()
parsed_url = urllibparse.urlparse(url)
parsed_qs = urllibparse.parse_qs(parsed_url.query)
self.assertNotIn('state', parsed_qs)
def test_get_authorize_url_passes_state_from_constructor(self):
state = "STATE"
auth = SpotifyImplicitGrant("CLID", "REDIR", state)
url = auth.get_authorize_url()
parsed_url = urllibparse.urlparse(url)
parsed_qs = urllibparse.parse_qs(parsed_url.query)
self.assertEqual(parsed_qs['state'][0], state)
def test_get_authorize_url_passes_state_from_func_call(self):
state = "STATE"
auth = SpotifyImplicitGrant("CLID", "REDIR", "NOT STATE")
url = auth.get_authorize_url(state=state)
parsed_url = urllibparse.urlparse(url)
parsed_qs = urllibparse.parse_qs(parsed_url.query)
self.assertEqual(parsed_qs['state'][0], state)
def test_get_authorize_url_does_not_show_dialog_by_default(self):
auth = SpotifyImplicitGrant("CLID", "REDIR")
url = auth.get_authorize_url()
parsed_url = urllibparse.urlparse(url)
parsed_qs = urllibparse.parse_qs(parsed_url.query)
self.assertNotIn('show_dialog', parsed_qs)
def test_get_authorize_url_shows_dialog_when_requested(self):
auth = SpotifyImplicitGrant("CLID", "REDIR", show_dialog=True)
url = auth.get_authorize_url()
parsed_url = urllibparse.urlparse(url)
parsed_qs = urllibparse.parse_qs(parsed_url.query)
self.assertTrue(parsed_qs['show_dialog'])
class SpotifyPKCECacheTest(unittest.TestCase):
@patch.multiple(SpotifyPKCE,
@@ -398,13 +247,12 @@ class SpotifyPKCECacheTest(unittest.TestCase):
opener.return_value = _token_file(json.dumps(tok, ensure_ascii=False))
is_token_expired.return_value = False
spot = _make_pkceauth(scope, path)
cache_handler = CacheFileHandler(cache_path=path)
spot = _make_pkceauth(scope, cache_handler=cache_handler)
cached_tok = spot.cache_handler.get_cached_token()
cached_tok_legacy = spot.get_cached_token()
opener.assert_called_with(path)
self.assertIsNotNone(cached_tok)
self.assertIsNotNone(cached_tok_legacy)
self.assertEqual(refresh_access_token.call_count, 0)
@patch.multiple(SpotifyPKCE,
@@ -421,7 +269,8 @@ class SpotifyPKCECacheTest(unittest.TestCase):
opener.return_value = token_file
refresh_access_token.return_value = fresh_tok
spot = _make_pkceauth(scope, path)
cache_handler = CacheFileHandler(cache_path=path)
spot = _make_pkceauth(scope, cache_handler=cache_handler)
spot.validate_token(spot.cache_handler.get_cached_token())
is_token_expired.assert_called_with(expired_tok)
@@ -441,7 +290,8 @@ class SpotifyPKCECacheTest(unittest.TestCase):
opener.return_value = _token_file(json.dumps(tok, ensure_ascii=False))
is_token_expired.return_value = False
spot = _make_pkceauth(requested_scope, path)
cache_handler = CacheFileHandler(cache_path=path)
spot = _make_pkceauth(requested_scope, cache_handler=cache_handler)
cached_tok = spot.validate_token(spot.cache_handler.get_cached_token())
opener.assert_called_with(path)
@@ -457,27 +307,13 @@ class SpotifyPKCECacheTest(unittest.TestCase):
fi = _fake_file()
opener.return_value = fi
spot = SpotifyPKCE("CLID", "REDIR", "STATE", scope, path)
cache_handler = CacheFileHandler(cache_path=path)
spot = SpotifyPKCE("CLID", "REDIR", "STATE", scope, cache_handler=cache_handler)
spot.cache_handler.save_token_to_cache(tok)
opener.assert_called_with(path, 'w')
self.assertTrue(fi.write.called)
@patch('spotipy.cache_handler.open', create=True)
def test_saves_to_cache_path_legacy(self, opener):
scope = "playlist-modify-private"
path = ".cache-username"
tok = _make_fake_token(1, 1, scope)
fi = _fake_file()
opener.return_value = fi
spot = SpotifyPKCE("CLID", "REDIR", "STATE", scope, path)
spot._save_token_info(tok)
opener.assert_called_with(path, 'w')
self.assertTrue(fi.write.called)
class TestSpotifyPKCE(unittest.TestCase):
+25
View File
@@ -88,3 +88,28 @@ class SpotipyScopeTest(TestCase):
self.assertEqual(normalized_scope_string_2, "")
self.assertIsNone(self.normalize_scope(None))
def test_all_scopes(self):
expected_scopes = {
Scope.user_read_currently_playing,
Scope.playlist_read_collaborative,
Scope.playlist_modify_private,
Scope.user_read_playback_position,
Scope.user_library_modify,
Scope.user_top_read,
Scope.user_read_playback_state,
Scope.user_read_email,
Scope.ugc_image_upload,
Scope.user_read_private,
Scope.playlist_modify_public,
Scope.user_library_read,
Scope.streaming,
Scope.user_read_recently_played,
Scope.user_follow_read,
Scope.user_follow_modify,
Scope.app_remote_control,
Scope.playlist_read_private,
Scope.user_modify_playback_state,
}
self.assertEqual(expected_scopes, Scope.all())