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 [
644 lyrics_match(
645 syncedLyrics="[00:01.234] 3-decimal synced lyrics"
646 )
647 ],
648 "[00:01.234] 3-decimal synced lyrics",
649 id="synced with 3-decimal millisecond timestamp",
650 ),
651 pytest.param(
652 [lyrics_match(duration=1)], None, id="none: duration too short"
653 ),
654 pytest.param(
655 [lyrics_match(instrumental=True)], "", id="instrumental track"
656 ),
657 pytest.param(
658 [lyrics_match(syncedLyrics=None)],
659 "plain",
660 id="plain by default",
661 ),
662 pytest.param(
663 [lyrics_match(plainLyrics=None, syncedLyrics=None)],
664 None,
665 id="none: no lyrics text despite instrumental being False",
666 ),
667 pytest.param(
668 [
669 lyrics_match(
670 duration=ITEM_DURATION,
671 syncedLyrics=None,
672 plainLyrics="plain with closer duration",
673 ),
674 lyrics_match(syncedLyrics=SYNCED, plainLyrics="plain 2"),
675 ],
676 SYNCED,
677 id="prefer synced lyrics even if plain duration is closer",
678 ),
679 pytest.param(
680 [
681 lyrics_match(
682 duration=ITEM_DURATION,
683 syncedLyrics=None,
684 plainLyrics="valid plain",
685 ),
686 lyrics_match(
687 duration=1, syncedLyrics="synced with invalid duration"
688 ),
689 ],
690 "valid plain",
691 id="ignore synced with invalid duration",
692 ),
693 pytest.param(
694 [
695 lyrics_match(
696 duration=59, syncedLyrics="[01:00.00] invalid synced"
697 )
698 ],
699 None,
700 id="ignore synced with a timestamp longer than duration",
701 ),
702 pytest.param(
703 [lyrics_match(syncedLyrics=None), lyrics_match()],
704 SYNCED,
705 id="prefer match with synced lyrics",
706 ),
707 ],
708 )
709 @pytest.mark.parametrize("plugin_config", [{"synced": True}])
710 def test_fetch_lyrics(self, fetch_lyrics, expected_lyrics):
711 lyrics = fetch_lyrics()
712 if expected_lyrics is None:
713 assert not lyrics
714 else:
715 assert lyrics
716 assert lyrics.text == expected_lyrics
717
718
719 class TestLRCMuxLyrics(LyricsBackendTest):
720 SYNCED = "[00:00.00] synced"
721 PLAIN = "plain"
722
723 @pytest.fixture(scope="class")
724 def backend_name(self):
725 return "lrcmux"
726
727 @pytest.mark.parametrize(
728 "plugin_config, mocked_text, expected_format, expected_level",
729 [
730 pytest.param({"synced": True}, SYNCED, "lrc", "line", id="synced"),
731 pytest.param({"synced": False}, PLAIN, "txt", "none", id="plain"),
732 pytest.param(
733 {"synced": True, "lrcmux": {"sources": ["ytmusic"]}},
734 SYNCED,
735 "lrc",
736 "line",
737 id="synced-sources",
738 ),
739 ],
740 )
741 def test_fetch_lyrics(
742 self,
743 backend,
744 requests_mock,
745 mocked_text,
746 expected_format,
747 expected_level,
748 plugin_config,
749 ):
750 requests_mock.get(backend.url, text=mocked_text)
751 result = backend.fetch("la", "la", "la", 0)
752 assert result
753 assert result.text == mocked_text
754 assert result.backend == "lrcmux"
755 assert f"format={expected_format}" in result.url
756 assert f"level={expected_level}" in result.url
757 if sources := (plugin_config.get("lrcmux") or {}).get("sources"):
758 assert f"sources={','.join(sources)}" in result.url
759
760 @pytest.mark.parametrize("plugin_config", [{}])
761 def test_not_found(self, backend, requests_mock):
762 requests_mock.get(backend.url, status_code=HTTPStatus.NOT_FOUND)
763 assert backend.fetch("la", "la", "", 0) is None
764
765 @pytest.mark.parametrize("plugin_config", [{}])
766 def test_empty_response(self, backend, requests_mock):
767 requests_mock.get(backend.url, text="")
768 assert backend.fetch("la", "la", "", 0) is None
769
770
771 @pytest.mark.requires_import("langdetect")
772 class TestTranslation:
773 @pytest.fixture(autouse=True)
774 def _patch_bing(self, requests_mock):
775 def callback(request, _):
776 if b"Refrain" in request.body:
777 translations = (
778 ""
779 " | [Refrain : Doja Cat]"
780 " | Difficile pour moi de te laisser partir (Te laisser partir, te laisser partir)" # noqa: E501
781 " | Mon corps ne me laissait pas le cacher (Cachez-le)"
782 " | [Chorus]"
783 " | Quoi qu’il arrive, je ne plierais pas (Ne plierait pas, ne plierais pas)" # noqa: E501
784 " | Chevauchant à travers le tonnerre, la foudre"
785 )
786 elif b"00:00.00" in request.body:
787 translations = (
788 ""
789 " | [00:00.00] Quelques paroles synchronisées"
790 " | [00:01.00] Quelques paroles plus synchronisées"
791 )
792 else:
793 translations = (
794 ""
795 " | Quelques paroles synchronisées"
796 " | Quelques paroles plus synchronisées"
797 )
798
799 return [
800 {
801 "detectedLanguage": {"language": "en", "score": 1.0},
802 "translations": [{"text": translations, "to": "fr"}],
803 }
804 ]
805
806 requests_mock.post(lyrics.Translator.TRANSLATE_URL, json=callback)
807
808 @pytest.mark.parametrize(
809 "new_lyrics, old_lyrics, expected",
810 [
811 pytest.param(
812 """
813 [Refrain: Doja Cat]
814 Hard for me to let you go (Let you go, let you go)
815 My body wouldn't let me hide it (Hide it)
816 [Chorus]
817 No matter what, I wouldn't fold (Wouldn't fold, wouldn't fold)
818 Ridin' through the thunder, lightnin'""",
819 Lyrics(""),
820 """
821 [Refrain: Doja Cat] / [Refrain : Doja Cat]
822 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)
823 My body wouldn't let me hide it (Hide it) / Mon corps ne me laissait pas le cacher (Cachez-le)
824 [Chorus]
825 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)
826 Ridin' through the thunder, lightnin' / Chevauchant à travers le tonnerre, la foudre""", # noqa: E501
827 id="plain",
828 ),
829 pytest.param(
830 """
831 [00:00.00] Some synced lyrics
832 [00:00.50]
833 [00:01.00] Some more synced lyrics
834 """,
835 Lyrics(""),
836 """
837 [00:00.00] Some synced lyrics / Quelques paroles synchronisées
838 [00:00.50]
839 [00:01.00] Some more synced lyrics / Quelques paroles plus synchronisées""", # noqa: E501
840 id="synced",
841 ),
842 pytest.param(
843 "Quelques paroles",
844 Lyrics(""),
845 "Quelques paroles",
846 id="already in the target language",
847 ),
848 pytest.param(
849 "Some lyrics",
850 Lyrics(
851 "Some lyrics / Some translation",
852 language="EN",
853 translation_language="FR",
854 ),
855 "Some lyrics / Some translation",
856 id="already translated",
857 ),
858 ],
859 )
860 def test_translate(self, new_lyrics, old_lyrics, expected):
861 plugin = lyrics.LyricsPlugin()
862 bing = lyrics.Translator(plugin._log, "123", "FR", ["EN"])
863
864 assert bing.translate(
865 Lyrics(textwrap.dedent(new_lyrics)), old_lyrics
866 ).full_text == textwrap.dedent(expected)
867
868
869 class TestRestFiles:
870 @pytest.fixture
871 def rest_dir(self, tmp_path):
872 return tmp_path
873
874 @pytest.fixture
875 def rest_files(self, rest_dir):
876 return lyrics.RestFiles(rest_dir)
877
878 def test_write(self, rest_dir: Path, rest_files):
879 items = [
880 Item(albumartist=aa, album=a, title=t, lyrics=lyr)
881 for aa, a, t, lyr in [
882 ("Artist One", "Album One", "Song One", "Lyrics One"),
883 ("Artist One", "Album One", "Song Two", "Lyrics Two"),
884 ("Artist Two", "Album Two", "Song Three", "Lyrics Three"),
885 ]
886 ]
887
888 rest_files.write(items)
889
890 assert (rest_dir / "index.rst").exists()
891 assert (rest_dir / "conf.py").exists()
892
893 artist_one_file = rest_dir / "artists" / "artist-one.rst"
894 artist_two_file = rest_dir / "artists" / "artist-two.rst"
895 assert artist_one_file.exists()
896 assert artist_two_file.exists()
897
898 c = artist_one_file.read_text()
899 assert (
900 c.index("Artist One")
901 < c.index("Album One")
902 < c.index("Song One")
903 < c.index("Lyrics One")
904 < c.index("Song Two")
905 < c.index("Lyrics Two")
906 )
907
908 c = artist_two_file.read_text()
909 assert (
910 c.index("Artist Two")
911 < c.index("Album Two")
912 < c.index("Song Three")
913 < c.index("Lyrics Three")
914 )
915
916
917 class TestLyricsRestDirectory(PluginTestHelper):
918 plugin = "lyrics"
919
920 @pytest.mark.parametrize(
921 "config_path, arg_path, output_path",
922 [
923 pytest.param(
924 "test/config", "test/cmd", "test/cmd", id="config and cmd arg"
925 ),
926 pytest.param("test/config", None, "test/config", id="config only"),
927 pytest.param(None, "test/cmd", "test/cmd", id="cmd arg only"),
928 pytest.param(
929 "~/test/config", None, "~/test/config", id="user home path"
930 ),
931 ],
932 )
933 def test_rest_config(self, monkeypatch, config_path, arg_path, output_path):
934 test_capture = {}
935
936 class MockRestFiles:
937 def __init__(self, directory):
938 test_capture["directory"] = directory
939
940 def write(self, items):
941 test_capture["items"] = items
942
943 monkeypatch.setattr(lyrics, "RestFiles", MockRestFiles)
944 self.add_item(lyrics="hello")
945
946 cmd_args = [] if arg_path is None else ["-r", arg_path]
947 with self.configure_plugin({"rest_directory": config_path}):
948 self.run_command("lyrics", *cmd_args)
949
950 assert test_capture.get("directory") == Path(output_path).expanduser()
951
952
953 class TestLyricsKeepSyncedCommand(PluginTestHelper):
954 plugin = "lyrics"
955
956 @pytest.mark.parametrize(
957 "config_keep_synced, cmd_args, expected_keep_synced",
958 [
959 pytest.param(False, (), False, id="disabled-by-default"),
960 pytest.param(True, (), True, id="enabled-by-config"),
961 pytest.param(False, ("--keep-synced",), True, id="cli-enables"),
962 pytest.param(
963 True, ("--no-keep-synced",), False, id="cli-disables-config"
964 ),
965 ],
966 )
967 def test_keep_synced_cli_option(
968 self, monkeypatch, config_keep_synced, cmd_args, expected_keep_synced
969 ):
970 self.config["lyrics"]["keep_synced"] = config_keep_synced
971 self.add_item(lyrics="[00:00.00] old synced")
972 observed_keep_synced = []
973
974 def capture_keep_synced(plugin, *_):
975 observed_keep_synced.append(plugin.config["keep_synced"].get(bool))
976
977 monkeypatch.setattr(
978 lyrics.LyricsPlugin, "add_item_lyrics", capture_keep_synced
979 )
980
981 self.run_command("lyrics", *cmd_args)
982
983 assert observed_keep_synced.pop(0) is expected_keep_synced
984
985
986 class TestLyricsSyltProperty:
987 """Unit tests for the Lyrics.sylt timestamp-to-millisecond converter."""
988
989 @pytest.mark.parametrize(
990 "lrc_text, expected_sylt",
991 [
992 pytest.param(
993 "[00:01.00] line one\n[00:02.50] line two",
994 [("line one", 1000), ("line two", 2500)],
995 id="basic-lrc-to-ms",
996 ),
997 pytest.param(
998 "[01:30.50] one and a half minutes",
999 [("one and a half minutes", 90500)],
1000 id="over-one-minute",
1001 ),
1002 pytest.param(
1003 "plain lyrics without timestamps",
1004 [],
1005 id="plain-lyrics-have-no-sylt",
1006 ),
1007 pytest.param(
1008 "[00:00.00] timed\nuntimed line\n[00:05.00] timed again",
1009 [("timed", 0), ("timed again", 5000)],
1010 id="untimed-lines-omitted",
1011 ),
1012 pytest.param(
1013 "[00:00.00] \n[00:01.00] second",
1014 [("", 0), ("second", 1000)],
1015 id="empty-text-line-included",
1016 ),
1017 ],
1018 )
1019 def test_sylt(self, lrc_text, expected_sylt):
1020 assert Lyrics(lrc_text).sylt == expected_sylt
1021
1022
1023 class TestSyncedLyricsWrite(LyricsPluginMixin):
1024 """Tests that add_item_lyrics passes the correct synced_lyrics tag."""
1025
1026 SYNCED_LRC = "[00:01.00] hello\n[00:02.00] world"
1027
1028 @pytest.fixture
1029 def backend_name(self):
1030 return "lrclib"
1031
1032 def test_sylt_data_passed_for_synced_lyrics(
1033 self, monkeypatch, helper, lyrics_plugin
1034 ):
1035 monkeypatch.setattr(
1036 lyrics_plugin, "find_lyrics", lambda _: Lyrics(self.SYNCED_LRC)
1037 )
1038 item = helper.create_item(id=1, lyrics="")
1039 calls = []
1040 monkeypatch.setattr(
1041 type(item), "try_write", lambda self, **kw: calls.append(kw) or True
1042 )
1043
1044 lyrics_plugin.add_item_lyrics(item, write=True)
1045
1046 assert calls == [
1047 {"tags": {"synced_lyrics": [("hello", 1000), ("world", 2000)]}}
1048 ]
1049
1050 def test_lrc_text_kept_in_db_for_synced(
1051 self, monkeypatch, helper, lyrics_plugin
1052 ):
1053 """LRC text is stored in the DB so keep_synced detection still works."""
1054 monkeypatch.setattr(
1055 lyrics_plugin, "find_lyrics", lambda _: Lyrics(self.SYNCED_LRC)
1056 )
1057 item = helper.create_item(id=1, lyrics="")
1058 monkeypatch.setattr(type(item), "try_write", lambda self, **kw: True)
1059
1060 lyrics_plugin.add_item_lyrics(item, write=True)
1061
1062 assert item.lyrics == self.SYNCED_LRC
1063
1064 def test_sylt_cleared_for_plain_lyrics(
1065 self, monkeypatch, helper, lyrics_plugin
1066 ):
1067 monkeypatch.setattr(
1068 lyrics_plugin, "find_lyrics", lambda _: Lyrics("plain lyrics")
1069 )
1070 item = helper.create_item(id=1, lyrics="")
1071 calls = []
1072 monkeypatch.setattr(
1073 type(item), "try_write", lambda self, **kw: calls.append(kw) or True
1074 )
1075
1076 lyrics_plugin.add_item_lyrics(item, write=True)
1077
1078 assert calls == [{"tags": {"synced_lyrics": None}}]
1079
1080 def test_sylt_and_uslt_written_to_mp3(
1081 self, monkeypatch, helper, lyrics_plugin
1082 ):
1083 """Integration: SYLT + plain USLT are written to a real MP3 file."""
1084 import mutagen
1085
1086 monkeypatch.setattr(
1087 lyrics_plugin, "find_lyrics", lambda _: Lyrics(self.SYNCED_LRC)
1088 )
1089 item = helper.add_item_fixture(format="MP3", lyrics="")
1090
1091 lyrics_plugin.add_item_lyrics(item, write=True)
1092
1093 f = mutagen.File(item.path)
1094 assert f.tags.getall("SYLT"), "SYLT frame should be present"
1095 assert f.tags["SYLT::XXX"].text == [("hello", 1000), ("world", 2000)]
1096 assert f.tags.getall("USLT"), "USLT frame should be present"
1097 # USLT retains the full LRC text (with timestamps) so players that
1098 # parse LRC in USLT, and non-ID3 formats, continue to work.
1099 assert f.tags["USLT::XXX"].text == self.SYNCED_LRC