forked from beetbox/beets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_ui.py
1640 lines (1353 loc) · 54.7 KB
/
test_ui.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
"""Tests for the command-line interface."""
import os
import platform
import re
import shutil
import subprocess
import sys
import unittest
from unittest.mock import Mock, patch
import pytest
from confuse import ConfigError
from mediafile import MediaFile
from beets import autotag, config, library, plugins, ui, util
from beets.autotag.match import distance
from beets.test import _common
from beets.test.helper import (
BeetsTestCase,
PluginTestCase,
capture_stdout,
control_stdin,
has_program,
)
from beets.ui import commands
from beets.util import MoveOperation, syspath
class ListTest(BeetsTestCase):
def setUp(self):
super().setUp()
self.item = _common.item()
self.item.path = "xxx/yyy"
self.lib.add(self.item)
self.lib.add_album([self.item])
def _run_list(self, query="", album=False, path=False, fmt=""):
with capture_stdout() as stdout:
commands.list_items(self.lib, query, album, fmt)
return stdout
def test_list_outputs_item(self):
stdout = self._run_list()
assert "the title" in stdout.getvalue()
def test_list_unicode_query(self):
self.item.title = "na\xefve"
self.item.store()
self.lib._connection().commit()
stdout = self._run_list(["na\xefve"])
out = stdout.getvalue()
assert "na\xefve" in out
def test_list_item_path(self):
stdout = self._run_list(fmt="$path")
assert stdout.getvalue().strip() == "xxx/yyy"
def test_list_album_outputs_something(self):
stdout = self._run_list(album=True)
assert len(stdout.getvalue()) > 0
def test_list_album_path(self):
stdout = self._run_list(album=True, fmt="$path")
assert stdout.getvalue().strip() == "xxx"
def test_list_album_omits_title(self):
stdout = self._run_list(album=True)
assert "the title" not in stdout.getvalue()
def test_list_uses_track_artist(self):
stdout = self._run_list()
assert "the artist" in stdout.getvalue()
assert "the album artist" not in stdout.getvalue()
def test_list_album_uses_album_artist(self):
stdout = self._run_list(album=True)
assert "the artist" not in stdout.getvalue()
assert "the album artist" in stdout.getvalue()
def test_list_item_format_artist(self):
stdout = self._run_list(fmt="$artist")
assert "the artist" in stdout.getvalue()
def test_list_item_format_multiple(self):
stdout = self._run_list(fmt="$artist - $album - $year")
assert "the artist - the album - 0001" == stdout.getvalue().strip()
def test_list_album_format(self):
stdout = self._run_list(album=True, fmt="$genre")
assert "the genre" in stdout.getvalue()
assert "the album" not in stdout.getvalue()
class RemoveTest(BeetsTestCase):
def setUp(self):
super().setUp()
self.io.install()
# Copy a file into the library.
self.item_path = os.path.join(_common.RSRC, b"full.mp3")
self.i = library.Item.from_path(self.item_path)
self.lib.add(self.i)
self.i.move(operation=MoveOperation.COPY)
def test_remove_items_no_delete(self):
self.io.addinput("y")
commands.remove_items(self.lib, "", False, False, False)
items = self.lib.items()
assert len(list(items)) == 0
self.assertExists(self.i.path)
def test_remove_items_with_delete(self):
self.io.addinput("y")
commands.remove_items(self.lib, "", False, True, False)
items = self.lib.items()
assert len(list(items)) == 0
self.assertNotExists(self.i.path)
def test_remove_items_with_force_no_delete(self):
commands.remove_items(self.lib, "", False, False, True)
items = self.lib.items()
assert len(list(items)) == 0
self.assertExists(self.i.path)
def test_remove_items_with_force_delete(self):
commands.remove_items(self.lib, "", False, True, True)
items = self.lib.items()
assert len(list(items)) == 0
self.assertNotExists(self.i.path)
def test_remove_items_select_with_delete(self):
i2 = library.Item.from_path(self.item_path)
self.lib.add(i2)
i2.move(operation=MoveOperation.COPY)
for s in ("s", "y", "n"):
self.io.addinput(s)
commands.remove_items(self.lib, "", False, True, False)
items = self.lib.items()
assert len(list(items)) == 1
# There is probably no guarantee that the items are queried in any
# spcecific order, thus just ensure that exactly one was removed.
# To improve upon this, self.io would need to have the capability to
# generate input that depends on previous output.
num_existing = 0
num_existing += 1 if os.path.exists(syspath(self.i.path)) else 0
num_existing += 1 if os.path.exists(syspath(i2.path)) else 0
assert num_existing == 1
def test_remove_albums_select_with_delete(self):
a1 = self.add_album_fixture()
a2 = self.add_album_fixture()
path1 = a1.items()[0].path
path2 = a2.items()[0].path
items = self.lib.items()
assert len(list(items)) == 3
for s in ("s", "y", "n"):
self.io.addinput(s)
commands.remove_items(self.lib, "", True, True, False)
items = self.lib.items()
assert len(list(items)) == 2 # incl. the item from setUp()
# See test_remove_items_select_with_delete()
num_existing = 0
num_existing += 1 if os.path.exists(syspath(path1)) else 0
num_existing += 1 if os.path.exists(syspath(path2)) else 0
assert num_existing == 1
class ModifyTest(BeetsTestCase):
def setUp(self):
super().setUp()
self.album = self.add_album_fixture()
[self.item] = self.album.items()
def modify_inp(self, inp, *args):
with control_stdin(inp):
self.run_command("modify", *args)
def modify(self, *args):
self.modify_inp("y", *args)
# Item tests
def test_modify_item(self):
self.modify("title=newTitle")
item = self.lib.items().get()
assert item.title == "newTitle"
def test_modify_item_abort(self):
item = self.lib.items().get()
title = item.title
self.modify_inp("n", "title=newTitle")
item = self.lib.items().get()
assert item.title == title
def test_modify_item_no_change(self):
title = "Tracktitle"
item = self.add_item_fixture(title=title)
self.modify_inp("y", "title", f"title={title}")
item = self.lib.items(title).get()
assert item.title == title
def test_modify_write_tags(self):
self.modify("title=newTitle")
item = self.lib.items().get()
item.read()
assert item.title == "newTitle"
def test_modify_dont_write_tags(self):
self.modify("--nowrite", "title=newTitle")
item = self.lib.items().get()
item.read()
assert item.title != "newTitle"
def test_move(self):
self.modify("title=newTitle")
item = self.lib.items().get()
assert b"newTitle" in item.path
def test_not_move(self):
self.modify("--nomove", "title=newTitle")
item = self.lib.items().get()
assert b"newTitle" not in item.path
def test_no_write_no_move(self):
self.modify("--nomove", "--nowrite", "title=newTitle")
item = self.lib.items().get()
item.read()
assert b"newTitle" not in item.path
assert item.title != "newTitle"
def test_update_mtime(self):
item = self.item
old_mtime = item.mtime
self.modify("title=newTitle")
item.load()
assert old_mtime != item.mtime
assert item.current_mtime() == item.mtime
def test_reset_mtime_with_no_write(self):
item = self.item
self.modify("--nowrite", "title=newTitle")
item.load()
assert 0 == item.mtime
def test_selective_modify(self):
title = "Tracktitle"
album = "album"
original_artist = "composer"
new_artist = "coverArtist"
for i in range(0, 10):
self.add_item_fixture(
title=f"{title}{i}", artist=original_artist, album=album
)
self.modify_inp(
"s\ny\ny\ny\nn\nn\ny\ny\ny\ny\nn", title, f"artist={new_artist}"
)
original_items = self.lib.items(f"artist:{original_artist}")
new_items = self.lib.items(f"artist:{new_artist}")
assert len(list(original_items)) == 3
assert len(list(new_items)) == 7
def test_modify_formatted(self):
for i in range(0, 3):
self.add_item_fixture(
title=f"title{i}", artist="artist", album="album"
)
items = list(self.lib.items())
self.modify("title=${title} - append")
for item in items:
orig_title = item.title
item.load()
assert item.title == f"{orig_title} - append"
# Album Tests
def test_modify_album(self):
self.modify("--album", "album=newAlbum")
album = self.lib.albums().get()
assert album.album == "newAlbum"
def test_modify_album_write_tags(self):
self.modify("--album", "album=newAlbum")
item = self.lib.items().get()
item.read()
assert item.album == "newAlbum"
def test_modify_album_dont_write_tags(self):
self.modify("--album", "--nowrite", "album=newAlbum")
item = self.lib.items().get()
item.read()
assert item.album == "the album"
def test_album_move(self):
self.modify("--album", "album=newAlbum")
item = self.lib.items().get()
item.read()
assert b"newAlbum" in item.path
def test_album_not_move(self):
self.modify("--nomove", "--album", "album=newAlbum")
item = self.lib.items().get()
item.read()
assert b"newAlbum" not in item.path
def test_modify_album_formatted(self):
item = self.lib.items().get()
orig_album = item.album
self.modify("--album", "album=${album} - append")
item.load()
assert item.album == f"{orig_album} - append"
# Misc
def test_write_initial_key_tag(self):
self.modify("initial_key=C#m")
item = self.lib.items().get()
mediafile = MediaFile(syspath(item.path))
assert mediafile.initial_key == "C#m"
def test_set_flexattr(self):
self.modify("flexattr=testAttr")
item = self.lib.items().get()
assert item.flexattr == "testAttr"
def test_remove_flexattr(self):
item = self.lib.items().get()
item.flexattr = "testAttr"
item.store()
self.modify("flexattr!")
item = self.lib.items().get()
assert "flexattr" not in item
@unittest.skip("not yet implemented")
def test_delete_initial_key_tag(self):
item = self.lib.items().get()
item.initial_key = "C#m"
item.write()
item.store()
mediafile = MediaFile(syspath(item.path))
assert mediafile.initial_key == "C#m"
self.modify("initial_key!")
mediafile = MediaFile(syspath(item.path))
assert mediafile.initial_key is None
def test_arg_parsing_colon_query(self):
(query, mods, dels) = commands.modify_parse_args(
["title:oldTitle", "title=newTitle"]
)
assert query == ["title:oldTitle"]
assert mods == {"title": "newTitle"}
def test_arg_parsing_delete(self):
(query, mods, dels) = commands.modify_parse_args(
["title:oldTitle", "title!"]
)
assert query == ["title:oldTitle"]
assert dels == ["title"]
def test_arg_parsing_query_with_exclaimation(self):
(query, mods, dels) = commands.modify_parse_args(
["title:oldTitle!", "title=newTitle!"]
)
assert query == ["title:oldTitle!"]
assert mods == {"title": "newTitle!"}
def test_arg_parsing_equals_in_value(self):
(query, mods, dels) = commands.modify_parse_args(
["title:foo=bar", "title=newTitle"]
)
assert query == ["title:foo=bar"]
assert mods == {"title": "newTitle"}
class WriteTest(BeetsTestCase):
def write_cmd(self, *args):
return self.run_with_output("write", *args)
def test_update_mtime(self):
item = self.add_item_fixture()
item["title"] = "a new title"
item.store()
item = self.lib.items().get()
assert item.mtime == 0
self.write_cmd()
item = self.lib.items().get()
assert item.mtime == item.current_mtime()
def test_non_metadata_field_unchanged(self):
"""Changing a non-"tag" field like `bitrate` and writing should
have no effect.
"""
# An item that starts out "clean".
item = self.add_item_fixture()
item.read()
# ... but with a mismatched bitrate.
item.bitrate = 123
item.store()
output = self.write_cmd()
assert output == ""
def test_write_metadata_field(self):
item = self.add_item_fixture()
item.read()
old_title = item.title
item.title = "new title"
item.store()
output = self.write_cmd()
assert f"{old_title} -> new title" in output
class MoveTest(BeetsTestCase):
def setUp(self):
super().setUp()
self.io.install()
self.itempath = os.path.join(self.libdir, b"srcfile")
shutil.copy(
syspath(os.path.join(_common.RSRC, b"full.mp3")),
syspath(self.itempath),
)
# Add a file to the library but don't copy it in yet.
self.i = library.Item.from_path(self.itempath)
self.lib.add(self.i)
self.album = self.lib.add_album([self.i])
# Alternate destination directory.
self.otherdir = os.path.join(self.temp_dir, b"testotherdir")
def _move(
self,
query=(),
dest=None,
copy=False,
album=False,
pretend=False,
export=False,
):
commands.move_items(
self.lib, dest, query, copy, album, pretend, export=export
)
def test_move_item(self):
self._move()
self.i.load()
assert b"libdir" in self.i.path
self.assertExists(self.i.path)
self.assertNotExists(self.itempath)
def test_copy_item(self):
self._move(copy=True)
self.i.load()
assert b"libdir" in self.i.path
self.assertExists(self.i.path)
self.assertExists(self.itempath)
def test_move_album(self):
self._move(album=True)
self.i.load()
assert b"libdir" in self.i.path
self.assertExists(self.i.path)
self.assertNotExists(self.itempath)
def test_copy_album(self):
self._move(copy=True, album=True)
self.i.load()
assert b"libdir" in self.i.path
self.assertExists(self.i.path)
self.assertExists(self.itempath)
def test_move_item_custom_dir(self):
self._move(dest=self.otherdir)
self.i.load()
assert b"testotherdir" in self.i.path
self.assertExists(self.i.path)
self.assertNotExists(self.itempath)
def test_move_album_custom_dir(self):
self._move(dest=self.otherdir, album=True)
self.i.load()
assert b"testotherdir" in self.i.path
self.assertExists(self.i.path)
self.assertNotExists(self.itempath)
def test_pretend_move_item(self):
self._move(dest=self.otherdir, pretend=True)
self.i.load()
assert b"srcfile" in self.i.path
def test_pretend_move_album(self):
self._move(album=True, pretend=True)
self.i.load()
assert b"srcfile" in self.i.path
def test_export_item_custom_dir(self):
self._move(dest=self.otherdir, export=True)
self.i.load()
assert self.i.path == self.itempath
self.assertExists(self.otherdir)
def test_export_album_custom_dir(self):
self._move(dest=self.otherdir, album=True, export=True)
self.i.load()
assert self.i.path == self.itempath
self.assertExists(self.otherdir)
def test_pretend_export_item(self):
self._move(dest=self.otherdir, pretend=True, export=True)
self.i.load()
assert b"srcfile" in self.i.path
self.assertNotExists(self.otherdir)
class UpdateTest(BeetsTestCase):
def setUp(self):
super().setUp()
self.io.install()
# Copy a file into the library.
item_path = os.path.join(_common.RSRC, b"full.mp3")
item_path_two = os.path.join(_common.RSRC, b"full.flac")
self.i = library.Item.from_path(item_path)
self.i2 = library.Item.from_path(item_path_two)
self.lib.add(self.i)
self.lib.add(self.i2)
self.i.move(operation=MoveOperation.COPY)
self.i2.move(operation=MoveOperation.COPY)
self.album = self.lib.add_album([self.i, self.i2])
# Album art.
artfile = os.path.join(self.temp_dir, b"testart.jpg")
_common.touch(artfile)
self.album.set_art(artfile)
self.album.store()
util.remove(artfile)
def _update(
self,
query=(),
album=False,
move=False,
reset_mtime=True,
fields=None,
exclude_fields=None,
):
self.io.addinput("y")
if reset_mtime:
self.i.mtime = 0
self.i.store()
commands.update_items(
self.lib,
query,
album,
move,
False,
fields=fields,
exclude_fields=exclude_fields,
)
def test_delete_removes_item(self):
assert list(self.lib.items())
util.remove(self.i.path)
util.remove(self.i2.path)
self._update()
assert not list(self.lib.items())
def test_delete_removes_album(self):
assert self.lib.albums()
util.remove(self.i.path)
util.remove(self.i2.path)
self._update()
assert not self.lib.albums()
def test_delete_removes_album_art(self):
artpath = self.album.artpath
self.assertExists(artpath)
util.remove(self.i.path)
util.remove(self.i2.path)
self._update()
self.assertNotExists(artpath)
def test_modified_metadata_detected(self):
mf = MediaFile(syspath(self.i.path))
mf.title = "differentTitle"
mf.save()
self._update()
item = self.lib.items().get()
assert item.title == "differentTitle"
def test_modified_metadata_moved(self):
mf = MediaFile(syspath(self.i.path))
mf.title = "differentTitle"
mf.save()
self._update(move=True)
item = self.lib.items().get()
assert b"differentTitle" in item.path
def test_modified_metadata_not_moved(self):
mf = MediaFile(syspath(self.i.path))
mf.title = "differentTitle"
mf.save()
self._update(move=False)
item = self.lib.items().get()
assert b"differentTitle" not in item.path
def test_selective_modified_metadata_moved(self):
mf = MediaFile(syspath(self.i.path))
mf.title = "differentTitle"
mf.genre = "differentGenre"
mf.save()
self._update(move=True, fields=["title"])
item = self.lib.items().get()
assert b"differentTitle" in item.path
assert item.genre != "differentGenre"
def test_selective_modified_metadata_not_moved(self):
mf = MediaFile(syspath(self.i.path))
mf.title = "differentTitle"
mf.genre = "differentGenre"
mf.save()
self._update(move=False, fields=["title"])
item = self.lib.items().get()
assert b"differentTitle" not in item.path
assert item.genre != "differentGenre"
def test_modified_album_metadata_moved(self):
mf = MediaFile(syspath(self.i.path))
mf.album = "differentAlbum"
mf.save()
self._update(move=True)
item = self.lib.items().get()
assert b"differentAlbum" in item.path
def test_modified_album_metadata_art_moved(self):
artpath = self.album.artpath
mf = MediaFile(syspath(self.i.path))
mf.album = "differentAlbum"
mf.save()
self._update(move=True)
album = self.lib.albums()[0]
assert artpath != album.artpath
assert album.artpath is not None
def test_selective_modified_album_metadata_moved(self):
mf = MediaFile(syspath(self.i.path))
mf.album = "differentAlbum"
mf.genre = "differentGenre"
mf.save()
self._update(move=True, fields=["album"])
item = self.lib.items().get()
assert b"differentAlbum" in item.path
assert item.genre != "differentGenre"
def test_selective_modified_album_metadata_not_moved(self):
mf = MediaFile(syspath(self.i.path))
mf.album = "differentAlbum"
mf.genre = "differentGenre"
mf.save()
self._update(move=True, fields=["genre"])
item = self.lib.items().get()
assert b"differentAlbum" not in item.path
assert item.genre == "differentGenre"
def test_mtime_match_skips_update(self):
mf = MediaFile(syspath(self.i.path))
mf.title = "differentTitle"
mf.save()
# Make in-memory mtime match on-disk mtime.
self.i.mtime = os.path.getmtime(syspath(self.i.path))
self.i.store()
self._update(reset_mtime=False)
item = self.lib.items().get()
assert item.title == "full"
def test_multivalued_albumtype_roundtrip(self):
# https://github.com/beetbox/beets/issues/4528
# albumtypes is empty for our test fixtures, so populate it first
album = self.album
correct_albumtypes = ["album", "live"]
# Setting albumtypes does not set albumtype, currently.
# Using x[0] mirrors https://github.com/beetbox/mediafile/blob/057432ad53b3b84385e5582f69f44dc00d0a725d/mediafile.py#L1928 # noqa: E501
correct_albumtype = correct_albumtypes[0]
album.albumtype = correct_albumtype
album.albumtypes = correct_albumtypes
album.try_sync(write=True, move=False)
album.load()
assert album.albumtype == correct_albumtype
assert album.albumtypes == correct_albumtypes
self._update()
album.load()
assert album.albumtype == correct_albumtype
assert album.albumtypes == correct_albumtypes
def test_modified_metadata_excluded(self):
mf = MediaFile(syspath(self.i.path))
mf.lyrics = "new lyrics"
mf.save()
self._update(exclude_fields=["lyrics"])
item = self.lib.items().get()
assert item.lyrics != "new lyrics"
class PrintTest(BeetsTestCase):
def setUp(self):
super().setUp()
self.io.install()
def test_print_without_locale(self):
lang = os.environ.get("LANG")
if lang:
del os.environ["LANG"]
try:
ui.print_("something")
except TypeError:
self.fail("TypeError during print")
finally:
if lang:
os.environ["LANG"] = lang
def test_print_with_invalid_locale(self):
old_lang = os.environ.get("LANG")
os.environ["LANG"] = ""
old_ctype = os.environ.get("LC_CTYPE")
os.environ["LC_CTYPE"] = "UTF-8"
try:
ui.print_("something")
except ValueError:
self.fail("ValueError during print")
finally:
if old_lang:
os.environ["LANG"] = old_lang
else:
del os.environ["LANG"]
if old_ctype:
os.environ["LC_CTYPE"] = old_ctype
else:
del os.environ["LC_CTYPE"]
class ImportTest(BeetsTestCase):
def test_quiet_timid_disallowed(self):
config["import"]["quiet"] = True
config["import"]["timid"] = True
with pytest.raises(ui.UserError):
commands.import_files(None, [], None)
def test_parse_paths_from_logfile(self):
if os.path.__name__ == "ntpath":
logfile_content = (
"import started Wed Jun 15 23:08:26 2022\n"
"asis C:\\music\\Beatles, The\\The Beatles; C:\\music\\Beatles, The\\The Beatles\\CD 01; C:\\music\\Beatles, The\\The Beatles\\CD 02\n" # noqa: E501
"duplicate-replace C:\\music\\Bill Evans\\Trio '65\n"
"skip C:\\music\\Michael Jackson\\Bad\n"
"skip C:\\music\\Soulwax\\Any Minute Now\n"
)
expected_paths = [
"C:\\music\\Beatles, The\\The Beatles",
"C:\\music\\Michael Jackson\\Bad",
"C:\\music\\Soulwax\\Any Minute Now",
]
else:
logfile_content = (
"import started Wed Jun 15 23:08:26 2022\n"
"asis /music/Beatles, The/The Beatles; /music/Beatles, The/The Beatles/CD 01; /music/Beatles, The/The Beatles/CD 02\n" # noqa: E501
"duplicate-replace /music/Bill Evans/Trio '65\n"
"skip /music/Michael Jackson/Bad\n"
"skip /music/Soulwax/Any Minute Now\n"
)
expected_paths = [
"/music/Beatles, The/The Beatles",
"/music/Michael Jackson/Bad",
"/music/Soulwax/Any Minute Now",
]
logfile = os.path.join(self.temp_dir, b"logfile.log")
with open(logfile, mode="w") as fp:
fp.write(logfile_content)
actual_paths = list(commands._paths_from_logfile(logfile))
assert actual_paths == expected_paths
@_common.slow_test()
class TestPluginTestCase(PluginTestCase):
plugin = "test"
def setUp(self):
super().setUp()
config["pluginpath"] = [_common.PLUGINPATH]
class ConfigTest(TestPluginTestCase):
def setUp(self):
super().setUp()
# Don't use the BEETSDIR from `helper`. Instead, we point the home
# directory there. Some tests will set `BEETSDIR` themselves.
del os.environ["BEETSDIR"]
# Also set APPDATA, the Windows equivalent of setting $HOME.
appdata_dir = os.fsdecode(
os.path.join(self.temp_dir, b"AppData", b"Roaming")
)
self._orig_cwd = os.getcwd()
self.test_cmd = self._make_test_cmd()
commands.default_commands.append(self.test_cmd)
# Default user configuration
if platform.system() == "Windows":
self.user_config_dir = os.fsencode(
os.path.join(appdata_dir, "beets")
)
else:
self.user_config_dir = os.path.join(
self.temp_dir, b".config", b"beets"
)
os.makedirs(syspath(self.user_config_dir))
self.user_config_path = os.path.join(
self.user_config_dir, b"config.yaml"
)
# Custom BEETSDIR
self.beetsdir = os.path.join(self.temp_dir, b"beetsdir")
os.makedirs(syspath(self.beetsdir))
self.env_patcher = patch(
"os.environ",
{"HOME": os.fsdecode(self.temp_dir), "APPDATA": appdata_dir},
)
self.env_patcher.start()
self._reset_config()
def tearDown(self):
self.env_patcher.stop()
commands.default_commands.pop()
os.chdir(syspath(self._orig_cwd))
super().tearDown()
def _make_test_cmd(self):
test_cmd = ui.Subcommand("test", help="test")
def run(lib, options, args):
test_cmd.lib = lib
test_cmd.options = options
test_cmd.args = args
test_cmd.func = run
return test_cmd
def _reset_config(self):
# Config should read files again on demand
config.clear()
config._materialized = False
def write_config_file(self):
return open(self.user_config_path, "w")
def test_paths_section_respected(self):
with self.write_config_file() as config:
config.write("paths: {x: y}")
self.run_command("test", lib=None)
key, template = self.test_cmd.lib.path_formats[0]
assert key == "x"
assert template.original == "y"
def test_default_paths_preserved(self):
default_formats = ui.get_path_formats()
self._reset_config()
with self.write_config_file() as config:
config.write("paths: {x: y}")
self.run_command("test", lib=None)
key, template = self.test_cmd.lib.path_formats[0]
assert key == "x"
assert template.original == "y"
assert self.test_cmd.lib.path_formats[1:] == default_formats
def test_nonexistant_db(self):
with self.write_config_file() as config:
config.write("library: /xxx/yyy/not/a/real/path")
with pytest.raises(ui.UserError):
self.run_command("test", lib=None)
def test_user_config_file(self):
with self.write_config_file() as file:
file.write("anoption: value")
self.run_command("test", lib=None)
assert config["anoption"].get() == "value"
def test_replacements_parsed(self):
with self.write_config_file() as config:
config.write("replace: {'[xy]': z}")
self.run_command("test", lib=None)
replacements = self.test_cmd.lib.replacements
repls = [(p.pattern, s) for p, s in replacements] # Compare patterns.
assert repls == [("[xy]", "z")]
def test_multiple_replacements_parsed(self):
with self.write_config_file() as config:
config.write("replace: {'[xy]': z, foo: bar}")
self.run_command("test", lib=None)
replacements = self.test_cmd.lib.replacements
repls = [(p.pattern, s) for p, s in replacements]
assert repls == [("[xy]", "z"), ("foo", "bar")]
def test_cli_config_option(self):
config_path = os.path.join(self.temp_dir, b"config.yaml")
with open(config_path, "w") as file:
file.write("anoption: value")
self.run_command("--config", config_path, "test", lib=None)
assert config["anoption"].get() == "value"
def test_cli_config_file_overwrites_user_defaults(self):
with open(self.user_config_path, "w") as file:
file.write("anoption: value")
cli_config_path = os.path.join(self.temp_dir, b"config.yaml")
with open(cli_config_path, "w") as file:
file.write("anoption: cli overwrite")
self.run_command("--config", cli_config_path, "test", lib=None)
assert config["anoption"].get() == "cli overwrite"
def test_cli_config_file_overwrites_beetsdir_defaults(self):
os.environ["BEETSDIR"] = os.fsdecode(self.beetsdir)
env_config_path = os.path.join(self.beetsdir, b"config.yaml")
with open(env_config_path, "w") as file:
file.write("anoption: value")
cli_config_path = os.path.join(self.temp_dir, b"config.yaml")
with open(cli_config_path, "w") as file:
file.write("anoption: cli overwrite")
self.run_command("--config", cli_config_path, "test", lib=None)
assert config["anoption"].get() == "cli overwrite"
# @unittest.skip('Difficult to implement with optparse')
# def test_multiple_cli_config_files(self):
# cli_config_path_1 = os.path.join(self.temp_dir, b'config.yaml')
# cli_config_path_2 = os.path.join(self.temp_dir, b'config_2.yaml')
#
# with open(cli_config_path_1, 'w') as file:
# file.write('first: value')
#
# with open(cli_config_path_2, 'w') as file:
# file.write('second: value')
#
# self.run_command('--config', cli_config_path_1,
# '--config', cli_config_path_2, 'test', lib=None)
# assert config['first'].get() == 'value'
# assert config['second'].get() == 'value'
#
# @unittest.skip('Difficult to implement with optparse')
# def test_multiple_cli_config_overwrite(self):