Debian Codegraph @

test/test_library.py

raw
1 """Tests for non-query database functions of Item."""
2
3 from __future__ import annotations
4
5 import os
6 import os.path
7 import re
8 import shutil
9 import stat
10 import unittest
11 from pathlib import Path
12 from unittest.mock import patch
13
14 import pytest
15 from mediafile import MediaFile, UnreadableFileError
16
17 import beets.dbcore.query
18 import beets.library
19 from beets import config, plugins, util
20 from beets.library import Album
21 from beets.test import _common
22 from beets.test._common import item
23 from beets.test.helper import TestHelper
24 from beets.util import as_string, bytestring_path, normpath
25
26 # Shortcut to path normalization.
27 np = util.normpath
28
29
30 class PytestItemHelper(TestHelper):
31 def get_first_item(self):
32 """Retrieve first item from library."""
33 return next(iter(self.lib.items()))
34
35 @pytest.fixture
36 def item(self):
37 return _common.item()
38
39 @pytest.fixture
40 def item_in_db(self):
41 return _common.item(self.lib)
42
43
44 class TestLoad(PytestItemHelper):
45 def test_load_restores_data_from_db(self, item_in_db):
46 original_title = item_in_db.title
47 item_in_db.title = "something"
48 item_in_db.load()
49 assert original_title == item_in_db.title
50
51 def test_load_clears_dirty_flags(self, item_in_db):
52 item_in_db.artist = "something"
53 assert "artist" in item_in_db._dirty
54 item_in_db.load()
55 assert "artist" not in item_in_db._dirty
56
57
58 class TestStore(PytestItemHelper):
59 def test_store_changes_database_value(self, item_in_db):
60 new_year = 1987
61 item_in_db.year = new_year
62 item_in_db.store()
63
64 assert self.lib.get_item(item_in_db.id).year == new_year
65
66 def test_store_only_writes_dirty_fields(self, item_in_db):
67 new_year = 1987
68 item_in_db._values_fixed["year"] = new_year # change w/o dirtying
69 item_in_db.store()
70
71 assert self.lib.get_item(item_in_db.id).year != new_year
72
73 def test_store_clears_dirty_flags(self, item_in_db):
74 item_in_db.composers = ["tvp"]
75 item_in_db.store()
76 assert "composers" not in item_in_db._dirty
77
78 def test_store_album_cascades_flex_deletes(self):
79 album = Album(flex1="Flex-1")
80 self.lib.add(album)
81 item = _common.item()
82 item.album_id = album.id
83 item.flex1 = "Flex-1"
84 self.lib.add(item)
85 del album.flex1
86 album.store()
87 assert "flex1" not in album
88 assert "flex1" not in album.items()[0]
89
90 def test_store_does_not_propagate_artpath_to_items(self):
91 item = _common.item()
92 self.lib.add(item)
93 album = self.lib.add_album([item])
94 assert "artpath" not in Album.item_keys
95 album.artpath = b"/abs/path/to/cover.jpg"
96 album.store()
97 stored = self.lib.get_item(item.id)
98 assert not stored.get("artpath", with_album=False)
99
100
101 class TestAdd(PytestItemHelper):
102 def test_item_add_inserts_row(self, item):
103 self.lib.add(item)
104 new_grouping = (
105 self.lib._connection()
106 .execute(
107 "select grouping from items where composers = ?",
108 (item._type("composers").to_sql(item.composers),),
109 )
110 .fetchone()["grouping"]
111 )
112 assert new_grouping == item.grouping
113
114 def test_library_add_path_inserts_row(self):
115 item = beets.library.Item.from_path(_common.RSRC / "full.mp3")
116 self.lib.add(item)
117 new_grouping = (
118 self.lib._connection()
119 .execute(
120 "select grouping from items where composers = ?",
121 (item._type("composers").to_sql(item.composers),),
122 )
123 .fetchone()["grouping"]
124 )
125 assert new_grouping == item.grouping
126
127 def test_library_add_one_database_change_event(
128 self, item, caplog: pytest.LogCaptureFixture
129 ):
130 """Test library.add emits only one database_change event."""
131
132 item.path = beets.util.normpath(self.temp_path / "a" / "b.mp3")
133 item.album = "a"
134 item.title = "b"
135
136 with caplog.at_level("DEBUG", logger="beets"):
137 self.lib.add(item)
138
139 assert caplog.text.count("Sending event: database_change") == 1
140
141
142 class TestRemove(PytestItemHelper):
143 def test_remove_deletes_from_db(self, item_in_db):
144 item_in_db.remove()
145 c = self.lib._connection().execute("select * from items")
146 assert c.fetchone() is None
147
148
149 class TestGetSet(PytestItemHelper):
150 def test_set_changes_value(self, item):
151 item.bpm = 4915
152 assert item.bpm == 4915
153
154 def test_set_sets_dirty_flag(self, item):
155 item.comp = not item.comp
156 assert "comp" in item._dirty
157
158 def test_set_does_not_dirty_if_value_unchanged(self, item):
159 item.title = item.title
160 assert "title" not in item._dirty
161
162 def test_invalid_field_raises_attributeerror(self, item):
163 with pytest.raises(AttributeError):
164 item.xyzzy
165
166 def test_album_fallback(self, item_in_db):
167 # integration test of item-album fallback
168 album = self.lib.add_album([item_in_db])
169 album["flex"] = "foo"
170 album.store()
171
172 assert "flex" in item_in_db
173 assert "flex" not in item_in_db.keys(with_album=False)
174 assert item_in_db["flex"] == "foo"
175 assert item_in_db.get("flex") == "foo"
176 assert item_in_db.get("flex", with_album=False) is None
177 assert item_in_db.get("flexx") is None
178
179
180 class TestDestination(PytestItemHelper):
181 """Confirm tests handle temporary directory path containing '.'"""
182
183 def create_temp_dir(self, **kwargs):
184 kwargs["prefix"] = "."
185 return super().create_temp_dir(**kwargs)
186
187 def test_directory_works_with_trailing_slash(self, item_in_db):
188 self.lib.directory = b"one/"
189 self.lib.path_formats = [("default", "two")]
190 assert item_in_db.destination() == np("one/two")
191
192 def test_directory_works_without_trailing_slash(self, item_in_db):
193 self.lib.directory = b"one"
194 self.lib.path_formats = [("default", "two")]
195 assert item_in_db.destination() == np("one/two")
196
197 def test_destination_substitutes_metadata_values(self, item_in_db):
198 self.lib.directory = b"base"
199 self.lib.path_formats = [("default", "$album/$artist $title")]
200 item_in_db.title = "three"
201 item_in_db.artist = "two"
202 item_in_db.album = "one"
203 assert item_in_db.destination() == np("base/one/two three")
204
205 def test_destination_preserves_extension(self, item_in_db):
206 self.lib.directory = b"base"
207 self.lib.path_formats = [("default", "$title")]
208 item_in_db.path = "hey.audioformat"
209 assert item_in_db.destination() == np("base/the title.audioformat")
210
211 def test_lower_case_extension(self, item_in_db):
212 self.lib.directory = b"base"
213 self.lib.path_formats = [("default", "$title")]
214 item_in_db.path = "hey.MP3"
215 assert item_in_db.destination() == np("base/the title.mp3")
216
217 def test_destination_pads_some_indices(self, item_in_db):
218 self.lib.directory = b"base"
219 self.lib.path_formats = [
220 ("default", "$track $tracktotal $disc $disctotal $bpm")
221 ]
222 item_in_db.track = 1
223 item_in_db.tracktotal = 2
224 item_in_db.disc = 3
225 item_in_db.disctotal = 4
226 item_in_db.bpm = 5
227 assert item_in_db.destination() == np("base/01 02 03 04 5")
228
229 def test_destination_pads_date_values(self, item_in_db):
230 self.lib.directory = b"base"
231 self.lib.path_formats = [("default", "$year-$month-$day")]
232 item_in_db.year = 1
233 item_in_db.month = 2
234 item_in_db.day = 3
235 assert item_in_db.destination() == np("base/0001-02-03")
236
237 def test_destination_escapes_slashes(self, item_in_db):
238 self.lib.path_formats = [("default", "$artist/$album/$track $title")]
239 item_in_db.album = "one/two"
240 dest = item_in_db.destination()
241 assert b"one" in dest
242 assert b"two" in dest
243 assert b"one/two" not in dest
244
245 def test_destination_escapes_leading_dot(self, item_in_db):
246 self.lib.path_formats = [("default", "$artist/$album/$track $title")]
247 item_in_db.album = ".something"
248 dest = item_in_db.destination()
249 assert b"something" in dest
250 assert b"/.something" not in dest
251
252 def test_destination_preserves_legitimate_slashes(self, item_in_db):
253 self.lib.path_formats = [("default", "$artist/$album/$track $title")]
254 item_in_db.artist = "one"
255 item_in_db.album = "two"
256 dest = item_in_db.destination()
257 assert os.path.join(b"one", b"two") in dest
258
259 def test_destination_long_names_truncated(self, item_in_db):
260 item_in_db.title = "X" * 300
261 item_in_db.artist = "Y" * 300
262 for c in item_in_db.destination().split(util.PATH_SEP):
263 assert len(c) <= 255
264
265 def test_destination_long_names_keep_extension(self, item_in_db):
266 item_in_db.title = "X" * 300
267 item_in_db.path = b"something.extn"
268 dest = item_in_db.destination()
269 assert dest[-5:] == b".extn"
270
271 def test_distination_windows_removes_both_separators(self, item_in_db):
272 item_in_db.title = "one \\ two / three.mp3"
273 with _common.platform_windows():
274 p = item_in_db.destination()
275 assert b"one \\ two" not in p
276 assert b"one / two" not in p
277 assert b"two \\ three" not in p
278 assert b"two / three" not in p
279
280 def test_path_with_format(self, item_in_db):
281 self.lib.path_formats = [("default", "$artist/$album ($format)")]
282 p = item_in_db.destination()
283 assert b"(FLAC)" in p
284
285 def test_heterogeneous_album_gets_single_directory(self):
286 i1, i2 = _common.item(self.lib), _common.item(self.lib)
287 self.lib.add_album([i1, i2])
288 i1.year, i2.year = 2009, 2010
289 self.lib.path_formats = [("default", "$album ($year)/$track $title")]
290 dest1, dest2 = i1.destination(), i2.destination()
291 assert os.path.dirname(dest1) == os.path.dirname(dest2)
292
293 def test_default_path_for_non_compilations(self, item_in_db):
294 item_in_db.comp = False
295 self.lib.add_album([item_in_db])
296 self.lib.directory = b"one"
297 self.lib.path_formats = [("default", "two"), ("comp:true", "three")]
298 assert item_in_db.destination() == np("one/two")
299
300 def test_singleton_path(self, item_in_db):
301 self.lib.directory = b"one"
302 self.lib.path_formats = [
303 ("default", "two"),
304 ("singleton:true", "four"),
305 ("comp:true", "three"),
306 ]
307 assert item_in_db.destination() == np("one/four")
308
309 def test_comp_before_singleton_path(self, item_in_db):
310 item_in_db.comp = True
311 self.lib.directory = b"one"
312 self.lib.path_formats = [
313 ("default", "two"),
314 ("comp:true", "three"),
315 ("singleton:true", "four"),
316 ]
317 assert item_in_db.destination() == np("one/three")
318
319 def test_comp_path(self, item_in_db):
320 item_in_db.comp = True
321 self.lib.add_album([item_in_db])
322 self.lib.directory = b"one"
323 self.lib.path_formats = [("default", "two"), ("comp:true", "three")]
324 assert item_in_db.destination() == np("one/three")
325
326 def test_multi_value_string_query_path(self, item_in_db):
327 item_in_db.genres = ["Classical"]
328 self.lib.directory = b"one"
329 self.lib.path_formats = [
330 ("default", "two"),
331 ("genres:=~Classical", "three"),
332 ]
333 assert item_in_db.destination() == np("one/three")
334
335 def test_multi_value_match_query_path(self, item_in_db):
336 item_in_db.genres = ["Classical"]
337 self.lib.directory = b"one"
338 self.lib.path_formats = [
339 ("default", "two"),
340 ("genres:=Classical", "three"),
341 ]
342 assert item_in_db.destination() == np("one/three")
343
344 def test_multi_value_string_query_path_no_substring_match(self, item_in_db):
345 item_in_db.genres = ["Neoclassical"]
346 self.lib.directory = b"one"
347 self.lib.path_formats = [
348 ("default", "two"),
349 ("genres:=~Classical", "three"),
350 ]
351 assert item_in_db.destination() == np("one/two")
352
353 def test_albumtype_query_path(self, item_in_db):
354 item_in_db.comp = True
355 self.lib.add_album([item_in_db])
356 item_in_db.albumtype = "sometype"
357 self.lib.directory = b"one"
358 self.lib.path_formats = [
359 ("default", "two"),
360 ("albumtype:sometype", "four"),
361 ("comp:true", "three"),
362 ]
363 assert item_in_db.destination() == np("one/four")
364
365 def test_albumtype_path_fallback_to_comp(self, item_in_db):
366 item_in_db.comp = True
367 self.lib.add_album([item_in_db])
368 item_in_db.albumtype = "sometype"
369 self.lib.directory = b"one"
370 self.lib.path_formats = [
371 ("default", "two"),
372 ("albumtype:anothertype", "four"),
373 ("comp:true", "three"),
374 ]
375 assert item_in_db.destination() == np("one/three")
376
377 def test_get_formatted_does_not_replace_separators(self, item_in_db):
378 with _common.platform_posix():
379 name = str(Path("a") / "b")
380 item_in_db.title = name
381 newname = item_in_db.formatted().get("title")
382 assert name == newname
383
384 def test_get_formatted_pads_with_zero(self, item_in_db):
385 with _common.platform_posix():
386 item_in_db.track = 1
387 name = item_in_db.formatted().get("track")
388 assert name.startswith("0")
389
390 def test_get_formatted_uses_kbps_bitrate(self, item_in_db):
391 with _common.platform_posix():
392 item_in_db.bitrate = 12345
393 val = item_in_db.formatted().get("bitrate")
394 assert val == "12kbps"
395
396 def test_get_formatted_uses_khz_samplerate(self, item_in_db):
397 with _common.platform_posix():
398 item_in_db.samplerate = 12345
399 val = item_in_db.formatted().get("samplerate")
400 assert val == "12kHz"
401
402 def test_get_formatted_datetime(self, item_in_db):
403 with _common.platform_posix():
404 item_in_db.added = 1368302461.210265
405 val = item_in_db.formatted().get("added")
406 assert val.startswith("2013")
407
408 def test_get_formatted_none(self, item_in_db):
409 with _common.platform_posix():
410 item_in_db.some_other_field = None
411 val = item_in_db.formatted().get("some_other_field")
412 assert val == ""
413
414 def test_artist_falls_back_to_albumartist(self, item_in_db):
415 item_in_db.artist = ""
416 item_in_db.albumartist = "something"
417 self.lib.path_formats = [("default", "$artist")]
418 p = item_in_db.destination()
419 assert p.rsplit(util.PATH_SEP, 1)[1] == b"something"
420
421 def test_albumartist_falls_back_to_artist(self, item_in_db):
422 item_in_db.artist = "trackartist"
423 item_in_db.albumartist = ""
424 self.lib.path_formats = [("default", "$albumartist")]
425 p = item_in_db.destination()
426 assert p.rsplit(util.PATH_SEP, 1)[1] == b"trackartist"
427
428 def test_artist_overrides_albumartist(self, item_in_db):
429 item_in_db.artist = "theartist"
430 item_in_db.albumartist = "something"
431 self.lib.path_formats = [("default", "$artist")]
432 p = item_in_db.destination()
433 assert p.rsplit(util.PATH_SEP, 1)[1] == b"theartist"
434
435 def test_albumartist_overrides_artist(self, item_in_db):
436 item_in_db.artist = "theartist"
437 item_in_db.albumartist = "something"
438 self.lib.path_formats = [("default", "$albumartist")]
439 p = item_in_db.destination()
440 assert p.rsplit(util.PATH_SEP, 1)[1] == b"something"
441
442 def test_unicode_extension_in_fragment(self, item_in_db):
443 self.lib.path_formats = [("default", "foo")]
444 item_in_db.path = Path("bar.caf\xe9")
445 with patch("sys.platform", "linux"):
446 dest = item_in_db.destination(relative_to_libdir=True)
447 assert as_string(dest) == "foo.caf\xe9"
448
449 def test_asciify_character_expanding_to_slash(self, item_in_db):
450 config["asciify_paths"] = True
451 self.lib.directory = b"lib"
452 self.lib.path_formats = [("default", "$title")]
453 item_in_db.title = "ab\xa2\xbdd"
454 assert item_in_db.destination() == np("lib/abC_ 1_2d")
455
456 def test_destination_with_replacements(self, item_in_db):
457 self.lib.directory = b"base"
458 self.lib.replacements = [(re.compile(r"a"), "e")]
459 self.lib.path_formats = [("default", "$album/$title")]
460 item_in_db.title = "foo"
461 item_in_db.album = "bar"
462 assert item_in_db.destination() == np("base/ber/foo")
463
464 @unittest.skip("unimplemented: #359")
465 def test_destination_with_empty_component(self, item_in_db):
466 self.lib.directory = b"base"
467 self.lib.replacements = [(re.compile(r"^$"), "_")]
468 self.lib.path_formats = [("default", "$album/$artist/$title")]
469 item_in_db.title = "three"
470 item_in_db.artist = ""
471 item_in_db.albumartist = ""
472 item_in_db.album = "one"
473 assert item_in_db.destination() == np("base/one/_/three")
474
475 @unittest.skip("unimplemented: #359")
476 def test_destination_with_empty_final_component(self, item_in_db):
477 self.lib.directory = b"base"
478 self.lib.replacements = [(re.compile(r"^$"), "_")]
479 self.lib.path_formats = [("default", "$album/$title")]
480 item_in_db.title = ""
481 item_in_db.album = "one"
482 item_in_db.path = "foo.mp3"
483 assert item_in_db.destination() == np("base/one/_.mp3")
484
485 def test_album_field_query(self, item_in_db):
486 self.lib.directory = b"one"
487 self.lib.path_formats = [("default", "two"), ("flex:foo", "three")]
488 album = self.lib.add_album([item_in_db])
489 assert item_in_db.destination() == np("one/two")
490 album["flex"] = "foo"
491 album.store()
492 assert item_in_db.destination() == np("one/three")
493
494 def test_album_field_in_template(self, item_in_db):
495 self.lib.directory = b"one"
496 self.lib.path_formats = [("default", "$flex/two")]
497 album = self.lib.add_album([item_in_db])
498 album["flex"] = "foo"
499 album.store()
500 assert item_in_db.destination() == np("one/foo/two")
501
502
503 class TestItemFormattedMapping(PytestItemHelper):
504 def test_formatted_item_value(self, item_in_db):
505 formatted = item_in_db.formatted()
506 assert formatted["artist"] == "the artist"
507
508 def test_get_unset_field(self, item_in_db):
509 formatted = item_in_db.formatted()
510 with pytest.raises(KeyError):
511 formatted["other_field"]
512
513 def test_get_method_with_default(self, item_in_db):
514 formatted = item_in_db.formatted()
515 assert formatted.get("other_field") == ""
516
517 def test_get_method_with_specified_default(self, item_in_db):
518 formatted = item_in_db.formatted()
519 assert formatted.get("other_field", "default") == "default"
520
521 def test_item_precedence(self, item_in_db):
522 album = self.lib.add_album([item_in_db])
523 album["artist"] = "foo"
524 album.store()
525 assert "foo" != item_in_db.formatted().get("artist")
526
527 def test_album_flex_field(self, item_in_db):
528 album = self.lib.add_album([item_in_db])
529 album["flex"] = "foo"
530 album.store()
531 assert "foo" == item_in_db.formatted().get("flex")
532
533 def test_album_field_overrides_item_field_for_path(self, item_in_db):
534 # Make the album inconsistent with the item.
535 album = self.lib.add_album([item_in_db])
536 album.album = "foo"
537 album.store()
538 item_in_db.album = "bar"
539 item_in_db.store()
540
541 # Ensure the album takes precedence.
542 formatted = item_in_db.formatted(for_path=True)
543 assert formatted["album"] == "foo"
544
545 def test_artist_falls_back_to_albumartist(self, item_in_db):
546 item_in_db.artist = ""
547 formatted = item_in_db.formatted()
548 assert formatted["artist"] == "the album artist"
549
550 def test_albumartist_falls_back_to_artist(self, item_in_db):
551 item_in_db.albumartist = ""
552 formatted = item_in_db.formatted()
553 assert formatted["albumartist"] == "the artist"
554
555 def test_both_artist_and_albumartist_empty(self, item_in_db):
556 item_in_db.artist = ""
557 item_in_db.albumartist = ""
558 formatted = item_in_db.formatted()
559 assert formatted["albumartist"] == ""
560
561
562 class PathFormattingMixin:
563 """Utilities for testing path formatting."""
564
565 lib: beets.library.Library
566
567 def _setf(self, fmt):
568 self.lib.path_formats.insert(0, ("default", fmt))
569
570 def _assert_dest(self, dest, item):
571 # Handle paths on Windows.
572 if os.path.sep != "/":
573 dest = dest.replace(b"/", os.path.sep.encode())
574
575 # Paths are normalized based on the CWD.
576 dest = normpath(dest)
577
578 actual = item.destination()
579
580 assert actual == dest
581
582
583 class TestDestinationFunction(TestHelper, PathFormattingMixin):
584 @pytest.fixture(autouse=True)
585 def item(self, setup):
586 self.lib.directory = b"/base"
587 self.lib.path_formats = [("default", "path")]
588 return item(self.lib)
589
590 def test_upper_case_literal(self, item):
591 self._setf("%upper{foo}")
592 self._assert_dest(b"/base/FOO", item)
593
594 def test_upper_case_variable(self, item):
595 self._setf("%upper{$title}")
596 self._assert_dest(b"/base/THE TITLE", item)
597
598 def test_capitalize_variable(self, item):
599 self._setf("%capitalize{$title}")
600 self._assert_dest(b"/base/The title", item)
601
602 def test_title_case_variable(self, item):
603 self._setf("%title{$title}")
604 self._assert_dest(b"/base/The Title", item)
605
606 def test_title_case_variable_aphostrophe(self, item):
607 self._setf("%title{I can't}")
608 self._assert_dest(b"/base/I Can't", item)
609
610 def test_asciify_variable(self, item):
611 self._setf("%asciify{ab\xa2\xbdd}")
612 self._assert_dest(b"/base/abC_ 1_2d", item)
613
614 def test_left_variable(self, item):
615 self._setf("%left{$title, 3}")
616 self._assert_dest(b"/base/the", item)
617
618 def test_right_variable(self, item):
619 self._setf("%right{$title,3}")
620 self._assert_dest(b"/base/tle", item)
621
622 def test_if_false(self, item):
623 self._setf("x%if{,foo}")
624 self._assert_dest(b"/base/x", item)
625
626 def test_if_false_value(self, item):
627 self._setf("x%if{false,foo}")
628 self._assert_dest(b"/base/x", item)
629
630 def test_if_true(self, item):
631 self._setf("%if{bar,foo}")
632 self._assert_dest(b"/base/foo", item)
633
634 def test_if_else_false(self, item):
635 self._setf("%if{,foo,baz}")
636 self._assert_dest(b"/base/baz", item)
637
638 def test_if_else_false_value(self, item):
639 self._setf("%if{false,foo,baz}")
640 self._assert_dest(b"/base/baz", item)
641
642 def test_if_int_value(self, item):
643 self._setf("%if{0,foo,baz}")
644 self._assert_dest(b"/base/baz", item)
645
646 def test_nonexistent_function(self, item):
647 self._setf("%foo{bar}")
648 self._assert_dest(b"/base/%foo{bar}", item)
649
650 def test_if_def_field_return_self(self, item):
651 item.bar = 3
652 self._setf("%ifdef{bar}")
653 self._assert_dest(b"/base/3", item)
654
655 def test_if_def_field_not_defined(self, item):
656 self._setf(" %ifdef{bar}/$artist")
657 self._assert_dest(b"/base/the artist", item)
658
659 def test_if_def_field_not_defined_2(self, item):
660 self._setf("$artist/%ifdef{bar}")
661 self._assert_dest(b"/base/the artist", item)
662
663 def test_if_def_true(self, item):
664 self._setf("%ifdef{artist,cool}")
665 self._assert_dest(b"/base/cool", item)
666
667 def test_if_def_true_complete(self, item):
668 item.series = "Now"
669 self._setf("%ifdef{series,$series Series,Albums}/$album")
670 self._assert_dest(b"/base/Now Series/the album", item)
671
672 def test_if_def_false_complete(self, item):
673 self._setf("%ifdef{plays,$plays,not_played}")
674 self._assert_dest(b"/base/not_played", item)
675
676 def test_first(self, item):
677 item.albumtypes = ["album", "compilation"]
678 self._setf("%first{$albumtypes}")
679 self._assert_dest(b"/base/album", item)
680
681 def test_first_skip(self, item):
682 item.albumtype = "album; ep; compilation"
683 self._setf("%first{$albumtype,1,2}")
684 self._assert_dest(b"/base/compilation", item)
685
686 def test_first_different_sep(self, item):
687 self._setf("%first{Alice / Bob / Eve,2,0, / , & }")
688 self._assert_dest(b"/base/Alice & Bob", item)
689
690
691 class TestDisambiguation(TestHelper, PathFormattingMixin):
692 @pytest.fixture(autouse=True)
693 def items(self, setup):
694 self.lib.directory = b"/base"
695 self.lib.path_formats = [("default", "path")]
696
697 i1 = item()
698 i1.year = 2001
699 self.lib.add_album([i1])
700 i2 = item()
701 i2.year = 2002
702 self.lib.add_album([i2])
703 self.lib._connection().commit()
704
705 self._setf("foo%aunique{albumartist album,year}/$title")
706 return i1, i2
707
708 def test_unique_expands_to_disambiguating_year(self, items):
709 i1, _i2 = items
710 self._assert_dest(b"/base/foo [2001]/the title", i1)
711
712 def test_unique_with_default_arguments_uses_albumtype(self, items):
713 i1, _i2 = items
714 album2 = self.lib.get_album(i1)
715 album2.albumtype = "bar"
716 album2.store()
717 self._setf("foo%aunique{}/$title")
718 self._assert_dest(b"/base/foo [bar]/the title", i1)
719
720 def test_unique_expands_to_nothing_for_distinct_albums(self, items):
721 i1, i2 = items
722 album2 = self.lib.get_album(i2)
723 album2.album = "different album"
724 album2.store()
725
726 self._assert_dest(b"/base/foo/the title", i1)
727
728 def test_use_fallback_numbers_when_identical(self, items):
729 i1, i2 = items
730 album2 = self.lib.get_album(i2)
731 album2.year = 2001
732 album2.store()
733
734 self._assert_dest(b"/base/foo [1]/the title", i1)
735 self._assert_dest(b"/base/foo [2]/the title", i2)
736
737 def test_unique_falls_back_to_second_distinguishing_field(self, items):
738 i1, _i2 = items
739 self._setf("foo%aunique{albumartist album,month year}/$title")
740 self._assert_dest(b"/base/foo [2001]/the title", i1)
741
742 def test_unique_sanitized(self, items):
743 i1, i2 = items
744 album2 = self.lib.get_album(i2)
745 album2.year = 2001
746 album1 = self.lib.get_album(i1)
747 album1.albumtype = "foo/bar"
748 album2.store()
749 album1.store()
750 self._setf("foo%aunique{albumartist album,albumtype}/$title")
751 self._assert_dest(b"/base/foo [foo_bar]/the title", i1)
752
753 def test_drop_empty_disambig_string(self, items):
754 i1, i2 = items
755 album1 = self.lib.get_album(i1)
756 album1.albumdisambig = None
757 album2 = self.lib.get_album(i2)
758 album2.albumdisambig = "foo"
759 album1.store()
760 album2.store()
761 self._setf("foo%aunique{albumartist album,albumdisambig}/$title")
762 self._assert_dest(b"/base/foo/the title", i1)
763
764 def test_change_brackets(self, items):
765 i1, _i2 = items
766 self._setf("foo%aunique{albumartist album,year,()}/$title")
767 self._assert_dest(b"/base/foo (2001)/the title", i1)
768
769 def test_remove_brackets(self, items):
770 i1, _i2 = items
771 self._setf("foo%aunique{albumartist album,year,}/$title")
772 self._assert_dest(b"/base/foo 2001/the title", i1)
773
774 def test_key_flexible_attribute(self, items):
775 i1, i2 = items
776 album1 = self.lib.get_album(i1)
777 album1.flex = "flex1"
778 album2 = self.lib.get_album(i2)
779 album2.flex = "flex2"
780 album1.store()
781 album2.store()
782 self._setf("foo%aunique{albumartist album flex,year}/$title")
783 self._assert_dest(b"/base/foo/the title", i1)
784
785
786 class TestSingletonDisambiguation(TestHelper, PathFormattingMixin):
787 @pytest.fixture(autouse=True)
788 def items(self, setup):
789 self.lib.directory = b"/base"
790 self.lib.path_formats = [("default", "path")]
791
792 i1 = item()
793 i1.year = 2001
794 self.lib.add(i1)
795 i2 = item()
796 i2.year = 2002
797 self.lib.add(i2)
798 self.lib._connection().commit()
799
800 self._setf("foo/$title%sunique{artist title,year}")
801 return i1, i2
802
803 def test_sunique_expands_to_disambiguating_year(self, items):
804 i1, _i2 = items
805 self._assert_dest(b"/base/foo/the title [2001]", i1)
806
807 def test_sunique_with_default_arguments_uses_trackdisambig(self, items):
808 i1, i2 = items
809 i1.trackdisambig = "live version"
810 i1.year = i2.year
811 i1.store()
812 self._setf("foo/$title%sunique{}")
813 self._assert_dest(b"/base/foo/the title [live version]", i1)
814
815 def test_sunique_expands_to_nothing_for_distinct_singletons(self, items):
816 i1, i2 = items
817 i2.title = "different track"
818 i2.store()
819
820 self._assert_dest(b"/base/foo/the title", i1)
821
822 def test_sunique_does_not_match_album(self, items):
823 i1, i2 = items
824 self.lib.add_album([i2])
825 self._assert_dest(b"/base/foo/the title", i1)
826
827 def test_sunique_use_fallback_numbers_when_identical(self, items):
828 i1, i2 = items
829 i2.year = i1.year
830 i2.store()
831
832 self._assert_dest(b"/base/foo/the title [1]", i1)
833 self._assert_dest(b"/base/foo/the title [2]", i2)
834
835 def test_sunique_falls_back_to_second_distinguishing_field(self, items):
836 i1, _i2 = items
837 self._setf("foo/$title%sunique{albumartist album,month year}")
838 self._assert_dest(b"/base/foo/the title [2001]", i1)
839
840 def test_sunique_sanitized(self, items):
841 i1, i2 = items
842 i2.year = i1.year
843 i1.trackdisambig = "foo/bar"
844 i2.store()
845 i1.store()
846 self._setf("foo/$title%sunique{artist title,trackdisambig}")
847 self._assert_dest(b"/base/foo/the title [foo_bar]", i1)
848
849 def test_drop_empty_disambig_string(self, items):
850 i1, i2 = items
851 i1.trackdisambig = None
852 i2.trackdisambig = "foo"
853 i1.store()
854 i2.store()
855 self._setf("foo/$title%sunique{albumartist album,trackdisambig}")
856 self._assert_dest(b"/base/foo/the title", i1)
857
858 def test_change_brackets(self, items):
859 i1, _i2 = items
860 self._setf("foo/$title%sunique{artist title,year,()}")
861 self._assert_dest(b"/base/foo/the title (2001)", i1)
862
863 def test_remove_brackets(self, items):
864 i1, _i2 = items
865 self._setf("foo/$title%sunique{artist title,year,}")
866 self._assert_dest(b"/base/foo/the title 2001", i1)
867
868 def test_key_flexible_attribute(self, items):
869 i1, i2 = items
870 i1.flex = "flex1"
871 i2.flex = "flex2"
872 i1.store()
873 i2.store()
874 self._setf("foo/$title%sunique{artist title flex,year}")
875 self._assert_dest(b"/base/foo/the title", i1)
876
877
878 class TestPluginDestination(TestHelper):
879 @pytest.fixture(autouse=True)
880 def item(self, setup):
881 # Mock beets.plugins.item_field_getters.
882 self._tv_map = {}
883
884 def field_getters():
885 getters = {}
886 for key, value in self._tv_map.items():
887 getters[key] = lambda _: value
888 return getters
889
890 self.old_field_getters = plugins.item_field_getters
891 plugins.item_field_getters = field_getters
892
893 self.lib.directory = b"/base"
894 self.lib.path_formats = [("default", "$artist $foo")]
895
896 yield _common.item(self.lib)
897
898 plugins.item_field_getters = self.old_field_getters
899
900 def _assert_dest(self, dest, item):
901 with _common.platform_posix():
902 the_dest = item.destination()
903 assert the_dest == b"/base/" + dest
904
905 def test_undefined_value_not_substituted(self, item):
906 self._assert_dest(b"the artist $foo", item)
907
908 def test_plugin_value_not_substituted(self, item):
909 self._tv_map = {"foo": "bar"}
910 self._assert_dest(b"the artist bar", item)
911
912 def test_plugin_value_overrides_attribute(self, item):
913 self._tv_map = {"artist": "bar"}
914 self._assert_dest(b"bar $foo", item)
915
916 def test_plugin_value_sanitized(self, item):
917 self._tv_map = {"foo": "bar/baz"}
918 self._assert_dest(b"the artist bar_baz", item)
919
920
921 class TestAlbumInfo(PytestItemHelper):
922 @pytest.fixture
923 def item_in_album(self, item):
924 self.lib.add_album((item,))
925 return item
926
927 def test_albuminfo_reflects_metadata(self, item_in_album):
928 ai = self.lib.get_album(item_in_album)
929 assert ai.mb_albumartistid == item_in_album.mb_albumartistid
930 assert ai.albumartist == item_in_album.albumartist
931 assert ai.album == item_in_album.album
932 assert ai.year == item_in_album.year
933
934 def test_albuminfo_stores_art(self, item_in_album):
935 ai = self.lib.get_album(item_in_album)
936 ai.artpath = os.fsdecode(np("/my/great/art"))
937 ai.store()
938 new_ai = self.lib.get_album(item_in_album)
939 assert new_ai.artpath == np("/my/great/art")
940
941 def test_albuminfo_for_two_items_doesnt_duplicate_row(self, item_in_album):
942 i2 = _common.item(self.lib)
943 self.lib.get_album(item_in_album)
944 self.lib.get_album(i2)
945
946 c = self.lib._connection().cursor()
947 c.execute("select * from albums where album=?", (item_in_album.album,))
948 # Cursor should only return one row.
949 assert c.fetchone() is not None
950 assert c.fetchone() is None
951
952 def test_individual_tracks_have_no_albuminfo(self):
953 i2 = _common.item()
954 i2.album = "aTotallyDifferentAlbum"
955 self.lib.add(i2)
956 ai = self.lib.get_album(i2)
957 assert ai is None
958
959 def test_get_album_by_id(self, item_in_album):
960 ai = self.lib.get_album(item_in_album)
961 ai = self.lib.get_album(item_in_album.id)
962 assert ai is not None
963
964 def test_album_items_consistent(self, item_in_album):
965 ai = self.lib.get_album(item_in_album)
966 assert item_in_album.id in {i.id for i in ai.items()}
967
968 def test_albuminfo_changes_affect_items(self, item_in_album):
969 ai = self.lib.get_album(item_in_album)
970 ai.album = "myNewAlbum"
971 ai.store()
972 assert self.get_first_item().album == "myNewAlbum"
973
974 def test_albuminfo_change_albumartist_changes_items(self, item_in_album):
975 ai = self.lib.get_album(item_in_album)
976 ai.albumartist = "myNewArtist"
977 ai.store()
978 item = self.get_first_item()
979 assert item.albumartist == "myNewArtist"
980 assert item.artist != "myNewArtist"
981
982 def test_albuminfo_change_artist_does_change_items(self, item_in_album):
983 ai = self.lib.get_album(item_in_album)
984 ai.artist = "myNewArtist"
985 ai.store(inherit=True)
986 assert self.get_first_item().artist == "myNewArtist"
987
988 def test_albuminfo_change_artist_does_not_change_items(self, item_in_album):
989 ai = self.lib.get_album(item_in_album)
990 ai.artist = "myNewArtist"
991 ai.store(inherit=False)
992 assert self.get_first_item().artist != "myNewArtist"
993
994 def test_albuminfo_remove_removes_items(self, item_in_album):
995 item_id = item_in_album.id
996 self.lib.get_album(item_in_album).remove()
997 c = self.lib._connection().execute(
998 "SELECT id FROM items WHERE id=?", (item_id,)
999 )
1000 assert c.fetchone() is None
1001
1002 def test_removing_last_item_removes_album(self, item_in_album):
1003 assert len(self.lib.albums()) == 1
1004 item_in_album.remove()
1005 assert len(self.lib.albums()) == 0
1006
1007 def test_noop_albuminfo_changes_affect_items(self, item_in_album):
1008 item = self.get_first_item()
1009 item.album = "foobar"
1010 item.store()
1011 ai = self.lib.get_album(item_in_album)
1012 ai.album = ai.album
1013 ai.store()
1014 item = self.get_first_item()
1015 assert item.album == ai.album
1016
1017
1018 class TestArtDestination(TestHelper):
1019 @pytest.fixture(autouse=True)
1020 def item_and_album(self, setup):
1021 config["art_filename"] = "artimage"
1022 config["replace"] = {"X": "Y"}
1023 self.lib.replacements = [(re.compile("X"), "Y")]
1024 self.lib.path_formats = [("default", "$artist/$album/$track $title")]
1025 item = _common.item(self.lib)
1026 item.path = item.destination()
1027 ai = self.lib.add_album((item,))
1028 return item, ai
1029
1030 def test_art_filename_respects_setting(self, item_and_album):
1031 _i, ai = item_and_album
1032 art = ai.art_destination("something.jpg")
1033 new_art = bytestring_path(f"{os.path.sep}artimage.jpg")
1034 assert new_art in art
1035
1036 def test_art_path_in_item_dir(self, item_and_album):
1037 i, ai = item_and_album
1038 art = ai.art_destination("something.jpg")
1039 track = i.destination()
1040 assert os.path.dirname(art) == os.path.dirname(track)
1041
1042 def test_art_path_sanitized(self, item_and_album):
1043 _i, ai = item_and_album
1044 config["art_filename"] = "artXimage"
1045 art = ai.art_destination("something.jpg")
1046 assert b"artYimage" in art
1047
1048
1049 class TestPathString(PytestItemHelper):
1050 def test_item_path_is_bytestring(self, item_in_db):
1051 assert isinstance(item_in_db.path, bytes)
1052
1053 def test_fetched_item_path_is_bytestring(self, item_in_db):
1054 assert isinstance(self.get_first_item().path, bytes)
1055
1056 def test_unicode_path_becomes_bytestring(self, item_in_db):
1057 item_in_db.path = "unicodepath"
1058 assert isinstance(item_in_db.path, bytes)
1059
1060 def test_unicode_in_database_becomes_bytestring(self, item_in_db):
1061 self.lib._connection().execute(
1062 """
1063 update items set path=? where id=?
1064 """,
1065 (item_in_db.id, "somepath"),
1066 )
1067 assert isinstance(self.get_first_item().path, bytes)
1068
1069 def test_special_chars_preserved_in_database(self, item_in_db):
1070 path = Path("b\xe1r")
1071 item_in_db.path = path
1072 item_in_db.store()
1073 assert self.get_first_item().filepath == self.lib_path / path
1074
1075 def test_special_char_path_added_to_database(self, item, item_in_db):
1076 item_in_db.remove()
1077 path = Path("b\xe1r")
1078 item = _common.item()
1079 item.path = path
1080 self.lib.add(item)
1081 assert self.get_first_item().filepath == self.lib_path / path
1082
1083 def test_destination_returns_bytestring(self, item_in_db):
1084 item_in_db.artist = "b\xe1r"
1085 dest = item_in_db.destination()
1086 assert isinstance(dest, bytes)
1087
1088 def test_art_destination_returns_bytestring(self, item_in_db):
1089 item_in_db.artist = "b\xe1r"
1090 alb = self.lib.add_album([item_in_db])
1091 dest = alb.art_destination("image.jpg")
1092 assert isinstance(dest, bytes)
1093
1094 def test_artpath_stores_special_chars(self, item_in_db):
1095 path = Path("b\xe1r")
1096 alb = self.lib.add_album([item_in_db])
1097 alb.artpath = path
1098 alb.store()
1099 stored_path = (
1100 self.lib._connection()
1101 .execute("select artpath from albums where id=?", (alb.id,))
1102 .fetchone()[0]
1103 )
1104 alb = self.lib.get_album(item_in_db)
1105 assert stored_path == os.fsencode(path)
1106 assert alb.art_filepath == self.lib_path / path
1107
1108 def test_sanitize_path_with_special_chars(self):
1109 path = "b\xe1r?"
1110 new_path = util.sanitize_path(path)
1111 assert new_path.startswith("b\xe1r")
1112
1113 def test_sanitize_path_returns_unicode(self):
1114 path = "b\xe1r?"
1115 new_path = util.sanitize_path(path)
1116 assert isinstance(new_path, str)
1117
1118 def test_unicode_artpath_becomes_bytestring(self, item_in_db):
1119 alb = self.lib.add_album([item_in_db])
1120 alb.artpath = "somep\xe1th"
1121 assert isinstance(alb.artpath, bytes)
1122
1123 def test_unicode_artpath_in_database_decoded(self, item_in_db):
1124 alb = self.lib.add_album([item_in_db])
1125 self.lib._connection().execute(
1126 "update albums set artpath=? where id=?", ("somep\xe1th", alb.id)
1127 )
1128 alb = self.lib.get_album(alb.id)
1129 assert isinstance(alb.artpath, bytes)
1130
1131 def test_relative_path_is_stored(self, item_in_db):
1132 relative_path = Path("abc") / "foo.mp3"
1133 absolute_path = self.lib_path / relative_path
1134 item_in_db.path = absolute_path
1135 item_in_db.store()
1136 stored_path = (
1137 self.lib._connection()
1138 .execute("select path from items where id=?", (item_in_db.id,))
1139 .fetchone()[0]
1140 )
1141 album = self.lib.add_album([item_in_db])
1142
1143 assert item_in_db.filepath == absolute_path
1144 assert stored_path == util.path_as_posix(os.fsencode(relative_path))
1145 assert album.filepath == absolute_path.parent
1146
1147
1148 class TestMtime(TestHelper):
1149 @pytest.fixture(autouse=True)
1150 def item(self, setup):
1151 self.ipath = self.temp_path / "testfile.mp3"
1152 shutil.copy(_common.RSRC / "full.mp3", self.ipath)
1153 item = beets.library.Item.from_path(self.ipath)
1154 self.lib.add(item)
1155 yield item
1156 if self.ipath.exists():
1157 self.ipath.unlink()
1158
1159 def _mtime(self):
1160 return int(self.ipath.stat().st_mtime)
1161
1162 def test_mtime_initially_up_to_date(self, item):
1163 assert item.mtime >= self._mtime()
1164
1165 def test_mtime_reset_on_db_modify(self, item):
1166 item.title = "something else"
1167 assert item.mtime < self._mtime()
1168
1169 def test_mtime_up_to_date_after_write(self, item):
1170 item.title = "something else"
1171 item.write()
1172 assert item.mtime >= self._mtime()
1173
1174 def test_mtime_up_to_date_after_read(self, item):
1175 item.title = "something else"
1176 item.read()
1177 assert item.mtime >= self._mtime()
1178
1179
1180 class TestImportTime(TestHelper):
1181 def added(self):
1182 self.track = item()
1183 self.album = self.lib.add_album((self.track,))
1184 assert self.album.added > 0
1185 assert self.track.added > 0
1186
1187 def test_atime_for_singleton(self):
1188 self.singleton = item(self.lib)
1189 assert self.singleton.added > 0
1190
1191
1192 class TestTemplate(PytestItemHelper):
1193 def test_year_formatted_in_template(self, item_in_db):
1194 item_in_db.year = 123
1195 item_in_db.store()
1196 assert item_in_db.evaluate_template("$year") == "0123"
1197
1198 def test_album_flexattr_appears_in_item_template(self, item_in_db):
1199 self.album = self.lib.add_album([item_in_db])
1200 self.album.foo = "baz"
1201 self.album.store()
1202 assert item_in_db.evaluate_template("$foo") == "baz"
1203
1204 def test_album_and_item_format(self, item_in_db):
1205 config["format_album"] = "foö $foo"
1206 album = beets.library.Album()
1207 album.foo = "bar"
1208 album.tagada = "togodo"
1209 assert f"{album}" == "foö bar"
1210 assert f"{album:$tagada}" == "togodo"
1211 assert str(album) == "foö bar"
1212 assert bytes(album) == b"fo\xc3\xb6 bar"
1213
1214 config["format_item"] = "bar $foo"
1215 item = beets.library.Item()
1216 item.foo = "bar"
1217 item.tagada = "togodo"
1218 assert f"{item}" == "bar bar"
1219 assert f"{item:$tagada}" == "togodo"
1220
1221
1222 class TestUnicodePath(PytestItemHelper):
1223 def test_unicode_path(self, item_in_db):
1224 item_in_db.path = _common.RSRC / "unicode\u2019d.mp3"
1225 # If there are any problems with unicode paths, we will raise
1226 # here and fail.
1227 item_in_db.read()
1228 item_in_db.write()
1229
1230
1231 class TestWrite(TestHelper):
1232 def test_write_nonexistant(self):
1233 item = self.create_item()
1234 item.path = b"/path/does/not/exist"
1235 with pytest.raises(beets.library.ReadError):
1236 item.write()
1237
1238 def test_no_write_permission(self):
1239 item = self.add_item_fixture()
1240 item.filepath.chmod(stat.S_IRUSR)
1241
1242 try:
1243 with pytest.raises(beets.library.WriteError) as exc_info:
1244 item.write()
1245 assert "super:" not in str(exc_info.value)
1246
1247 finally:
1248 # Restore write permissions so the file can be cleaned up.
1249 item.filepath.chmod(stat.S_IRUSR | stat.S_IWUSR)
1250
1251 def test_write_with_custom_path(self):
1252 item = self.add_item_fixture()
1253 custom_path = self.temp_path / "custom.mp3"
1254 shutil.copy(item.filepath, custom_path)
1255
1256 item["artist"] = "new artist"
1257 assert MediaFile(custom_path).artist != "new artist"
1258 assert MediaFile(item.filepath).artist != "new artist"
1259
1260 item.write(custom_path)
1261 assert MediaFile(custom_path).artist == "new artist"
1262 assert MediaFile(item.filepath).artist != "new artist"
1263
1264 def test_write_custom_tags(self):
1265 item = self.add_item_fixture(artist="old artist")
1266 item.write(tags={"artist": "new artist"})
1267 assert item.artist != "new artist"
1268 assert MediaFile(item.filepath).artist == "new artist"
1269
1270 def test_write_multi_tags(self):
1271 item = self.add_item_fixture(artist="old artist")
1272 item.write(tags={"artists": ["old artist", "another artist"]})
1273
1274 assert MediaFile(item.filepath).artists == [
1275 "old artist",
1276 "another artist",
1277 ]
1278
1279 def test_write_multi_tags_id3v23(self):
1280 item = self.add_item_fixture(artist="old artist")
1281 item.write(
1282 tags={"artists": ["old artist", "another artist"]}, id3v23=True
1283 )
1284
1285 assert MediaFile(item.filepath).artists == ["old artist/another artist"]
1286
1287 def test_write_date_field(self):
1288 # Since `date` is not a MediaField, this should do nothing.
1289 item = self.add_item_fixture()
1290 clean_year = item.year
1291 item.date = "foo"
1292 item.write()
1293 assert MediaFile(item.filepath).year == clean_year
1294
1295
1296 class TestItemRead(PytestItemHelper):
1297 def test_unreadable_raise_read_error(self, item_in_db):
1298 unreadable = _common.RSRC / "image-2x3.png"
1299 with pytest.raises(beets.library.ReadError) as exc_info:
1300 item_in_db.read(unreadable)
1301 assert isinstance(exc_info.value.reason, UnreadableFileError)
1302
1303 def test_nonexistent_raise_read_error(self, item_in_db):
1304 with pytest.raises(beets.library.ReadError):
1305 item_in_db.read("/thisfiledoesnotexist")
1306
1307 def test_read_error_str_includes_reason(self, item_in_db):
1308 unreadable = _common.RSRC / "image-2x3.png"
1309 with pytest.raises(beets.library.ReadError) as exc_info:
1310 item_in_db.read(unreadable)
1311 message = str(exc_info.value)
1312 assert "super:" not in message
1313 assert str(exc_info.value.reason) in message
1314
1315
1316 class TestItemReadGenre(TestHelper):
1317 def test_read_semicolon_delimited_genres(self):
1318 """Semicolon-delimited genre tags are split into individual genres on read."""
1319 path = self.create_mediafile_fixture()
1320 mf = MediaFile(path)
1321 mf.genres = ["Jazz; Funk; Soul"]
1322 mf.save()
1323 item = beets.library.Item.from_path(path)
1324 assert item.genres == ["Jazz", "Funk", "Soul"]
1325
1326
1327 class TestFilesize(TestHelper):
1328 def test_filesize(self):
1329 item = self.add_item_fixture()
1330 assert item.filesize != 0
1331
1332 def test_nonexistent_file(self):
1333 item = beets.library.Item()
1334 assert item.filesize == 0
1335
1336
1337 class TestItemPruneDirsClutter(TestHelper):
1338 """Regression tests: prune_dirs respects config["clutter"] during move/remove."""
1339
1340 def _drop_clutter(self, directory: Path) -> Path:
1341 """Create a clutter file in *directory* (bytes path)."""
1342 path = directory / "unwanted.log"
1343 path.touch()
1344 return path
1345
1346 def test_move_prunes_dir_with_config_clutter(self):
1347 """After moving an item, old dir is removed even when only clutter remains."""
1348 config["clutter"] = ["*.log"]
1349 item = self.add_item_fixture()
1350 old_dir = item.filepath.parent
1351 self._drop_clutter(old_dir)
1352
1353 # Change artist so the destination path differs, forcing a real move.
1354 item.artist = "new artist"
1355 item.store()
1356 item.move()
1357
1358 assert not old_dir.exists()
1359
1360 def test_remove_prunes_dir_with_config_clutter(self):
1361 """After deleting an item, its dir is removed even when only clutter remains."""
1362 config["clutter"] = ["*.log"]
1363 item = self.add_item_fixture()
1364 old_dir = item.filepath.parent
1365 self._drop_clutter(old_dir)
1366
1367 item.remove(delete=True)
1368
1369 assert not old_dir.exists()
1370
1371
1372 class TestParseQuery:
1373 def test_parse_invalid_query_string(self):
1374 with pytest.raises(beets.dbcore.query.ParsingError):
1375 beets.library.parse_query_string('foo"', None)
1376
1377 def test_parse_bytes(self):
1378 with pytest.raises(AssertionError):
1379 beets.library.parse_query_string(b"query", None)