Debian Codegraph @

test/test_importer.py

raw
1 """Tests for the general importer functionality."""
2
3 from __future__ import annotations
4
5 import os
6 import re
7 import shutil
8 import stat
9 import sys
10 import unicodedata
11 import unittest
12 from contextlib import contextmanager
13 from functools import cached_property
14 from io import StringIO
15 from pathlib import Path
16 from tarfile import TarFile
17 from tempfile import mkstemp
18 from typing import Literal
19 from unittest.mock import Mock, patch
20 from zipfile import ZipFile
21
22 import pytest
23 from mediafile import MediaFile
24
25 from beets import config, importer, logging, plugins, ui, util
26 from beets.autotag import AlbumInfo, AlbumMatch, Distance, TrackInfo
27 from beets.importer.state import ImportState
28 from beets.importer.tasks import (
29 ImportTaskFactory,
30 albums_in_dir,
31 resolve_upgrade,
32 resolve_upgrade_target,
33 )
34 from beets.library import Item
35 from beets.test import _common
36 from beets.test.helper import (
37 NEEDS_FFPROBE,
38 NEEDS_REFLINK,
39 AsIsImporterMixin,
40 AutotagImportHelper,
41 AutotagImportTestCase,
42 AutotagStub,
43 BeetsTestCase,
44 ImportHelper,
45 PluginMixin,
46 TerminalImportMixin,
47 TerminalImportSessionFixture,
48 TestHelper,
49 has_program,
50 is_importable,
51 )
52 from beets.util import bytestring_path, syspath
53 from beets.util.extension import remux_mpeglayer3_wav
54
55
56 class PathsMixin:
57 import_media: list[MediaFile]
58
59 @cached_property
60 def track_import_path(self) -> Path:
61 return Path(self.import_media[0].path)
62
63 @cached_property
64 def album_path(self) -> Path:
65 return self.track_import_path.parent
66
67 @cached_property
68 def track_lib_path(self):
69 return self.lib_path / "Tag Artist" / "Tag Album" / "Tag Track 1.mp3"
70
71
72 class TestNonAutotaggedImport(PathsMixin, AsIsImporterMixin, ImportHelper):
73 db_on_disk = True
74
75 def test_album_created_with_track_artist(self):
76 self.run_asis_importer()
77
78 albums = self.lib.albums()
79 assert len(albums) == 1
80 assert albums[0].albumartist == "Tag Artist"
81
82 def test_import_copy_arrives(self):
83 self.run_asis_importer()
84
85 assert self.track_lib_path.exists()
86
87 def test_threaded_import_copy_arrives(self):
88 config["threaded"] = True
89
90 self.run_asis_importer()
91 assert self.track_lib_path.exists()
92
93 def test_import_with_move_deletes_import_files(self):
94 assert self.album_path.exists()
95 assert self.track_import_path.exists()
96 (self.album_path / "alog.log").touch()
97 config["clutter"] = ["*.log"]
98
99 self.run_asis_importer(move=True)
100
101 assert not self.track_import_path.exists()
102 assert not self.album_path.exists()
103
104 def test_threaded_import_move_arrives(self):
105 self.run_asis_importer(move=True, threaded=True)
106
107 assert self.track_lib_path.exists()
108 assert not self.track_import_path.exists()
109
110 def test_import_without_delete_retains_files(self):
111 self.run_asis_importer(delete=False)
112
113 assert self.track_import_path.exists()
114
115 def test_import_with_delete_removes_files(self):
116 self.run_asis_importer(delete=True)
117
118 assert not self.album_path.exists()
119 assert not self.track_import_path.exists()
120
121 def test_album_mb_albumartistids(self):
122 self.run_asis_importer()
123 album = self.lib.albums()[0]
124 assert album.mb_albumartistids == album.items()[0].mb_albumartistids
125
126 @pytest.mark.skipif(not _common.HAVE_SYMLINK, reason="need symlinks")
127 def test_import_link_arrives(self):
128 self.run_asis_importer(link=True)
129
130 assert self.track_lib_path.exists()
131 assert self.track_lib_path.is_symlink()
132 assert self.track_lib_path.resolve() == self.track_import_path.resolve()
133
134 @pytest.mark.skipif(not _common.HAVE_HARDLINK, reason="need hardlinks")
135 def test_import_hardlink_arrives(self):
136 self.run_asis_importer(hardlink=True)
137
138 assert self.track_lib_path.exists()
139 media_stat = self.track_import_path.stat()
140 lib_media_stat = self.track_lib_path.stat()
141 assert media_stat[stat.ST_INO] == lib_media_stat[stat.ST_INO]
142 assert media_stat[stat.ST_DEV] == lib_media_stat[stat.ST_DEV]
143
144 @NEEDS_REFLINK
145 def test_import_reflink_arrives(self):
146 # Detecting reflinks is currently tricky due to various fs
147 # implementations, we'll just check the file exists.
148 self.run_asis_importer(reflink=True)
149
150 assert self.track_lib_path.exists()
151
152 def test_import_reflink_auto_arrives(self):
153 # Should pass regardless of reflink support due to fallback.
154 self.run_asis_importer(reflink="auto")
155
156 assert self.track_lib_path.exists()
157
158
159 def create_archive(session):
160 handle, path = mkstemp(dir=session.temp_path)
161 path = bytestring_path(path)
162 os.close(handle)
163 archive = ZipFile(os.fsdecode(path), mode="w")
164 archive.write(_common.RSRC / "full.mp3", "full.mp3")
165 archive.close()
166 return bytestring_path(path)
167
168
169 class TestRmTemp(TestHelper):
170 """Tests that temporarily extracted archives are properly removed
171 after usage.
172 """
173
174 def setup_beets(self):
175 super().setup_beets()
176 self.want_resume = False
177 self.config["incremental"] = False
178 self.config["copy"] = False
179 self.config["move"] = False
180 self.config["delete"] = False
181 self._old_home = None
182
183 def test_rm(self):
184 zip_path = create_archive(self)
185 archive_task = importer.ArchiveImportTask(zip_path)
186 archive_task.extract()
187 tmp_path = Path(os.fsdecode(archive_task.toppath))
188 assert tmp_path.exists()
189 archive_task.finalize(self)
190 assert not tmp_path.exists()
191
192 def test_archive_removed_on_move_complete(self):
193 zip_path = create_archive(self)
194 archive_task = importer.ArchiveImportTask(zip_path)
195 archive_task.extract()
196 for root, _, files in os.walk(archive_task.toppath):
197 for f in files:
198 os.remove(os.path.join(root, f))
199 assert Path(os.fsdecode(zip_path)).exists()
200 archive_task.cleanup(move=True)
201 assert not Path(os.fsdecode(zip_path)).exists()
202
203 def test_archive_preserved_on_move_partial(self):
204 zip_path = create_archive(self)
205 archive_task = importer.ArchiveImportTask(zip_path)
206 archive_task.extract()
207 archive_task.cleanup(move=True)
208 assert Path(os.fsdecode(zip_path)).exists()
209
210 def test_archive_preserved_on_copy(self):
211 zip_path = create_archive(self)
212 archive_task = importer.ArchiveImportTask(zip_path)
213 archive_task.extract()
214 archive_task.cleanup(copy=True)
215 assert Path(os.fsdecode(zip_path)).exists()
216
217 def test_tempdir_removed_in_all_modes(self):
218 for cleanup_kwargs in (
219 {},
220 {"move": True},
221 {"copy": True},
222 {"copy": True, "delete": True},
223 ):
224 zip_path = create_archive(self)
225 archive_task = importer.ArchiveImportTask(zip_path)
226 archive_task.extract()
227 tmp_path = Path(os.fsdecode(archive_task.toppath))
228 assert tmp_path.exists(), f"extract failed for {cleanup_kwargs}"
229 archive_task.cleanup(**cleanup_kwargs)
230 assert not tmp_path.exists(), (
231 f"tempdir {tmp_path} not removed for {cleanup_kwargs}"
232 )
233
234
235 class TestImportZip(AsIsImporterMixin, ImportHelper):
236 def create_archive(self):
237 return create_archive(self)
238
239 def test_import_zip(self):
240 archive_path = self.create_archive()
241 assert len(self.lib.items()) == 0
242 assert len(self.lib.albums()) == 0
243
244 self.run_asis_importer(import_dir=archive_path)
245 assert len(self.lib.items()) == 1
246 assert len(self.lib.albums()) == 1
247
248
249 class TestImportTar(TestImportZip):
250 def create_archive(self):
251 (handle, path) = mkstemp(dir=self.temp_path)
252 path = bytestring_path(path)
253 os.close(handle)
254 archive = TarFile(os.fsdecode(path), mode="w")
255 archive.add(_common.RSRC / "full.mp3", "full.mp3")
256 archive.close()
257 return path
258
259
260 @pytest.mark.skipif(
261 not (is_importable("rarfile") and has_program("unrar")),
262 reason="rarfile or unrar program not found",
263 )
264 class TestImportRar(TestImportZip):
265 def create_archive(self):
266 return _common.RSRC / "archive.rar"
267
268
269 @pytest.mark.skipif(not is_importable("py7zr"), reason="py7zr is not available")
270 class TestImport7z(TestImportZip):
271 def create_archive(self):
272 return _common.RSRC / "archive.7z"
273
274
275 @pytest.mark.skip(reason="Implement me!")
276 class TestImportPasswordRar(TestImportZip):
277 def create_archive(self):
278 return _common.RSRC / "password.rar"
279
280
281 class ImportSingletonTest(AutotagImportTestCase):
282 """Test ``APPLY`` and ``ASIS`` choices for an import session with
283 singletons config set to True.
284 """
285
286 def setUp(self):
287 super().setUp()
288 self.prepare_album_for_import(1)
289 self.importer = self.setup_singleton_importer()
290
291 def test_apply_asis_adds_only_singleton_track(self):
292 self.importer.add_choice(importer.Action.ASIS)
293 self.importer.run()
294
295 # album not added
296 assert not self.lib.albums()
297 assert self.lib.items().get().title == "Tag Track 1"
298 assert (self.lib_path / "singletons" / "Tag Track 1.mp3").exists()
299
300 def test_apply_candidate_adds_track(self):
301 self.importer.add_choice(importer.Action.APPLY)
302 self.importer.run()
303
304 assert not self.lib.albums()
305 assert self.lib.items().get().title == "Applied Track 1"
306 assert (self.lib_path / "singletons" / "Applied Track 1.mp3").exists()
307
308 def test_apply_from_scratch_removes_other_metadata(self):
309 config["import"]["from_scratch"] = True
310
311 for mediafile in self.import_media:
312 mediafile.comments = "Tag Comment"
313 mediafile.save()
314
315 self.importer.add_choice(importer.Action.APPLY)
316 self.importer.run()
317 assert self.lib.items().get().comments == ""
318
319 def test_skip_does_not_add_track(self):
320 self.importer.add_choice(importer.Action.SKIP)
321 self.importer.run()
322
323 assert not self.lib.items()
324
325 def test_skip_first_add_second_asis(self):
326 self.prepare_album_for_import(2)
327
328 self.importer.add_choice(importer.Action.SKIP)
329 self.importer.add_choice(importer.Action.ASIS)
330 self.importer.run()
331
332 assert len(self.lib.items()) == 1
333
334 def test_import_single_files(self):
335 resource_path = _common.RSRC / "empty.mp3"
336 single_path = self.import_path / "track_2.mp3"
337
338 util.copy(resource_path, single_path)
339 import_files = [self.import_path / "album", single_path]
340 self.setup_importer()
341 self.importer.paths = list(map(os.fsencode, import_files))
342
343 self.importer.add_choice(importer.Action.ASIS)
344 self.importer.add_choice(importer.Action.ASIS)
345 self.importer.run()
346
347 assert len(self.lib.items()) == 2
348 assert len(self.lib.albums()) == 2
349
350 def test_set_fields(self):
351 genres = ["\U0001f3b7 Jazz", "Rock"]
352 collection = "To Listen"
353 disc = 0
354
355 config["import"]["set_fields"] = {
356 "genres": "; ".join(genres),
357 "collection": collection,
358 "disc": disc,
359 "title": "$title - formatted",
360 }
361
362 # As-is item import.
363 assert self.lib.albums().get() is None
364 self.importer.add_choice(importer.Action.ASIS)
365 self.importer.run()
366
367 for item in self.lib.items():
368 item.load() # TODO: Not sure this is necessary.
369 assert item.genres == genres
370 assert item.collection == collection
371 assert item.title == "Tag Track 1 - formatted"
372 assert item.disc == disc
373 # Remove item from library to test again with APPLY choice.
374 item.remove()
375
376 # Autotagged.
377 assert not self.lib.albums()
378 self.importer.clear_choices()
379 self.importer.add_choice(importer.Action.APPLY)
380 self.importer.run()
381
382 for item in self.lib.items():
383 item.load()
384 assert item.genres == genres
385 assert item.collection == collection
386 assert item.title == "Applied Track 1 - formatted"
387 assert item.disc == disc
388
389
390 @pytest.mark.skipif(
391 not has_program("ffprobe", ["-L"]),
392 reason="need ffprobe for format recognition",
393 )
394 class TestImportFormat(ImportHelper):
395 """Test fix_extension during import."""
396
397 def test_recognize_format(self):
398 resource_src = _common.RSRC / "no_ext"
399 resource_path = self.import_path / "no_ext"
400 util.copy(resource_src, resource_path)
401 self.setup_importer(autotag=False)
402 self.importer.paths = [os.fsencode(resource_path)]
403 self.importer.run()
404 assert self.lib.items().get().path.endswith(b".mp3")
405
406 def test_recognize_format_already_exist(self, caplog):
407 resource_path = _common.RSRC / "no_ext"
408 temp_resource_path = self.temp_path / "no_ext"
409 util.copy(resource_path, temp_resource_path)
410 new_path = self.temp_path / "no_ext.mp3"
411 util.copy(temp_resource_path, new_path)
412 self.setup_importer(autotag=False)
413 self.importer.paths = [os.fsencode(temp_resource_path)]
414 with caplog.at_level("DEBUG"):
415 self.importer.run()
416 assert (
417 "Import file with matching format to original target"
418 in caplog.messages
419 )
420 assert self.lib.items().get().path.endswith(b".mp3")
421
422 def test_recognize_format_not_music(self):
423 resource_path = _common.RSRC / "no_ext_not_music"
424 self.setup_importer(autotag=False)
425 self.importer.paths = [os.fsencode(resource_path)]
426 self.importer.run()
427 assert len(self.lib.items()) == 0
428
429 def test_recognize_format_change_original(self):
430 config["import"]["fix_ext_inplace"] = True
431 resource_src = _common.RSRC / "no_ext"
432 resource_path = self.temp_path / "no_ext"
433 util.copy(resource_src, resource_path)
434 self.setup_importer(autotag=False)
435 self.importer.paths = [os.fsencode(resource_path)]
436 self.importer.run()
437 assert not Path(self.temp_path / "no_ext").exists()
438
439 def test_recognize_format_keep_original(self):
440 config["import"]["fix_ext_inplace"] = False
441 resource_src = _common.RSRC / "no_ext"
442 resource_path = self.temp_path / "no_ext"
443 util.copy(resource_src, resource_path)
444 self.setup_importer(autotag=False)
445 self.importer.paths = [os.fsencode(resource_path)]
446 self.importer.run()
447 assert Path(self.temp_path / "no_ext").exists()
448
449
450 class TestImport(PathsMixin, AutotagImportHelper):
451 """Test APPLY, ASIS and SKIP choices."""
452
453 def setup_beets(self):
454 super().setup_beets()
455 self.prepare_album_for_import(1)
456 self.setup_importer()
457
458 def test_asis_moves_album_and_track(self):
459 self.importer.add_choice(importer.Action.ASIS)
460 self.importer.run()
461
462 assert self.lib.albums().get().album == "Tag Album"
463 item = self.lib.items().get()
464 assert item.title == "Tag Track 1"
465 assert item.filepath.exists()
466
467 def test_apply_moves_album_and_track(self):
468 self.importer.add_choice(importer.Action.APPLY)
469 self.importer.run()
470
471 assert self.lib.albums().get().album == "Applied Album"
472 item = self.lib.items().get()
473 assert item.title == "Applied Track 1"
474 assert item.filepath.exists()
475
476 def test_apply_from_scratch_removes_other_metadata(self):
477 config["import"]["from_scratch"] = True
478
479 for mediafile in self.import_media:
480 mediafile.genres = ["Tag Genre"]
481 mediafile.save()
482
483 self.importer.add_choice(importer.Action.APPLY)
484 self.importer.run()
485 assert not self.lib.items().get().genres
486
487 def test_apply_from_scratch_keeps_format(self):
488 config["import"]["from_scratch"] = True
489
490 self.importer.add_choice(importer.Action.APPLY)
491 self.importer.run()
492 assert self.lib.items().get().format == "MP3"
493
494 def test_apply_from_scratch_keeps_bitrate(self):
495 config["import"]["from_scratch"] = True
496 bitrate = 80000
497
498 self.importer.add_choice(importer.Action.APPLY)
499 self.importer.run()
500 assert self.lib.items().get().bitrate == bitrate
501
502 def test_apply_with_move_deletes_import(self):
503 assert self.track_import_path.exists()
504
505 config["import"]["move"] = True
506 self.importer.add_choice(importer.Action.APPLY)
507 self.importer.run()
508
509 assert not self.track_import_path.exists()
510
511 def test_apply_with_delete_deletes_import(self):
512 assert self.track_import_path.exists()
513
514 config["import"]["delete"] = True
515 self.importer.add_choice(importer.Action.APPLY)
516 self.importer.run()
517
518 assert not self.track_import_path.exists()
519
520 def test_skip_does_not_add_track(self):
521 self.importer.add_choice(importer.Action.SKIP)
522 self.importer.run()
523
524 assert not self.lib.items()
525
526 @NEEDS_FFPROBE
527 def test_skip_non_album_dirs(self):
528 assert (self.import_path / "album").exists()
529 (self.import_path / "cruft").touch()
530 self.importer.add_choice(importer.Action.APPLY)
531 self.importer.run()
532
533 assert len(self.lib.albums()) == 1
534
535 def test_unmatched_tracks_not_added(self):
536 self.prepare_album_for_import(2)
537 self.matcher.matching = self.matcher.MISSING
538 self.importer.add_choice(importer.Action.APPLY)
539 self.importer.run()
540 assert len(self.lib.items()) == 1
541
542 @NEEDS_FFPROBE
543 def test_empty_directory_warning(self, caplog):
544 import_dir = self.temp_path / "empty"
545 import_dir.mkdir()
546 (import_dir / "non-audio").touch()
547 self.setup_importer(import_dir=import_dir)
548 with caplog.at_level("DEBUG"):
549 self.importer.run()
550
551 assert f"No files imported from {import_dir}" in caplog.messages
552
553 @NEEDS_FFPROBE
554 def test_empty_directory_singleton_warning(self, caplog):
555 import_dir = self.temp_path / "empty"
556 import_dir.mkdir()
557 (import_dir / "non-audio").touch()
558 self.setup_singleton_importer(import_dir=import_dir)
559 with caplog.at_level("DEBUG"):
560 self.importer.run()
561
562 assert f"No files imported from {import_dir}" in caplog.messages
563
564 def test_asis_no_data_source(self):
565 assert self.lib.items().get() is None
566
567 self.importer.add_choice(importer.Action.ASIS)
568 self.importer.run()
569
570 with pytest.raises(AttributeError):
571 self.lib.items().get().data_source
572
573 def test_set_fields(self):
574 genres = ["\U0001f3b7 Jazz", "Rock"]
575 collection = "To Listen"
576 disc = 0
577 comments = "managed by beets"
578
579 config["import"]["set_fields"] = {
580 "genres": "; ".join(genres),
581 "collection": collection,
582 "disc": disc,
583 "comments": comments,
584 "album": "$album - formatted",
585 }
586
587 # As-is album import.
588 assert self.lib.albums().get() is None
589 self.importer.add_choice(importer.Action.ASIS)
590 self.importer.run()
591
592 for album in self.lib.albums():
593 assert album.genres == genres
594 assert album.comments == comments
595 for item in album.items():
596 assert item.get("genres", with_album=False) == genres
597 assert item.get("collection", with_album=False) == collection
598 assert item.get("comments", with_album=False) == comments
599 assert (
600 item.get("album", with_album=False)
601 == "Tag Album - formatted"
602 )
603 assert item.disc == disc
604 # Remove album from library to test again with APPLY choice.
605 album.remove()
606
607 # Autotagged.
608 assert self.lib.albums().get() is None
609 self.importer.clear_choices()
610 self.importer.add_choice(importer.Action.APPLY)
611 self.importer.run()
612
613 for album in self.lib.albums():
614 assert album.genres == genres
615 assert album.comments == comments
616 for item in album.items():
617 assert item.get("genres", with_album=False) == genres
618 assert item.get("collection", with_album=False) == collection
619 assert item.get("comments", with_album=False) == comments
620 assert (
621 item.get("album", with_album=False)
622 == "Applied Album - formatted"
623 )
624 assert item.disc == disc
625
626
627 class ImportTracksTest(AutotagImportTestCase):
628 """Test TRACKS and APPLY choice."""
629
630 def setUp(self):
631 super().setUp()
632 self.prepare_album_for_import(1)
633 self.setup_importer()
634
635 def test_apply_tracks_adds_singleton_track(self):
636 self.importer.add_choice(importer.Action.TRACKS)
637 self.importer.add_choice(importer.Action.APPLY)
638 self.importer.add_choice(importer.Action.APPLY)
639 self.importer.run()
640
641 assert self.lib.items().get().title == "Applied Track 1"
642 assert not self.lib.albums()
643
644 def test_apply_tracks_adds_singleton_path(self):
645 self.importer.add_choice(importer.Action.TRACKS)
646 self.importer.add_choice(importer.Action.APPLY)
647 self.importer.add_choice(importer.Action.APPLY)
648 self.importer.run()
649
650 assert (self.lib_path / "singletons" / "Applied Track 1.mp3").exists()
651
652
653 class ImportRescanTest(AutotagImportTestCase):
654 """Test the Rescan directory action.
655
656 Directory mutations must land when the first prompt is answered, not
657 before ``run()`` -- an edit made earlier would be visible to the
658 initial scan too and wouldn't exercise rescanning. Hence
659 ``_run_with_cleanup_before_first_prompt``.
660 """
661
662 def setUp(self):
663 super().setUp()
664 self.album_path = self.prepare_album_for_import(2)[0].parent
665 self.setup_importer()
666
667 def _run_with_cleanup_before_first_prompt(self, cleanup):
668 """Run the importer, calling `cleanup` as the first prompt is
669 answered -- the user editing the directory while paused there.
670 """
671 original_choose_match = self.importer.choose_match
672 state = {"done": False}
673
674 def choose_match_and_cleanup(task):
675 if not state["done"]:
676 state["done"] = True
677 cleanup()
678 return original_choose_match(task)
679
680 with patch.object(
681 self.importer, "choose_match", side_effect=choose_match_and_cleanup
682 ):
683 self.importer.run()
684
685 def test_rescan_picks_up_file_added_after_initial_scan(self):
686 self.importer.add_choice(importer.Action.RESCAN)
687 self.importer.add_choice(importer.Action.APPLY)
688
689 self._run_with_cleanup_before_first_prompt(
690 lambda: self.prepare_track_for_import(3, self.album_path)
691 )
692
693 assert len(self.lib.items()) == 3
694
695 def test_rescan_picks_up_file_removed_after_initial_scan(self):
696 self.importer.add_choice(importer.Action.RESCAN)
697 self.importer.add_choice(importer.Action.APPLY)
698
699 self._run_with_cleanup_before_first_prompt(
700 lambda: (self.album_path / "track_2.mp3").unlink()
701 )
702
703 assert len(self.lib.items()) == 1
704
705 def test_rescan_of_emptied_directory_imports_nothing(self):
706 self.importer.add_choice(importer.Action.RESCAN)
707
708 def cleanup():
709 for track in self.album_path.glob("*.mp3"):
710 track.unlink()
711
712 self._run_with_cleanup_before_first_prompt(cleanup)
713
714 assert not self.lib.items()
715
716 def test_rescan_with_only_unreadable_files_imports_nothing(self):
717 self.importer.add_choice(importer.Action.RESCAN)
718
719 def cleanup():
720 # Directory still has a music file by extension, but it can't
721 # actually be read as an item.
722 for track in self.album_path.glob("*.mp3"):
723 track.unlink()
724 (self.album_path / "track_1.mp3").write_bytes(b"not a real mp3")
725
726 self._run_with_cleanup_before_first_prompt(cleanup)
727
728 assert not self.lib.items()
729
730 def test_rescan_with_multiple_subdirectories_finds_all_albums(self):
731 self.importer.add_choice(importer.Action.RESCAN)
732 self.importer.add_choice(importer.Action.APPLY)
733 self.importer.add_choice(importer.Action.APPLY)
734
735 def cleanup():
736 # Simulate the user splitting the messy directory into two
737 # proper album subdirectories.
738 for track in self.album_path.glob("*.mp3"):
739 track.unlink()
740 self.prepare_album_for_import(2, album_path=self.album_path / "one")
741 self.prepare_album_for_import(2, album_path=self.album_path / "two")
742
743 self._run_with_cleanup_before_first_prompt(cleanup)
744
745 assert len(self.lib.albums()) == 2
746
747 def test_rescan_of_multidisc_album_does_not_duplicate_tasks(self):
748 """`task.paths` for a multi-disc album holds the album root and
749 each disc subdirectory. Rescanning must not walk each
750 independently -- that produced three tasks for a two-disc album.
751 """
752 for track in self.album_path.glob("*.mp3"):
753 track.unlink()
754 self.prepare_album_for_import(1, album_path=self.album_path / "CD1")
755 self.prepare_album_for_import(1, album_path=self.album_path / "CD2")
756 self.setup_importer()
757 self.importer.add_choice(importer.Action.RESCAN)
758 self.importer.add_choice(importer.Action.APPLY)
759
760 self._run_with_cleanup_before_first_prompt(lambda: None)
761
762 assert len(self.lib.albums()) == 1
763 assert len(self.lib.items()) == 2
764
765 def test_rescan_preserves_multidisc_album_grouping(self):
766 for track in self.album_path.glob("*.mp3"):
767 track.unlink()
768 self.prepare_album_for_import(1, album_path=self.album_path / "CD1")
769 self.prepare_album_for_import(1, album_path=self.album_path / "CD2")
770 self.importer.add_choice(importer.Action.RESCAN)
771 self.importer.add_choice(importer.Action.APPLY)
772 self.importer.add_choice(importer.Action.APPLY)
773
774 self._run_with_cleanup_before_first_prompt(lambda: None)
775
776 assert len(self.lib.albums()) == 1
777
778 def test_rescan_preserves_flat_album_grouping(self):
779 self.prepare_album_for_import(2, album_id=2)
780 self.setup_importer(flat=True)
781 self.importer.add_choice(importer.Action.RESCAN)
782 self.importer.add_choice(importer.Action.APPLY)
783 self.importer.add_choice(importer.Action.APPLY)
784
785 self._run_with_cleanup_before_first_prompt(lambda: None)
786
787 assert len(self.lib.albums()) == 1
788
789 def test_rescan_of_single_file_import(self):
790 """When the import path is a single file, rescanning must still
791 find it (walking a file with `albums_in_dir` finds no music).
792 """
793 track_path = self.prepare_album_for_import(1)[0]
794 self.setup_importer(import_dir=track_path)
795 self.importer.add_choice(importer.Action.RESCAN)
796 self.importer.add_choice(importer.Action.APPLY)
797
798 self._run_with_cleanup_before_first_prompt(lambda: None)
799
800 assert len(self.lib.items()) == 1
801
802 def test_rescan_preserves_toppath_for_move_pruning(self):
803 """Rescanned tasks must keep the original `toppath`. Pruning
804 stops at `toppath`, so using the album directory itself would
805 leave it behind, empty and un-pruned, after a move.
806 """
807 self.setup_importer(move=True)
808 self.importer.add_choice(importer.Action.RESCAN)
809 self.importer.add_choice(importer.Action.APPLY)
810
811 self._run_with_cleanup_before_first_prompt(lambda: None)
812
813 assert not self.album_path.exists()
814
815 def test_rescan_preserves_toppath_for_resume_state(self):
816 """Rescanned tasks must keep the original `toppath`. Resume
817 progress is keyed by `toppath`, so using the album directory
818 itself would leave stale, never-reset progress behind.
819 """
820 self.setup_importer(resume=True)
821 self.importer.add_choice(importer.Action.RESCAN)
822 self.importer.add_choice(importer.Action.APPLY)
823
824 self._run_with_cleanup_before_first_prompt(lambda: None)
825
826 # A completed import resets progress for its toppath at the end.
827 assert not ImportState().tagprogress
828
829 def test_rescan_of_sibling_multidisc_album_does_not_duplicate_tasks(self):
830 """Sibling disc directories with no wrapping album directory can
831 only be reconstructed by walking their shared parent, which also
832 finds an unrelated sibling album. The rescan must regroup the
833 discs into one task and leave the sibling alone.
834 """
835 for track in self.album_path.glob("*.mp3"):
836 track.unlink()
837 self.album_path.rmdir()
838 self.prepare_album_for_import(
839 1, album_path=self.import_path / "Set Disc 1"
840 )
841 self.prepare_album_for_import(
842 1, album_path=self.import_path / "Set Disc 2"
843 )
844 self.prepare_album_for_import(
845 1, album_path=self.import_path / "Other Album"
846 )
847 self.setup_importer()
848
849 # "Other Album" sorts first; leave it as-is, then no-op rescan
850 # the two-disc album.
851 self.importer.add_choice(importer.Action.ASIS)
852 self.importer.add_choice(importer.Action.RESCAN)
853 self.importer.add_choice(importer.Action.APPLY)
854
855 self._run_with_cleanup_before_first_prompt(lambda: None)
856
857 albums = self.lib.albums()
858 assert len(albums) == 2
859 assert sorted(len(list(a.items())) for a in albums) == [1, 2]
860
861 def test_rescan_of_normal_album_scans_only_its_own_directory(self):
862 """A plain album under a larger toppath must be rediscovered
863 from its own directory, not from `toppath` -- otherwise every
864 rescan walks far more of the filesystem than necessary.
865 """
866 self.importer.add_choice(importer.Action.RESCAN)
867 self.importer.add_choice(importer.Action.APPLY)
868
869 with patch(
870 "beets.importer.stages.ImportTaskFactory", wraps=ImportTaskFactory
871 ) as mock_factory:
872 self._run_with_cleanup_before_first_prompt(lambda: None)
873
874 scanned_toppaths = [
875 call.args[0] for call in mock_factory.call_args_list
876 ]
877 album_path_bytes = os.fsencode(str(self.album_path))
878 import_path_bytes = os.fsencode(str(self.import_path))
879
880 # Discovery is scoped to the album's own directory; `toppath` is
881 # only touched by the initial scan and the task-emitting factory
882 # (see `rescan_tasks`), never by a discovery walk.
883 assert scanned_toppaths.count(album_path_bytes) == 1
884 assert scanned_toppaths.count(import_path_bytes) == 2
885
886
887 class TestRescanChoiceAvailability(
888 TerminalImportMixin, PluginMixin, AutotagImportHelper
889 ):
890 """The "Rescan directory" choice must not be offered for tasks with
891 no directory scope to rescan: "Group albums" output, toppath-less
892 query tasks, singletons.
893 """
894
895 @pytest.fixture(autouse=True)
896 def setup_prompt_choice(self, io):
897 self.prepare_album_for_import(2)
898 self.setup_importer()
899 self.input_options_patcher = patch(
900 "beets.ui.input_options", side_effect=ui.input_options
901 )
902 self.mock_input_options = self.input_options_patcher.start()
903 yield
904 self.input_options_patcher.stop()
905
906 def test_rescan_choice_withheld_after_group_albums(self):
907 self.importer.add_choice(importer.Action.ALBUMS)
908 self.importer.add_choice(importer.Action.SKIP)
909 self.importer.run()
910
911 assert self.mock_input_options.call_count >= 2
912 first_opts, second_opts = (
913 call.args[0] for call in self.mock_input_options.call_args_list[:2]
914 )
915 assert "Rescan directory" in first_opts
916 assert "Rescan directory" not in second_opts
917
918 def test_rescan_choice_forced_by_plugin_on_singleton_task_is_ignored(self):
919 """A singleton task's `paths` is a single item file, not an
920 album directory. A plugin forcing Rescan there must not wrap it
921 back into a mismatched album-style task.
922 """
923
924 class ForceRescanPlugin(plugins.BeetsPlugin):
925 def __init__(self):
926 super().__init__()
927 self.register_listener("import_task_choice", self.force_rescan)
928
929 def force_rescan(self, session, task):
930 if not task.is_album:
931 task.choice_flag = importer.Action.RESCAN
932
933 self.register_plugin(ForceRescanPlugin)
934 self.importer.add_choice(importer.Action.TRACKS)
935 self.importer.run()
936
937 assert not self.lib.items()
938
939 def test_rescan_choice_forced_by_plugin_on_grouped_task_is_ignored(self):
940 """A plugin forcing Rescan onto a Group-albums task must be
941 ignored (falling back to Skip) rather than misbehave.
942 """
943
944 class ForceRescanPlugin(plugins.BeetsPlugin):
945 def __init__(self):
946 super().__init__()
947 self.register_listener("import_task_choice", self.force_rescan)
948
949 def force_rescan(self, session, task):
950 if task.is_grouped:
951 task.choice_flag = importer.Action.RESCAN
952
953 self.register_plugin(ForceRescanPlugin)
954 self.importer.add_choice(importer.Action.ALBUMS)
955 self.importer.run()
956
957 assert not self.lib.albums()
958
959 def test_rescan_choice_forced_by_plugin_on_toppathless_task_is_ignored(
960 self,
961 ):
962 """`task.toppath` is None for library-query tasks (`beet import
963 -L`). A plugin forcing Rescan there must not reach
964 `rescan_tasks`'s `assert task.toppath is not None`.
965 """
966
967 class ForceRescanPlugin(plugins.BeetsPlugin):
968 def __init__(self):
969 super().__init__()
970 self.register_listener("import_task_choice", self.force_rescan)
971
972 def force_rescan(self, session, task):
973 task.choice_flag = importer.Action.RESCAN
974
975 # Get an album into the library first, via the normal importer.
976 self.importer.add_choice(importer.Action.ASIS)
977 self.importer.run()
978 assert len(self.lib.albums()) == 1
979
980 self.register_plugin(ForceRescanPlugin)
981
982 query_session = TerminalImportSessionFixture(
983 self.lib,
984 loghandler=None,
985 query="album:'Tag Album'",
986 io=self.io,
987 paths=None,
988 )
989 query_session.default_choice = importer.Action.APPLY
990
991 query_session.run() # Must not raise.
992
993 assert len(self.lib.albums()) == 1
994
995
996 class ImportCompilationTest(AutotagImportTestCase):
997 """Test ASIS import of a folder containing tracks with different artists."""
998
999 def setUp(self):
1000 super().setUp()
1001 self.prepare_album_for_import(3)
1002 self.setup_importer()
1003
1004 def test_asis_homogenous_sets_albumartist(self):
1005 self.importer.add_choice(importer.Action.ASIS)
1006 self.importer.run()
1007 assert self.lib.albums().get().albumartist == "Tag Artist"
1008 for item in self.lib.items():
1009 assert item.albumartist == "Tag Artist"
1010
1011 def test_asis_heterogenous_sets_various_albumartist(self):
1012 self.import_media[0].artist = "Other Artist"
1013 self.import_media[0].save()
1014 self.import_media[1].artist = "Another Artist"
1015 self.import_media[1].save()
1016
1017 self.importer.add_choice(importer.Action.ASIS)
1018 self.importer.run()
1019 assert self.lib.albums().get().albumartist == "Various Artists"
1020 for item in self.lib.items():
1021 assert item.albumartist == "Various Artists"
1022
1023 def test_asis_heterogenous_sets_compilation(self):
1024 self.import_media[0].artist = "Other Artist"
1025 self.import_media[0].save()
1026 self.import_media[1].artist = "Another Artist"
1027 self.import_media[1].save()
1028
1029 self.importer.add_choice(importer.Action.ASIS)
1030 self.importer.run()
1031 for item in self.lib.items():
1032 assert item.comp
1033
1034 def test_asis_sets_majority_albumartist(self):
1035 self.import_media[0].artist = "Other Artist"
1036 self.import_media[0].save()
1037 self.import_media[1].artist = "Other Artist"
1038 self.import_media[1].save()
1039
1040 self.importer.add_choice(importer.Action.ASIS)
1041 self.importer.run()
1042 assert self.lib.albums().get().albumartist == "Other Artist"
1043 for item in self.lib.items():
1044 assert item.albumartist == "Other Artist"
1045
1046 def test_asis_albumartist_tag_sets_albumartist(self):
1047 self.import_media[0].artist = "Other Artist"
1048 self.import_media[1].artist = "Another Artist"
1049 for mediafile in self.import_media:
1050 mediafile.albumartist = "Album Artist"
1051 mediafile.mb_albumartistid = "Album Artist ID"
1052 mediafile.save()
1053
1054 self.importer.add_choice(importer.Action.ASIS)
1055 self.importer.run()
1056 assert self.lib.albums().get().albumartist == "Album Artist"
1057 assert self.lib.albums().get().mb_albumartistid == "Album Artist ID"
1058 for item in self.lib.items():
1059 assert item.albumartist == "Album Artist"
1060 assert item.mb_albumartistid == "Album Artist ID"
1061
1062 def test_asis_albumartists_tag_sets_multi_albumartists(self):
1063 self.import_media[0].artist = "Other Artist"
1064 self.import_media[0].artists = ["Other Artist", "Other Artist 2"]
1065 self.import_media[1].artist = "Another Artist"
1066 self.import_media[1].artists = ["Another Artist", "Another Artist 2"]
1067 for mediafile in self.import_media:
1068 mediafile.albumartist = "Album Artist"
1069 mediafile.albumartists = ["Album Artist 1", "Album Artist 2"]
1070 mediafile.mb_albumartistid = "Album Artist ID"
1071 mediafile.save()
1072
1073 self.importer.add_choice(importer.Action.ASIS)
1074 self.importer.run()
1075 assert self.lib.albums().get().albumartist == "Album Artist"
1076 assert self.lib.albums().get().albumartists == [
1077 "Album Artist 1",
1078 "Album Artist 2",
1079 ]
1080 assert self.lib.albums().get().mb_albumartistid == "Album Artist ID"
1081
1082 # Make sure both custom media items get tested
1083 asserted_multi_artists_0 = False
1084 asserted_multi_artists_1 = False
1085 for item in self.lib.items():
1086 assert item.albumartist == "Album Artist"
1087 assert item.albumartists == ["Album Artist 1", "Album Artist 2"]
1088 assert item.mb_albumartistid == "Album Artist ID"
1089
1090 if item.artist == "Other Artist":
1091 asserted_multi_artists_0 = True
1092 assert item.artists == ["Other Artist", "Other Artist 2"]
1093 if item.artist == "Another Artist":
1094 asserted_multi_artists_1 = True
1095 assert item.artists == ["Another Artist", "Another Artist 2"]
1096
1097 assert asserted_multi_artists_0
1098 assert asserted_multi_artists_1
1099
1100
1101 class ImportExistingTest(PathsMixin, AutotagImportTestCase):
1102 """Test importing files that are already in the library directory."""
1103
1104 def setUp(self):
1105 super().setUp()
1106 self.prepare_album_for_import(1)
1107
1108 self.reimporter = self.setup_importer(import_dir=self.lib_path)
1109 self.importer = self.setup_importer()
1110
1111 def tearDown(self):
1112 super().tearDown()
1113 self.matcher.restore()
1114
1115 @cached_property
1116 def applied_track_path(self) -> Path:
1117 return Path(str(self.track_lib_path).replace("Tag", "Applied"))
1118
1119 def test_does_not_duplicate_item_nor_album(self):
1120 self.importer.run()
1121 assert len(self.lib.items()) == 1
1122 assert len(self.lib.albums()) == 1
1123
1124 self.reimporter.add_choice(importer.Action.APPLY)
1125 self.reimporter.run()
1126
1127 assert len(self.lib.items()) == 1
1128 assert len(self.lib.albums()) == 1
1129
1130 def test_does_not_duplicate_singleton_track(self):
1131 self.importer.add_choice(importer.Action.TRACKS)
1132 self.importer.add_choice(importer.Action.APPLY)
1133 self.importer.run()
1134 assert len(self.lib.items()) == 1
1135
1136 self.reimporter.add_choice(importer.Action.TRACKS)
1137 self.reimporter.add_choice(importer.Action.APPLY)
1138 self.reimporter.run()
1139 assert len(self.lib.items()) == 1
1140
1141 def test_asis_updates_metadata_and_moves_file(self):
1142 self.importer.run()
1143
1144 medium = MediaFile(self.lib.items().get().path)
1145 medium.title = "New Title"
1146 medium.save()
1147
1148 self.reimporter.add_choice(importer.Action.ASIS)
1149 self.reimporter.run()
1150
1151 assert self.lib.items().get().title == "New Title"
1152 assert not self.applied_track_path.exists()
1153 assert self.applied_track_path.with_name("New Title.mp3").exists()
1154
1155 def test_asis_updated_without_copy_does_not_move_file(self):
1156 self.importer.run()
1157 medium = MediaFile(self.lib.items().get().path)
1158 medium.title = "New Title"
1159 medium.save()
1160
1161 config["import"]["copy"] = False
1162 self.reimporter.add_choice(importer.Action.ASIS)
1163 self.reimporter.run()
1164
1165 assert self.applied_track_path.exists()
1166 assert not self.applied_track_path.with_name("New Title.mp3").exists()
1167
1168 def test_outside_file_is_copied(self):
1169 config["import"]["copy"] = False
1170 self.importer.run()
1171 assert self.lib.items().get().filepath == self.track_import_path
1172
1173 self.reimporter = self.setup_importer()
1174 self.reimporter.add_choice(importer.Action.APPLY)
1175 self.reimporter.run()
1176
1177 assert self.applied_track_path.exists()
1178 assert self.lib.items().get().filepath == self.applied_track_path
1179
1180
1181 class GroupAlbumsImportTest(AutotagImportTestCase):
1182 matching = AutotagStub.NONE
1183
1184 def setUp(self):
1185 super().setUp()
1186 self.prepare_album_for_import(3)
1187 self.setup_importer()
1188
1189 # Split tracks into two albums and use both as-is
1190 self.importer.add_choice(importer.Action.ALBUMS)
1191 self.importer.add_choice(importer.Action.ASIS)
1192 self.importer.add_choice(importer.Action.ASIS)
1193
1194 def test_add_album_for_different_artist_and_different_album(self):
1195 self.import_media[0].artist = "Artist B"
1196 self.import_media[0].album = "Album B"
1197 self.import_media[0].save()
1198
1199 self.importer.run()
1200 albums = {album.album for album in self.lib.albums()}
1201 assert albums == {"Album B", "Tag Album"}
1202
1203 def test_add_album_for_different_artist_and_same_albumartist(self):
1204 self.import_media[0].artist = "Artist B"
1205 self.import_media[0].albumartist = "Album Artist"
1206 self.import_media[0].save()
1207 self.import_media[1].artist = "Artist C"
1208 self.import_media[1].albumartist = "Album Artist"
1209 self.import_media[1].save()
1210
1211 self.importer.run()
1212 artists = {album.albumartist for album in self.lib.albums()}
1213 assert artists == {"Album Artist", "Tag Artist"}
1214
1215 def test_add_album_for_same_artist_and_different_album(self):
1216 self.import_media[0].album = "Album B"
1217 self.import_media[0].save()
1218
1219 self.importer.run()
1220 albums = {album.album for album in self.lib.albums()}
1221 assert albums == {"Album B", "Tag Album"}
1222
1223 def test_add_album_for_same_album_and_different_artist(self):
1224 self.import_media[0].artist = "Artist B"
1225 self.import_media[0].save()
1226
1227 self.importer.run()
1228 artists = {album.albumartist for album in self.lib.albums()}
1229 assert artists == {"Artist B", "Tag Artist"}
1230
1231 def test_incremental(self):
1232 config["import"]["incremental"] = True
1233 self.import_media[0].album = "Album B"
1234 self.import_media[0].save()
1235
1236 self.importer.run()
1237 albums = {album.album for album in self.lib.albums()}
1238 assert albums == {"Album B", "Tag Album"}
1239
1240
1241 class GlobalGroupAlbumsImportTest(GroupAlbumsImportTest):
1242 def setUp(self):
1243 super().setUp()
1244 self.importer.clear_choices()
1245 self.importer.default_choice = importer.Action.ASIS
1246 config["import"]["group_albums"] = True
1247
1248
1249 class ChooseCandidateTest(AutotagImportTestCase):
1250 matching = AutotagStub.BAD
1251
1252 def setUp(self):
1253 super().setUp()
1254 self.prepare_album_for_import(1)
1255 self.setup_importer()
1256
1257 def test_choose_first_candidate(self):
1258 self.importer.add_choice(1)
1259 self.importer.run()
1260 assert self.lib.albums().get().album == "Applied Album M"
1261
1262 def test_choose_second_candidate(self):
1263 self.importer.add_choice(2)
1264 self.importer.run()
1265 assert self.lib.albums().get().album == "Applied Album MM"
1266
1267
1268 class InferAlbumDataTest(unittest.TestCase):
1269 def setUp(self):
1270 super().setUp()
1271
1272 i1 = _common.item()
1273 i2 = _common.item()
1274 i3 = _common.item()
1275 i1.title = "first item"
1276 i2.title = "second item"
1277 i3.title = "third item"
1278 i1.comp = i2.comp = i3.comp = False
1279 i1.albumartist = i2.albumartist = i3.albumartist = ""
1280 i1.mb_albumartistid = i2.mb_albumartistid = i3.mb_albumartistid = ""
1281 self.items = [i1, i2, i3]
1282
1283 self.task = importer.ImportTask(
1284 paths=["a path"], toppath="top path", items=self.items
1285 )
1286
1287 def test_asis_homogenous_single_artist(self):
1288 self.task.set_choice(importer.Action.ASIS)
1289 self.task.align_album_level_fields()
1290 assert not self.items[0].comp
1291 assert self.items[0].albumartist == self.items[2].artist
1292
1293 def test_asis_heterogenous_va(self):
1294 self.items[0].artist = "another artist"
1295 self.items[1].artist = "some other artist"
1296 self.task.set_choice(importer.Action.ASIS)
1297
1298 self.task.align_album_level_fields()
1299
1300 assert self.items[0].comp
1301 assert self.items[0].albumartist == "Various Artists"
1302
1303 def test_asis_comp_applied_to_all_items(self):
1304 self.items[0].artist = "another artist"
1305 self.items[1].artist = "some other artist"
1306 self.task.set_choice(importer.Action.ASIS)
1307
1308 self.task.align_album_level_fields()
1309
1310 for item in self.items:
1311 assert item.comp
1312 assert item.albumartist == "Various Artists"
1313
1314 def test_asis_majority_artist_single_artist(self):
1315 self.items[0].artist = "another artist"
1316 self.task.set_choice(importer.Action.ASIS)
1317
1318 self.task.align_album_level_fields()
1319
1320 assert not self.items[0].comp
1321 assert self.items[0].albumartist == self.items[2].artist
1322
1323 def test_asis_track_albumartist_override(self):
1324 self.items[0].artist = "another artist"
1325 self.items[1].artist = "some other artist"
1326 for item in self.items:
1327 item.albumartist = "some album artist"
1328 item.mb_albumartistid = "some album artist id"
1329 self.task.set_choice(importer.Action.ASIS)
1330
1331 self.task.align_album_level_fields()
1332
1333 assert self.items[0].albumartist == "some album artist"
1334 assert self.items[0].mb_albumartistid == "some album artist id"
1335
1336 def test_apply_gets_artist_and_id(self):
1337 self.task.set_choice(AlbumMatch(Distance(), None, {})) # APPLY
1338
1339 self.task.align_album_level_fields()
1340
1341 assert self.items[0].albumartist == self.items[0].artist
1342 assert self.items[0].mb_albumartistid == self.items[0].mb_artistid
1343
1344 def test_apply_lets_album_values_override(self):
1345 for item in self.items:
1346 item.albumartist = "some album artist"
1347 item.mb_albumartistid = "some album artist id"
1348 self.task.set_choice(AlbumMatch(Distance(), None, {})) # APPLY
1349
1350 self.task.align_album_level_fields()
1351
1352 assert self.items[0].albumartist == "some album artist"
1353 assert self.items[0].mb_albumartistid == "some album artist id"
1354
1355 def test_small_single_artist_album(self):
1356 self.items = [self.items[0]]
1357 self.task.items = self.items
1358 self.task.set_choice(importer.Action.ASIS)
1359 self.task.align_album_level_fields()
1360 assert not self.items[0].comp
1361
1362
1363 def album_candidates_mock(*args, **kwargs):
1364 """Create an AlbumInfo object for testing."""
1365 yield AlbumInfo(
1366 artist="artist",
1367 album="album",
1368 tracks=[TrackInfo(title="new title", track_id="trackid", index=0)],
1369 album_id="albumid",
1370 artist_id="artistid",
1371 flex="flex",
1372 )
1373
1374
1375 @patch(
1376 "beets.metadata_plugins.candidates", Mock(side_effect=album_candidates_mock)
1377 )
1378 class TestImportDuplicateAlbum(PluginMixin, ImportHelper):
1379 plugin = "musicbrainz"
1380
1381 def setup_beets(self):
1382 super().setup_beets()
1383 # Original album
1384 self.add_album_fixture(albumartist="artist", album="album")
1385
1386 # Create import session
1387 self.prepare_album_for_import(1)
1388 self.importer = self.setup_importer(
1389 duplicate_keys={"album": "albumartist album"}
1390 )
1391
1392 def test_remove_duplicate_album(self):
1393 item = self.lib.items().get()
1394 assert item.title == "t\xeftle 0"
1395 assert item.filepath.exists()
1396
1397 self.config["import"]["duplicate_action"] = "remove"
1398 self.importer.run()
1399
1400 assert not item.filepath.exists()
1401 assert len(self.lib.albums()) == 1
1402 assert len(self.lib.items()) == 1
1403 item = self.lib.items().get()
1404 assert item.title == "new title"
1405
1406 def test_remove_duplicate_album_deletes_art(self):
1407 album = self.lib.albums().get()
1408 art_source = _common.RSRC / "abbey.jpg"
1409 album.set_art(art_source)
1410 album.store()
1411 old_artpath = album.art_filepath
1412
1413 assert old_artpath.exists()
1414
1415 self.config["import"]["duplicate_action"] = "remove"
1416 self.importer.run()
1417
1418 assert not old_artpath.exists()
1419 assert len(self.lib.albums()) == 1
1420
1421 def test_no_autotag_removes_duplicate_album(self):
1422 config["import"]["autotag"] = False
1423 album = self.lib.albums().get()
1424 item = self.lib.items().get()
1425 assert item.title == "t\xeftle 0"
1426 assert item.filepath.exists()
1427
1428 # Imported item has the same albumartist and album as the one in the
1429 # library album. We use album metadata (not item metadata) since
1430 # duplicate detection uses album-level fields.
1431 import_file = os.path.join(
1432 self.importer.paths[0], b"album", b"track_1.mp3"
1433 )
1434 import_file = MediaFile(import_file)
1435 import_file.artist = album.albumartist
1436 import_file.albumartist = album.albumartist
1437 import_file.album = album.album
1438 import_file.title = "new title"
1439 import_file.save()
1440
1441 self.config["import"]["duplicate_action"] = "remove"
1442 self.importer.run()
1443
1444 # Old duplicate should be removed, new one imported
1445 assert len(self.lib.albums()) == 1
1446 assert len(self.lib.items()) == 1
1447 # The new item should be in the library
1448 assert self.lib.items().get().title == "new title"
1449
1450 def test_keep_duplicate_album(self):
1451 self.config["import"]["duplicate_action"] = "keep"
1452 self.importer.run()
1453
1454 assert len(self.lib.albums()) == 2
1455 assert len(self.lib.items()) == 2
1456
1457 def test_skip_duplicate_album(self):
1458 item = self.lib.items().get()
1459 assert item.title == "t\xeftle 0"
1460
1461 self.config["import"]["duplicate_action"] = "skip"
1462 self.importer.run()
1463
1464 assert len(self.lib.albums()) == 1
1465 assert len(self.lib.items()) == 1
1466 item = self.lib.items().get()
1467 assert item.title == "t\xeftle 0"
1468
1469 def test_merge_duplicate_album(self):
1470 self.config["import"]["duplicate_action"] = "merge"
1471 self.importer.run()
1472
1473 assert len(self.lib.albums()) == 1
1474
1475 def test_twice_in_import_dir(self):
1476 pytest.skip(reason="write me")
1477
1478 def test_keep_when_extra_key_is_different(self):
1479 config["import"]["duplicate_keys"]["album"] = "albumartist album flex"
1480
1481 item = self.lib.items().get()
1482 import_file = MediaFile(
1483 os.path.join(self.importer.paths[0], b"album", b"track_1.mp3")
1484 )
1485 import_file.artist = item["artist"]
1486 import_file.albumartist = item["artist"]
1487 import_file.album = item["album"]
1488 import_file.title = item["title"]
1489 import_file.flex = "different"
1490
1491 self.config["import"]["duplicate_action"] = "skip"
1492 self.importer.run()
1493
1494 assert len(self.lib.albums()) == 2
1495 assert len(self.lib.items()) == 2
1496
1497 def add_album_fixture(self, **kwargs):
1498 # TODO move this into upstream
1499 album = super().add_album_fixture()
1500 album.update(kwargs)
1501 album.store()
1502 return album
1503
1504
1505 @patch(
1506 "beets.metadata_plugins.candidates", Mock(side_effect=album_candidates_mock)
1507 )
1508 class TestImportDuplicateAlbumThreaded(PluginMixin, ImportHelper):
1509 """Regression test for #6601: threaded merge must propagate context vars."""
1510
1511 plugin = "musicbrainz"
1512 # Each thread gets its own connection; :memory: would give each thread an
1513 # empty DB, so we need a real file that all threads share.
1514 db_on_disk = True
1515
1516 def setup_beets(self):
1517 super().setup_beets()
1518 self.add_album_fixture(albumartist="artist", album="album")
1519 self.prepare_album_for_import(1)
1520 self.importer = self.setup_importer(
1521 duplicate_keys={"album": "albumartist album"}
1522 )
1523
1524 def add_album_fixture(self, **kwargs):
1525 album = super().add_album_fixture()
1526 album.update(kwargs)
1527 album.store()
1528 return album
1529
1530 def test_merge_duplicate_album_threaded(self):
1531 self.config["threaded"] = True
1532 self.config["import"]["duplicate_action"] = "merge"
1533 self.importer.run()
1534
1535 assert len(self.lib.albums()) == 1
1536 for item in self.lib.items():
1537 assert item.filepath.exists(), f"item path not found: {item.path}"
1538
1539 # Without the fix, lost context vars cause relative paths to stay
1540 # unresolved, so items land in different (duplicate) directories.
1541 album_dirs = {item.filepath.parent for item in self.lib.items()}
1542 assert len(album_dirs) == 1, (
1543 f"expected single album dir, got {album_dirs}"
1544 )
1545
1546
1547 def item_candidates_mock(*args, **kwargs):
1548 yield TrackInfo(
1549 artist="artist", title="title", track_id="new trackid", index=0
1550 )
1551
1552
1553 @patch(
1554 "beets.metadata_plugins.item_candidates",
1555 Mock(side_effect=item_candidates_mock),
1556 )
1557 class TestImportDuplicateSingleton(ImportHelper):
1558 def setup_beets(self):
1559 super().setup_beets()
1560 # Original file in library
1561 self.add_item_fixture(
1562 artist="artist", title="title", mb_trackid="old trackid"
1563 )
1564
1565 # Import session
1566 self.prepare_album_for_import(1)
1567 self.importer = self.setup_singleton_importer(
1568 duplicate_keys={"album": "artist title"}
1569 )
1570
1571 def test_remove_duplicate(self):
1572 item = self.lib.items().get()
1573 assert item.mb_trackid == "old trackid"
1574 assert item.filepath.exists()
1575
1576 self.config["import"]["duplicate_action"] = "remove"
1577 self.importer.run()
1578
1579 assert not item.filepath.exists()
1580 assert len(self.lib.items()) == 1
1581 item = self.lib.items().get()
1582 assert item.mb_trackid == "new trackid"
1583
1584 def test_keep_duplicate(self):
1585 assert len(self.lib.items()) == 1
1586
1587 self.config["import"]["duplicate_action"] = "keep"
1588 self.importer.run()
1589
1590 assert len(self.lib.items()) == 2
1591
1592 def test_skip_duplicate(self):
1593 item = self.lib.items().get()
1594 assert item.mb_trackid == "old trackid"
1595
1596 self.config["import"]["duplicate_action"] = "skip"
1597 self.importer.run()
1598
1599 assert len(self.lib.items()) == 1
1600 item = self.lib.items().get()
1601 assert item.mb_trackid == "old trackid"
1602
1603 def test_keep_when_extra_key_is_different(self):
1604 config["import"]["duplicate_keys"]["item"] = "artist title flex"
1605 item = self.lib.items().get()
1606 item.flex = "different"
1607 item.store()
1608 assert len(self.lib.items()) == 1
1609
1610 self.config["import"]["duplicate_action"] = "skip"
1611 self.importer.run()
1612
1613 assert len(self.lib.items()) == 2
1614
1615 def test_no_autotag_removes_duplicate_singleton(self):
1616 config["import"]["autotag"] = False
1617 item = self.lib.items().get()
1618 assert item.mb_trackid == "old trackid"
1619 assert item.filepath.exists()
1620
1621 # Imported item has the same artist and title as the one in the
1622 # library. We use item metadata since duplicate detection uses
1623 # item-level fields for singletons.
1624 import_file = os.path.join(
1625 self.importer.paths[0], b"album", b"track_1.mp3"
1626 )
1627 import_file = MediaFile(import_file)
1628 import_file.artist = item.artist
1629 import_file.title = item.title
1630 import_file.mb_trackid = "new trackid"
1631 import_file.save()
1632
1633 self.config["import"]["duplicate_action"] = "remove"
1634 self.importer.run()
1635
1636 # Old duplicate should be removed, new one imported
1637 assert len(self.lib.items()) == 1
1638 # The new item should be in the library
1639 assert self.lib.items().get().mb_trackid == "new trackid"
1640
1641 def test_twice_in_import_dir(self):
1642 pytest.skip(reason="write me")
1643
1644 def add_item_fixture(self, **kwargs):
1645 # Move this to TestHelper
1646 item = self.add_item_fixtures()[0]
1647 item.update(kwargs)
1648 item.store()
1649 return item
1650
1651
1652 @contextmanager
1653 def bitrate_overrides(bitrates_by_title):
1654 """Force specific per-title bitrates on newly-read import items.
1655
1656 The test mp3 fixtures all share one real bitrate, so this patches
1657 `ImportTaskFactory.read_item` to simulate different-quality
1658 encodes without needing distinct binary fixtures.
1659 """
1660 original = ImportTaskFactory.read_item
1661
1662 def patched(self, path):
1663 item = original(self, path)
1664 if item is not None and item.title in bitrates_by_title:
1665 item.bitrate = bitrates_by_title[item.title]
1666 return item
1667
1668 with patch.object(ImportTaskFactory, "read_item", patched):
1669 yield
1670
1671
1672 DUP_KEYS = ["artist", "title"]
1673
1674
1675 def test_duplicate_action_prompt_options():
1676 assert importer.DuplicateAction.strict_options() == [
1677 "Skip new",
1678 "Merge all",
1679 "Remove old",
1680 "Keep all",
1681 "Upgrade",
1682 ]
1683
1684
1685 class ResolveUpgradeTest(unittest.TestCase):
1686 """Unit tests for `resolve_upgrade`, the per-track decision
1687 algorithm behind `duplicate_action: upgrade`.
1688 """
1689
1690 def _item(self, artist="artist", title="title", bitrate=128000):
1691 return Item(artist=artist, title=title, bitrate=bitrate)
1692
1693 def test_matched_better_bitrate_replaces_old(self):
1694 old = self._item(bitrate=128000)
1695 new = self._item(bitrate=320000)
1696 kept, superseded = resolve_upgrade([new], [old], DUP_KEYS)
1697 assert kept == [new]
1698 assert superseded == [old]
1699
1700 def test_matched_worse_bitrate_keeps_old(self):
1701 old = self._item(bitrate=320000)
1702 new = self._item(bitrate=128000)
1703 kept, superseded = resolve_upgrade([new], [old], DUP_KEYS)
1704 assert kept == []
1705 assert superseded == []
1706
1707 def test_matched_equal_bitrate_keeps_old(self):
1708 old = self._item(bitrate=128000)
1709 new = self._item(bitrate=128000)
1710 kept, superseded = resolve_upgrade([new], [old], DUP_KEYS)
1711 assert kept == []
1712 assert superseded == []
1713
1714 def test_unmatched_new_item_always_kept(self):
1715 old = self._item(title="old title", bitrate=320000)
1716 new = self._item(title="new title", bitrate=64000)
1717 kept, superseded = resolve_upgrade([new], [old], DUP_KEYS)
1718 assert kept == [new]
1719 assert superseded == []
1720
1721 def test_mixed_batch(self):
1722 old_a = self._item(title="A", bitrate=128000)
1723 old_d = self._item(title="D", bitrate=128000)
1724 new_a = self._item(title="A", bitrate=320000) # upgrade, wins
1725 new_b = self._item(title="B", bitrate=64000) # no old counterpart
1726 kept, superseded = resolve_upgrade(
1727 [new_a, new_b], [old_a, old_d], DUP_KEYS
1728 )
1729 assert kept == [new_a, new_b]
1730 assert superseded == [old_a]
1731
1732 def test_duplicate_keys_all_old_superseded_when_new_is_best(self):
1733 """When multiple old items share a key and the new item beats
1734 all of them, every old copy should be superseded."""
1735 old_a = self._item(bitrate=128000)
1736 old_b = self._item(bitrate=96000)
1737 new = self._item(bitrate=320000)
1738 kept, superseded = resolve_upgrade([new], [old_a, old_b], DUP_KEYS)
1739 assert kept == [new]
1740 assert sorted(superseded, key=lambda i: i.bitrate) == [old_b, old_a]
1741
1742 def test_duplicate_keys_rejected_when_new_is_not_best(self):
1743 """When an old item with the same key has bitrate >= the new
1744 item, the new item should be dropped to prevent a downgrade."""
1745 old_a = self._item(bitrate=128000)
1746 old_b = self._item(bitrate=320000)
1747 new = self._item(bitrate=256000)
1748 kept, superseded = resolve_upgrade([new], [old_a, old_b], DUP_KEYS)
1749 assert kept == []
1750 assert superseded == []
1751
1752
1753 class ResolveUpgradeTargetTest(TestHelper):
1754 """Unit tests for `resolve_upgrade_target`: when `found_duplicates`
1755 implicates more than one distinct old album, only the one it
1756 overlaps with the most should be treated as the upgrade target,
1757 and every other candidate album must be left untouched.
1758
1759 Regression coverage for
1760 https://github.com/beetbox/beets/pull/6842#discussion_r3635292074:
1761 comparing new tracks against the *best* old candidate pooled
1762 across every duplicate album could silently attribute a
1763 supersession to the wrong album (or decline an upgrade that only
1764 looked bad because of an unrelated album's better copy).
1765 """
1766
1767 def setUp(self):
1768 self.setup_beets()
1769
1770 def tearDown(self):
1771 self.teardown_beets()
1772
1773 def _item(self, title, bitrate):
1774 return self.add_item_fixture(
1775 artist="Tag Artist",
1776 albumartist="Tag Artist",
1777 album="Tag Album",
1778 title=title,
1779 bitrate=bitrate,
1780 )
1781
1782 def test_targets_album_with_most_overlap(self):
1783 # Album A: a high-bitrate track (never worth upgrading) plus a
1784 # low-bitrate one; Album B: both tracks low-bitrate.
1785 a_t1 = self._item("T1", 1400000)
1786 a_t2 = self._item("T2", 320000)
1787 album_a = self.lib.add_album([a_t1, a_t2])
1788
1789 b_t1 = self._item("T1", 320000)
1790 b_t2 = self._item("T2", 320000)
1791 album_b = self.lib.add_album([b_t1, b_t2])
1792
1793 new_t1 = Item(artist="Tag Artist", title="T1", bitrate=900000)
1794 new_t2 = Item(artist="Tag Artist", title="T2", bitrate=900000)
1795
1796 kept, superseded, old_album_ids = resolve_upgrade_target(
1797 [new_t1, new_t2], [album_a, album_b], DUP_KEYS
1798 )
1799
1800 # Album B overlaps on both tracks and is chosen as the sole
1801 # target; Album A (and its higher-bitrate T1) is never touched.
1802 assert old_album_ids == [album_b.id]
1803 assert kept == [new_t1, new_t2]
1804 assert superseded == [b_t1, b_t2]
1805 assert a_t1 not in superseded
1806 assert a_t2 not in superseded
1807
1808 def test_single_duplicate_album_behaves_as_before(self):
1809 old_t1 = self._item("T1", 128000)
1810 album = self.lib.add_album([old_t1])
1811 new_t1 = Item(artist="Tag Artist", title="T1", bitrate=320000)
1812
1813 kept, superseded, old_album_ids = resolve_upgrade_target(
1814 [new_t1], [album], DUP_KEYS
1815 )
1816
1817 assert kept == [new_t1]
1818 assert superseded == [old_t1]
1819 assert old_album_ids == [album.id]
1820
1821
1822 @patch(
1823 "beets.metadata_plugins.candidates", Mock(side_effect=album_candidates_mock)
1824 )
1825 class TestImportDuplicateAlbumUpgrade(PluginMixin, ImportHelper):
1826 """Album-level `duplicate_action: upgrade`, full track-for-track
1827 overlap (the whole album is either replaced or left alone).
1828 """
1829
1830 plugin = "musicbrainz"
1831
1832 def setup_beets(self):
1833 super().setup_beets()
1834 # Existing album with one track, matching what the incoming
1835 # import will be tagged as (see `album_candidates_mock`).
1836 self.old_item = self.add_item_fixture(
1837 artist="artist",
1838 albumartist="artist",
1839 album="album",
1840 title="new title",
1841 mb_trackid="old trackid",
1842 bitrate=128000,
1843 )
1844 self.old_album = self.lib.add_album([self.old_item])
1845
1846 self.prepare_album_for_import(1)
1847 self.importer = self.setup_importer(
1848 duplicate_keys={"album": "albumartist album"}
1849 )
1850 self.config["import"]["duplicate_action"] = "upgrade"
1851
1852 def test_upgrade_replaces_lower_quality_duplicate(self):
1853 with bitrate_overrides({"Tag Track 1": 320000}):
1854 self.importer.run()
1855
1856 assert len(self.lib.albums()) == 1
1857 assert len(self.lib.items()) == 1
1858 item = self.lib.items().get()
1859 assert item.title == "new title"
1860 assert item.bitrate == 320000
1861 assert self.lib.get_item(self.old_item.id) is None
1862
1863 def test_upgrade_skips_lower_quality_new_copy(self):
1864 with bitrate_overrides({"Tag Track 1": 64000}):
1865 self.importer.run()
1866
1867 assert len(self.lib.albums()) == 1
1868 assert len(self.lib.items()) == 1
1869 item = self.lib.items().get()
1870 assert item.id == self.old_item.id
1871 assert item.bitrate == 128000
1872 assert self.old_item.filepath.exists()
1873
1874
1875 class TestImportDuplicateAlbumUpgradeMixed(ImportHelper):
1876 """Album-level `duplicate_action: upgrade` where the new import
1877 mixes a genuine quality upgrade of one existing track with tracks
1878 that have no old counterpart at all (e.g. filling in a
1879 previously-incomplete album). The surviving old tracks and the
1880 kept new tracks must end up in the same album.
1881 """
1882
1883 def setup_beets(self):
1884 super().setup_beets()
1885 self.old_track1 = self.add_item_fixture(
1886 artist="Tag Artist",
1887 albumartist="Tag Artist",
1888 album="Tag Album",
1889 title="Tag Track 1",
1890 bitrate=64000,
1891 )
1892 self.old_track4 = self.add_item_fixture(
1893 artist="Tag Artist",
1894 albumartist="Tag Artist",
1895 album="Tag Album",
1896 title="Tag Track 4",
1897 bitrate=64000,
1898 )
1899 self.old_album = self.lib.add_album([self.old_track1, self.old_track4])
1900
1901 self.prepare_album_for_import(3) # Tag Track 1, 2, 3
1902 self.importer = self.setup_importer(autotag=False)
1903 self.config["import"]["duplicate_action"] = "upgrade"
1904
1905 def test_upgrade_and_new_tracks_join_existing_album(self):
1906 with bitrate_overrides({"Tag Track 1": 320000}):
1907 self.importer.run()
1908
1909 assert len(self.lib.albums()) == 1
1910 items = list(self.lib.items())
1911 assert len(items) == 4
1912 by_title = {i.title: i for i in items}
1913 assert by_title["Tag Track 1"].bitrate == 320000
1914 assert by_title["Tag Track 4"].bitrate == 64000
1915 assert "Tag Track 2" in by_title
1916 assert "Tag Track 3" in by_title
1917 assert all(i.album_id == self.old_album.id for i in items)
1918 assert self.lib.get_item(self.old_track1.id) is None
1919 # Untouched old track keeps its original row and file.
1920 assert by_title["Tag Track 4"].id == self.old_track4.id
1921 assert self.old_track4.filepath.exists()
1922
1923 def test_rejected_upgrade_still_adds_new_tracks(self):
1924 with bitrate_overrides({"Tag Track 1": 40000}):
1925 self.importer.run()
1926
1927 assert len(self.lib.albums()) == 1
1928 items = list(self.lib.items())
1929 assert len(items) == 4
1930 by_title = {i.title: i for i in items}
1931 assert by_title["Tag Track 1"].id == self.old_track1.id
1932 assert by_title["Tag Track 1"].bitrate == 64000
1933 assert "Tag Track 2" in by_title
1934 assert "Tag Track 3" in by_title
1935 assert all(i.album_id == self.old_album.id for i in items)
1936 assert self.old_track1.filepath.exists()
1937
1938
1939 @patch(
1940 "beets.metadata_plugins.item_candidates",
1941 Mock(side_effect=item_candidates_mock),
1942 )
1943 class TestImportDuplicateSingletonUpgrade(ImportHelper):
1944 def setup_beets(self):
1945 super().setup_beets()
1946 self.old_item = self.add_item_fixture(
1947 artist="artist",
1948 title="title",
1949 mb_trackid="old trackid",
1950 bitrate=128000,
1951 )
1952
1953 self.prepare_album_for_import(1)
1954 self.importer = self.setup_singleton_importer()
1955 self.config["import"]["duplicate_action"] = "upgrade"
1956
1957 def test_upgrade_replaces_lower_quality_duplicate(self):
1958 with bitrate_overrides({"Tag Track 1": 320000}):
1959 self.importer.run()
1960
1961 assert len(self.lib.items()) == 1
1962 item = self.lib.items().get()
1963 assert item.mb_trackid == "new trackid"
1964 assert item.bitrate == 320000
1965 assert self.lib.get_item(self.old_item.id) is None
1966
1967 def test_upgrade_skips_lower_quality_new_copy(self):
1968 with bitrate_overrides({"Tag Track 1": 64000}):
1969 self.importer.run()
1970
1971 assert len(self.lib.items()) == 1
1972 item = self.lib.items().get()
1973 assert item.id == self.old_item.id
1974 assert item.mb_trackid == "old trackid"
1975 assert self.old_item.filepath.exists()
1976
1977
1978 class TagLogTest(TestHelper):
1979 def test_tag_log_line(self):
1980 sio = StringIO()
1981 handler = logging.StreamHandler(sio)
1982 session = _common.import_session(self.lib, loghandler=handler)
1983 session.tag_log("status", "path")
1984 assert "status path" in sio.getvalue()
1985
1986 def test_tag_log_unicode(self):
1987 sio = StringIO()
1988 handler = logging.StreamHandler(sio)
1989 session = _common.import_session(self.lib, loghandler=handler)
1990 session.tag_log("status", "caf\xe9") # send unicode
1991 assert "status caf\xe9" in sio.getvalue()
1992
1993
1994 class TestResumeImport(ImportHelper):
1995 @patch("beets.plugins.send")
1996 def test_resume_album(self, plugins_send):
1997 self.prepare_albums_for_import(2)
1998 self.importer = self.setup_importer(autotag=False, resume=True)
1999
2000 # Aborts import after one album. This also ensures that we skip
2001 # the first album in the second try.
2002 def raise_exception(event, **kwargs):
2003 if event == "album_imported":
2004 raise importer.ImportAbortError
2005
2006 plugins_send.side_effect = raise_exception
2007
2008 self.importer.run()
2009 assert len(self.lib.albums()) == 1
2010 assert self.lib.albums("album:'Album 1'").get() is not None
2011
2012 self.importer.run()
2013 assert len(self.lib.albums()) == 2
2014 assert self.lib.albums("album:'Album 2'").get() is not None
2015
2016 @patch("beets.plugins.send")
2017 def test_resume_singleton(self, plugins_send):
2018 self.prepare_album_for_import(2)
2019 self.importer = self.setup_singleton_importer(
2020 autotag=False, resume=True
2021 )
2022
2023 # Aborts import after one track. This also ensures that we skip
2024 # the first album in the second try.
2025 def raise_exception(event, **kwargs):
2026 if event == "item_imported":
2027 raise importer.ImportAbortError
2028
2029 plugins_send.side_effect = raise_exception
2030
2031 self.importer.run()
2032 assert len(self.lib.items()) == 1
2033 assert self.lib.items("title:'Track 1'").get() is not None
2034
2035 self.importer.run()
2036 assert len(self.lib.items()) == 2
2037 assert self.lib.items("title:'Track 1'").get() is not None
2038
2039
2040 class TestIncrementalImport(AsIsImporterMixin, ImportHelper):
2041 def test_incremental_album(self):
2042 importer = self.run_asis_importer(incremental=True)
2043
2044 # Change album name so the original file would be imported again
2045 # if incremental was off.
2046 album = self.lib.albums().get()
2047 album["album"] = "edited album"
2048 album.store()
2049
2050 importer.run()
2051 assert len(self.lib.albums()) == 2
2052
2053 def test_incremental_item(self):
2054 importer = self.run_asis_importer(incremental=True, singletons=True)
2055
2056 # Change track name so the original file would be imported again
2057 # if incremental was off.
2058 item = self.lib.items().get()
2059 item["artist"] = "edited artist"
2060 item.store()
2061
2062 importer.run()
2063 assert len(self.lib.items()) == 2
2064
2065 def test_invalid_state_file(self):
2066 self.config["statefile"].as_path().write_bytes(b"000")
2067 self.run_asis_importer(incremental=True)
2068 assert len(self.lib.albums()) == 1
2069
2070
2071 def _mkmp3(path):
2072 shutil.copyfile(_common.RSRC / "min.mp3", path)
2073
2074
2075 class AlbumsInDirTest(BeetsTestCase):
2076 def setUp(self):
2077 super().setUp()
2078
2079 # create a directory structure for testing
2080 base = (self.temp_path / "tempdir").resolve()
2081 base.mkdir()
2082
2083 album1_dir = base / "album1"
2084 album2_dir = base / "album2"
2085 album3_dir = base / "more" / "album3"
2086 album4_dir = base / "more" / "album4"
2087 album1_dir.mkdir()
2088 album2_dir.mkdir()
2089 album3_dir.mkdir(parents=True)
2090 album4_dir.mkdir(parents=True)
2091
2092 _mkmp3(album1_dir / "album1song1.mp3")
2093 _mkmp3(album1_dir / "album1song2.mp3")
2094 _mkmp3(album2_dir / "album2song.mp3")
2095 _mkmp3(album3_dir / "album3song.mp3")
2096 _mkmp3(album4_dir / "album4song.mp3")
2097 self.base = str(base)
2098
2099 def test_finds_all_albums(self):
2100 albums = list(albums_in_dir(self.base))
2101 assert len(albums) == 4
2102
2103 def test_separates_contents(self):
2104 found = []
2105 for _, album in albums_in_dir(self.base):
2106 found.append(re.search(r"album(.)song", album[0]).group(1))
2107 assert "1" in found
2108 assert "2" in found
2109 assert "3" in found
2110 assert "4" in found
2111
2112 def test_finds_multiple_songs(self):
2113 for _, album in albums_in_dir(self.base):
2114 n = re.search(r"album(.)song", album[0]).group(1)
2115 if n == "1":
2116 assert len(album) == 2
2117 else:
2118 assert len(album) == 1
2119
2120
2121 class MultiDiscAlbumsInDirTest(BeetsTestCase):
2122 def create_music(self, files=True, ascii_=True):
2123 """Create some music in multiple album directories.
2124
2125 `files` indicates whether to create the files (otherwise, only
2126 directories are made). `ascii_` indicates ACII-only filenames;
2127 otherwise, we use Unicode names.
2128 """
2129 self.base = (self.temp_path / "tempdir").resolve()
2130 self.base.mkdir()
2131
2132 name = "CAT" if ascii_ else "C\xc1T"
2133 name_alt_case = "CAt" if ascii_ else "C\xc1t"
2134
2135 self.dirs = [
2136 # Nested album, multiple subdirs.
2137 # Also, false positive marker in root dir, and subtitle for disc 3.
2138 self.base / "ABCD1234",
2139 self.base / "ABCD1234" / "cd 1",
2140 self.base / "ABCD1234" / "cd 3 - bonus",
2141 # Nested album, single subdir.
2142 # Also, punctuation between marker and disc number.
2143 self.base / "album",
2144 self.base / "album" / "cd _ 1",
2145 # Flattened album, case typo.
2146 # Also, false positive marker in parent dir.
2147 self.base / "artist [CD5]",
2148 self.base / "artist [CD5]" / f"{name} disc 1",
2149 self.base / "artist [CD5]" / f"{name_alt_case} disc 2",
2150 # Single disc album, sorted between CAT discs.
2151 self.base / "artist [CD5]" / f"{name} S",
2152 ]
2153 deep_dirs = [*self.dirs[:3], self.dirs[4], *self.dirs[6:]]
2154 self.files = [d / f"song{i}.mp3" for i, d in enumerate(deep_dirs)]
2155
2156 if not ascii_:
2157 self.dirs = [self._normalize_path(p) for p in self.dirs]
2158 self.files = [self._normalize_path(p) for p in self.files]
2159
2160 for path in self.dirs:
2161 path.mkdir()
2162 if files:
2163 for path in self.files:
2164 _mkmp3(path)
2165
2166 self.dirs = list(map(str, self.dirs))
2167 self.files = list(map(str, self.files))
2168 self.base = str(self.base)
2169
2170 def _normalize_path(self, path: Path) -> Path:
2171 """Normalize a path's Unicode combining form according to the
2172 platform.
2173 """
2174 norm_form: Literal["NFD", "NFC"] = (
2175 "NFD" if sys.platform == "darwin" else "NFC"
2176 )
2177 return Path(unicodedata.normalize(norm_form, str(path)))
2178
2179 def test_coalesce_nested_album_multiple_subdirs(self):
2180 self.create_music()
2181 albums = list(albums_in_dir(self.base))
2182 assert len(albums) == 4
2183 root, items = albums[0]
2184 assert root == self.dirs[0:3]
2185 assert len(items) == 3
2186
2187 def test_coalesce_nested_album_single_subdir(self):
2188 self.create_music()
2189 albums = list(albums_in_dir(self.base))
2190 root, items = albums[1]
2191 assert root == self.dirs[3:5]
2192 assert len(items) == 1
2193
2194 def test_coalesce_flattened_album_case_typo(self):
2195 self.create_music()
2196 albums = list(albums_in_dir(self.base))
2197 root, items = albums[2]
2198 assert root == self.dirs[6:8]
2199 assert len(items) == 2
2200
2201 def test_single_disc_album(self):
2202 self.create_music()
2203 albums = list(albums_in_dir(self.base))
2204 root, items = albums[3]
2205 assert root == self.dirs[8:]
2206 assert len(items) == 1
2207
2208 def test_do_not_yield_empty_album(self):
2209 self.create_music(files=False)
2210 albums = list(albums_in_dir(self.base))
2211 assert len(albums) == 0
2212
2213 def test_single_disc_unicode(self):
2214 self.create_music(ascii_=False)
2215 albums = list(albums_in_dir(self.base))
2216 root, items = albums[3]
2217 assert root == self.dirs[8:]
2218 assert len(items) == 1
2219
2220 def test_coalesce_multiple_unicode(self):
2221 self.create_music(ascii_=False)
2222 albums = list(albums_in_dir(self.base))
2223 assert len(albums) == 4
2224 root, items = albums[0]
2225 assert root == self.dirs[0:3]
2226 assert len(items) == 3
2227
2228 def test_coalesce_markers(self):
2229 for i, (marker, suffix1, suffix2) in enumerate(
2230 [
2231 ("Disc", " 1", " 02"), # titlecase, space-separated
2232 ("disk 757", " 1", " 02"), # lowercase, numerical suffix
2233 ("CD", "01", "02"), # uppercase, no space (e.g. CD01)
2234 ("disc", "_1", "_2"), # underscore separator (e.g. disc_1)
2235 ("cAsSeTtE", " 1", " 02"), # mixed case
2236 ("Digital Media", " 1", " 02"), # multiple spaces
2237 ("vinyl", " 1", " 02"), # lowercase
2238 ("12 vinyl", " 1", " 02"), # common prefix
2239 ]
2240 ):
2241 with self.subTest(marker=marker, suffix1=suffix1, suffix2=suffix2):
2242 base = self.temp_path / f"marker_{i}"
2243 base.mkdir()
2244
2245 album_dir = base / "Album Name"
2246 album_dir.mkdir()
2247
2248 discs = []
2249 for suffix in (suffix1, suffix2):
2250 disc = album_dir / f"{marker}{suffix}"
2251 disc.mkdir()
2252 _mkmp3(disc / "song.mp3")
2253 discs.append(str(disc))
2254
2255 albums = list(albums_in_dir(str(base)))
2256 assert len(albums) == 1
2257 root, items = albums[0]
2258 for disc in discs:
2259 assert disc in root
2260 assert len(items) == 2
2261
2262 def test_no_coalesce_mismatched_prefixes(self):
2263 # "CD 02" and "Enhanced CD 01" share the "cd" marker but have
2264 # different prefixes, so they should not be collapsed.
2265 base = self.temp_path / "mismatched"
2266 base.mkdir()
2267
2268 album_dir = base / "Album Name"
2269 album_dir.mkdir()
2270
2271 for subdir in ("CD 02", "Enhanced CD 01"):
2272 d = album_dir / subdir
2273 d.mkdir()
2274 _mkmp3(d / "song.mp3")
2275
2276 albums = list(albums_in_dir(str(base)))
2277 assert len(albums) == 2
2278
2279
2280 class ReimportTest(AutotagImportTestCase):
2281 """Test "re-imports", in which the autotagging machinery is used for
2282 music that's already in the library.
2283
2284 This works by importing new database entries for the same files and
2285 replacing the old data with the new data. We also copy over flexible
2286 attributes and the added date.
2287 """
2288
2289 matching = AutotagStub.GOOD
2290
2291 def setUp(self):
2292 super().setUp()
2293
2294 # The existing album.
2295 album = self.add_album_fixture()
2296 album.added = 4242.0
2297 album.foo = "bar" # Some flexible attribute.
2298 album.data_source = "original_source"
2299 album.store()
2300 item = album.items().get()
2301 item.baz = "qux"
2302 item.added = 4747.0
2303 item.store()
2304
2305 def _setup_session(self, singletons=False):
2306 self.setup_importer(import_dir=self.lib_path, singletons=singletons)
2307 self.importer.add_choice(importer.Action.APPLY)
2308
2309 def _album(self):
2310 return self.lib.albums().get()
2311
2312 def _item(self):
2313 return self.lib.items().get()
2314
2315 def test_reimported_album_gets_new_metadata(self):
2316 self._setup_session()
2317 assert self._album().album == "\xe4lbum"
2318 self.importer.run()
2319 assert self._album().album == "the album"
2320
2321 def test_reimported_album_preserves_flexattr(self):
2322 self._setup_session()
2323 self.importer.run()
2324 assert self._album().foo == "bar"
2325
2326 def test_reimported_album_preserves_added(self):
2327 self._setup_session()
2328 self.importer.run()
2329 assert self._album().added == 4242.0
2330
2331 def test_reimported_album_preserves_item_flexattr(self):
2332 self._setup_session()
2333 self.importer.run()
2334 assert self._item().baz == "qux"
2335
2336 def test_reimported_album_preserves_item_added(self):
2337 self._setup_session()
2338 self.importer.run()
2339 assert self._item().added == 4747.0
2340
2341 def test_reimported_item_gets_new_metadata(self):
2342 self._setup_session(True)
2343 assert self._item().title == "t\xeftle 0"
2344 self.importer.run()
2345 assert self._item().title == "full"
2346
2347 def test_reimported_item_preserves_flexattr(self):
2348 self._setup_session(True)
2349 self.importer.run()
2350 assert self._item().baz == "qux"
2351
2352 def test_reimported_item_preserves_added(self):
2353 self._setup_session(True)
2354 self.importer.run()
2355 assert self._item().added == 4747.0
2356
2357 def test_reimported_item_preserves_art(self):
2358 self._setup_session()
2359 art_source = _common.RSRC / "abbey.jpg"
2360 replaced_album = self._album()
2361 replaced_album.set_art(art_source)
2362 replaced_album.store()
2363 old_artpath = replaced_album.art_filepath
2364 self.importer.run()
2365 new_album = self._album()
2366 new_artpath = new_album.art_destination(art_source)
2367 assert new_album.artpath == new_artpath
2368 assert new_album.art_filepath.exists()
2369 if new_artpath != old_artpath:
2370 assert not old_artpath.exists()
2371
2372 def test_reimported_album_has_new_flexattr(self):
2373 self._setup_session()
2374 assert self._album().get("bandcamp_album_id") is None
2375 self.importer.run()
2376 assert self._album().bandcamp_album_id == "bc_url"
2377
2378 def test_reimported_album_not_preserves_flexattr(self):
2379 self._setup_session()
2380
2381 self.importer.run()
2382 assert self._album().data_source == "match_source"
2383
2384
2385 class TestImportPretend(ImportHelper):
2386 """Test the pretend commandline option."""
2387
2388 def setup_beets(self):
2389 super().setup_beets()
2390 self.album_track_path = self.prepare_album_for_import(1)[0]
2391 self.single_path = self.prepare_track_for_import(2, self.import_path)
2392 self.album_path = self.album_track_path.parent
2393
2394 def _run(self, importer, caplog):
2395 with caplog.at_level("DEBUG"):
2396 importer.run()
2397 assert len(self.lib.items()) == 0
2398 assert len(self.lib.albums()) == 0
2399 return [
2400 r.message
2401 for r in caplog.records
2402 if not r.message.startswith("Sending event:")
2403 ]
2404
2405 def test_import_singletons_pretend(self, caplog):
2406 assert self._run(
2407 self.setup_singleton_importer(pretend=True), caplog
2408 ) == [
2409 f"Singleton: {self.single_path}",
2410 f"Singleton: {self.album_track_path}",
2411 ]
2412
2413 def test_import_album_pretend(self, caplog):
2414 assert self._run(self.setup_importer(pretend=True), caplog) == [
2415 f"Album: {self.import_path}",
2416 f" {self.single_path}",
2417 f"Album: {self.album_path}",
2418 f" {self.album_track_path}",
2419 ]
2420
2421 def test_import_pretend_empty(self, caplog):
2422 empty_path = self.temp_path / "empty"
2423 empty_path.mkdir()
2424
2425 importer = self.setup_importer(pretend=True, import_dir=empty_path)
2426
2427 assert self._run(importer, caplog) == [
2428 f"No files imported from {empty_path}"
2429 ]
2430
2431
2432 def mocked_get_albums_by_ids(ids):
2433 """Return album candidate for the given id.
2434
2435 The two albums differ only in the release title and artist name, so that
2436 ID_RELEASE_0 is a closer match to the items created by
2437 ImportHelper.prepare_album_for_import().
2438 """
2439 # Map IDs to (release title, artist), so the distances are different.
2440 album_artist_map = {
2441 TestImportId.ID_RELEASE_0: ("VALID_RELEASE_0", "TAG ARTIST"),
2442 TestImportId.ID_RELEASE_1: ("VALID_RELEASE_1", "DISTANT_MATCH"),
2443 }
2444
2445 for id_ in ids:
2446 album, artist = album_artist_map[id_]
2447 yield AlbumInfo(
2448 album_id=id_,
2449 album=album,
2450 artist_id="some-id",
2451 artist=artist,
2452 albumstatus="Official",
2453 tracks=[
2454 TrackInfo(
2455 track_id="bar",
2456 title="foo",
2457 artist_id="some-id",
2458 artist=artist,
2459 length=59,
2460 index=9,
2461 track_allt="A2",
2462 )
2463 ],
2464 )
2465
2466
2467 def mocked_get_tracks_by_ids(ids):
2468 """Return track candidate for the given id.
2469
2470 The two tracks differ only in the release title and artist name, so that
2471 ID_RELEASE_0 is a closer match to the items created by
2472 ImportHelper.prepare_album_for_import().
2473 """
2474 # Map IDs to (recording title, artist), so the distances are different.
2475 title_artist_map = {
2476 TestImportId.ID_RECORDING_0: ("VALID_RECORDING_0", "TAG ARTIST"),
2477 TestImportId.ID_RECORDING_1: ("VALID_RECORDING_1", "DISTANT_MATCH"),
2478 }
2479
2480 for id_ in ids:
2481 title, artist = title_artist_map[id_]
2482 yield TrackInfo(
2483 track_id=id_,
2484 title=title,
2485 artist_id="some-id",
2486 artist=artist,
2487 length=59,
2488 )
2489
2490
2491 @patch(
2492 "beets.metadata_plugins.tracks_for_ids",
2493 Mock(side_effect=mocked_get_tracks_by_ids),
2494 )
2495 @patch(
2496 "beets.metadata_plugins.albums_for_ids",
2497 Mock(side_effect=mocked_get_albums_by_ids),
2498 )
2499 class TestImportId(ImportHelper):
2500 ID_RELEASE_0 = "00000000-0000-0000-0000-000000000000"
2501 ID_RELEASE_1 = "11111111-1111-1111-1111-111111111111"
2502 ID_RECORDING_0 = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
2503 ID_RECORDING_1 = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
2504
2505 def setup_beets(self):
2506 super().setup_beets()
2507 self.prepare_album_for_import(1)
2508
2509 def test_one_mbid_one_album(self):
2510 self.setup_importer(search_ids=[self.ID_RELEASE_0])
2511
2512 self.importer.add_choice(importer.Action.APPLY)
2513 self.importer.run()
2514 assert self.lib.albums().get().album == "VALID_RELEASE_0"
2515
2516 def test_several_mbid_one_album(self):
2517 self.setup_importer(search_ids=[self.ID_RELEASE_0, self.ID_RELEASE_1])
2518
2519 self.importer.add_choice(2) # Pick the 2nd best match (release 1).
2520 self.importer.add_choice(importer.Action.APPLY)
2521 self.importer.run()
2522 assert self.lib.albums().get().album == "VALID_RELEASE_1"
2523
2524 def test_one_mbid_one_singleton(self):
2525 self.setup_singleton_importer(search_ids=[self.ID_RECORDING_0])
2526
2527 self.importer.add_choice(importer.Action.APPLY)
2528 self.importer.run()
2529 assert self.lib.items().get().title == "VALID_RECORDING_0"
2530
2531 def test_several_mbid_one_singleton(self):
2532 self.setup_singleton_importer(
2533 search_ids=[self.ID_RECORDING_0, self.ID_RECORDING_1]
2534 )
2535
2536 self.importer.add_choice(2) # Pick the 2nd best match (recording 1).
2537 self.importer.add_choice(importer.Action.APPLY)
2538 self.importer.run()
2539 assert self.lib.items().get().title == "VALID_RECORDING_1"
2540
2541 def test_candidates_album(self):
2542 """Test directly ImportTask.lookup_candidates()."""
2543 task = importer.ImportTask(
2544 paths=os.fsencode(self.import_path),
2545 toppath="top path",
2546 items=[_common.item()],
2547 )
2548
2549 task.lookup_candidates([self.ID_RELEASE_0, self.ID_RELEASE_1])
2550
2551 assert {"VALID_RELEASE_0", "VALID_RELEASE_1"} == {
2552 c.info.album for c in task.candidates
2553 }
2554
2555 def test_candidates_singleton(self):
2556 """Test directly SingletonImportTask.lookup_candidates()."""
2557 task = importer.SingletonImportTask(
2558 toppath="top path", item=_common.item()
2559 )
2560
2561 task.lookup_candidates([self.ID_RECORDING_0, self.ID_RECORDING_1])
2562
2563 assert {"VALID_RECORDING_0", "VALID_RECORDING_1"} == {
2564 c.info.title for c in task.candidates
2565 }
2566
2567
2568 class TestMpeglayerWavImport(AsIsImporterMixin, ImportHelper):
2569 """Test remuxing of WAVE_FORMAT_MPEGLAYER3 WAV files."""
2570
2571 def test_remux_mpeglayer3_wav(self):
2572 src = _common.RSRC / "mpeglayer3.wav"
2573 dest = self.temp_path / "mpeglayer3.wav"
2574 shutil.copy(src, syspath(dest))
2575
2576 mp3_path = remux_mpeglayer3_wav(dest)
2577
2578 assert mp3_path is not None
2579 assert mp3_path.suffix == ".mp3"
2580 assert mp3_path.exists()
2581 assert not dest.exists()
2582
2583 def test_remux_mpeglayer3_wav_disabled(self):
2584 """When remux_mp3_in_wav is disabled, WAV file should not be remuxed."""
2585 self.config["import"]["remux_mp3_in_wav"] = False
2586 src = _common.RSRC / "mpeglayer3.wav"
2587 dest = self.import_path / "mpeglayer3.wav"
2588 shutil.copy(src, syspath(dest))
2589
2590 self.run_asis_importer()
2591 assert dest.exists()