Debian Codegraph @

test/ui/test_ui.py

raw
1 """Tests for the command-line interface."""
2
3 import os
4 import platform
5 import sys
6 import unittest
7 from pathlib import Path
8 from unittest.mock import patch
9
10 import pytest
11 from confuse import ConfigError
12
13 from beets import config, plugins, ui
14 from beets.exceptions import UserError
15 from beets.test import _common
16 from beets.test.helper import BeetsTestCase, IOMixin, PluginTestCase
17 from beets.ui import _open_library, commands
18
19
20 class PrintTest(IOMixin, unittest.TestCase):
21 def test_print_without_locale(self):
22 with patch.dict(os.environ, {}, clear=False):
23 os.environ.pop("LANG", None)
24
25 ui.print_("something")
26
27 @patch.dict(os.environ, {"LANG": "", "LC_CTYPE": "UTF-8"}, clear=False)
28 def test_print_with_invalid_locale(self):
29 ui.print_("something")
30
31
32 class ShowModelChangesTest(IOMixin, BeetsTestCase):
33 def test_uses_database_state_when_old_not_provided(self):
34 item = self.add_item_fixture(title="old title")
35 old_label = format(item.get_fresh_from_db())
36
37 item.title = "new title"
38
39 assert ui.show_model_changes(item) is True
40 assert self.io.getoutput().splitlines() == [
41 old_label,
42 " title: old title -> new title",
43 ]
44
45
46 class TestPluginTestCase(PluginTestCase):
47 plugin = "test"
48
49 def setUp(self):
50 self.config["pluginpath"] = [_common.PLUGINPATH]
51 super().setUp()
52
53
54 class ConfigTest(IOMixin, TestPluginTestCase):
55 def setUp(self):
56 super().setUp()
57
58 # Don't use the BEETSDIR from `helper`. Instead, we point the home
59 # directory there. Some tests will set `BEETSDIR` themselves.
60 del os.environ["BEETSDIR"]
61
62 # Also set APPDATA, the Windows equivalent of setting $HOME.
63 appdata_dir = self.temp_path / "AppData" / "Roaming"
64
65 self._orig_cwd = Path.cwd()
66 self.test_cmd = self._make_test_cmd()
67 commands.default_commands.append(self.test_cmd)
68
69 # Default user configuration
70 if platform.system() == "Windows":
71 self.user_config_dir = appdata_dir / "beets"
72 else:
73 self.user_config_dir = self.temp_path / ".config" / "beets"
74 self.user_config_dir.mkdir(parents=True, exist_ok=True)
75 self.user_config_path = self.user_config_dir / "config.yaml"
76
77 # Custom BEETSDIR
78 self.beetsdir = self.temp_path / "beetsdir"
79 self.beetsdir.mkdir(parents=True, exist_ok=True)
80
81 self.env_config_path = self.beetsdir / "config.yaml"
82 self.cli_config_path = self.temp_path / "config.yaml"
83 self.env_patcher = patch(
84 "os.environ",
85 {"HOME": str(self.temp_path), "APPDATA": str(appdata_dir)},
86 )
87 self.env_patcher.start()
88
89 self._reset_config()
90
91 def run_command(self, *args, **kwargs):
92 # We need to reload the lib based on the
93 # current config
94 self.lib = _open_library(self.config)
95 super().run_command(*args, **kwargs)
96
97 def tearDown(self):
98 self.env_patcher.stop()
99 commands.default_commands.pop()
100 os.chdir(self._orig_cwd)
101 super().tearDown()
102
103 def _make_test_cmd(self):
104 test_cmd = ui.Subcommand("test", help="test")
105
106 def run(lib, options, args):
107 test_cmd.lib = lib
108 test_cmd.options = options
109 test_cmd.args = args
110
111 test_cmd.func = run
112 return test_cmd
113
114 def _reset_config(self):
115 # Config should read files again on demand
116 config.clear()
117 config._materialized = False
118
119 def write_config_file(self):
120 return self.user_config_path.open("w")
121
122 def test_paths_section_respected(self):
123 with self.write_config_file() as config:
124 config.write("paths: {x: y}")
125
126 self.run_command("test")
127 assert self.test_cmd.lib.path_formats[0] == ("x", "y")
128
129 def test_nonexistant_db(self):
130 with self.write_config_file() as config:
131 config.write("library: /xxx/yyy/not/a/real/path")
132
133 self.io.addinput("n")
134 with pytest.raises(UserError):
135 self.run_command("test")
136
137 def test_user_config_file(self):
138 with self.write_config_file() as file:
139 file.write("anoption: value")
140
141 self.run_command("test")
142 assert config["anoption"].get() == "value"
143
144 def test_replacements_parsed(self):
145 with self.write_config_file() as config:
146 config.write("replace: {'[xy]': z}")
147
148 self.run_command("test")
149 replacements = self.test_cmd.lib.replacements
150 repls = [(p.pattern, s) for p, s in replacements] # Compare patterns.
151 assert repls == [("[xy]", "z")]
152
153 def test_multiple_replacements_parsed(self):
154 with self.write_config_file() as config:
155 config.write("replace: {'[xy]': z, foo: bar}")
156 self.run_command("test")
157 replacements = self.test_cmd.lib.replacements
158 repls = [(p.pattern, s) for p, s in replacements]
159 assert repls == [("[xy]", "z"), ("foo", "bar")]
160
161 def test_cli_config_option(self):
162 self.cli_config_path.write_text("anoption: value")
163 self.run_command("--config", str(self.cli_config_path), "test")
164 assert config["anoption"].get() == "value"
165
166 def test_cli_config_file_overwrites_user_defaults(self):
167 self.user_config_path.write_text("anoption: value")
168
169 self.cli_config_path.write_text("anoption: cli overwrite")
170 self.run_command("--config", str(self.cli_config_path), "test")
171 assert config["anoption"].get() == "cli overwrite"
172
173 def test_cli_config_file_overwrites_beetsdir_defaults(self):
174 os.environ["BEETSDIR"] = str(self.beetsdir)
175 self.env_config_path.write_text("anoption: value")
176
177 self.cli_config_path.write_text("anoption: cli overwrite")
178 self.run_command("--config", str(self.cli_config_path), "test")
179 assert config["anoption"].get() == "cli overwrite"
180
181 # @unittest.skip('Difficult to implement with optparse')
182 # def test_multiple_cli_config_files(self):
183 # cli_config_path_1 = self.temp_path / 'config.yaml'
184 # cli_config_path_2 = self.temp_path / 'config_2.yaml'
185 #
186 # with open(cli_config_path_1, 'w') as file:
187 # file.write('first: value')
188 #
189 # with open(cli_config_path_2, 'w') as file:
190 # file.write('second: value')
191 #
192 # self.run_command('--config', cli_config_path_1,
193 # '--config', cli_config_path_2, 'test')
194 # assert config['first'].get() == 'value'
195 # assert config['second'].get() == 'value'
196 #
197 # @unittest.skip('Difficult to implement with optparse')
198 # def test_multiple_cli_config_overwrite(self):
199 # cli_overwrite_config_path = self.temp_path / 'overwrite_config.yaml'
200 #
201 # self.cli_config_path.write_text("anoption: value")
202 #
203 # with open(cli_overwrite_config_path, 'w') as file:
204 # file.write('anoption: overwrite')
205 #
206 # self.run_command('--config', str(self.cli_config_path),
207 # '--config', cli_overwrite_config_path, 'test')
208 # assert config['anoption'].get() == 'cli overwrite'
209
210 # FIXME: fails on windows
211 @unittest.skipIf(sys.platform == "win32", "win32")
212 def test_cli_config_paths_resolve_relative_to_user_dir(self):
213 self.cli_config_path.write_text("library: beets.db\nstatefile: state")
214
215 self.run_command("--config", str(self.cli_config_path), "test")
216 assert config["library"].as_path() == self.user_config_dir / "beets.db"
217 assert config["statefile"].as_path() == self.user_config_dir / "state"
218
219 def test_cli_config_paths_resolve_relative_to_beetsdir(self):
220 os.environ["BEETSDIR"] = str(self.beetsdir)
221
222 self.cli_config_path.write_text("library: beets.db\nstatefile: state")
223
224 self.run_command("--config", str(self.cli_config_path), "test")
225 assert config["library"].as_path() == self.beetsdir / "beets.db"
226 assert config["statefile"].as_path() == self.beetsdir / "state"
227
228 def test_command_line_option_relative_to_working_dir(self):
229 config.read()
230 os.chdir(self.temp_path)
231 self.run_command("--library", "foo.db", "test")
232 assert config["library"].as_path() == Path.cwd() / "foo.db"
233
234 def test_cli_config_file_loads_plugin_commands(self):
235 self.cli_config_path.write_text(
236 f"pluginpath: {_common.PLUGINPATH}\nplugins: test"
237 )
238
239 self.run_command("--config", str(self.cli_config_path), "plugin")
240 plugs = plugins.find_plugins()
241 assert len(plugs) == 1
242 assert plugs[0].is_test_plugin
243 self.unload_plugins()
244
245 def test_beetsdir_config(self):
246 os.environ["BEETSDIR"] = str(self.beetsdir)
247
248 self.env_config_path.write_text("anoption: overwrite")
249
250 config.read()
251 assert config["anoption"].get() == "overwrite"
252
253 def test_beetsdir_points_to_file_error(self):
254 beetsdir = self.temp_path / "beetsfile"
255 beetsdir.touch()
256 os.environ["BEETSDIR"] = str(beetsdir)
257 with pytest.raises(ConfigError):
258 self.run_command("test")
259
260 def test_beetsdir_config_does_not_load_default_user_config(self):
261 os.environ["BEETSDIR"] = str(self.beetsdir)
262
263 self.user_config_path.write_text("anoption: value")
264
265 config.read()
266 assert not config["anoption"].exists()
267
268 def test_default_config_paths_resolve_relative_to_beetsdir(self):
269 os.environ["BEETSDIR"] = str(self.beetsdir)
270
271 config.read()
272 assert config["library"].as_path() == self.beetsdir / "library.db"
273 assert config["statefile"].as_path() == self.beetsdir / "state.pickle"
274
275 def test_beetsdir_config_paths_resolve_relative_to_beetsdir(self):
276 os.environ["BEETSDIR"] = str(self.beetsdir)
277
278 self.env_config_path.write_text("library: beets.db\nstatefile: state")
279
280 config.read()
281 assert config["library"].as_path() == self.beetsdir / "beets.db"
282 assert config["statefile"].as_path() == self.beetsdir / "state"
283
284
285 class PluginTest(TestPluginTestCase):
286 def test_plugin_command_from_pluginpath(self):
287 self.run_command("test")
288
289
290 class CommonOptionsParserCliTest(IOMixin, BeetsTestCase):
291 """Test CommonOptionsParser and formatting LibModel formatting on 'list'
292 command.
293 """
294
295 def setUp(self):
296 super().setUp()
297 self.item = _common.item()
298 self.item.path = b"xxx/yyy"
299 self.lib.add(self.item)
300 self.lib.add_album([self.item])
301
302 def test_base(self):
303 output = self.run_with_output("ls")
304 assert output == "the artist - the album - the title\n"
305
306 output = self.run_with_output("ls", "-a")
307 assert output == "the album artist - the album\n"
308
309 def test_path_option(self):
310 output = self.run_with_output("ls", "-p")
311 assert output == f"{self.lib_path / 'xxx/yyy'}\n"
312
313 output = self.run_with_output("ls", "-a", "-p")
314 assert output == f"{self.lib_path / 'xxx'}\n"
315
316 def test_format_option(self):
317 output = self.run_with_output("ls", "-f", "$artist")
318 assert output == "the artist\n"
319
320 output = self.run_with_output("ls", "-a", "-f", "$albumartist")
321 assert output == "the album artist\n"
322
323 def test_format_option_unicode(self):
324 output = self.run_with_output("ls", "-f", "caf\xe9")
325 assert output == "caf\xe9\n"
326
327 def test_root_format_option(self):
328 output = self.run_with_output(
329 "--format-item", "$artist", "--format-album", "foo", "ls"
330 )
331 assert output == "the artist\n"
332
333 output = self.run_with_output(
334 "--format-item", "foo", "--format-album", "$albumartist", "ls", "-a"
335 )
336 assert output == "the album artist\n"
337
338 def test_help(self):
339 output = self.run_with_output("help")
340 assert "Usage:" in output
341
342 # command description is on the same line
343 assert (
344 "config show or edit the user configuration" in output
345 ), "unexpected command description formatting"
346
347 output = self.run_with_output("help", "list")
348 assert "Usage:" in output
349
350 with pytest.raises(UserError):
351 self.run_command("help", "this.is.not.a.real.command")
352
353 def test_stats(self):
354 output = self.run_with_output("stats")
355 assert "Approximate total size:" in output
356
357 # # Need to have more realistic library setup for this to work
358 # output = self.run_with_output('stats', '-e')
359 # assert 'Total size:' in output
360
361 def test_version(self):
362 output = self.run_with_output("version")
363 assert "Python version" in output
364 assert "no plugins loaded" in output
365
366 # # Need to have plugin loaded
367 # output = self.run_with_output('version')
368 # assert 'plugins: ' in output
369
370
371 class CommonOptionsParserTest(unittest.TestCase):
372 def test_album_option(self):
373 parser = ui.CommonOptionsParser()
374 assert not parser._album_flags
375 parser.add_album_option()
376 assert bool(parser._album_flags)
377
378 assert parser.parse_args([]) == ({"album": False}, [])
379 assert parser.parse_args(["-a"]) == ({"album": True}, [])
380 assert parser.parse_args(["--album"]) == ({"album": True}, [])
381
382 def test_path_option(self):
383 parser = ui.CommonOptionsParser()
384 parser.add_path_option()
385 assert not parser._album_flags
386
387 config["format_item"].set("$foo")
388 assert parser.parse_args([]) == ({"path": None}, [])
389 assert config["format_item"].as_str() == "$foo"
390
391 assert parser.parse_args(["-p"]) == (
392 {"path": True, "format": "$path"},
393 [],
394 )
395 assert parser.parse_args(["--path"]) == (
396 {"path": True, "format": "$path"},
397 [],
398 )
399
400 assert config["format_item"].as_str() == "$path"
401 assert config["format_album"].as_str() == "$path"
402
403 def test_format_option(self):
404 parser = ui.CommonOptionsParser()
405 parser.add_format_option()
406 assert not parser._album_flags
407
408 config["format_item"].set("$foo")
409 assert parser.parse_args([]) == ({"format": None}, [])
410 assert config["format_item"].as_str() == "$foo"
411
412 assert parser.parse_args(["-f", "$bar"]) == ({"format": "$bar"}, [])
413 assert parser.parse_args(["--format", "$baz"]) == (
414 {"format": "$baz"},
415 [],
416 )
417
418 assert config["format_item"].as_str() == "$baz"
419 assert config["format_album"].as_str() == "$baz"
420
421 def test_format_option_with_target(self):
422 with pytest.raises(KeyError):
423 ui.CommonOptionsParser().add_format_option(target="thingy")
424
425 parser = ui.CommonOptionsParser()
426 parser.add_format_option(target="item")
427
428 config["format_item"].set("$item")
429 config["format_album"].set("$album")
430
431 assert parser.parse_args(["-f", "$bar"]) == ({"format": "$bar"}, [])
432
433 assert config["format_item"].as_str() == "$bar"
434 assert config["format_album"].as_str() == "$album"
435
436 def test_format_option_with_album(self):
437 parser = ui.CommonOptionsParser()
438 parser.add_album_option()
439 parser.add_format_option()
440
441 config["format_item"].set("$item")
442 config["format_album"].set("$album")
443
444 parser.parse_args(["-f", "$bar"])
445 assert config["format_item"].as_str() == "$bar"
446 assert config["format_album"].as_str() == "$album"
447
448 parser.parse_args(["-a", "-f", "$foo"])
449 assert config["format_item"].as_str() == "$bar"
450 assert config["format_album"].as_str() == "$foo"
451
452 parser.parse_args(["-f", "$foo2", "-a"])
453 assert config["format_album"].as_str() == "$foo2"
454
455 def test_add_all_common_options(self):
456 parser = ui.CommonOptionsParser()
457 parser.add_all_common_options()
458 assert parser.parse_args([]) == (
459 {"album": False, "path": None, "format": None},
460 [],
461 )
462
463
464 class TestEncoding:
465 """Tests for the `terminal_encoding` config option and our
466 `_in_encoding` and `_out_encoding` utility functions.
467 """
468
469 def test_out_encoding_overridden(self, config):
470 config["terminal_encoding"] = "fake_encoding"
471 assert ui._out_encoding() == "fake_encoding"
472
473 def test_in_encoding_overridden(self, config):
474 config["terminal_encoding"] = "fake_encoding"
475 assert ui._in_encoding() == "fake_encoding"
476
477 def test_out_encoding_default_utf8(self, config):
478 config["terminal_encoding"] = None
479 with patch("sys.stdout") as stdout:
480 stdout.encoding = None
481 assert ui._out_encoding() == "utf-8"
482
483 def test_in_encoding_default_utf8(self, config):
484 config["terminal_encoding"] = None
485 with patch("sys.stdin") as stdin:
486 stdin.encoding = None
487 assert ui._in_encoding() == "utf-8"