Merge branch 'master' into master

This commit is contained in:
Stéphane Bruckert authored and GitHub committed 2020-01-15 19:16:38 +00:00
commit 9b8c90dbe1
61 files changed
+1113 -770

No files matched your search

-222
View File
@@ -1,222 +0,0 @@
# -*- coding: latin-1 -*-
import spotipy
from spotipy import util
import unittest
import pprint
import sys
import simplejson as json
'''
Since these tests require authentication they are maintained
separately from the other tests.
These tests try to be benign and leave your collection and
playlists in a relatively stable state.
'''
class AuthTestSpotipy(unittest.TestCase):
'''
These tests require user authentication
'''
playlist = "spotify:user:plamere:playlist:2oCEWyyAPbZp9xhVSxZavx"
four_tracks = ["spotify:track:6RtPijgfPKROxEzTHNRiDp",
"spotify:track:7IHOIqZUUInxjVkko181PB",
"4VrWlk8IQxevMvERoX08iC",
"http://open.spotify.com/track/3cySlItpiPiIAzU3NyHCJf"]
two_tracks = ["spotify:track:6RtPijgfPKROxEzTHNRiDp",
"spotify:track:7IHOIqZUUInxjVkko181PB"]
other_tracks=["spotify:track:2wySlB6vMzCbQrRnNGOYKa",
"spotify:track:29xKs5BAHlmlX1u4gzQAbJ",
"spotify:track:1PB7gRWcvefzu7t3LJLUlf"]
bad_id = 'BAD_ID'
def test_track_bad_id(self):
try:
track = spotify.track(self.bad_id)
self.assertTrue(False)
except spotipy.SpotifyException:
self.assertTrue(True)
def test_basic_user_profile(self):
user = spotify.user(username)
self.assertTrue(user['id'] == username)
def test_current_user(self):
user = spotify.current_user()
self.assertTrue(user['id'] == username)
def test_me(self):
user = spotify.me()
self.assertTrue(user['id'] == username)
def test_user_playlists(self):
playlists = spotify.user_playlists(username, limit=5)
self.assertTrue('items' in playlists)
self.assertTrue(len(playlists['items']) == 5)
def test_user_playlist_tracks(self):
playlists = spotify.user_playlists(username, limit=5)
self.assertTrue('items' in playlists)
for playlist in playlists['items']:
user = playlist['owner']['id']
pid = playlist['id']
results = spotify.user_playlist_tracks(user, pid)
self.assertTrue(len(results['items']) >= 0)
def user_playlist_tracks(self, user, playlist_id = None, fields=None,
limit=100, offset=0):
# known API issue currently causes this test to fail
# the issue is that the API doesn't currently respect the
# limit paramter
self.assertTrue(len(playlists['items']) == 5)
def test_current_user_saved_tracks(self):
tracks = spotify.current_user_saved_tracks()
self.assertTrue(len(tracks['items']) > 0)
def test_current_user_saved_albums(self):
albums = spotify.current_user_saved_albums()
self.assertTrue(len(albums['items']) > 0)
def test_current_user_playlists(self):
playlists = spotify.current_user_playlists(limit=10)
self.assertTrue('items' in playlists)
self.assertTrue(len(playlists['items']) == 10)
def test_user_playlist_follow(self):
spotify.user_playlist_follow_playlist('plamere', '4erXB04MxwRAVqcUEpu30O')
follows = spotify.user_playlist_is_following('plamere', '4erXB04MxwRAVqcUEpu30O', ['plamere'])
self.assertTrue(len(follows) == 1, 'proper follows length')
self.assertTrue(follows[0], 'is following')
spotify.user_playlist_unfollow('plamere', '4erXB04MxwRAVqcUEpu30O')
follows = spotify.user_playlist_is_following('plamere', '4erXB04MxwRAVqcUEpu30O', ['plamere'])
self.assertTrue(len(follows) == 1, 'proper follows length')
self.assertFalse(follows[0], 'is no longer following')
def test_current_user_save_and_unsave_tracks(self):
tracks = spotify.current_user_saved_tracks()
total = tracks['total']
spotify.current_user_saved_tracks_add(self.four_tracks)
tracks = spotify.current_user_saved_tracks()
new_total = tracks['total']
self.assertTrue(new_total - total == len(self.four_tracks))
tracks = spotify.current_user_saved_tracks_delete(self.four_tracks)
tracks = spotify.current_user_saved_tracks()
new_total = tracks['total']
self.assertTrue(new_total == total)
def test_categories(self):
response = spotify.categories()
self.assertTrue(len(response['categories']) > 0)
def test_category_playlists(self):
response = spotify.categories()
for cat in response['categories']['items']:
cat_id = cat['id']
response = spotify.category_playlists(category_id=cat_id)
self.assertTrue(len(response['playlists']["items"]) > 0)
def test_new_releases(self):
response = spotify.new_releases()
self.assertTrue(len(response['albums']) > 0)
def test_featured_releases(self):
response = spotify.featured_playlists()
self.assertTrue(len(response['playlists']) > 0)
def test_current_user_follows(self):
response = spotify.current_user_followed_artists()
artists = response['artists']
self.assertTrue(len(artists['items']) > 0)
def test_current_user_top_tracks(self):
response = spotify.current_user_top_tracks()
items = response['items']
self.assertTrue(len(items) > 0)
def test_current_user_top_artists(self):
response = spotify.current_user_top_artists()
items = response['items']
self.assertTrue(len(items) > 0)
def get_or_create_spotify_playlist(self, username, playlist_name):
playlists = spotify.user_playlists(username)
while playlists:
for item in playlists['items']:
if item['name'] == playlist_name:
return item['id']
playlists = spotify.next(playlists)
playlist = spotify.user_playlist_create(username, playlist_name)
playlist_id = playlist['uri']
return playlist_id
def test_user_playlist_ops(self):
# create empty playlist
playlist_id = self.get_or_create_spotify_playlist(username,
'spotipy-testing-playlist-1')
# remove all tracks from it
spotify.user_playlist_replace_tracks(username, playlist_id,[])
playlist = spotify.user_playlist(username, playlist_id)
self.assertTrue(playlist['tracks']['total'] == 0)
self.assertTrue(len(playlist['tracks']['items']) == 0)
# add tracks to it
spotify.user_playlist_add_tracks(username, playlist_id, self.four_tracks)
playlist = spotify.user_playlist(username, playlist_id)
self.assertTrue(playlist['tracks']['total'] == 4)
self.assertTrue(len(playlist['tracks']['items']) == 4)
# remove two tracks from it
spotify.user_playlist_remove_all_occurrences_of_tracks (username,
playlist_id, self.two_tracks)
playlist = spotify.user_playlist(username, playlist_id)
self.assertTrue(playlist['tracks']['total'] == 2)
self.assertTrue(len(playlist['tracks']['items']) == 2)
# replace with 3 other tracks
spotify.user_playlist_replace_tracks(username,
playlist_id, self.other_tracks)
playlist = spotify.user_playlist(username, playlist_id)
self.assertTrue(playlist['tracks']['total'] == 3)
self.assertTrue(len(playlist['tracks']['items']) == 3)
if __name__ == '__main__':
if len(sys.argv) > 1:
username = sys.argv[1]
del sys.argv[1]
scope = 'playlist-modify-public '
scope += 'user-library-read '
scope += 'user-follow-read '
scope += 'user-library-modify '
scope += 'user-read-private '
scope += 'user-top-read'
token = util.prompt_for_user_token(username, scope)
spotify = spotipy.Spotify(auth=token)
spotify.trace = False
unittest.main()
else:
print("Usage: %s username" % (sys.argv[0],))
-70
View File
@@ -1,70 +0,0 @@
# -*- coding: latin-1 -*-
import spotipy
from spotipy import util
import unittest
import pprint
import sys
import simplejson as json
from spotipy.oauth2 import SpotifyClientCredentials
'''
Since these tests require authentication they are maintained
separately from the other tests.
These tests try to be benign and leave your collection and
playlists in a relatively stable state.
'''
class AuthTestSpotipy(unittest.TestCase):
'''
These tests require user authentication
'''
playlist = "spotify:user:plamere:playlist:2oCEWyyAPbZp9xhVSxZavx"
four_tracks = ["spotify:track:6RtPijgfPKROxEzTHNRiDp",
"spotify:track:7IHOIqZUUInxjVkko181PB",
"4VrWlk8IQxevMvERoX08iC",
"http://open.spotify.com/track/3cySlItpiPiIAzU3NyHCJf"]
two_tracks = ["spotify:track:6RtPijgfPKROxEzTHNRiDp",
"spotify:track:7IHOIqZUUInxjVkko181PB"]
other_tracks=["spotify:track:2wySlB6vMzCbQrRnNGOYKa",
"spotify:track:29xKs5BAHlmlX1u4gzQAbJ",
"spotify:track:1PB7gRWcvefzu7t3LJLUlf"]
bad_id = 'BAD_ID'
def test_audio_analysis(self):
result = spotify.audio_analysis(self.four_tracks[0])
assert('beats' in result)
def test_audio_features(self):
results = spotify.audio_features(self.four_tracks)
self.assertTrue(len(results) == len(self.four_tracks))
for track in results:
assert('speechiness' in track)
def test_audio_features_with_bad_track(self):
bad_tracks = []
bad_tracks = ['spotify:track:bad']
input = self.four_tracks + bad_tracks
results = spotify.audio_features(input)
self.assertTrue(len(results) == len(input))
for track in results[:-1]:
if track != None:
assert('speechiness' in track)
self.assertTrue(results[-1] == None)
def test_recommendations(self):
results = spotify.recommendations(seed_tracks=self.four_tracks, min_danceability=0, max_loudness=0, target_popularity=50)
self.assertTrue(len(results['tracks']) == 20)
if __name__ == '__main__':
client_credentials_manager = SpotifyClientCredentials()
spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
spotify.trace = False
unittest.main()
-27
View File
@@ -1,27 +0,0 @@
# -*- coding: latin-1 -*-
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import unittest
'''
Client Credentials Requests Tests
'''
class ClientCredentialsTestSpotipy(unittest.TestCase):
'''
These tests require user authentication
'''
muse_urn = 'spotify:artist:12Chz98pHFMPJEknJQMWvI'
def test_request_with_token(self):
artist = spotify.artist(self.muse_urn)
self.assertTrue(artist['name'] == 'Muse')
if __name__ == '__main__':
spotify_cc = SpotifyClientCredentials()
spotify = spotipy.Spotify(client_credentials_manager=spotify_cc)
spotify.trace = False
unittest.main()
+312
View File
@@ -0,0 +1,312 @@
# -*- coding: utf-8 -*-
"""
These tests require user authentication - provide client credentials using the
following environment variables
::
'SPOTIPY_CLIENT_USERNAME'
'SPOTIPY_CLIENT_ID'
'SPOTIPY_CLIENT_SECRET'
'SPOTIPY_REDIRECT_URI'
"""
from __future__ import print_function
from spotipy import (
CLIENT_CREDS_ENV_VARS as CCEV,
prompt_for_user_token,
Spotify,
SpotifyException,
)
import os
import sys
import unittest
sys.path.insert(0, os.path.abspath(os.pardir))
class AuthTestSpotipy(unittest.TestCase):
"""
These tests require user authentication - provide client credentials using
the following environment variables
::
'SPOTIPY_CLIENT_USERNAME'
'SPOTIPY_CLIENT_ID'
'SPOTIPY_CLIENT_SECRET'
'SPOTIPY_REDIRECT_URI'
"""
playlist = "spotify:user:plamere:playlist:2oCEWyyAPbZp9xhVSxZavx"
playlist_new_id = "spotify:playlist:7GlxpQjjxRjmbb3RP2rDqI"
four_tracks = ["spotify:track:6RtPijgfPKROxEzTHNRiDp",
"spotify:track:7IHOIqZUUInxjVkko181PB",
"4VrWlk8IQxevMvERoX08iC",
"http://open.spotify.com/track/3cySlItpiPiIAzU3NyHCJf"]
two_tracks = ["spotify:track:6RtPijgfPKROxEzTHNRiDp",
"spotify:track:7IHOIqZUUInxjVkko181PB"]
other_tracks = ["spotify:track:2wySlB6vMzCbQrRnNGOYKa",
"spotify:track:29xKs5BAHlmlX1u4gzQAbJ",
"spotify:track:1PB7gRWcvefzu7t3LJLUlf"]
album_ids = ["spotify:album:6kL09DaURb7rAoqqaA51KU",
"spotify:album:6RTzC0rDbvagTSJLlY7AKl"]
bad_id = 'BAD_ID'
@classmethod
def setUpClass(self):
missing = list(filter(lambda var: not os.getenv(CCEV[var]), CCEV))
if missing:
raise Exception(
('Please set the client credentials for the test application'
' using the following environment variables: {}').format(
CCEV.values()))
self.username = os.getenv(CCEV['client_username'])
self.scope = (
'playlist-modify-public '
'user-library-read '
'user-follow-read '
'user-library-modify '
'user-read-private '
'user-top-read '
'user-follow-modify'
)
self.token = prompt_for_user_token(self.username, scope=self.scope)
self.spotify = Spotify(auth=self.token)
def test_track_bad_id(self):
try:
self.spotify.track(self.bad_id)
self.assertTrue(False)
except SpotifyException:
self.assertTrue(True)
def test_basic_user_profile(self):
user = self.spotify.user(self.username)
self.assertTrue(user['id'] == self.username.lower())
def test_current_user(self):
user = self.spotify.current_user()
self.assertTrue(user['id'] == self.username.lower())
def test_me(self):
user = self.spotify.me()
self.assertTrue(user['id'] == self.username.lower())
def test_user_playlists(self):
playlists = self.spotify.user_playlists(self.username, limit=5)
self.assertTrue('items' in playlists)
self.assertTrue(len(playlists['items']) == 5)
def test_user_playlist_tracks(self):
playlists = self.spotify.user_playlists(self.username, limit=5)
self.assertTrue('items' in playlists)
for playlist in playlists['items']:
user = playlist['owner']['id']
pid = playlist['id']
results = self.spotify.user_playlist_tracks(user, pid)
self.assertTrue(len(results['items']) >= 0)
# known API issue currently causes this test to fail
# the issue is that the API doesn't currently respect the
# limit parameter
# def user_playlist_tracks(self, user, playlist_id=None, fields=None,
# limit=100, offset=0):
# self.assertTrue(len(playlists['items']) == 5)
def test_current_user_saved_albums(self):
# List
albums = self.spotify.current_user_saved_albums()
self.assertTrue(len(albums['items']) == 1)
# Add
self.spotify.current_user_saved_albums_add(self.album_ids)
# Contains
self.assertTrue(
self.spotify.current_user_saved_albums_contains(
self.album_ids) == [
True, True])
# Remove
self.spotify.current_user_saved_albums_delete(self.album_ids)
albums = self.spotify.current_user_saved_albums()
self.assertTrue(len(albums['items']) == 1)
def test_current_user_playlists(self):
playlists = self.spotify.current_user_playlists(limit=10)
self.assertTrue('items' in playlists)
self.assertTrue(len(playlists['items']) == 10)
def test_user_playlist_follow(self):
self.spotify.user_playlist_follow_playlist(
'plamere', '4erXB04MxwRAVqcUEpu30O')
follows = self.spotify.user_playlist_is_following(
'plamere', '4erXB04MxwRAVqcUEpu30O', [
self.spotify.current_user()['id']])
self.assertTrue(len(follows) == 1, 'proper follows length')
self.assertTrue(follows[0], 'is following')
self.spotify.user_playlist_unfollow(
'plamere', '4erXB04MxwRAVqcUEpu30O')
follows = self.spotify.user_playlist_is_following(
'plamere', '4erXB04MxwRAVqcUEpu30O', [
self.spotify.current_user()['id']])
self.assertTrue(len(follows) == 1, 'proper follows length')
self.assertFalse(follows[0], 'is no longer following')
def test_current_user_saved_tracks(self):
tracks = self.spotify.current_user_saved_tracks()
self.assertTrue(len(tracks['items']) > 0)
def test_current_user_save_and_unsave_tracks(self):
tracks = self.spotify.current_user_saved_tracks()
total = tracks['total']
self.spotify.current_user_saved_tracks_add(self.four_tracks)
tracks = self.spotify.current_user_saved_tracks()
new_total = tracks['total']
self.assertTrue(new_total - total == len(self.four_tracks))
tracks = self.spotify.current_user_saved_tracks_delete(
self.four_tracks)
tracks = self.spotify.current_user_saved_tracks()
new_total = tracks['total']
self.assertTrue(new_total == total)
def test_categories(self):
response = self.spotify.categories()
self.assertTrue(len(response['categories']) > 0)
def test_category_playlists(self):
response = self.spotify.categories()
for cat in response['categories']['items']:
cat_id = cat['id']
response = self.spotify.category_playlists(category_id=cat_id)
if len(response['playlists']["items"]) > 0:
break
self.assertTrue(True)
def test_new_releases(self):
response = self.spotify.new_releases()
self.assertTrue(len(response['albums']) > 0)
def test_featured_releases(self):
response = self.spotify.featured_playlists()
self.assertTrue(len(response['playlists']) > 0)
def test_current_user_follows(self):
response = self.spotify.current_user_followed_artists()
artists = response['artists']
self.assertTrue(len(artists['items']) > 0)
def test_current_user_top_tracks(self):
response = self.spotify.current_user_top_tracks()
items = response['items']
self.assertTrue(len(items) > 0)
def test_current_user_top_artists(self):
response = self.spotify.current_user_top_artists()
items = response['items']
self.assertTrue(len(items) > 0)
def get_or_create_spotify_playlist(self, playlist_name):
playlists = self.spotify.user_playlists(self.username)
while playlists:
for item in playlists['items']:
if item['name'] == playlist_name:
return item['id']
playlists = self.spotify.next(playlists)
playlist = self.spotify.user_playlist_create(
self.username, playlist_name)
playlist_id = playlist['uri']
return playlist_id
def test_user_playlist_ops(self):
sp = self.spotify
# create empty playlist
playlist_id = self.get_or_create_spotify_playlist(
'spotipy-testing-playlist-1')
# remove all tracks from it
sp.user_playlist_replace_tracks(
self.username, playlist_id, [])
playlist = sp.user_playlist(self.username, playlist_id)
self.assertTrue(playlist['tracks']['total'] == 0)
self.assertTrue(len(playlist['tracks']['items']) == 0)
# add tracks to it
sp.user_playlist_add_tracks(
self.username, playlist_id, self.four_tracks)
playlist = sp.user_playlist(self.username, playlist_id)
self.assertTrue(playlist['tracks']['total'] == 4)
self.assertTrue(len(playlist['tracks']['items']) == 4)
# remove two tracks from it
sp.user_playlist_remove_all_occurrences_of_tracks(self.username,
playlist_id,
self.two_tracks)
playlist = sp.user_playlist(self.username, playlist_id)
self.assertTrue(playlist['tracks']['total'] == 2)
self.assertTrue(len(playlist['tracks']['items']) == 2)
# replace with 3 other tracks
sp.user_playlist_replace_tracks(self.username,
playlist_id,
self.other_tracks)
playlist = sp.user_playlist(self.username, playlist_id)
self.assertTrue(playlist['tracks']['total'] == 3)
self.assertTrue(len(playlist['tracks']['items']) == 3)
def test_playlist(self):
# New playlist ID
pl = self.spotify.playlist(self.playlist_new_id)
self.assertTrue(pl["tracks"]["total"] > 0)
# Old playlist ID
pl = self.spotify.playlist(self.playlist)
self.assertTrue(pl["tracks"]["total"] > 0)
def test_user_follows_and_unfollows_artist(self):
# Initially follows 1 artist
res = self.spotify.current_user_followed_artists()
self.assertTrue(res['artists']['total'] == 1)
# Follow 2 more artists
artists = ["6DPYiyq5kWVQS4RGwxzPC7", "0NbfKEOTQCcwd6o7wSDOHI"]
self.spotify.user_follow_artists(artists)
res = self.spotify.current_user_followed_artists()
self.assertTrue(res['artists']['total'] == 3)
# Unfollow these 2 artists
self.spotify.user_unfollow_artists(artists)
res = self.spotify.current_user_followed_artists()
self.assertTrue(res['artists']['total'] == 1)
def test_user_follows_and_unfollows_user(self):
# TODO improve after implementing `me/following/contains`
users = ["11111204", "xlqeojt6n7on0j7coh9go8ifd"]
# Follow 2 more users
self.spotify.user_follow_users(users)
# Unfollow these 2 users
self.spotify.user_unfollow_users(users)
if __name__ == '__main__':
unittest.main()
+91
View File
@@ -0,0 +1,91 @@
# -*- coding: utf-8 -*-
"""
These tests require user authentication - provide client credentials using the
following environment variables
::
'SPOTIPY_CLIENT_USERNAME'
'SPOTIPY_CLIENT_ID'
'SPOTIPY_CLIENT_SECRET'
'SPOTIPY_REDIRECT_URI'
"""
from spotipy import (
Spotify,
SpotifyClientCredentials,
)
import os
import sys
import unittest
sys.path.insert(0, os.path.abspath(os.pardir))
class AuthTestSpotipy(unittest.TestCase):
"""
These tests require user authentication - provide client credentials using
the following environment variables
::
'SPOTIPY_CLIENT_USERNAME'
'SPOTIPY_CLIENT_ID'
'SPOTIPY_CLIENT_SECRET'
'SPOTIPY_REDIRECT_URI'
"""
playlist = "spotify:user:plamere:playlist:2oCEWyyAPbZp9xhVSxZavx"
four_tracks = ["spotify:track:6RtPijgfPKROxEzTHNRiDp",
"spotify:track:7IHOIqZUUInxjVkko181PB",
"4VrWlk8IQxevMvERoX08iC",
"http://open.spotify.com/track/3cySlItpiPiIAzU3NyHCJf"]
two_tracks = ["spotify:track:6RtPijgfPKROxEzTHNRiDp",
"spotify:track:7IHOIqZUUInxjVkko181PB"]
other_tracks = ["spotify:track:2wySlB6vMzCbQrRnNGOYKa",
"spotify:track:29xKs5BAHlmlX1u4gzQAbJ",
"spotify:track:1PB7gRWcvefzu7t3LJLUlf"]
bad_id = 'BAD_ID'
@classmethod
def setUpClass(self):
self.spotify = Spotify(
client_credentials_manager=SpotifyClientCredentials())
self.spotify.trace = False
def test_audio_analysis(self):
result = self.spotify.audio_analysis(self.four_tracks[0])
assert('beats' in result)
def test_audio_features(self):
results = self.spotify.audio_features(self.four_tracks)
self.assertTrue(len(results) == len(self.four_tracks))
for track in results:
assert('speechiness' in track)
def test_audio_features_with_bad_track(self):
bad_tracks = []
bad_tracks = ['spotify:track:bad']
input = self.four_tracks + bad_tracks
results = self.spotify.audio_features(input)
self.assertTrue(len(results) == len(input))
for track in results[:-1]:
if track is not None:
assert('speechiness' in track)
self.assertTrue(results[-1] is None)
def test_recommendations(self):
results = self.spotify.recommendations(
seed_tracks=self.four_tracks,
min_danceability=0,
max_loudness=0,
target_popularity=50)
self.assertTrue(len(results['tracks']) == 20)
if __name__ == '__main__':
unittest.main()
+43
View File
@@ -0,0 +1,43 @@
# -*- coding: utf-8 -*-
""" Client Credentials Requests Tests """
from spotipy import (
Spotify,
SpotifyClientCredentials,
)
import os
import sys
import unittest
sys.path.insert(0, os.path.abspath(os.pardir))
class ClientCredentialsTestSpotipy(unittest.TestCase):
"""
These tests require user authentication - provide client credentials using
the following environment variables
::
'SPOTIPY_CLIENT_USERNAME'
'SPOTIPY_CLIENT_ID'
'SPOTIPY_CLIENT_SECRET'
'SPOTIPY_REDIRECT_URI'
"""
@classmethod
def setUpClass(self):
self.spotify = Spotify(
client_credentials_manager=SpotifyClientCredentials())
self.spotify.trace = False
muse_urn = 'spotify:artist:12Chz98pHFMPJEknJQMWvI'
def test_request_with_token(self):
artist = self.spotify.artist(self.muse_urn)
self.assertTrue(artist['name'] == 'Muse')
if __name__ == '__main__':
unittest.main()
+11 -3
View File
@@ -1,13 +1,20 @@
from spotipy.oauth2 import SpotifyOAuth
import json
# -*- coding: utf-8 -*-
import six.moves.urllib.parse as urllibparse
from spotipy import SpotifyOAuth
import io
import json
import os
import sys
import unittest
sys.path.insert(0, os.path.abspath(os.pardir))
try:
import unittest.mock as mock
except ImportError:
import mock
import six.moves.urllib.parse as urllibparse
patch = mock.patch
DEFAULT = mock.DEFAULT
@@ -166,4 +173,5 @@ class TestSpotifyOAuth(unittest.TestCase):
if __name__ == '__main__':
unittest.main()
+35 -26
View File
@@ -1,7 +1,9 @@
# -*- coding: latin-1 -*-
import spotipy
# -*- coding: utf-8 -*-
import os
import sys
import unittest
import pprint
import requests
from spotipy.client import SpotifyException
from spotipy.oauth2 import SpotifyClientCredentials
@@ -9,6 +11,18 @@ from spotipy.oauth2 import SpotifyClientCredentials
class TestSpotipy(unittest.TestCase):
"""
These tests require user authentication - provide client credentials using
the following environment variables
::
'SPOTIPY_CLIENT_USERNAME'
'SPOTIPY_CLIENT_ID'
'SPOTIPY_CLIENT_SECRET'
'SPOTIPY_REDIRECT_URI'
"""
creep_urn = 'spotify:track:3HfB5hBU0dmBt8T0iCmH42'
creep_id = '3HfB5hBU0dmBt8T0iCmH42'
creep_url = 'http://open.spotify.com/track/3HfB5hBU0dmBt8T0iCmH42'
@@ -20,9 +34,9 @@ class TestSpotipy(unittest.TestCase):
radiohead_urn = 'spotify:artist:4Z8W4fKeB5YxbusRsdQVPb'
angeles_haydn_urn = 'spotify:album:1vAbqAeuJVWNAe7UR00bdM'
bad_id = 'BAD_ID'
def setUp(self):
client_credentials_manager = SpotifyClientCredentials()
self.spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
@@ -43,20 +57,22 @@ class TestSpotipy(unittest.TestCase):
def test_album_tracks(self):
results = self.spotify.album_tracks(self.pinkerton_urn)
self.assertTrue(len(results['items']) == 10)
def test_album_tracks_many(self):
results = self.spotify.album_tracks(self.angeles_haydn_urn)
tracks = results['items']
total, received = results['total'], len(tracks)
while received < total:
results = self.spotify.album_tracks(self.angeles_haydn_urn, offset=received)
results = self.spotify.album_tracks(
self.angeles_haydn_urn, offset=received)
tracks.extend(results['items'])
received = len(tracks)
self.assertEqual(received, total)
def test_albums(self):
results = self.spotify.albums([self.pinkerton_urn, self.pablo_honey_urn])
results = self.spotify.albums(
[self.pinkerton_urn, self.pablo_honey_urn])
self.assertTrue('albums' in results)
self.assertTrue(len(results['albums']) == 2)
@@ -74,9 +90,9 @@ class TestSpotipy(unittest.TestCase):
def test_track_bad_urn(self):
try:
track = self.spotify.track(self.el_scorcho_bad_urn)
self.spotify.track(self.el_scorcho_bad_urn)
self.assertTrue(False)
except spotipy.SpotifyException:
except SpotifyException:
self.assertTrue(True)
def test_tracks(self):
@@ -125,18 +141,19 @@ class TestSpotipy(unittest.TestCase):
def test_search_timeout(self):
client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager, requests_timeout=.1)
try:
results = sp.search(q='my*', type='track')
sp.search(q='my*', type='track')
self.assertTrue(False, 'unexpected search timeout')
except requests.exceptions.Timeout:
self.assertTrue(True, 'expected search timeout')
def test_album_search(self):
results = self.spotify.search(q='weezer pinkerton', type='album')
self.assertTrue('albums' in results)
self.assertTrue(len(results['albums']['items']) > 0)
self.assertTrue(results['albums']['items'][0]['name'].find('Pinkerton') >= 0)
self.assertTrue(results['albums']['items'][0]
['name'].find('Pinkerton') >= 0)
def test_track_search(self):
results = self.spotify.search(q='el scorcho weezer', type='track')
@@ -150,27 +167,20 @@ class TestSpotipy(unittest.TestCase):
def test_track_bad_id(self):
try:
track = self.spotify.track(self.bad_id)
self.spotify.track(self.bad_id)
self.assertTrue(False)
except spotipy.SpotifyException:
self.assertTrue(True)
def test_track_bad_id(self):
try:
track = self.spotify.track(self.bad_id)
self.assertTrue(False)
except spotipy.SpotifyException:
except SpotifyException:
self.assertTrue(True)
def test_unauthenticated_post_fails(self):
with self.assertRaises(SpotifyException) as cm:
self.spotify.user_playlist_create("spotify", "Best hits of the 90s")
self.spotify.user_playlist_create(
"spotify", "Best hits of the 90s")
self.assertTrue(cm.exception.http_status == 401 or
cm.exception.http_status == 403)
cm.exception.http_status == 403)
def test_custom_requests_session(self):
from requests import Session
sess = Session()
sess = requests.Session()
sess.headers["user-agent"] = "spotipy-test"
client_credentials_manager = SpotifyClientCredentials()
with_custom_session = spotipy.Spotify(client_credentials_manager=client_credentials_manager, requests_session=sess)
@@ -184,7 +194,6 @@ class TestSpotipy(unittest.TestCase):
self.assertTrue(with_no_session.user(user="akx")["uri"] == "spotify:user:akx")
'''
Need tests for: