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