Debian Codegraph @

test/test_util.py

raw
1 """Tests for base utils from the beets.util package."""
2
3 import os
4 import platform
5 import re
6 import subprocess
7 import sys
8 import unittest
9 from pathlib import Path
10 from unittest.mock import Mock, patch
11
12 import pytest
13
14 from beets import util
15 from beets.library import Item
16 from beets.test import _common
17 from beets.test.helper import NEEDS_REFLINK, BeetsTestCase
18
19 _p = pytest.param
20
21
22 class UtilTest(unittest.TestCase):
23 def test_open_anything(self):
24 with _common.system_mock("Windows"):
25 assert util.open_anything() == 'cmd /c start ""'
26
27 with _common.system_mock("Darwin"):
28 assert util.open_anything() == "open"
29
30 with _common.system_mock("Tagada"):
31 assert util.open_anything() == "xdg-open"
32
33 @patch("os.execlp")
34 @patch("beets.util.open_anything")
35 def test_interactive_open(self, mock_open, mock_execlp):
36 mock_open.return_value = "tagada"
37 util.interactive_open(["foo"], util.open_anything())
38 mock_execlp.assert_called_once_with("tagada", "tagada", "foo")
39 mock_execlp.reset_mock()
40
41 util.interactive_open(["foo"], "bar")
42 mock_execlp.assert_called_once_with("bar", "bar", "foo")
43
44 def test_sanitize_unix_replaces_leading_dot(self):
45 with _common.platform_posix():
46 p = util.sanitize_path("one/.two/three")
47 assert "." not in p
48
49 def test_sanitize_windows_replaces_trailing_dot(self):
50 with _common.platform_windows():
51 p = util.sanitize_path("one/two./three")
52 assert "." not in p
53
54 def test_sanitize_windows_replaces_illegal_chars(self):
55 with _common.platform_windows():
56 p = util.sanitize_path(':*?"<>|')
57 assert ":" not in p
58 assert "*" not in p
59 assert "?" not in p
60 assert '"' not in p
61 assert "<" not in p
62 assert ">" not in p
63 assert "|" not in p
64
65 def test_sanitize_windows_replaces_trailing_space(self):
66 with _common.platform_windows():
67 p = util.sanitize_path("one/two /three")
68 assert " " not in p
69
70 def test_sanitize_path_works_on_empty_string(self):
71 with _common.platform_posix():
72 p = util.sanitize_path("")
73 assert p == ""
74
75 def test_sanitize_with_custom_replace_overrides_built_in_sub(self):
76 with _common.platform_posix():
77 p = util.sanitize_path("a/.?/b", [(re.compile(r"foo"), "bar")])
78 assert p == "a/.?/b"
79
80 def test_sanitize_with_custom_replace_adds_replacements(self):
81 with _common.platform_posix():
82 p = util.sanitize_path("foo/bar", [(re.compile(r"foo"), "bar")])
83 assert p == "bar/bar"
84
85 @unittest.skip("unimplemented: #359")
86 def test_sanitize_empty_component(self):
87 with _common.platform_posix():
88 p = util.sanitize_path("foo//bar", [(re.compile(r"^$"), "_")])
89 assert p == "foo/_/bar"
90
91 @patch("beets.util.subprocess.Popen")
92 def test_command_output(self, mock_popen):
93 def popen_fail(*args, **kwargs):
94 m = Mock(returncode=1)
95 m.communicate.return_value = "foo", "bar"
96 return m
97
98 mock_popen.side_effect = popen_fail
99 with pytest.raises(subprocess.CalledProcessError) as exc_info:
100 util.command_output(["taga", "\xc3\xa9"])
101 assert exc_info.value.returncode == 1
102 assert exc_info.value.cmd == "taga \xc3\xa9"
103
104 def test_case_sensitive_default(self):
105 path = util.bytestring_path(util.normpath("/this/path/does/not/exist"))
106
107 assert util.case_sensitive(path) == (platform.system() != "Windows")
108
109 @unittest.skipIf(sys.platform == "win32", "fs is not case sensitive")
110 def test_case_sensitive_detects_sensitive(self):
111 # FIXME: Add tests for more code paths of case_sensitive()
112 # when the filesystem on the test runner is not case sensitive
113 pass
114
115 @unittest.skipIf(sys.platform != "win32", "fs is case sensitive")
116 def test_case_sensitive_detects_insensitive(self):
117 # FIXME: Add tests for more code paths of case_sensitive()
118 # when the filesystem on the test runner is case sensitive
119 pass
120
121
122 class PathConversionTest(unittest.TestCase):
123 def test_syspath_windows_format(self):
124 with _common.platform_windows():
125 path = Path("a") / "b" / "c"
126 outpath = util.syspath(path)
127 assert isinstance(outpath, str)
128 assert outpath.startswith("\\\\?\\")
129
130 def test_syspath_windows_format_unc_path(self):
131 # The \\?\ prefix on Windows behaves differently with UNC
132 # (network share) paths.
133 path = "\\\\server\\share\\file.mp3"
134 with _common.platform_windows():
135 outpath = util.syspath(path)
136 assert isinstance(outpath, str)
137 assert outpath == "\\\\?\\UNC\\server\\share\\file.mp3"
138
139 def test_syspath_posix_unchanged(self):
140 with _common.platform_posix():
141 path = str(Path("a") / "b" / "c")
142 outpath = util.syspath(path)
143 assert path == outpath
144
145 def _windows_bytestring_path(self, path):
146 with _common.platform_windows():
147 return util.bytestring_path(path)
148
149 def test_bytestring_path_windows_encodes_utf8(self):
150 path = "caf\xe9"
151 outpath = self._windows_bytestring_path(path)
152 assert path == outpath.decode("utf-8")
153
154 def test_bytesting_path_windows_removes_magic_prefix(self):
155 path = "\\\\?\\C:\\caf\xe9"
156 outpath = self._windows_bytestring_path(path)
157 assert outpath == "C:\\caf\xe9".encode()
158
159
160 class TestPathLegalization:
161 _p = pytest.param
162
163 @pytest.fixture(autouse=True)
164 def _patch_max_filename_length(self, monkeypatch):
165 monkeypatch.setattr("beets.util.get_max_filename_length", lambda: 5)
166
167 @pytest.mark.parametrize(
168 "path, expected",
169 [
170 _p("abcdeX/fgh", "abcde/fgh", id="truncate-parent-dir"),
171 _p("abcde/fXX.ext", "abcde/f.ext", id="truncate-filename"),
172 # note that 🎹 is 4 bytes long:
173 # >>> "🎹".encode("utf-8")
174 # b'\xf0\x9f\x8e\xb9'
175 _p("a🎹/a.ext", "a🎹/a.ext", id="unicode-fit"),
176 _p("ab🎹/a.ext", "ab/a.ext", id="unicode-truncate-fully-one-byte-over-limit"),
177 _p("f.a.e", "f.a.e", id="persist-dot-in-filename"), # see #5771
178 ],
179 ) # fmt: skip
180 def test_truncate(self, path, expected):
181 path = path.replace("/", os.path.sep)
182 expected = expected.replace("/", os.path.sep)
183
184 assert util.truncate_path(path) == expected
185
186 @pytest.mark.parametrize(
187 "replacements, expected_path, expected_truncated",
188 [ # [ repl before truncation, repl after truncation ]
189 _p([ ], "_abcd", False, id="default"),
190 _p([(r"abcdX$", "1ST"), ], ":1ST", False, id="1st_valid"),
191 _p([(r"abcdX$", "TOO_LONG"), ], ":TOO_", False, id="1st_truncated"),
192 _p([(r"abcdX$", "1ST"), (r"1ST$", "2ND") ], ":2ND", False, id="both_valid"),
193 _p([(r"abcdX$", "TOO_LONG"), (r"TOO_$", "2ND") ], ":2ND", False, id="1st_truncated_2nd_valid"),
194 _p([(r"abcdX$", "1ST"), (r"1ST$", "TOO_LONG") ], ":TOO_", False, id="1st_valid_2nd_truncated"),
195 # if the logic truncates the path twice, it ends up applying the default replacements
196 _p([(r"abcdX$", "TOO_LONG"), (r"TOO_$", "TOO_LONG") ], "_TOO_", True, id="both_truncated_default_repl_applied"),
197 ]
198 ) # fmt: skip
199 def test_replacements(
200 self, replacements, expected_path, expected_truncated
201 ):
202 replacements = [(re.compile(pat), repl) for pat, repl in replacements]
203
204 assert util.legalize_path(":abcdX", replacements, "") == (
205 expected_path,
206 expected_truncated,
207 )
208
209
210 class TestPlurality:
211 @pytest.mark.parametrize(
212 "objs, expected_obj, expected_freq",
213 [
214 pytest.param([1, 1, 1, 1], 1, 4, id="consensus"),
215 pytest.param([1, 1, 2, 1], 1, 3, id="near consensus"),
216 pytest.param([1, 1, 2, 2, 3], 1, 2, id="conflict-first-wins"),
217 ],
218 )
219 def test_plurality(self, objs, expected_obj, expected_freq):
220 assert (expected_obj, expected_freq) == util.plurality(objs)
221
222 def test_empty_sequence_raises_error(self):
223 with pytest.raises(ValueError, match="must be non-empty"):
224 util.plurality([])
225
226 def test_get_most_common_tags(self):
227 items = [
228 Item(albumartist="aartist", label="label 1", album="album"),
229 Item(albumartist="aartist", label="label 2", album="album"),
230 Item(albumartist="aartist", label="label 3", album="another album"),
231 ]
232
233 likelies = util.get_most_common_tags(items)
234
235 assert likelies["albumartist"] == "aartist"
236 assert likelies["album"] == "album"
237 # albumartist consensus overrides artist
238 assert likelies["artist"] == "aartist"
239 assert likelies["label"] == "label 1"
240 assert likelies["year"] == 0
241
242
243 class HelperTest(unittest.TestCase):
244 def test_ancestry_works_on_file(self):
245 p = "/a/b/c"
246 a = ["/", "/a", "/a/b"]
247 assert util.ancestry(p) == a
248
249 def test_ancestry_works_on_dir(self):
250 p = "/a/b/c/"
251 a = ["/", "/a", "/a/b", "/a/b/c"]
252 assert util.ancestry(p) == a
253
254 def test_ancestry_works_on_relative(self):
255 p = "a/b/c"
256 a = ["a", "a/b"]
257 assert util.ancestry(p) == a
258
259 def test_components_works_on_file(self):
260 p = "/a/b/c"
261 a = ["/", "a", "b", "c"]
262 assert util.components(p) == a
263
264 def test_components_works_on_dir(self):
265 p = "/a/b/c/"
266 a = ["/", "a", "b", "c"]
267 assert util.components(p) == a
268
269 def test_components_works_on_relative(self):
270 p = "a/b/c"
271 a = ["a", "b", "c"]
272 assert util.components(p) == a
273
274 def test_forward_slash(self):
275 p = rb"C:\a\b\c"
276 a = rb"C:/a/b/c"
277 assert util.path_as_posix(p) == a
278
279
280 class FilePathTestCase(BeetsTestCase):
281 def setUp(self):
282 super().setUp()
283
284 self.path = self.temp_path / "testfile"
285 self.path.touch()
286
287
288 # Tests that we can "delete" nonexistent files.
289 class SoftRemoveTest(FilePathTestCase):
290 def test_soft_remove_deletes_file(self):
291 util.remove(self.path, True)
292 assert not self.path.exists()
293
294 def test_soft_remove_silent_on_no_file(self):
295 util.remove(self.path / "XXX", True)
296
297
298 class SafeMoveCopyTest(FilePathTestCase):
299 def setUp(self):
300 super().setUp()
301
302 self.otherpath = self.temp_path / "testfile2"
303 self.otherpath.touch()
304 self.dest = Path(f"{self.path}.dest")
305
306 def test_successful_move(self):
307 util.move(self.path, self.dest)
308 assert self.dest.exists()
309 assert not self.path.exists()
310
311 def test_successful_copy(self):
312 util.copy(self.path, self.dest)
313 assert self.dest.exists()
314 assert self.path.exists()
315
316 @NEEDS_REFLINK
317 def test_successful_reflink(self):
318 util.reflink(str(self.path), str(self.dest))
319 assert self.dest.exists()
320 assert self.path.exists()
321
322 def test_unsuccessful_move(self):
323 with pytest.raises(util.FilesystemError):
324 util.move(self.path, self.otherpath)
325
326 def test_unsuccessful_copy(self):
327 with pytest.raises(util.FilesystemError):
328 util.copy(self.path, self.otherpath)
329
330 def test_unsuccessful_reflink(self):
331 with pytest.raises(util.FilesystemError, match="target exists"):
332 util.reflink(self.path, self.otherpath)
333
334 def test_self_move(self):
335 util.move(self.path, self.path)
336 assert self.path.exists()
337
338 def test_self_copy(self):
339 util.copy(self.path, self.path)
340 assert self.path.exists()
341
342
343 class PruneTest(BeetsTestCase):
344 def setUp(self):
345 super().setUp()
346
347 self.base = self.temp_path / "testdir"
348 self.base.mkdir()
349 self.sub = self.base / "subdir"
350 self.sub.mkdir()
351
352 def test_prune_existent_directory(self):
353 util.prune_dirs(self.sub, self.base)
354 assert self.base.exists()
355 assert not self.sub.exists()
356
357 def test_prune_nonexistent_directory(self):
358 util.prune_dirs(self.sub / "another", self.base)
359 assert self.base.exists()
360 assert not self.sub.exists()
361
362
363 class WalkTest(BeetsTestCase):
364 def setUp(self):
365 super().setUp()
366
367 self.base = self.temp_path / "testdir"
368 self.base.mkdir()
369 (self.base / "y").touch()
370 (self.base / "x").touch()
371 base_d = self.base / "d"
372 base_d.mkdir()
373 (base_d / "z").touch()
374 self.str_base = str(self.base)
375
376 def test_sorted_files(self):
377 res = list(util.sorted_walk(self.str_base))
378 assert len(res) == 2
379 assert res[0] == (self.str_base, ["d"], ["x", "y"])
380 assert res[1] == (str(self.base / "d"), [], ["z"])
381
382 def test_ignore_file(self):
383 res = list(util.sorted_walk(self.str_base, ("x",)))
384 assert len(res) == 2
385 assert res[0] == (self.str_base, ["d"], ["y"])
386 assert res[1] == (str(self.base / "d"), [], ["z"])
387
388 def test_ignore_directory(self):
389 res = list(util.sorted_walk(self.str_base, ("d",)))
390 assert len(res) == 1
391 assert res[0] == (self.str_base, [], ["x", "y"])
392
393 def test_ignore_everything(self):
394 res = list(util.sorted_walk(self.str_base, ("*",)))
395 assert len(res) == 1
396 assert res[0] == (self.str_base, [], [])
397
398
399 class UniquePathTest(BeetsTestCase):
400 def setUp(self):
401 super().setUp()
402
403 self.base = self.temp_path / "testdir"
404 self.base.mkdir()
405 (self.base / "x.mp3").touch()
406 (self.base / "x.1.mp3").touch()
407 (self.base / "x.2.mp3").touch()
408 (self.base / "y.mp3").touch()
409
410 def test_new_file_unchanged(self):
411 path = util.unique_path(self.base / "z.mp3")
412 assert path == self.base / "z.mp3"
413
414 def test_conflicting_file_appends_1(self):
415 path = util.unique_path(self.base / "y.mp3")
416 assert path == str(self.base / "y.1.mp3")
417
418 def test_conflicting_file_appends_higher_number(self):
419 path = util.unique_path(self.base / "x.mp3")
420 assert path == str(self.base / "x.3.mp3")
421
422 def test_conflicting_file_with_number_increases_number(self):
423 path = util.unique_path(self.base / "x.1.mp3")
424 assert path == str(self.base / "x.3.mp3")
425
426 def test_conflicting_file_with_multi_digit_number_increases_number(self):
427 (self.base / "w.10.mp3").touch()
428 path = util.unique_path(self.base / "w.10.mp3")
429 assert path == str(self.base / "w.11.mp3")
430
431
432 class MkDirAllTest(BeetsTestCase):
433 def test_mkdirall(self):
434 child = self.temp_path / "foo" / "bar" / "baz" / "quz.mp3"
435 util.mkdirall(child)
436 assert not child.exists()
437 assert child.parent.exists()
438 assert child.parent.is_dir()
439
440
441 class TestAsciifyPath:
442 @pytest.fixture(autouse=True)
443 def _setup_config(self, config):
444 config["path_sep_replace"] = "_"
445
446 @pytest.mark.parametrize(
447 "platform, normalization",
448 [
449 _p("darwin", "NFD", id="macos"),
450 _p("linux", "NFC", id="other-platform"),
451 ],
452 )
453 def test_normalizes_unicode_for_platform(
454 self, monkeypatch, platform, normalization
455 ):
456 normalize = Mock(wraps=util.unicodedata.normalize)
457 monkeypatch.setattr("sys.platform", platform)
458 monkeypatch.setattr("beets.util.unicodedata.normalize", normalize)
459
460 assert util.asciify_path("caf\xe9") == "cafe"
461 normalize.assert_called_once_with(normalization, "caf\xe9")
462
463 @pytest.mark.parametrize(
464 "path, expected",
465 [
466 _p("plain", "plain", id="ascii"),
467 _p("\u201c\u00f6\u2014\u00cf\u201d", '"o--I"', id="unicode"),
468 _p(
469 f"caf\xe9{os.sep}na\xefve",
470 f"cafe{os.sep}naive",
471 id="path-components",
472 ),
473 ],
474 )
475 def test_transliterates_path(self, path, expected):
476 assert util.asciify_path(path) == expected
477
478 @pytest.mark.parametrize(
479 "replacement, expected",
480 [
481 _p("_", "abC_ 1_2d", id="default"),
482 _p("-", "abC- 1-2d", id="configured"),
483 ],
484 )
485 def test_replaces_generated_separators(self, config, replacement, expected):
486 config["path_sep_replace"] = replacement
487
488 assert util.asciify_path("ab\xa2\xbdd") == expected
489
490 def test_normalizes_alternate_path_separator(self, monkeypatch):
491 monkeypatch.setattr("beets.util.os.sep", "/")
492 monkeypatch.setattr("beets.util.os.altsep", "\\")
493
494 assert util.asciify_path("caf\xe9\\na\xefve") == "cafe/naive"
495
496
497 class EditorCommandTest(unittest.TestCase):
498 def test_editor_command_from_config(self):
499 """editor config option takes priority over environment variables."""
500 from beets import config
501
502 config.set({"editor": "nano"})
503 with patch.dict(os.environ, {"VISUAL": "vim", "EDITOR": "emacs"}):
504 assert util.editor_command() == "nano"
505
506 def test_editor_command_falls_back_to_visual(self):
507 """Falls back to $VISUAL when no editor config is set."""
508 with patch.dict(
509 os.environ, {"VISUAL": "vim", "EDITOR": "emacs"}, clear=True
510 ):
511 assert util.editor_command() == "vim"
512
513 def test_editor_command_falls_back_to_editor_env(self):
514 """Falls back to $EDITOR when no editor config or $VISUAL is set."""
515 with patch.dict(os.environ, {"EDITOR": "emacs"}, clear=True):
516 assert util.editor_command() == "emacs"