Debian Codegraph @

test/plugins/test_art.py

raw
1 """Tests for the album art fetchers."""
2
3 from __future__ import annotations
4
5 import os
6 import shutil
7 from pathlib import Path
8 from typing import TYPE_CHECKING
9 from unittest.mock import patch
10
11 import confuse
12 import pytest
13
14 from beets import config, importer, logging, util
15 from beets.autotag import AlbumInfo, AlbumMatch, Distance
16 from beets.library import Album
17 from beets.test import _common
18 from beets.test.helper import (
19 RUNNING_IN_CI,
20 FetchImageHelper,
21 TestHelper,
22 has_program,
23 is_importable,
24 )
25 from beets.util import clean_module_tempdir
26 from beets.util.artresizer import ArtResizer
27 from beetsplug import fetchart
28
29 if TYPE_CHECKING:
30 from collections.abc import Iterator, Sequence
31 from unittest.mock import MagicMock
32
33 logger = logging.getLogger("beets.test_art")
34
35 REQUIRES_ARTRESIZER = pytest.mark.skipif(
36 not (has_program("magick") or is_importable("PIL")) and not RUNNING_IN_CI,
37 reason="requires ImageMagick or Pillow",
38 )
39
40
41 class Settings(fetchart.FetchArtPlugin):
42 """Used to pass settings to the ArtSources when the plugin isn't fully
43 instantiated.
44 """
45
46 def __init__(self, **kwargs):
47 for k, v in kwargs.items():
48 setattr(self, k, v)
49
50
51 class DummyRemoteArtSource(fetchart.RemoteArtSource):
52 NAME = "Dummy Art Source"
53 ID = "dummy"
54
55 def get(
56 self,
57 album,
58 plugin: fetchart.FetchArtPlugin,
59 paths: Sequence[bytes] | None,
60 ) -> Iterator[fetchart.Candidate]:
61 return iter(())
62
63
64 class UseThePlugin(TestHelper):
65 modules = (fetchart.__name__, ArtResizer.__module__)
66
67 @pytest.fixture(autouse=True)
68 def setup_plugin(self, setup):
69 self.plugin = fetchart.FetchArtPlugin()
70
71 @pytest.fixture(autouse=True)
72 def requests_mock_all(self, requests_mock):
73 """Will disable all outgoing requests and raise an error!
74
75 Tests need to mock all requests!
76 """
77 # Register some “safe” mocks you actually want to allow, if any:
78 # requests_mock.get("https://example.com/health", json={"status": "ok"})
79
80 # Disable any URL not explicitly mocked
81 return
82
83 @pytest.fixture(autouse=True, scope="class")
84 def cleanup(self):
85 try:
86 yield
87 finally:
88 for module in self.modules:
89 clean_module_tempdir(module)
90
91 @pytest.fixture
92 def dpath(self) -> bytes:
93 dpath = self.temp_path / "arttest"
94 dpath.mkdir()
95 return os.fsencode(dpath)
96
97
98 class CAAData:
99 """Helper mixin for mocking requests to the Cover Art Archive."""
100
101 MBID_RELASE = "rid"
102 MBID_GROUP = "rgid"
103
104 RELEASE_URL = f"coverartarchive.org/release/{MBID_RELASE}"
105 GROUP_URL = f"coverartarchive.org/release-group/{MBID_GROUP}"
106
107 RELEASE_URL = f"https://{RELEASE_URL}"
108 GROUP_URL = f"https://{GROUP_URL}"
109
110 RESPONSE_RELEASE = """{
111 "images": [
112 {
113 "approved": false,
114 "back": false,
115 "comment": "GIF",
116 "edit": 12345,
117 "front": true,
118 "id": 12345,
119 "image": "http://coverartarchive.org/release/rid/12345.gif",
120 "thumbnails": {
121 "1200": "http://coverartarchive.org/release/rid/12345-1200.jpg",
122 "250": "http://coverartarchive.org/release/rid/12345-250.jpg",
123 "500": "http://coverartarchive.org/release/rid/12345-500.jpg",
124 "large": "http://coverartarchive.org/release/rid/12345-500.jpg",
125 "small": "http://coverartarchive.org/release/rid/12345-250.jpg"
126 },
127 "types": ["Front"]
128 },
129 {
130 "approved": false,
131 "back": false,
132 "comment": "",
133 "edit": 12345,
134 "front": false,
135 "id": 12345,
136 "image": "http://coverartarchive.org/release/rid/12345.jpg",
137 "thumbnails": {
138 "1200": "http://coverartarchive.org/release/rid/12345-1200.jpg",
139 "250": "http://coverartarchive.org/release/rid/12345-250.jpg",
140 "500": "http://coverartarchive.org/release/rid/12345-500.jpg",
141 "large": "http://coverartarchive.org/release/rid/12345-500.jpg",
142 "small": "http://coverartarchive.org/release/rid/12345-250.jpg"
143 },
144 "types": ["Front"]
145 }
146 ],
147 "release": "https://musicbrainz.org/release/releaseid"
148 }"""
149 RESPONSE_RELEASE_WITHOUT_THUMBNAILS = """{
150 "images": [
151 {
152 "approved": false,
153 "back": false,
154 "comment": "GIF",
155 "edit": 12345,
156 "front": true,
157 "id": 12345,
158 "image": "http://coverartarchive.org/release/rid/12345.gif",
159 "types": ["Front"]
160 },
161 {
162 "approved": false,
163 "back": false,
164 "comment": "",
165 "edit": 12345,
166 "front": false,
167 "id": 12345,
168 "image": "http://coverartarchive.org/release/rid/12345.jpg",
169 "thumbnails": {
170 "large": "http://coverartarchive.org/release/rgid/12345-500.jpg",
171 "small": "http://coverartarchive.org/release/rgid/12345-250.jpg"
172 },
173 "types": ["Front"]
174 }
175 ],
176 "release": "https://musicbrainz.org/release/releaseid"
177 }"""
178 RESPONSE_GROUP = """{
179 "images": [
180 {
181 "approved": false,
182 "back": false,
183 "comment": "",
184 "edit": 12345,
185 "front": true,
186 "id": 12345,
187 "image": "http://coverartarchive.org/release/releaseid/12345.jpg",
188 "thumbnails": {
189 "1200": "http://coverartarchive.org/release/rgid/12345-1200.jpg",
190 "250": "http://coverartarchive.org/release/rgid/12345-250.jpg",
191 "500": "http://coverartarchive.org/release/rgid/12345-500.jpg",
192 "large": "http://coverartarchive.org/release/rgid/12345-500.jpg",
193 "small": "http://coverartarchive.org/release/rgid/12345-250.jpg"
194 },
195 "types": ["Front"]
196 }
197 ],
198 "release": "https://musicbrainz.org/release/release-id"
199 }"""
200 RESPONSE_GROUP_WITHOUT_THUMBNAILS = """{
201 "images": [
202 {
203 "approved": false,
204 "back": false,
205 "comment": "",
206 "edit": 12345,
207 "front": true,
208 "id": 12345,
209 "image": "http://coverartarchive.org/release/releaseid/12345.jpg",
210 "types": ["Front"]
211 }
212 ],
213 "release": "https://musicbrainz.org/release/release-id"
214 }"""
215
216
217 class TestFetchImage(UseThePlugin, FetchImageHelper):
218 URL = "http://example.com/test.jpg"
219
220 @pytest.fixture
221 def settings(self) -> Settings:
222 return Settings(maxwidth=0)
223
224 @pytest.fixture
225 def source(self) -> DummyRemoteArtSource:
226 return DummyRemoteArtSource(logger, self.plugin.config)
227
228 @pytest.fixture
229 def candidate(self, source: DummyRemoteArtSource) -> fetchart.Candidate:
230 return fetchart.Candidate(logger, source.ID, url=self.URL)
231
232 def test_invalid_type_returns_none(
233 self, source, candidate, settings, image_request_mock
234 ) -> None:
235 image_request_mock.get(self.URL, content_type="image/watercolour")
236 source.fetch_image(candidate, settings)
237 assert candidate.path is None
238
239 def test_jpeg_type_returns_path(
240 self, source, candidate, settings, image_request_mock
241 ) -> None:
242 image_request_mock.get(self.URL, content_type="image/jpeg")
243 source.fetch_image(candidate, settings)
244 assert candidate.path is not None
245
246 def test_extension_set_by_content_type(
247 self, source, candidate, settings, image_request_mock
248 ) -> None:
249 image_request_mock.get(self.URL, content_type="image/png")
250 source.fetch_image(candidate, settings)
251 assert candidate.path is not None
252 assert os.path.splitext(candidate.path)[1] == b".png"
253 assert Path(os.fsdecode(candidate.path)).exists()
254
255 def test_does_not_rely_on_server_content_type(
256 self, source, candidate, settings, image_request_mock
257 ) -> None:
258 image_request_mock.get(
259 self.URL, content_type="image/jpeg", file_type="image/png"
260 )
261 source.fetch_image(candidate, settings)
262 assert candidate.path is not None
263 assert os.path.splitext(candidate.path)[1] == b".png"
264 assert Path(os.fsdecode(candidate.path)).exists()
265
266
267 class TestFSArt(UseThePlugin):
268 @pytest.fixture
269 def settings(self) -> Settings:
270 return Settings(cautious=False, cover_names=("art",), fallback=None)
271
272 @pytest.fixture
273 def source(self) -> fetchart.FileSystem:
274 return fetchart.FileSystem(logger, self.plugin.config)
275
276 def test_finds_jpg_in_directory(self, source, dpath, settings) -> None:
277 _common.touch(os.path.join(dpath, b"a.jpg"))
278 candidate = next(source.get(Album(), settings, [dpath]))
279 assert candidate.path == os.path.join(dpath, b"a.jpg")
280
281 def test_appropriately_named_file_takes_precedence(
282 self, source, dpath, settings
283 ) -> None:
284 _common.touch(os.path.join(dpath, b"a.jpg"))
285 _common.touch(os.path.join(dpath, b"art.jpg"))
286 candidate = next(source.get(Album(), settings, [dpath]))
287 assert candidate.path == os.path.join(dpath, b"art.jpg")
288
289 def test_non_image_file_not_identified(
290 self, source, dpath, settings
291 ) -> None:
292 _common.touch(os.path.join(dpath, b"a.txt"))
293 with pytest.raises(StopIteration):
294 next(source.get(Album(), settings, [dpath]))
295
296 def test_cautious_skips_fallback(self, source, dpath, settings) -> None:
297 _common.touch(os.path.join(dpath, b"a.jpg"))
298 settings.cautious = True
299 with pytest.raises(StopIteration):
300 next(source.get(Album(), settings, [dpath]))
301
302 def test_configured_fallback_is_used(self, source, dpath, settings) -> None:
303 fallback = self.temp_path / "a.jpg"
304 fallback.touch()
305 settings.fallback = fallback # type: ignore
306 candidate = next(source.get(Album(), settings, [dpath]))
307 assert candidate.path == fallback
308
309 def test_empty_dir(self, source, dpath, settings) -> None:
310 with pytest.raises(StopIteration):
311 next(source.get(Album(), settings, [dpath]))
312
313 def test_precedence_amongst_correct_files(
314 self, source, dpath, settings
315 ) -> None:
316 images = [b"front-cover.jpg", b"front.jpg", b"back.jpg"]
317 paths = [os.path.join(dpath, i) for i in images]
318 for p in paths:
319 _common.touch(p)
320 settings.cover_names = [b"cover", b"front", b"back"]
321 candidates = [
322 candidate.path
323 for candidate in source.get(Album(), settings, [dpath])
324 ]
325 assert candidates == paths
326
327 @patch("os.path.samefile")
328 def test_is_candidate_fallback_os_error(
329 self, mock_samefile, source
330 ) -> None:
331 mock_samefile.side_effect = OSError("os error")
332 fallback = self.temp_path / "a.jpg"
333 self.plugin.fallback = str(fallback)
334 candidate = fetchart.Candidate(logger, source.ID, os.fsencode(fallback))
335 result = self.plugin._is_candidate_fallback(candidate)
336 mock_samefile.assert_called_once()
337 assert not result
338
339
340 class TestCombined(UseThePlugin, FetchImageHelper, CAAData):
341 ASIN = "xxxx"
342 MBID = "releaseid"
343 AMAZON_URL = f"https://images.amazon.com/images/P/{ASIN}.01.LZZZZZZZ.jpg"
344 AMAZON_URL_2 = f"https://images.amazon.com/images/P/{ASIN}.02.LZZZZZZZ.jpg"
345 AAO_URL = f"https://www.albumart.org/index_detail.php?asin={ASIN}"
346
347 def test_main_interface_returns_amazon_art(self, image_request_mock):
348 image_request_mock.get(self.AMAZON_URL)
349 album = Album(asin=self.ASIN)
350 candidate = self.plugin.art_for_album(album, None)
351 assert candidate is not None
352
353 def test_main_interface_returns_none_for_missing_asin_and_path(self):
354 album = Album()
355 candidate = self.plugin.art_for_album(album, None)
356 assert candidate is None
357
358 def test_main_interface_gives_precedence_to_fs_art(
359 self, dpath, image_request_mock
360 ):
361 _common.touch(os.path.join(dpath, b"art.jpg"))
362 image_request_mock.get(self.AMAZON_URL)
363 album = Album(asin=self.ASIN)
364 candidate = self.plugin.art_for_album(album, [dpath])
365 assert candidate is not None
366 assert candidate.path == os.path.join(dpath, b"art.jpg")
367
368 def test_main_interface_falls_back_to_amazon(
369 self, dpath, image_request_mock
370 ):
371 image_request_mock.get(self.AMAZON_URL)
372 album = Album(asin=self.ASIN)
373 candidate = self.plugin.art_for_album(album, [dpath])
374 assert candidate is not None
375 assert not candidate.path.startswith(dpath)
376
377 def test_main_interface_tries_amazon_before_aao(
378 self, dpath, image_request_mock
379 ):
380 image_request_mock.get(self.AMAZON_URL)
381 album = Album(asin=self.ASIN)
382 self.plugin.art_for_album(album, [dpath])
383 assert image_request_mock.mocker.called_once
384 assert (
385 image_request_mock.mocker.request_history[0].url == self.AMAZON_URL
386 )
387
388 def test_main_interface_falls_back_to_aao(self, dpath, image_request_mock):
389 image_request_mock.get(self.AMAZON_URL, content_type="text/html")
390 image_request_mock.get(self.AMAZON_URL_2, content_type="text/html")
391 image_request_mock.get(self.AAO_URL, content_type="image/jpeg")
392 album = Album(asin=self.ASIN)
393 self.plugin.art_for_album(album, [dpath])
394 assert image_request_mock.mocker.request_history[-1].url == self.AAO_URL
395
396 def test_main_interface_uses_caa_when_mbid_available(
397 self, image_request_mock
398 ):
399 image_request_mock.get(self.RELEASE_URL, content=self.RESPONSE_RELEASE)
400 image_request_mock.get(self.GROUP_URL, content=self.RESPONSE_GROUP)
401 image_request_mock.get(
402 "http://coverartarchive.org/release/rid/12345.gif",
403 content_type="image/gif",
404 )
405 image_request_mock.get(
406 "http://coverartarchive.org/release/rid/12345.jpg",
407 content_type="image/jpeg",
408 )
409 album = Album(
410 mb_albumid=self.MBID_RELASE,
411 mb_releasegroupid=self.MBID_GROUP,
412 asin=self.ASIN,
413 )
414 candidate = self.plugin.art_for_album(album, None)
415 assert candidate is not None
416 assert image_request_mock.mocker.call_count == 3
417 assert (
418 image_request_mock.mocker.request_history[0].url == self.RELEASE_URL
419 )
420
421 def test_local_only_does_not_access_network(self, image_request_mock):
422 album = Album(mb_albumid=self.MBID, asin=self.ASIN)
423 self.plugin.art_for_album(album, None, local_only=True)
424 assert not image_request_mock.mocker.called
425
426 def test_local_only_gets_fs_image(self, dpath, image_request_mock):
427 _common.touch(os.path.join(dpath, b"art.jpg"))
428 album = Album(mb_albumid=self.MBID, asin=self.ASIN)
429 candidate = self.plugin.art_for_album(album, [dpath], local_only=True)
430 assert candidate is not None
431 assert candidate.path == os.path.join(dpath, b"art.jpg")
432 assert not image_request_mock.mocker.called
433
434
435 class TestAAO(UseThePlugin, FetchImageHelper):
436 ASIN = "xxxx"
437 AAO_URL = f"https://www.albumart.org/index_detail.php?asin={ASIN}"
438
439 @pytest.fixture
440 def settings(self) -> Settings:
441 return Settings()
442
443 @pytest.fixture
444 def source(self) -> fetchart.AlbumArtOrg:
445 return fetchart.AlbumArtOrg(logger, self.plugin.config)
446
447 def test_aao_scraper_finds_image(
448 self, source, settings, image_request_mock
449 ) -> None:
450 body = """
451 <br />
452 <a href="TARGET_URL" title="View larger image"
453 class="thickbox" style="color: #7E9DA2; text-decoration:none;">
454 <img src="http://www.albumart.org/images/zoom-icon.jpg"
455 alt="View larger image" width="17" height="15" border="0"/></a>
456 """
457 image_request_mock.get(
458 self.AAO_URL, content=body, content_type="text/html"
459 )
460 album = Album(asin=self.ASIN)
461 candidate = next(source.get(album, settings, []))
462 assert candidate.url == "TARGET_URL"
463
464 def test_aao_scraper_returns_no_result_when_no_image_present(
465 self, source, settings, image_request_mock
466 ) -> None:
467 image_request_mock.get(
468 self.AAO_URL, content="blah blah", content_type="text/html"
469 )
470 album = Album(asin=self.ASIN)
471 with pytest.raises(StopIteration):
472 next(source.get(album, settings, []))
473
474
475 class TestITunesStore(UseThePlugin, FetchImageHelper):
476 @pytest.fixture
477 def settings(self) -> Settings:
478 return Settings()
479
480 @pytest.fixture
481 def source(self) -> fetchart.ITunesStore:
482 return fetchart.ITunesStore(logger, self.plugin.config)
483
484 @pytest.fixture
485 def album(self) -> Album:
486 return Album(albumartist="some artist", album="some album")
487
488 def test_itunesstore_finds_image(
489 self, source, settings, album, image_request_mock
490 ):
491 json = """{
492 "results":
493 [
494 {
495 "artistName": "some artist",
496 "collectionName": "some album",
497 "artworkUrl100": "url_to_the_image"
498 }
499 ]
500 }"""
501 image_request_mock.get(
502 fetchart.ITunesStore.API_URL,
503 content=json,
504 content_type="application/json",
505 )
506 candidate = next(source.get(album, settings, []))
507 assert candidate.url == "url_to_the_image"
508 assert candidate.match == fetchart.MetadataMatch.EXACT
509
510 def test_itunesstore_no_result(
511 self, source, settings, album, image_request_mock, caplog
512 ):
513 json = '{"results": []}'
514 image_request_mock.get(
515 fetchart.ITunesStore.API_URL,
516 content=json,
517 content_type="application/json",
518 )
519 expected = "got no results"
520
521 with caplog.at_level("DEBUG", logger="beets.test_art"):
522 with pytest.raises(StopIteration):
523 next(source.get(album, settings, []))
524 assert expected in caplog.messages[1]
525
526 def test_itunesstore_requestexception(
527 self, source, settings, album, requests_mock, caplog
528 ):
529 requests_mock.get(
530 fetchart.ITunesStore.API_URL,
531 json={"error": "not found"},
532 status_code=404,
533 )
534 expected = "iTunes search failed: 404 Client Error"
535
536 with caplog.at_level("DEBUG", logger="beets.test_art"):
537 with pytest.raises(StopIteration):
538 next(source.get(album, settings, []))
539 assert expected in caplog.messages[1]
540
541 def test_itunesstore_fallback_match(
542 self, source: fetchart.ITunesStore, settings, album, image_request_mock
543 ):
544 json = """{
545 "results":
546 [
547 {
548 "collectionName": "some album",
549 "artworkUrl100": "url_to_the_image"
550 }
551 ]
552 }"""
553 image_request_mock.get(
554 fetchart.ITunesStore.API_URL,
555 content=json,
556 content_type="application/json",
557 )
558 candidate = next(source.get(album, settings, []))
559 assert candidate.url == "url_to_the_image"
560 assert candidate.match == fetchart.MetadataMatch.FALLBACK
561
562 def test_itunesstore_returns_result_without_artwork(
563 self, source, settings, album, image_request_mock, caplog
564 ):
565 json = """{
566 "results":
567 [
568 {
569 "artistName": "some artist",
570 "collectionName": "some album"
571 }
572 ]
573 }"""
574 image_request_mock.get(
575 fetchart.ITunesStore.API_URL,
576 content=json,
577 content_type="application/json",
578 )
579 expected = "Malformed itunes candidate"
580
581 with caplog.at_level("DEBUG", logger="beets.test_art"):
582 with pytest.raises(StopIteration):
583 next(source.get(album, settings, []))
584 assert expected in caplog.messages[1]
585
586 def test_itunesstore_returns_no_result_when_error_received(
587 self, source, settings, album, image_request_mock, caplog
588 ):
589 json = '{"error": {"errors": [{"reason": "some reason"}]}}'
590 image_request_mock.get(
591 fetchart.ITunesStore.API_URL,
592 content=json,
593 content_type="application/json",
594 )
595 expected = "not found in json. Fields are"
596
597 with caplog.at_level("DEBUG", logger="beets.test_art"):
598 with pytest.raises(StopIteration):
599 next(source.get(album, settings, []))
600 assert expected in caplog.messages[1]
601
602 def test_itunesstore_returns_no_result_with_malformed_response(
603 self, source, settings, album, image_request_mock, caplog
604 ):
605 json = """bla blup"""
606 image_request_mock.get(
607 fetchart.ITunesStore.API_URL,
608 content=json,
609 content_type="application/json",
610 )
611 expected = "Could not decode json response:"
612
613 with caplog.at_level("DEBUG", logger="beets.test_art"):
614 with pytest.raises(StopIteration):
615 next(source.get(album, settings, []))
616 assert expected in caplog.messages[1]
617
618
619 class TestGoogleImage(UseThePlugin, FetchImageHelper):
620 @pytest.fixture
621 def settings(self) -> Settings:
622 return Settings()
623
624 @pytest.fixture
625 def source(self) -> fetchart.GoogleImages:
626 return fetchart.GoogleImages(logger, self.plugin.config)
627
628 def test_google_art_finds_image(self, source, settings, image_request_mock):
629 album = Album(albumartist="some artist", album="some album")
630 json = '{"items": [{"link": "url_to_the_image"}]}'
631 image_request_mock.get(
632 fetchart.GoogleImages.URL,
633 content=json,
634 content_type="application/json",
635 )
636 candidate = next(source.get(album, settings, []))
637 assert candidate.url == "url_to_the_image"
638
639 def test_google_art_returns_no_result_when_error_received(
640 self, source, settings, image_request_mock
641 ):
642 album = Album(albumartist="some artist", album="some album")
643 json = '{"error": {"errors": [{"reason": "some reason"}]}}'
644 image_request_mock.get(
645 fetchart.GoogleImages.URL,
646 content=json,
647 content_type="application/json",
648 )
649 with pytest.raises(StopIteration):
650 next(source.get(album, settings, []))
651
652 def test_google_art_returns_no_result_with_malformed_response(
653 self, source, settings, image_request_mock
654 ):
655 album = Album(albumartist="some artist", album="some album")
656 json = """bla blup"""
657 image_request_mock.get(
658 fetchart.GoogleImages.URL,
659 content=json,
660 content_type="application/json",
661 )
662 with pytest.raises(StopIteration):
663 next(source.get(album, settings, []))
664
665
666 class TestCoverArtArchive(UseThePlugin, FetchImageHelper, CAAData):
667 @pytest.fixture
668 def settings(self) -> Settings:
669 return Settings(maxwidth=0)
670
671 @pytest.fixture
672 def source(self) -> fetchart.CoverArtArchive:
673 return fetchart.CoverArtArchive(logger, self.plugin.config)
674
675 def test_caa_finds_image(self, source, settings, image_request_mock):
676 album = Album(
677 mb_albumid=self.MBID_RELASE, mb_releasegroupid=self.MBID_GROUP
678 )
679 image_request_mock.get(self.RELEASE_URL, content=self.RESPONSE_RELEASE)
680 image_request_mock.get(self.GROUP_URL, content=self.RESPONSE_GROUP)
681 candidates = list(source.get(album, settings, []))
682 assert len(candidates) == 3
683 assert image_request_mock.mocker.call_count == 2
684 assert (
685 image_request_mock.mocker.request_history[0].url == self.RELEASE_URL
686 )
687
688 def test_fetchart_uses_caa_pre_sized_maxwidth_thumbs(
689 self, source, image_request_mock
690 ):
691 # CAA provides pre-sized thumbnails of width 250px, 500px, and 1200px
692 # We only test with one of them here
693 maxwidth = 1200
694 settings = Settings(maxwidth=maxwidth)
695
696 album = Album(
697 mb_albumid=self.MBID_RELASE, mb_releasegroupid=self.MBID_GROUP
698 )
699 image_request_mock.get(self.RELEASE_URL, content=self.RESPONSE_RELEASE)
700 image_request_mock.get(self.GROUP_URL, content=self.RESPONSE_GROUP)
701 candidates = list(source.get(album, settings, []))
702 assert len(candidates) == 3
703 for candidate in candidates:
704 assert candidate.url is not None
705 assert f"-{maxwidth}.jpg" in candidate.url
706
707 def test_caa_finds_image_if_maxwidth_is_set_and_thumbnails_is_empty(
708 self, source, image_request_mock
709 ):
710 # CAA provides pre-sized thumbnails of width 250px, 500px, and 1200px
711 # We only test with one of them here
712 maxwidth = 1200
713 settings = Settings(maxwidth=maxwidth)
714
715 album = Album(
716 mb_albumid=self.MBID_RELASE, mb_releasegroupid=self.MBID_GROUP
717 )
718 image_request_mock.get(
719 self.RELEASE_URL, content=self.RESPONSE_RELEASE_WITHOUT_THUMBNAILS
720 )
721 image_request_mock.get(
722 self.GROUP_URL, content=self.RESPONSE_GROUP_WITHOUT_THUMBNAILS
723 )
724 candidates = list(source.get(album, settings, []))
725 assert len(candidates) == 3
726 for candidate in candidates:
727 assert candidate.url is not None
728 assert f"-{maxwidth}.jpg" not in candidate.url
729
730
731 class TestFanartTV(UseThePlugin, FetchImageHelper):
732 RESPONSE_MULTIPLE = """{
733 "name": "artistname",
734 "mbid_id": "artistid",
735 "albums": {
736 "thereleasegroupid": {
737 "albumcover": [
738 {
739 "id": "24",
740 "url": "http://example.com/1.jpg",
741 "likes": "0"
742 },
743 {
744 "id": "42",
745 "url": "http://example.com/2.jpg",
746 "likes": "0"
747 },
748 {
749 "id": "23",
750 "url": "http://example.com/3.jpg",
751 "likes": "0"
752 }
753 ],
754 "cdart": [
755 {
756 "id": "123",
757 "url": "http://example.com/4.jpg",
758 "likes": "0",
759 "disc": "1",
760 "size": "1000"
761 }
762 ]
763 }
764 }
765 }"""
766 RESPONSE_NO_ART = """{
767 "name": "artistname",
768 "mbid_id": "artistid",
769 "albums": {
770 "thereleasegroupid": {
771 "cdart": [
772 {
773 "id": "123",
774 "url": "http://example.com/4.jpg",
775 "likes": "0",
776 "disc": "1",
777 "size": "1000"
778 }
779 ]
780 }
781 }
782 }"""
783 RESPONSE_ERROR = """{
784 "status": "error",
785 "error message": "the error message"
786 }"""
787 RESPONSE_MALFORMED = "bla blup"
788
789 @pytest.fixture
790 def settings(self):
791 return Settings(maxwidth=0)
792
793 @pytest.fixture
794 def source(self):
795 return fetchart.FanartTV(logger, self.plugin.config)
796
797 def test_fanarttv_finds_image(self, source, settings, image_request_mock):
798 album = Album(mb_releasegroupid="thereleasegroupid")
799 image_request_mock.get(
800 f"{fetchart.FanartTV.API_ALBUMS}thereleasegroupid",
801 content=self.RESPONSE_MULTIPLE,
802 content_type="application/json",
803 )
804 candidate = next(source.get(album, settings, []))
805 assert candidate.url == "http://example.com/1.jpg"
806
807 def test_fanarttv_returns_no_result_when_error_received(
808 self, source, settings, image_request_mock
809 ):
810 album = Album(mb_releasegroupid="thereleasegroupid")
811 image_request_mock.get(
812 f"{fetchart.FanartTV.API_ALBUMS}thereleasegroupid",
813 content=self.RESPONSE_ERROR,
814 content_type="application/json",
815 )
816 with pytest.raises(StopIteration):
817 next(source.get(album, settings, []))
818
819 def test_fanarttv_returns_no_result_with_malformed_response(
820 self, source, settings, image_request_mock
821 ):
822 album = Album(mb_releasegroupid="thereleasegroupid")
823 image_request_mock.get(
824 f"{fetchart.FanartTV.API_ALBUMS}thereleasegroupid",
825 content=self.RESPONSE_MALFORMED,
826 content_type="application/json",
827 )
828 with pytest.raises(StopIteration):
829 next(source.get(album, settings, []))
830
831 def test_fanarttv_only_other_images(
832 self, source, settings, image_request_mock
833 ):
834 # The source used to fail when there were images present, but no cover
835 album = Album(mb_releasegroupid="thereleasegroupid")
836 image_request_mock.get(
837 f"{fetchart.FanartTV.API_ALBUMS}thereleasegroupid",
838 content=self.RESPONSE_NO_ART,
839 content_type="application/json",
840 )
841 with pytest.raises(StopIteration):
842 next(source.get(album, settings, []))
843
844
845 class TestArtImporter(UseThePlugin):
846 @pytest.fixture(autouse=True)
847 def _setup(self, setup_plugin):
848 # Mock the album art fetcher to always return our test file.
849 self.art_file = self.temp_path / "tmpcover.jpg"
850 self.art_file.touch()
851 self.old_afa = self.plugin.art_for_album
852 self.afa_response = fetchart.Candidate(
853 logger, source_name="test", path=self.art_file
854 )
855
856 def art_for_album(i, p, local_only=False):
857 return self.afa_response
858
859 self.plugin.art_for_album = art_for_album
860
861 # Test library.
862 (self.lib_path / "album").mkdir()
863 itempath = self.lib_path / "album" / "test.mp3"
864 shutil.copyfile(_common.RSRC / "full.mp3", itempath)
865 self.i = _common.item()
866 self.i.path = itempath
867 self.album = self.lib.add_album([self.i])
868 self.lib._connection().commit()
869
870 # The import configuration.
871 self.session = _common.import_session(self.lib)
872
873 # Import task for the coroutine.
874 self.task = importer.ImportTask(None, None, [self.i])
875 self.task.is_album = True
876 self.task.album = self.album
877 info = AlbumInfo(
878 album="some album",
879 album_id="albumid",
880 artist="some artist",
881 artist_id="artistid",
882 tracks=[],
883 )
884 self.task.set_choice(AlbumMatch(Distance(), info, {}))
885 yield
886 self.plugin.art_for_album = self.old_afa
887
888 def _fetch_art(self, should_exist):
889 """Execute the fetch_art coroutine for the task and return the
890 album's resulting artpath. ``should_exist`` specifies whether to
891 assert that art path was set (to the correct value) or or that
892 the path was not set.
893 """
894 # Execute the two relevant parts of the importer.
895 self.plugin.fetch_art(self.session, self.task)
896 self.plugin.assign_art(self.session, self.task)
897
898 artpath = self.lib.albums()[0].art_filepath
899 if should_exist:
900 assert artpath == self.i.filepath.parent / "cover.jpg"
901 assert artpath.exists()
902 else:
903 assert artpath is None
904 return artpath
905
906 def test_fetch_art(self):
907 assert not self.lib.albums()[0].artpath
908 self._fetch_art(True)
909
910 def test_art_not_found(self):
911 self.afa_response = None
912 self._fetch_art(False)
913
914 def test_no_art_for_singleton(self):
915 self.task.is_album = False
916 self._fetch_art(False)
917
918 def test_leave_original_file_in_place(self):
919 self._fetch_art(True)
920 assert self.art_file.exists()
921
922 def test_delete_original_file(self):
923 prev_move = config["import"]["move"].get()
924 try:
925 config["import"]["move"] = True
926 self._fetch_art(True)
927 assert not self.art_file.exists()
928 finally:
929 config["import"]["move"] = prev_move
930
931 def test_do_not_delete_original_if_already_in_place(self):
932 artdest = self.i.filepath.parent / "cover.jpg"
933 shutil.copyfile(self.art_file, artdest)
934 self.afa_response = fetchart.Candidate(
935 logger, source_name="test", path=artdest
936 )
937 self._fetch_art(True)
938
939 def test_fetch_art_if_imported_file_deleted(self):
940 # See #1126. Test the following scenario:
941 # - Album art imported, `album.artpath` set.
942 # - Imported album art file subsequently deleted (by user or other
943 # program).
944 # `fetchart` should import album art again instead of printing the
945 # message "<album> has album art".
946 self._fetch_art(True)
947 util.remove(self.album.artpath)
948 self.plugin.batch_fetch_art(
949 self.lib, self.lib.albums(), force=False, quiet=False
950 )
951 assert self.album.art_filepath.exists()
952
953
954 class AlbumArtOperationMixin(UseThePlugin):
955 """Base test case for album art operations.
956
957 Provides common setup for testing album art processing operations by setting
958 up a mock filesystem source that returns a predefined test image.
959 """
960
961 IMAGE_PATH = _common.RSRC / "abbey-similar.jpg"
962 IMAGE_FILESIZE = IMAGE_PATH.stat().st_size
963 IMAGE_WIDTH = 500
964 IMAGE_HEIGHT = 490
965 IMAGE_WIDTH_HEIGHT_DIFF = IMAGE_WIDTH - IMAGE_HEIGHT
966
967 @pytest.fixture(autouse=True, scope="class")
968 def fs_mock(self, cleanup):
969 def fs_source_get(_self, album, settings, paths):
970 if paths:
971 yield fetchart.Candidate(
972 logger, source_name=_self.ID, path=self.IMAGE_PATH
973 )
974
975 with patch("beetsplug.fetchart.FileSystem.get", fs_source_get):
976 yield
977
978 def get_album_art(self):
979 return self.plugin.art_for_album(Album(), [""], True)
980
981
982 @REQUIRES_ARTRESIZER
983 class TestAlbumArtOperationConfiguration(AlbumArtOperationMixin):
984 """Check that scale & filesize configuration is respected.
985
986 Depending on `minwidth`, `enforce_ratio`, `margin_px`, and `margin_percent`
987 configuration the plugin should or should not return an art candidate.
988 """
989
990 def test_minwidth(self):
991 self.plugin.minwidth = self.IMAGE_WIDTH / 2
992 assert self.get_album_art()
993
994 self.plugin.minwidth = self.IMAGE_WIDTH * 2
995 assert not self.get_album_art()
996
997 def test_enforce_ratio(self):
998 self.plugin.enforce_ratio = True
999 assert not self.get_album_art()
1000
1001 self.plugin.enforce_ratio = False
1002 assert self.get_album_art()
1003
1004 def test_enforce_ratio_with_px_margin(self):
1005 self.plugin.enforce_ratio = True
1006
1007 self.plugin.margin_px = self.IMAGE_WIDTH_HEIGHT_DIFF * 0.5
1008 assert not self.get_album_art()
1009
1010 self.plugin.margin_px = self.IMAGE_WIDTH_HEIGHT_DIFF * 1.5
1011 assert self.get_album_art()
1012
1013 def test_enforce_ratio_with_percent_margin(self):
1014 self.plugin.enforce_ratio = True
1015 diff_by_width = self.IMAGE_WIDTH_HEIGHT_DIFF / self.IMAGE_WIDTH
1016
1017 self.plugin.margin_percent = diff_by_width * 0.5
1018 assert not self.get_album_art()
1019
1020 self.plugin.margin_percent = diff_by_width * 1.5
1021 assert self.get_album_art()
1022
1023
1024 @REQUIRES_ARTRESIZER
1025 class TestAlbumArtPerformOperation(AlbumArtOperationMixin):
1026 """Test that the art is resized and deinterlaced if necessary."""
1027
1028 @pytest.fixture
1029 def resizer_mock(self) -> Iterator[MagicMock]:
1030 with patch.object(
1031 ArtResizer.shared, "resize", return_value=self.IMAGE_PATH
1032 ) as mocked:
1033 yield mocked
1034
1035 @pytest.fixture
1036 def deinterlacer_mock(self) -> Iterator[MagicMock]:
1037 with patch.object(
1038 ArtResizer.shared, "deinterlace", return_value=self.IMAGE_PATH
1039 ) as mocked:
1040 yield mocked
1041
1042 def test_resize(self, resizer_mock):
1043 self.plugin.maxwidth = self.IMAGE_WIDTH / 2
1044 assert self.get_album_art()
1045 resizer_mock.assert_called_once()
1046
1047 def test_file_resized(self, resizer_mock):
1048 self.plugin.max_filesize = self.IMAGE_FILESIZE // 2
1049 assert self.get_album_art()
1050 resizer_mock.assert_called_once()
1051
1052 def test_file_not_resized(self, resizer_mock):
1053 self.plugin.max_filesize = self.IMAGE_FILESIZE
1054 assert self.get_album_art()
1055 resizer_mock.assert_not_called()
1056
1057 def test_file_resized_but_not_scaled(self, resizer_mock):
1058 self.plugin.maxwidth = self.IMAGE_WIDTH * 2
1059 self.plugin.max_filesize = self.IMAGE_FILESIZE // 2
1060 assert self.get_album_art()
1061 resizer_mock.assert_called_once()
1062
1063 def test_file_resized_and_scaled(self, resizer_mock):
1064 self.plugin.maxwidth = self.IMAGE_WIDTH / 2
1065 self.plugin.max_filesize = self.IMAGE_FILESIZE // 2
1066 assert self.get_album_art()
1067 assert resizer_mock.call_count == 2
1068
1069 def test_deinterlaced(self, deinterlacer_mock):
1070 self.plugin.deinterlace = True
1071 assert self.get_album_art()
1072 deinterlacer_mock.assert_called_once()
1073
1074 def test_not_deinterlaced(self, deinterlacer_mock):
1075 self.plugin.deinterlace = False
1076 assert self.get_album_art()
1077 deinterlacer_mock.assert_not_called()
1078
1079 def test_deinterlaced_and_resized(self, resizer_mock, deinterlacer_mock):
1080 self.plugin.maxwidth = self.IMAGE_WIDTH / 2
1081 self.plugin.deinterlace = True
1082 assert self.get_album_art()
1083 deinterlacer_mock.assert_called_once()
1084 resizer_mock.assert_called_once()
1085
1086
1087 class TestDeprecatedConfig:
1088 """While refactoring the plugin, the remote_priority option was deprecated,
1089 and a new codepath should translate its effect. Check that it actually does
1090 so.
1091 """
1092
1093 # If we subclassed UseThePlugin, the configuration change would either be
1094 # overwritten by BeetsTestCase or be set after constructing the
1095 # plugin object
1096 @pytest.fixture(autouse=True)
1097 def setup(self):
1098 config["fetchart"]["remote_priority"] = True
1099 self.plugin = fetchart.FetchArtPlugin()
1100
1101 def test_moves_filesystem_to_end(self):
1102 assert isinstance(self.plugin.sources[-1], fetchart.FileSystem)
1103
1104
1105 class TestEnforceRatioConfig:
1106 """Throw some data at the regexes."""
1107
1108 def _load_with_config(self, values, should_raise):
1109 if should_raise:
1110 for v in values:
1111 config["fetchart"]["enforce_ratio"] = v
1112 with pytest.raises(confuse.ConfigValueError):
1113 fetchart.FetchArtPlugin()
1114 else:
1115 for v in values:
1116 config["fetchart"]["enforce_ratio"] = v
1117 fetchart.FetchArtPlugin()
1118
1119 def test_px(self):
1120 self._load_with_config("0px 4px 12px 123px".split(), False)
1121 self._load_with_config("00px stuff5px".split(), True)
1122
1123 def test_percent(self):
1124 self._load_with_config("0% 0.00% 5.1% 5% 100%".split(), False)
1125 self._load_with_config("00% 1.234% foo5% 100.1%".split(), True)