Debian Codegraph @

test/plugins/test_spotify.py

raw
1 """Tests for the 'spotify' plugin"""
2
3 import json
4 from urllib.parse import parse_qs, urlparse
5
6 import responses
7
8 from beets.library import Item
9 from beets.test import _common
10 from beets.test.helper import PluginTestCase
11 from beetsplug import spotify
12
13
14 class ArgumentsMock:
15 def __init__(self, mode, show_failures):
16 self.mode = mode
17 self.show_failures = show_failures
18 self.verbose = 1
19
20
21 def _params(url):
22 """Get the query parameters from a URL."""
23 return parse_qs(urlparse(url).query)
24
25
26 class SpotifyPluginTest(PluginTestCase):
27 plugin = "spotify"
28 db_on_disk = True
29
30 @responses.activate
31 def setUp(self):
32 responses.add(
33 responses.POST,
34 spotify.SpotifyPlugin.oauth_token_url,
35 status=200,
36 json={
37 "access_token": "3XyiC3raJySbIAV5LVYj1DaWbcocNi3LAJTNXRnYY"
38 "GVUl6mbbqXNhW3YcZnQgYXNWHFkVGSMlc0tMuvq8CF",
39 "token_type": "Bearer",
40 "expires_in": 3600,
41 "scope": "",
42 },
43 )
44 super().setUp()
45 self.spotify = spotify.SpotifyPlugin()
46 opts = ArgumentsMock("list", False)
47 self.spotify._parse_opts(opts)
48
49 def test_args(self):
50 opts = ArgumentsMock("fail", True)
51 assert not self.spotify._parse_opts(opts)
52 opts = ArgumentsMock("list", False)
53 assert self.spotify._parse_opts(opts)
54
55 def test_empty_query(self):
56 assert self.spotify._match_library_tracks(self.lib, "1=2") is None
57
58 @responses.activate
59 def test_missing_request(self):
60 json_file = _common.RSRC / "spotify" / "missing_request.json"
61 response_body = json_file.read_bytes()
62
63 responses.add(
64 responses.GET,
65 spotify.SpotifyPlugin.search_url,
66 body=response_body,
67 status=200,
68 content_type="application/json",
69 )
70 item = Item(
71 mb_trackid="01234",
72 album="lkajsdflakjsd",
73 albumartist="ujydfsuihse",
74 title="duifhjslkef",
75 length=10,
76 )
77 item.add(self.lib)
78 assert [] == self.spotify._match_library_tracks(self.lib, "")
79
80 params = _params(responses.calls[0].request.url)
81 query = params["q"][0]
82 assert "duifhjslkef" in query
83 assert "artist:'ujydfsuihse'" in query
84 assert "album:'lkajsdflakjsd'" in query
85 assert params["type"] == ["track"]
86
87 @responses.activate
88 def test_track_request(self):
89 json_file = _common.RSRC / "spotify" / "track_request.json"
90 response_body = json_file.read_bytes()
91
92 responses.add(
93 responses.GET,
94 spotify.SpotifyPlugin.search_url,
95 body=response_body,
96 status=200,
97 content_type="application/json",
98 )
99 item = Item(
100 mb_trackid="01234",
101 album="Despicable Me 2",
102 albumartist="Pharrell Williams",
103 title="Happy",
104 length=10,
105 )
106 item.add(self.lib)
107 results = self.spotify._match_library_tracks(self.lib, "Happy")
108 assert 1 == len(results)
109 assert "6NPVjNh8Jhru9xOmyQigds" == results[0]["id"]
110 self.spotify._output_match_results(results)
111
112 params = _params(responses.calls[0].request.url)
113 query = params["q"][0]
114 assert "Happy" in query
115 assert "artist:'Pharrell Williams'" in query
116 assert "album:'Despicable Me 2'" in query
117 assert params["type"] == ["track"]
118
119 @responses.activate
120 def test_track_for_id(self):
121 """Tests if plugin is able to fetch a track by its Spotify ID"""
122
123 # Mock the Spotify 'Get Track' call
124 json_file = _common.RSRC / "spotify" / "track_info.json"
125 response_body = json_file.read_bytes()
126
127 responses.add(
128 responses.GET,
129 f"{spotify.SpotifyPlugin.track_url}/6NPVjNh8Jhru9xOmyQigds",
130 body=response_body,
131 status=200,
132 content_type="application/json",
133 )
134
135 # Mock the Spotify 'Get Album' call
136 json_file = _common.RSRC / "spotify" / "album_info.json"
137 response_body = json_file.read_bytes()
138
139 responses.add(
140 responses.GET,
141 f"{spotify.SpotifyPlugin.album_url}5l3zEmMrOhOzG8d8s83GOL",
142 body=response_body,
143 status=200,
144 content_type="application/json",
145 )
146
147 # Mock the Spotify 'Search' call
148 json_file = _common.RSRC / "spotify" / "track_request.json"
149 response_body = json_file.read_bytes()
150
151 responses.add(
152 responses.GET,
153 spotify.SpotifyPlugin.search_url,
154 body=response_body,
155 status=200,
156 content_type="application/json",
157 )
158
159 track_info = self.spotify.track_for_id("6NPVjNh8Jhru9xOmyQigds")
160 item = Item(
161 mb_trackid=track_info.track_id,
162 albumartist=track_info.artist,
163 title=track_info.title,
164 length=track_info.length,
165 )
166 item.add(self.lib)
167
168 results = self.spotify._match_library_tracks(self.lib, "Happy")
169 assert 1 == len(results)
170 assert "6NPVjNh8Jhru9xOmyQigds" == results[0]["id"]
171
172 @responses.activate
173 def test_japanese_track(self):
174 """Ensure non-ASCII characters remain unchanged in search queries"""
175
176 # Path to the mock JSON file for the Japanese track
177 json_file = _common.RSRC / "spotify" / "japanese_track_request.json"
178
179 # Load the mock JSON response
180 response_body = json_file.read_bytes()
181
182 # Mock Spotify Search API response
183 responses.add(
184 responses.GET,
185 spotify.SpotifyPlugin.search_url,
186 body=response_body,
187 status=200,
188 content_type="application/json",
189 )
190
191 # Create a mock item with Japanese metadata
192 item = Item(
193 mb_trackid="56789",
194 album="盗作",
195 albumartist="ヨルシカ",
196 title="思想犯",
197 length=10,
198 )
199 item.add(self.lib)
200
201 # Search without ascii encoding
202
203 with self.configure_plugin({"search_query_ascii": False}):
204 assert self.spotify.config["search_query_ascii"].get() is False
205 # Call the method to match library tracks
206 results = self.spotify._match_library_tracks(self.lib, item.title)
207
208 # Assertions to verify results
209 assert results is not None
210 assert 1 == len(results)
211 assert results[0]["name"] == item.title
212 assert results[0]["artists"][0]["name"] == item.albumartist
213 assert results[0]["album"]["name"] == item.album
214
215 # Verify search query parameters
216 params = _params(responses.calls[0].request.url)
217 query = params["q"][0]
218 assert item.title in query
219 assert f"artist:'{item.albumartist}'" in query
220 assert f"album:'{item.album}'" in query
221 assert not query.isascii()
222
223 # Is not found in the library if ascii encoding is enabled
224 with self.configure_plugin({"search_query_ascii": True}):
225 assert self.spotify.config["search_query_ascii"].get() is True
226 results = self.spotify._match_library_tracks(self.lib, item.title)
227 params = _params(responses.calls[1].request.url)
228 query = params["q"][0]
229
230 assert query.isascii()
231
232 @responses.activate
233 def test_multiartist_album_and_track(self):
234 """Tests if plugin is able to map multiple artists in an album and
235 track info correctly"""
236
237 # Mock the Spotify 'Get Album' call
238 json_file = _common.RSRC / "spotify" / "multiartist_album.json"
239 album_response_body = json_file.read_bytes()
240
241 responses.add(
242 responses.GET,
243 f"{spotify.SpotifyPlugin.album_url}0yhKyyjyKXWUieJ4w1IAEa",
244 body=album_response_body,
245 status=200,
246 content_type="application/json",
247 )
248
249 # Mock the Spotify 'Get Track' call
250 json_file = _common.RSRC / "spotify" / "multiartist_track.json"
251 track_response_body = json_file.read_bytes()
252
253 responses.add(
254 responses.GET,
255 f"{spotify.SpotifyPlugin.track_url}/6sjZfVJworBX6TqyjkxIJ1",
256 body=track_response_body,
257 status=200,
258 content_type="application/json",
259 )
260
261 album_info = self.spotify.album_for_id("0yhKyyjyKXWUieJ4w1IAEa")
262 assert album_info is not None
263 assert album_info.artist == "Project Skylate, Sugar Shrill"
264 assert album_info.artists == ["Project Skylate", "Sugar Shrill"]
265 assert album_info.artist_id == "6m8MRXIVKb6wQaPlBIDMr1"
266 assert album_info.artists_ids == [
267 "6m8MRXIVKb6wQaPlBIDMr1",
268 "4kkAIoQmNT5xEoNH5BuQLe",
269 ]
270
271 assert len(album_info.tracks) == 1
272 assert album_info.tracks[0].artist == "Foo, Bar"
273 assert album_info.tracks[0].artists == ["Foo", "Bar"]
274 assert album_info.tracks[0].artist_id == "12345"
275 assert album_info.tracks[0].artists_ids == ["12345", "67890"]
276
277 track_info = self.spotify.track_for_id("6sjZfVJworBX6TqyjkxIJ1")
278 assert track_info is not None
279 assert track_info.artist == "Foo, Bar"
280 assert track_info.artists == ["Foo", "Bar"]
281 assert track_info.artist_id == "12345"
282 assert track_info.artists_ids == ["12345", "67890"]
283
284 @responses.activate
285 def test_get_track_details_by_id_chunks_requests(self):
286 ids_per_request = []
287
288 def callback(request):
289 ids = _params(request.url)["ids"][0].split(",")
290 ids_per_request.append(len(ids))
291 return (
292 200,
293 {"Content-Type": "application/json"},
294 json.dumps(
295 {
296 "tracks": [
297 {
298 "id": track_id,
299 "popularity": 50,
300 "external_ids": {},
301 }
302 for track_id in ids
303 ]
304 }
305 ),
306 )
307
308 responses.add_callback(
309 responses.GET,
310 spotify.SpotifyPlugin.track_url,
311 callback=callback,
312 content_type="application/json",
313 )
314
315 track_ids = [f"track-{idx}" for idx in range(51)]
316 track_info = self.spotify.get_track_details_by_id(track_ids)
317
318 assert len(track_info) == 51
319 assert ids_per_request == [50, 1]
320
321 @responses.activate
322 def test_fetch_info_uses_batch_endpoints(self):
323 responses.add(
324 responses.GET,
325 spotify.SpotifyPlugin.track_url,
326 status=200,
327 json={
328 "tracks": [
329 {
330 "id": "id-1",
331 "popularity": 10,
332 "external_ids": {
333 "isrc": "isrc-1",
334 "ean": "ean-1",
335 "upc": "upc-1",
336 },
337 },
338 {
339 "id": "id-2",
340 "popularity": 20,
341 "external_ids": {
342 "isrc": "isrc-2",
343 "ean": "ean-2",
344 "upc": "upc-2",
345 },
346 },
347 {
348 "id": "id-3",
349 "popularity": 30,
350 "external_ids": {
351 "isrc": "isrc-3",
352 "ean": "ean-3",
353 "upc": "upc-3",
354 },
355 },
356 ]
357 },
358 content_type="application/json",
359 )
360 responses.add(
361 responses.GET,
362 spotify.SpotifyPlugin.audio_features_url,
363 status=200,
364 json={
365 "audio_features": [
366 {"id": "id-1", "tempo": 100.1, "energy": 0.4},
367 {"id": "id-2", "tempo": 110.2, "energy": 0.5},
368 {"id": "id-3", "tempo": 120.3, "energy": 0.6},
369 ]
370 },
371 content_type="application/json",
372 )
373
374 items = []
375 for idx in range(1, 4):
376 item = Item(title=f"Track {idx}", artist="Artist", length=10)
377 item.add(self.lib)
378 item["spotify_track_id"] = f"id-{idx}"
379 items.append(item)
380
381 self.spotify._fetch_info(self.lib, items, write=False, force=True)
382
383 get_calls = [
384 call for call in responses.calls if call.request.method == "GET"
385 ]
386 batch_track_calls = [
387 call
388 for call in get_calls
389 if urlparse(call.request.url).path == "/v1/tracks"
390 ]
391 single_track_calls = [
392 call
393 for call in get_calls
394 if urlparse(call.request.url).path.startswith("/v1/tracks/")
395 ]
396 batch_audio_calls = [
397 call
398 for call in get_calls
399 if urlparse(call.request.url).path == "/v1/audio-features"
400 ]
401 single_audio_calls = [
402 call
403 for call in get_calls
404 if urlparse(call.request.url).path.startswith("/v1/audio-features/")
405 ]
406
407 assert len(batch_track_calls) == 1
408 assert len(single_track_calls) == 0
409 assert len(batch_audio_calls) == 1
410 assert len(single_audio_calls) == 0
411
412 assert items[0]["spotify_track_popularity"] == 10
413 assert items[1]["spotify_track_popularity"] == 20
414 assert items[2]["spotify_track_popularity"] == 30
415
416 assert items[0]["spotify_tempo"] == 100.1
417 assert items[1]["spotify_tempo"] == 110.2
418 assert items[2]["spotify_tempo"] == 120.3
419
420 @responses.activate
421 def test_fetch_info_deduplicates_batch_ids(self):
422 seen_track_ids = []
423 seen_audio_ids = []
424
425 def track_callback(request):
426 ids = _params(request.url)["ids"][0].split(",")
427 seen_track_ids.append(ids)
428 return (
429 200,
430 {"Content-Type": "application/json"},
431 json.dumps(
432 {
433 "tracks": [
434 {
435 "id": track_id,
436 "popularity": 50,
437 "external_ids": {},
438 }
439 for track_id in ids
440 ]
441 }
442 ),
443 )
444
445 def audio_callback(request):
446 ids = _params(request.url)["ids"][0].split(",")
447 seen_audio_ids.append(ids)
448 return (
449 200,
450 {"Content-Type": "application/json"},
451 json.dumps(
452 {
453 "audio_features": [
454 {"id": track_id, "tempo": 100.0} for track_id in ids
455 ]
456 }
457 ),
458 )
459
460 responses.add_callback(
461 responses.GET,
462 spotify.SpotifyPlugin.track_url,
463 callback=track_callback,
464 content_type="application/json",
465 )
466 responses.add_callback(
467 responses.GET,
468 spotify.SpotifyPlugin.audio_features_url,
469 callback=audio_callback,
470 content_type="application/json",
471 )
472
473 items = []
474 for idx in range(2):
475 item = Item(title=f"Track {idx}", artist="Artist", length=10)
476 item.add(self.lib)
477 item["spotify_track_id"] = "shared-id"
478 items.append(item)
479
480 self.spotify._fetch_info(self.lib, items, write=False, force=True)
481
482 assert seen_track_ids == [["shared-id"]]
483 assert seen_audio_ids == [["shared-id"]]
484 assert items[0]["spotify_track_popularity"] == 50
485 assert items[1]["spotify_track_popularity"] == 50
486
487 @responses.activate
488 def test_fetch_info_writes_before_store(self):
489 responses.add(
490 responses.GET,
491 spotify.SpotifyPlugin.track_url,
492 status=200,
493 json={
494 "tracks": [{"id": "id-1", "popularity": 10, "external_ids": {}}]
495 },
496 content_type="application/json",
497 )
498 responses.add(
499 responses.GET,
500 spotify.SpotifyPlugin.audio_features_url,
501 status=200,
502 json={"audio_features": [{"id": "id-1", "tempo": 100.1}]},
503 content_type="application/json",
504 )
505
506 item = self.add_item_fixture(title="Track 1", artist="Artist")
507 item["spotify_track_id"] = "id-1"
508
509 with self.assertLogs("beets", level="DEBUG") as captured_logs:
510 self.spotify._fetch_info(self.lib, [item], write=True, force=True)
511
512 logs = captured_logs.output
513
514 write_event_index = next(
515 idx
516 for idx, message in enumerate(logs)
517 if message.endswith("Sending event: write")
518 )
519 database_change_index = next(
520 idx
521 for idx, message in enumerate(logs)
522 if message.endswith("Sending event: database_change")
523 )
524
525 assert write_event_index < database_change_index
526
527 @responses.activate
528 def test_track_audio_features_batch_disables_on_403(self):
529 responses.add(
530 responses.GET,
531 spotify.SpotifyPlugin.audio_features_url,
532 status=403,
533 json={"error": {"status": 403}},
534 content_type="application/json",
535 )
536
537 assert self.spotify.track_audio_features_batch(["id-1"]) == {}
538 assert self.spotify.audio_features_available is False
539 assert self.spotify.track_audio_features_batch(["id-2"]) == {}
540 assert len(responses.calls) == 1
541
542 @responses.activate
543 def test_track_audio_features_batch_keeps_partial_results_on_api_error(
544 self,
545 ):
546 def callback(request):
547 ids = _params(request.url)["ids"][0].split(",")
548 if "track-100" in ids:
549 return (
550 502,
551 {"Content-Type": "application/json"},
552 json.dumps({"error": {"status": 502}}),
553 )
554 return (
555 200,
556 {"Content-Type": "application/json"},
557 json.dumps(
558 {
559 "audio_features": [
560 {"id": track_id, "tempo": 100.0} for track_id in ids
561 ]
562 }
563 ),
564 )
565
566 responses.add_callback(
567 responses.GET,
568 spotify.SpotifyPlugin.audio_features_url,
569 callback=callback,
570 content_type="application/json",
571 )
572
573 track_ids = [f"track-{idx}" for idx in range(201)]
574 features = self.spotify.track_audio_features_batch(track_ids)
575
576 assert "track-0" in features
577 assert "track-99" in features
578 assert "track-100" not in features
579 assert "track-199" not in features
580 assert "track-200" in features