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