Debian Codegraph @

test/plugins/test_lyrics.py

raw
1 """Tests for the 'lyrics' plugin."""
2
3 from __future__ import annotations
4
5 import re
6 import textwrap
7 from functools import partial
8 from http import HTTPStatus
9 from pathlib import Path
10 from types import SimpleNamespace
11 from typing import TYPE_CHECKING
12
13 import pytest
14 import requests
15
16 from beets.library import Item
17 from beets.test.helper import PluginMixin, PluginTestHelper
18 from beets.util.lyrics import Lyrics
19 from beetsplug import lyrics
20
21 from .lyrics_pages import lyrics_pages
22
23 if TYPE_CHECKING:
24 from .lyrics_pages import LyricsPage
25
26 PHRASE_BY_TITLE = {
27 "Lady Madonna": "friday night arrives without a suitcase",
28 "Jazz'n'blues": "as i check my balance i kiss the screen",
29 "Beets song": "via plugins, beets becomes a panacea",
30 }
31
32
33 @pytest.fixture(scope="module")
34 def helper(module_helper):
35 """Reuse one module helper for explicit item and media-write checks.
36
37 Helper-backed tests mutate known items and write an MP3 fixture, but they do
38 not assert against the full library shared with other tests in this module.
39 """
40 return module_helper
41
42
43 class TestLyricsUtils:
44 @pytest.mark.parametrize(
45 "artist, title",
46 [
47 ("Various Artists", "Title"),
48 ("Artist", ""),
49 ("", "Title"),
50 (" ", ""),
51 ("", " "),
52 ("", ""),
53 ],
54 )
55 def test_search_empty(self, artist, title):
56 actual_pairs = lyrics.search_pairs(Item(artist=artist, title=title))
57
58 assert not list(actual_pairs)
59
60 @pytest.mark.parametrize(
61 "artist, artist_sort, expected_extra_artists",
62 [
63 ("Alice ft. Bob", "", ["Alice"]),
64 ("Alice feat Bob", "", ["Alice"]),
65 ("Alice feat. Bob", "", ["Alice"]),
66 ("Alice feats Bob", "", []),
67 ("Alice featuring Bob", "", ["Alice"]),
68 ("Alice & Bob", "", ["Alice"]),
69 ("Alice and Bob", "", ["Alice"]),
70 ("Alice", "", []),
71 ("Alice", "Alice", []),
72 ("Alice", "alice", []),
73 ("Alice", "alice ", []),
74 ("Alice", "Alice A", ["Alice A"]),
75 ("CHVRCHΞS", "CHVRCHES", ["CHVRCHES"]),
76 ("横山克", "Masaru Yokoyama", ["Masaru Yokoyama"]),
77 ],
78 )
79 def test_search_pairs_artists(
80 self, artist, artist_sort, expected_extra_artists
81 ):
82 item = Item(artist=artist, artist_sort=artist_sort, title="song")
83
84 actual_artists = [a for a, _ in lyrics.search_pairs(item)]
85
86 # Make sure that the original artist name is still the first entry
87 assert actual_artists == [artist, *expected_extra_artists]
88
89 @pytest.mark.parametrize(
90 "title, expected_extra_titles",
91 [
92 ("1/2", []),
93 ("1 / 2", ["1", "2"]),
94 ("Song (live)", ["Song"]),
95 ("Song (live) (new)", ["Song"]),
96 ("Song (live (new))", ["Song"]),
97 ("Song ft. B", ["Song"]),
98 ("Song featuring B", ["Song"]),
99 ("Song and B", []),
100 ("Song: B", ["Song"]),
101 ],
102 )
103 def test_search_pairs_titles(self, title, expected_extra_titles):
104 item = Item(title=title, artist="A")
105
106 actual_titles = {
107 t: None for _, tit in lyrics.search_pairs(item) for t in tit
108 }
109
110 assert list(actual_titles) == [title, *expected_extra_titles]
111
112 @pytest.mark.parametrize(
113 "text, expected",
114 [
115 ("test", "test"),
116 ("Mørdag", "mordag"),
117 ("l'été c'est fait pour jouer", "l-ete-c-est-fait-pour-jouer"),
118 ("\xe7afe au lait (boisson)", "cafe-au-lait-boisson"),
119 ("Multiple spaces -- and symbols! -- merged", "multiple-spaces-and-symbols-merged"), # noqa: E501
120 ("\u200bno-width-space", "no-width-space"),
121 ("El\u002dp", "el-p"),
122 ("\u200bblackbear", "blackbear"),
123 ("\u200d", ""),
124 ("\u2010", ""),
125 ],
126 ) # fmt: skip
127 def test_slug(self, text, expected):
128 assert lyrics.slug(text) == expected
129
130 @pytest.mark.parametrize(
131 "text, expected",
132 [
133 ("If They’re Shooting at You", "If-They-re-Shooting-at-You"),
134 ("‘Round Midnight", "-Round-Midnight"),
135 ("Don't Stop", "Don-t-Stop"),
136 ],
137 )
138 def test_musixmatch_encode(self, text, expected):
139 assert lyrics.MusiXmatch.encode(text) == expected
140
141
142 class TestHtml:
143 def test_scrape_strip_cruft(self):
144 initial = """<!--lyrics below-->
145 &nbsp;one
146 <br class='myclass'>
147 two !
148 <br><br \\>
149 <blink>four</blink>"""
150 expected = "<!--lyrics below-->\none\ntwo !\n\n<blink>four</blink>"
151
152 assert lyrics.Html.normalize_space(initial) == expected
153
154 def test_scrape_merge_paragraphs(self):
155 text = 'one</p><p class="myclass"></p><p>two</p><p>three'
156 expected = "one\n\ntwo\n\nthree"
157
158 assert lyrics.Html.merge_paragraphs(text) == expected
159
160
161 class TestSearchBackend:
162 @pytest.fixture
163 def backend(self, dist_thresh):
164 plugin = lyrics.LyricsPlugin()
165 plugin.config.set({"dist_thresh": dist_thresh})
166 return lyrics.SearchBackend(plugin.config, plugin._log)
167
168 @pytest.mark.parametrize(
169 "dist_thresh, target_artist, artist, should_match",
170 [
171 (0.11, "Target Artist", "Target Artist", True),
172 (0.11, "Target Artist", "Target Artis", True),
173 (0.11, "Target Artist", "Target Arti", False),
174 (0.11, "Psychonaut", "Psychonaut (BEL)", True),
175 (0.11, "beets song", "beats song", True),
176 (0.10, "beets song", "beats song", False),
177 (
178 0.11,
179 "Lucid Dreams (Forget Me)",
180 "Lucid Dreams (Remix) ft. Lil Uzi Vert",
181 False,
182 ),
183 (
184 0.12,
185 "Lucid Dreams (Forget Me)",
186 "Lucid Dreams (Remix) ft. Lil Uzi Vert",
187 True,
188 ),
189 ],
190 )
191 def test_check_match(self, backend, target_artist, artist, should_match):
192 result = lyrics.SearchResult(artist, "", "")
193
194 assert backend.check_match(target_artist, "", result) == should_match
195
196
197 @pytest.fixture(scope="module")
198 def lyrics_root_dir(pytestconfig: pytest.Config):
199 return pytestconfig.rootpath / "test" / "rsrc" / "lyrics"
200
201
202 class LyricsPluginMixin(PluginMixin):
203 plugin = "lyrics"
204
205 @pytest.fixture
206 def plugin_config(self):
207 """Return lyrics configuration to test."""
208 return {}
209
210 @pytest.fixture
211 def lyrics_plugin(self, backend_name, plugin_config):
212 """Set configuration and returns the plugin's instance."""
213 plugin_config["sources"] = [backend_name]
214 self.config[self.plugin].set(plugin_config)
215
216 return lyrics.LyricsPlugin()
217
218
219 class TestLyricsPlugin(LyricsPluginMixin):
220 @pytest.fixture
221 def backend_name(self):
222 """Return lyrics configuration to test."""
223 return "lrclib"
224
225 @pytest.mark.parametrize(
226 "request_kwargs, expected_log_match",
227 [
228 (
229 {"status_code": HTTPStatus.BAD_GATEWAY},
230 r"LRCLib: Request error: 502",
231 ),
232 ({"text": "invalid"}, r"LRCLib: Could not decode.*JSON"),
233 ],
234 )
235 def test_error_handling(
236 self,
237 requests_mock,
238 lyrics_plugin,
239 caplog,
240 request_kwargs,
241 expected_log_match,
242 ):
243 """Errors are logged with the backend name."""
244 requests_mock.get(lyrics.LRCLib.SEARCH_URL, **request_kwargs)
245
246 assert lyrics_plugin.get_lyrics("", "", "", 0.0) is None
247 assert caplog.messages
248 last_log = caplog.messages[-1]
249 assert last_log
250 assert re.search(expected_log_match, last_log, re.I)
251
252 @pytest.mark.parametrize(
253 "plugin_config, old_lyrics, found, expected",
254 [
255 pytest.param({}, "old", "new", "old", id="no_force_keeps_old"),
256 pytest.param(
257 {"force": True},
258 "old",
259 "new",
260 "new",
261 id="force_overwrites_with_new",
262 ),
263 pytest.param(
264 {"force": True, "local": True},
265 "old",
266 "new",
267 "old",
268 id="force_local_keeps_old",
269 ),
270 pytest.param(
271 {"force": True, "fallback": None},
272 "old",
273 None,
274 "old",
275 id="force_fallback_none_keeps_old",
276 ),
277 pytest.param(
278 {"force": True, "fallback": ""},
279 "old",
280 None,
281 "",
282 id="force_fallback_empty_uses_empty",
283 ),
284 pytest.param(
285 {"force": True, "fallback": "default"},
286 "old",
287 None,
288 "default",
289 id="force_fallback_default_uses_default",
290 ),
291 pytest.param(
292 {"force": True, "synced": True},
293 "[00:00.00] old synced",
294 "new plain",
295 "[00:00.00] old synced",
296 id="keep-existing-synced-lyrics",
297 ),
298 pytest.param(
299 {"force": True, "synced": True},
300 "[00:00.00] old synced",
301 "[00:00.00] new synced",
302 "[00:00.00] new synced",
303 id="replace-with-new-synced-lyrics",
304 ),
305 pytest.param(
306 {"force": True, "synced": False},
307 "[00:00.00] old synced",
308 "new plain",
309 "new plain",
310 id="replace-with-unsynced-lyrics-when-disabled",
311 ),
312 pytest.param(
313 {"force": True, "keep_synced": True},
314 "[00:00.00] old synced",
315 "new",
316 "[00:00.00] old synced",
317 id="keep_synced_keeps_old_synced",
318 ),
319 ],
320 )
321 def test_overwrite_config(
322 self, monkeypatch, helper, lyrics_plugin, old_lyrics, found, expected
323 ):
324 monkeypatch.setattr(
325 lyrics_plugin,
326 "find_lyrics",
327 lambda _: Lyrics(found) if found is not None else None,
328 )
329 item = helper.create_item(id=1, lyrics=old_lyrics)
330
331 lyrics_plugin.add_item_lyrics(item, False)
332
333 assert item.lyrics == expected
334
335 def test_set_additional_lyrics_info(
336 self, monkeypatch, helper, lyrics_plugin, is_importable
337 ):
338 lyrics = Lyrics(
339 "sing in the rain every hour of the day",
340 "lrclib",
341 url="https://lrclib.net/api/1",
342 )
343 monkeypatch.setattr(lyrics_plugin, "find_lyrics", lambda _: lyrics)
344 item = helper.add_item(
345 id=1, lyrics="", lyrics_translation_language="EN"
346 )
347
348 lyrics_plugin.add_item_lyrics(item, False)
349
350 item = helper.lib.get_item(item.id)
351
352 assert item.lyrics_url == lyrics.url
353 assert item.lyrics_instrumental == "0"
354 assert item.lyrics_backend == lyrics.backend
355 if is_importable("langdetect"):
356 assert item.lyrics_language == "EN"
357 else:
358 with pytest.raises(AttributeError):
359 item.lyrics_language
360 # make sure translation language is cleared
361 with pytest.raises(AttributeError):
362 item.lyrics_translation_language
363
364 def test_imported_skips_auto_ignored_items(
365 self, lyrics_plugin, monkeypatch
366 ):
367 lyrics_plugin.config["auto_ignore"].set("album:Greatest Hits")
368 items = [
369 Item(title="Old Song", album="Greatest Hits", genre="Rock"),
370 Item(title="Come Together", album="Abbey Road", genre="Rock"),
371 ]
372
373 calls = []
374 monkeypatch.setattr(
375 lyrics_plugin,
376 "add_item_lyrics",
377 lambda current_item, write: calls.append(
378 (current_item.title, write)
379 ),
380 )
381
382 task = SimpleNamespace(imported_items=lambda: items)
383 lyrics_plugin.imported(None, task)
384
385 assert calls == [("Come Together", False)]
386
387
388 class LyricsBackendTest(LyricsPluginMixin):
389 @pytest.fixture
390 def backend(self, lyrics_plugin):
391 """Return a lyrics backend instance."""
392 return lyrics_plugin.backends[0]
393
394 @pytest.fixture
395 def lyrics_html(self, lyrics_root_dir, file_name):
396 return (lyrics_root_dir / f"{file_name}.txt").read_text(
397 encoding="utf-8"
398 )
399
400
401 @pytest.mark.on_lyrics_update
402 class TestLyricsSources(LyricsBackendTest):
403 @pytest.fixture(scope="class")
404 def plugin_config(self):
405 return {"google_API_key": "test", "synced": True}
406
407 @pytest.fixture(
408 params=[pytest.param(lp, marks=lp.marks) for lp in lyrics_pages],
409 ids=str,
410 )
411 def lyrics_page(self, request):
412 return request.param
413
414 @pytest.fixture
415 def backend_name(self, lyrics_page):
416 return lyrics_page.backend
417
418 @pytest.fixture(autouse=True)
419 def _patch_google_search(self, requests_mock, lyrics_page):
420 """Mock the Google Search API to return the lyrics page under test."""
421 requests_mock.real_http = True
422
423 data = {
424 "items": [
425 {
426 "title": lyrics_page.url_title,
427 "link": lyrics_page.url,
428 "displayLink": lyrics_page.root_url,
429 }
430 ]
431 }
432 requests_mock.get(lyrics.Google.SEARCH_URL, json=data)
433
434 @pytest.fixture(autouse=True)
435 def _set_lrcmux_sources(self, lyrics_plugin, backend_name):
436 if backend_name == "lrcmux":
437 lyrics_plugin.config["lrcmux"]["sources"] = ["ytmusic"]
438
439 def test_backend_source(
440 self, monkeypatch, lyrics_plugin, lyrics_page: LyricsPage
441 ):
442 """Test parsed lyrics from each of the configured lyrics pages."""
443 monkeypatch.setattr(
444 "beetsplug.lyrics.LyricsRequestHandler.create_session",
445 lambda _: requests.Session(),
446 )
447 expected_lyrics = Lyrics(
448 lyrics_page.lyrics,
449 lyrics_page.backend,
450 url=lyrics_page.url,
451 language=lyrics_page.language,
452 )
453
454 actual_lyrics = lyrics_plugin.find_lyrics(
455 Item(
456 artist=lyrics_page.artist,
457 title=lyrics_page.track_title,
458 album="",
459 length=186.0,
460 )
461 )
462 assert actual_lyrics
463 assert actual_lyrics.text == expected_lyrics.text
464 assert actual_lyrics == expected_lyrics
465
466
467 class TestGoogleLyrics(LyricsBackendTest):
468 """Test scraping heuristics on a fake html page."""
469
470 @pytest.fixture(scope="class")
471 def backend_name(self):
472 return "google"
473
474 @pytest.fixture
475 def plugin_config(self):
476 return {"google_API_key": "test"}
477
478 @pytest.fixture(scope="class")
479 def file_name(self):
480 return "examplecom/beetssong"
481
482 @pytest.fixture
483 def search_item(self, url_title, url):
484 return {"title": url_title, "link": url}
485
486 @pytest.mark.parametrize("plugin_config", [{}])
487 def test_disabled_without_api_key(self, lyrics_plugin):
488 assert not lyrics_plugin.backends
489
490 def test_mocked_source_ok(self, backend, lyrics_html):
491 """Test that lyrics of the mocked page are correctly scraped"""
492 result = backend.scrape(lyrics_html).lower()
493
494 assert result
495 assert PHRASE_BY_TITLE["Beets song"] in result
496
497 @pytest.mark.parametrize(
498 "url_title, expected_artist, expected_title",
499 [
500 ("Artist - beets song Lyrics", "Artist", "beets song"),
501 ("www.azlyrics.com | Beats song by Artist", "Artist", "Beats song"),
502 ("lyric.com | seets bong lyrics by Artist", "Artist", "seets bong"),
503 ("foo", "", "foo"),
504 ("Artist - Beets Song lyrics | AZLyrics", "Artist", "Beets Song"),
505 ("Letra de Artist - Beets Song", "Artist", "Beets Song"),
506 ("Letra de Artist - Beets ...", "Artist", "Beets"),
507 ("Artist Beets Song", "Artist", "Beets Song"),
508 ("BeetsSong - Artist", "Artist", "BeetsSong"),
509 ("Artist - BeetsSong", "Artist", "BeetsSong"),
510 ("Beets Song", "", "Beets Song"),
511 ("Beets Song Artist", "Artist", "Beets Song"),
512 (
513 "BeetsSong (feat. Other & Another) - Artist",
514 "Artist",
515 "BeetsSong (feat. Other & Another)",
516 ),
517 (
518 (
519 "Beets song lyrics by Artist - original song full text. "
520 "Official Beets song lyrics, 2024 version | LyricsMode.com"
521 ),
522 "Artist",
523 "Beets song",
524 ),
525 ],
526 )
527 @pytest.mark.parametrize("url", ["http://doesntmatter.com"])
528 def test_make_search_result(
529 self, backend, search_item, expected_artist, expected_title
530 ):
531 result = backend.make_search_result("Artist", "Beets song", search_item)
532
533 assert result.artist == expected_artist
534 assert result.title == expected_title
535
536
537 class TestGeniusLyrics(LyricsBackendTest):
538 @pytest.fixture(scope="class")
539 def backend_name(self):
540 return "genius"
541
542 @pytest.mark.parametrize(
543 "file_name, expected_line_count",
544 [
545 ("geniuscom/2pacalleyezonmelyrics", 131),
546 ("geniuscom/Ttngchinchillalyrics", 29),
547 ("geniuscom/sample", 0), # see https://github.com/beetbox/beets/issues/3535
548 ],
549 ) # fmt: skip
550 def test_scrape(self, backend, lyrics_html, expected_line_count):
551 result = backend.scrape(lyrics_html) or ""
552
553 assert len(result.splitlines()) == expected_line_count
554
555
556 class TestTekstowoLyrics(LyricsBackendTest):
557 @pytest.fixture(scope="class")
558 def backend_name(self):
559 return "tekstowo"
560
561 @pytest.mark.parametrize(
562 "file_name, expecting_lyrics",
563 [
564 ("tekstowopl/piosenka24kgoldncityofangels1", True),
565 (
566 "tekstowopl/piosenkabeethovenbeethovenpianosonata17tempestthe3rdmovement",
567 False,
568 ),
569 ],
570 )
571 def test_scrape(self, backend, lyrics_html, expecting_lyrics):
572 assert bool(backend.scrape(lyrics_html)) == expecting_lyrics
573
574
575 LYRICS_DURATION = 950
576
577
578 def lyrics_match(**overrides):
579 return {
580 "id": 1,
581 "instrumental": False,
582 "duration": LYRICS_DURATION,
583 "syncedLyrics": "[00:00.00] synced",
584 "plainLyrics": "plain",
585 **overrides,
586 }
587
588
589 class TestLRCLibLyrics(LyricsBackendTest):
590 ITEM_DURATION = 999
591 SYNCED = "[00:00.00] synced"
592
593 @pytest.fixture(scope="class")
594 def backend_name(self):
595 return "lrclib"
596
597 @pytest.fixture
598 def fetch_lyrics(self, backend, requests_mock, response_data):
599 requests_mock.get(backend.GET_URL, status_code=HTTPStatus.NOT_FOUND)
600 requests_mock.get(backend.SEARCH_URL, json=response_data)
601
602 return partial(backend.fetch, "la", "la", "la", self.ITEM_DURATION)
603
604 @pytest.mark.parametrize("response_data", [[lyrics_match()]])
605 @pytest.mark.parametrize(
606 "plugin_config, expected_lyrics",
607 [
608 pytest.param({"synced": True}, SYNCED, id="pick-synced"),
609 pytest.param({"synced": False}, "plain", id="pick-plain"),
610 ],
611 )
612 def test_synced_config_option(
613 self, backend_name, fetch_lyrics, expected_lyrics
614 ):
615 lyrics = fetch_lyrics()
616
617 assert lyrics
618 assert lyrics.text == expected_lyrics
619 assert lyrics.backend == backend_name
620
621 @pytest.mark.parametrize(
622 "response_data", [[lyrics_match(plainLyrics=None)]]
623 )
624 @pytest.mark.parametrize("plugin_config", [{"synced": False}])
625 def test_null_plain_lyrics_falls_back_to_synced(self, fetch_lyrics):
626 """Use synced lyrics when 'plainLyrics' is null.
627
628 LRCLib may return a null 'plainLyrics' while still providing synced
629 lyrics, so preferring plain text must not discard the data we have.
630 The timestamps are dropped, since this is standing in for plain text.
631 """
632 lyrics = fetch_lyrics()
633
634 assert lyrics
635 assert lyrics.text == "synced"
636
637 @pytest.mark.parametrize(
638 "response_data, expected_lyrics",
639 [
640 pytest.param([], None, id="handle non-matching lyrics"),
641 pytest.param([lyrics_match()], SYNCED, id="synced when available"),
642 pytest.param(
643 [lyrics_match(duration=1)], None, id="none: duration too short"
644 ),
645 pytest.param(
646 [lyrics_match(instrumental=True)], "", id="instrumental track"
647 ),
648 pytest.param(
649 [lyrics_match(syncedLyrics=None)],
650 "plain",
651 id="plain by default",
652 ),
653 pytest.param(
654 [lyrics_match(plainLyrics=None, syncedLyrics=None)],
655 None,
656 id="none: no lyrics text despite instrumental being False",
657 ),
658 pytest.param(
659 [
660 lyrics_match(
661 duration=ITEM_DURATION,
662 syncedLyrics=None,
663 plainLyrics="plain with closer duration",
664 ),
665 lyrics_match(syncedLyrics=SYNCED, plainLyrics="plain 2"),
666 ],
667 SYNCED,
668 id="prefer synced lyrics even if plain duration is closer",
669 ),
670 pytest.param(
671 [
672 lyrics_match(
673 duration=ITEM_DURATION,
674 syncedLyrics=None,
675 plainLyrics="valid plain",
676 ),
677 lyrics_match(
678 duration=1, syncedLyrics="synced with invalid duration"
679 ),
680 ],
681 "valid plain",
682 id="ignore synced with invalid duration",
683 ),
684 pytest.param(
685 [
686 lyrics_match(
687 duration=59, syncedLyrics="[01:00.00] invalid synced"
688 )
689 ],
690 None,
691 id="ignore synced with a timestamp longer than duration",
692 ),
693 pytest.param(
694 [lyrics_match(syncedLyrics=None), lyrics_match()],
695 SYNCED,
696 id="prefer match with synced lyrics",
697 ),
698 ],
699 )
700 @pytest.mark.parametrize("plugin_config", [{"synced": True}])
701 def test_fetch_lyrics(self, fetch_lyrics, expected_lyrics):
702 lyrics = fetch_lyrics()
703 if expected_lyrics is None:
704 assert not lyrics
705 else:
706 assert lyrics
707 assert lyrics.text == expected_lyrics
708
709
710 class TestLRCMuxLyrics(LyricsBackendTest):
711 SYNCED = "[00:00.00] synced"
712 PLAIN = "plain"
713
714 @pytest.fixture(scope="class")
715 def backend_name(self):
716 return "lrcmux"
717
718 @pytest.mark.parametrize(
719 "plugin_config, mocked_text, expected_format, expected_level",
720 [
721 pytest.param({"synced": True}, SYNCED, "lrc", "line", id="synced"),
722 pytest.param({"synced": False}, PLAIN, "txt", "none", id="plain"),
723 pytest.param(
724 {"synced": True, "lrcmux": {"sources": ["ytmusic"]}},
725 SYNCED,
726 "lrc",
727 "line",
728 id="synced-sources",
729 ),
730 ],
731 )
732 def test_fetch_lyrics(
733 self,
734 backend,
735 requests_mock,
736 mocked_text,
737 expected_format,
738 expected_level,
739 plugin_config,
740 ):
741 requests_mock.get(backend.url, text=mocked_text)
742 result = backend.fetch("la", "la", "la", 0)
743 assert result
744 assert result.text == mocked_text
745 assert result.backend == "lrcmux"
746 assert f"format={expected_format}" in result.url
747 assert f"level={expected_level}" in result.url
748 if sources := (plugin_config.get("lrcmux") or {}).get("sources"):
749 assert f"sources={','.join(sources)}" in result.url
750
751 @pytest.mark.parametrize("plugin_config", [{}])
752 def test_not_found(self, backend, requests_mock):
753 requests_mock.get(backend.url, status_code=HTTPStatus.NOT_FOUND)
754 assert backend.fetch("la", "la", "", 0) is None
755
756 @pytest.mark.parametrize("plugin_config", [{}])
757 def test_empty_response(self, backend, requests_mock):
758 requests_mock.get(backend.url, text="")
759 assert backend.fetch("la", "la", "", 0) is None
760
761
762 @pytest.mark.requires_import("langdetect")
763 class TestTranslation:
764 @pytest.fixture(autouse=True)
765 def _patch_bing(self, requests_mock):
766 def callback(request, _):
767 if b"Refrain" in request.body:
768 translations = (
769 ""
770 " | [Refrain : Doja Cat]"
771 " | Difficile pour moi de te laisser partir (Te laisser partir, te laisser partir)" # noqa: E501
772 " | Mon corps ne me laissait pas le cacher (Cachez-le)"
773 " | [Chorus]"
774 " | Quoi qu’il arrive, je ne plierais pas (Ne plierait pas, ne plierais pas)" # noqa: E501
775 " | Chevauchant à travers le tonnerre, la foudre"
776 )
777 elif b"00:00.00" in request.body:
778 translations = (
779 ""
780 " | [00:00.00] Quelques paroles synchronisées"
781 " | [00:01.00] Quelques paroles plus synchronisées"
782 )
783 else:
784 translations = (
785 ""
786 " | Quelques paroles synchronisées"
787 " | Quelques paroles plus synchronisées"
788 )
789
790 return [
791 {
792 "detectedLanguage": {"language": "en", "score": 1.0},
793 "translations": [{"text": translations, "to": "fr"}],
794 }
795 ]
796
797 requests_mock.post(lyrics.Translator.TRANSLATE_URL, json=callback)
798
799 @pytest.mark.parametrize(
800 "new_lyrics, old_lyrics, expected",
801 [
802 pytest.param(
803 """
804 [Refrain: Doja Cat]
805 Hard for me to let you go (Let you go, let you go)
806 My body wouldn't let me hide it (Hide it)
807 [Chorus]
808 No matter what, I wouldn't fold (Wouldn't fold, wouldn't fold)
809 Ridin' through the thunder, lightnin'""",
810 Lyrics(""),
811 """
812 [Refrain: Doja Cat] / [Refrain : Doja Cat]
813 Hard for me to let you go (Let you go, let you go) / Difficile pour moi de te laisser partir (Te laisser partir, te laisser partir)
814 My body wouldn't let me hide it (Hide it) / Mon corps ne me laissait pas le cacher (Cachez-le)
815 [Chorus]
816 No matter what, I wouldn't fold (Wouldn't fold, wouldn't fold) / Quoi qu’il arrive, je ne plierais pas (Ne plierait pas, ne plierais pas)
817 Ridin' through the thunder, lightnin' / Chevauchant à travers le tonnerre, la foudre""", # noqa: E501
818 id="plain",
819 ),
820 pytest.param(
821 """
822 [00:00.00] Some synced lyrics
823 [00:00.50]
824 [00:01.00] Some more synced lyrics
825 """,
826 Lyrics(""),
827 """
828 [00:00.00] Some synced lyrics / Quelques paroles synchronisées
829 [00:00.50]
830 [00:01.00] Some more synced lyrics / Quelques paroles plus synchronisées""", # noqa: E501
831 id="synced",
832 ),
833 pytest.param(
834 "Quelques paroles",
835 Lyrics(""),
836 "Quelques paroles",
837 id="already in the target language",
838 ),
839 pytest.param(
840 "Some lyrics",
841 Lyrics(
842 "Some lyrics / Some translation",
843 language="EN",
844 translation_language="FR",
845 ),
846 "Some lyrics / Some translation",
847 id="already translated",
848 ),
849 ],
850 )
851 def test_translate(self, new_lyrics, old_lyrics, expected):
852 plugin = lyrics.LyricsPlugin()
853 bing = lyrics.Translator(plugin._log, "123", "FR", ["EN"])
854
855 assert bing.translate(
856 Lyrics(textwrap.dedent(new_lyrics)), old_lyrics
857 ).full_text == textwrap.dedent(expected)
858
859
860 class TestRestFiles:
861 @pytest.fixture
862 def rest_dir(self, tmp_path):
863 return tmp_path
864
865 @pytest.fixture
866 def rest_files(self, rest_dir):
867 return lyrics.RestFiles(rest_dir)
868
869 def test_write(self, rest_dir: Path, rest_files):
870 items = [
871 Item(albumartist=aa, album=a, title=t, lyrics=lyr)
872 for aa, a, t, lyr in [
873 ("Artist One", "Album One", "Song One", "Lyrics One"),
874 ("Artist One", "Album One", "Song Two", "Lyrics Two"),
875 ("Artist Two", "Album Two", "Song Three", "Lyrics Three"),
876 ]
877 ]
878
879 rest_files.write(items)
880
881 assert (rest_dir / "index.rst").exists()
882 assert (rest_dir / "conf.py").exists()
883
884 artist_one_file = rest_dir / "artists" / "artist-one.rst"
885 artist_two_file = rest_dir / "artists" / "artist-two.rst"
886 assert artist_one_file.exists()
887 assert artist_two_file.exists()
888
889 c = artist_one_file.read_text()
890 assert (
891 c.index("Artist One")
892 < c.index("Album One")
893 < c.index("Song One")
894 < c.index("Lyrics One")
895 < c.index("Song Two")
896 < c.index("Lyrics Two")
897 )
898
899 c = artist_two_file.read_text()
900 assert (
901 c.index("Artist Two")
902 < c.index("Album Two")
903 < c.index("Song Three")
904 < c.index("Lyrics Three")
905 )
906
907
908 class TestLyricsRestDirectory(PluginTestHelper):
909 plugin = "lyrics"
910
911 @pytest.mark.parametrize(
912 "config_path, arg_path, output_path",
913 [
914 pytest.param(
915 "test/config", "test/cmd", "test/cmd", id="config and cmd arg"
916 ),
917 pytest.param("test/config", None, "test/config", id="config only"),
918 pytest.param(None, "test/cmd", "test/cmd", id="cmd arg only"),
919 pytest.param(
920 "~/test/config", None, "~/test/config", id="user home path"
921 ),
922 ],
923 )
924 def test_rest_config(self, monkeypatch, config_path, arg_path, output_path):
925 test_capture = {}
926
927 class MockRestFiles:
928 def __init__(self, directory):
929 test_capture["directory"] = directory
930
931 def write(self, items):
932 test_capture["items"] = items
933
934 monkeypatch.setattr(lyrics, "RestFiles", MockRestFiles)
935 self.add_item(lyrics="hello")
936
937 cmd_args = [] if arg_path is None else ["-r", arg_path]
938 with self.configure_plugin({"rest_directory": config_path}):
939 self.run_command("lyrics", *cmd_args)
940
941 assert test_capture.get("directory") == Path(output_path).expanduser()
942
943
944 class TestLyricsKeepSyncedCommand(PluginTestHelper):
945 plugin = "lyrics"
946
947 @pytest.mark.parametrize(
948 "config_keep_synced, cmd_args, expected_keep_synced",
949 [
950 pytest.param(False, (), False, id="disabled-by-default"),
951 pytest.param(True, (), True, id="enabled-by-config"),
952 pytest.param(False, ("--keep-synced",), True, id="cli-enables"),
953 pytest.param(
954 True, ("--no-keep-synced",), False, id="cli-disables-config"
955 ),
956 ],
957 )
958 def test_keep_synced_cli_option(
959 self, monkeypatch, config_keep_synced, cmd_args, expected_keep_synced
960 ):
961 self.config["lyrics"]["keep_synced"] = config_keep_synced
962 self.add_item(lyrics="[00:00.00] old synced")
963 observed_keep_synced = []
964
965 def capture_keep_synced(plugin, *_):
966 observed_keep_synced.append(plugin.config["keep_synced"].get(bool))
967
968 monkeypatch.setattr(
969 lyrics.LyricsPlugin, "add_item_lyrics", capture_keep_synced
970 )
971
972 self.run_command("lyrics", *cmd_args)
973
974 assert observed_keep_synced.pop(0) is expected_keep_synced
975
976
977 class TestLyricsSyltProperty:
978 """Unit tests for the Lyrics.sylt timestamp-to-millisecond converter."""
979
980 @pytest.mark.parametrize(
981 "lrc_text, expected_sylt",
982 [
983 pytest.param(
984 "[00:01.00] line one\n[00:02.50] line two",
985 [("line one", 1000), ("line two", 2500)],
986 id="basic-lrc-to-ms",
987 ),
988 pytest.param(
989 "[01:30.50] one and a half minutes",
990 [("one and a half minutes", 90500)],
991 id="over-one-minute",
992 ),
993 pytest.param(
994 "plain lyrics without timestamps",
995 [],
996 id="plain-lyrics-have-no-sylt",
997 ),
998 pytest.param(
999 "[00:00.00] timed\nuntimed line\n[00:05.00] timed again",
1000 [("timed", 0), ("timed again", 5000)],
1001 id="untimed-lines-omitted",
1002 ),
1003 pytest.param(
1004 "[00:00.00] \n[00:01.00] second",
1005 [("", 0), ("second", 1000)],
1006 id="empty-text-line-included",
1007 ),
1008 ],
1009 )
1010 def test_sylt(self, lrc_text, expected_sylt):
1011 assert Lyrics(lrc_text).sylt == expected_sylt
1012
1013
1014 class TestSyncedLyricsWrite(LyricsPluginMixin):
1015 """Tests that add_item_lyrics passes the correct synced_lyrics tag."""
1016
1017 SYNCED_LRC = "[00:01.00] hello\n[00:02.00] world"
1018
1019 @pytest.fixture
1020 def backend_name(self):
1021 return "lrclib"
1022
1023 def test_sylt_data_passed_for_synced_lyrics(
1024 self, monkeypatch, helper, lyrics_plugin
1025 ):
1026 monkeypatch.setattr(
1027 lyrics_plugin, "find_lyrics", lambda _: Lyrics(self.SYNCED_LRC)
1028 )
1029 item = helper.create_item(id=1, lyrics="")
1030 calls = []
1031 monkeypatch.setattr(
1032 type(item), "try_write", lambda self, **kw: calls.append(kw) or True
1033 )
1034
1035 lyrics_plugin.add_item_lyrics(item, write=True)
1036
1037 assert calls == [
1038 {"tags": {"synced_lyrics": [("hello", 1000), ("world", 2000)]}}
1039 ]
1040
1041 def test_lrc_text_kept_in_db_for_synced(
1042 self, monkeypatch, helper, lyrics_plugin
1043 ):
1044 """LRC text is stored in the DB so keep_synced detection still works."""
1045 monkeypatch.setattr(
1046 lyrics_plugin, "find_lyrics", lambda _: Lyrics(self.SYNCED_LRC)
1047 )
1048 item = helper.create_item(id=1, lyrics="")
1049 monkeypatch.setattr(type(item), "try_write", lambda self, **kw: True)
1050
1051 lyrics_plugin.add_item_lyrics(item, write=True)
1052
1053 assert item.lyrics == self.SYNCED_LRC
1054
1055 def test_sylt_cleared_for_plain_lyrics(
1056 self, monkeypatch, helper, lyrics_plugin
1057 ):
1058 monkeypatch.setattr(
1059 lyrics_plugin, "find_lyrics", lambda _: Lyrics("plain lyrics")
1060 )
1061 item = helper.create_item(id=1, lyrics="")
1062 calls = []
1063 monkeypatch.setattr(
1064 type(item), "try_write", lambda self, **kw: calls.append(kw) or True
1065 )
1066
1067 lyrics_plugin.add_item_lyrics(item, write=True)
1068
1069 assert calls == [{"tags": {"synced_lyrics": None}}]
1070
1071 def test_sylt_and_uslt_written_to_mp3(
1072 self, monkeypatch, helper, lyrics_plugin
1073 ):
1074 """Integration: SYLT + plain USLT are written to a real MP3 file."""
1075 import mutagen
1076
1077 monkeypatch.setattr(
1078 lyrics_plugin, "find_lyrics", lambda _: Lyrics(self.SYNCED_LRC)
1079 )
1080 item = helper.add_item_fixture(format="MP3", lyrics="")
1081
1082 lyrics_plugin.add_item_lyrics(item, write=True)
1083
1084 f = mutagen.File(item.path)
1085 assert f.tags.getall("SYLT"), "SYLT frame should be present"
1086 assert f.tags["SYLT::XXX"].text == [("hello", 1000), ("world", 2000)]
1087 assert f.tags.getall("USLT"), "USLT frame should be present"
1088 # USLT retains the full LRC text (with timestamps) so players that
1089 # parse LRC in USLT, and non-ID3 formats, continue to work.
1090 assert f.tags["USLT::XXX"].text == self.SYNCED_LRC