Skip to content

Commit a4ad7d4

Browse files
authored
Remove lib parameter from _raw_main and _setup (#6547)
## Description The `lib` parameter on `_raw_main` and `_setup` was only used by the test harness. Rather than keep testing-specific logic in production code, this PR removes the parameter and updates the test harness to patch `_open_library` instead. - [x] ~~Changelog.~~ (Not needed as this is a purely internal factor imo)
2 parents e550482 + 7f48672 commit a4ad7d4

4 files changed

Lines changed: 42 additions & 36 deletions

File tree

beets/test/helper.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
from pathlib import Path
3939
from tempfile import gettempdir, mkdtemp, mkstemp
4040
from typing import Any, ClassVar
41-
from unittest.mock import patch
41+
from unittest.mock import Mock, patch
4242

4343
import pytest
4444
import responses
@@ -126,17 +126,21 @@ def config(self) -> beets.IncludeLazyConfig:
126126

127127

128128
class RunMixin:
129-
def run_command(self, *args, **kwargs):
129+
lib: Library
130+
131+
def run_command(self, *args, lib: Library | None = None):
130132
"""Run a beets command with an arbitrary amount of arguments. The
131133
Library` defaults to `self.lib`, but can be overridden with
132134
the keyword argument `lib`.
133135
"""
134-
sys.argv = ["beet"] # avoid leakage from test suite args
135-
lib = None
136-
if hasattr(self, "lib"):
137-
lib = self.lib
138-
lib = kwargs.get("lib", lib)
139-
beets.ui._raw_main(list(args), lib)
136+
sys.argv = ["beet", *args] # avoid leakage from test suite args
137+
lib = lib or self.lib
138+
139+
with (
140+
patch.object(lib, "_close", Mock()),
141+
patch("beets.ui._open_library", return_value=lib),
142+
):
143+
beets.ui._raw_main(list(args))
140144

141145

142146
@pytest.mark.usefixtures("io")

beets/ui/__init__.py

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -805,7 +805,7 @@ def parse_subcommand(self, args):
805805

806806

807807
def _setup(
808-
options: optparse.Values, lib: library.Library | None
808+
options: optparse.Values,
809809
) -> tuple[list[Subcommand], library.Library]:
810810
"""Prepare and global state and updates it with command line options.
811811
@@ -821,9 +821,8 @@ def _setup(
821821
subcommands = list(default_commands)
822822
subcommands.extend(plugins.commands())
823823

824-
if lib is None:
825-
lib = _open_library(config)
826-
plugins.send("library_opened", lib=lib)
824+
lib = _open_library(config)
825+
plugins.send("library_opened", lib=lib)
827826

828827
return subcommands, lib
829828

@@ -903,7 +902,7 @@ def _open_library(config: confuse.LazyConfig) -> library.Library:
903902
return lib
904903

905904

906-
def _raw_main(args: list[str], lib=None) -> None:
905+
def _raw_main(args: list[str]) -> None:
907906
"""A helper function for `main` without top-level exception
908907
handling.
909908
"""
@@ -984,20 +983,17 @@ def parse_csl_callback(
984983

985984
return config_edit(options)
986985

987-
test_lib = bool(lib)
988-
subcommands, lib = _setup(options, lib)
986+
subcommands, lib = _setup(options)
989987
parser.add_subcommand(*subcommands)
990988

991989
subcommand, suboptions, subargs = parser.parse_subcommand(subargs)
992990
subcommand.func(lib, suboptions, subargs)
993991

994992
plugins.send("cli_exit", lib=lib)
995-
if not test_lib:
996-
# Clean up the library unless it came from the test harness.
997-
lib._close()
993+
lib._close()
998994

999995

1000-
def main(args=None):
996+
def main(args: list[str]) -> None:
1001997
"""Run the main command-line interface for beets. Includes top-level
1002998
exception handlers that print friendly error messages.
1003999
"""

test/ui/commands/test_completion.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def test_completion(self):
4747
self.skipTest("could not read bash-completion script")
4848

4949
# Load completion script.
50-
self.run_command("completion", lib=None)
50+
self.run_command("completion")
5151
completion_script = self.io.getoutput().encode("utf-8")
5252
tester.stdin.writelines(completion_script.splitlines(True))
5353

test/ui/test_ui.py

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
from beets import config, plugins, ui
2828
from beets.test import _common
2929
from beets.test.helper import BeetsTestCase, IOMixin, PluginTestCase
30-
from beets.ui import commands
30+
from beets.ui import _open_library, commands
3131
from beets.util import syspath
3232

3333

@@ -126,6 +126,12 @@ def setUp(self):
126126

127127
self._reset_config()
128128

129+
def run_command(self, *args, **kwargs):
130+
# We need to reload the lib based on the
131+
# current config
132+
self.lib = _open_library(self.config)
133+
super().run_command(*args, **kwargs)
134+
129135
def tearDown(self):
130136
self.env_patcher.stop()
131137
commands.default_commands.pop()
@@ -155,7 +161,7 @@ def test_paths_section_respected(self):
155161
with self.write_config_file() as config:
156162
config.write("paths: {x: y}")
157163

158-
self.run_command("test", lib=None)
164+
self.run_command("test")
159165
key, template = self.test_cmd.lib.path_formats[0]
160166
assert key == "x"
161167
assert template.original == "y"
@@ -166,7 +172,7 @@ def test_default_paths_preserved(self):
166172
self._reset_config()
167173
with self.write_config_file() as config:
168174
config.write("paths: {x: y}")
169-
self.run_command("test", lib=None)
175+
self.run_command("test")
170176
key, template = self.test_cmd.lib.path_formats[0]
171177
assert key == "x"
172178
assert template.original == "y"
@@ -178,36 +184,36 @@ def test_nonexistant_db(self):
178184

179185
self.io.addinput("n")
180186
with pytest.raises(ui.UserError):
181-
self.run_command("test", lib=None)
187+
self.run_command("test")
182188

183189
def test_user_config_file(self):
184190
with self.write_config_file() as file:
185191
file.write("anoption: value")
186192

187-
self.run_command("test", lib=None)
193+
self.run_command("test")
188194
assert config["anoption"].get() == "value"
189195

190196
def test_replacements_parsed(self):
191197
with self.write_config_file() as config:
192198
config.write("replace: {'[xy]': z}")
193199

194-
self.run_command("test", lib=None)
200+
self.run_command("test")
195201
replacements = self.test_cmd.lib.replacements
196202
repls = [(p.pattern, s) for p, s in replacements] # Compare patterns.
197203
assert repls == [("[xy]", "z")]
198204

199205
def test_multiple_replacements_parsed(self):
200206
with self.write_config_file() as config:
201207
config.write("replace: {'[xy]': z, foo: bar}")
202-
self.run_command("test", lib=None)
208+
self.run_command("test")
203209
replacements = self.test_cmd.lib.replacements
204210
repls = [(p.pattern, s) for p, s in replacements]
205211
assert repls == [("[xy]", "z"), ("foo", "bar")]
206212

207213
def test_cli_config_option(self):
208214
with open(self.cli_config_path, "w") as file:
209215
file.write("anoption: value")
210-
self.run_command("--config", self.cli_config_path, "test", lib=None)
216+
self.run_command("--config", self.cli_config_path, "test")
211217
assert config["anoption"].get() == "value"
212218

213219
def test_cli_config_file_overwrites_user_defaults(self):
@@ -216,7 +222,7 @@ def test_cli_config_file_overwrites_user_defaults(self):
216222

217223
with open(self.cli_config_path, "w") as file:
218224
file.write("anoption: cli overwrite")
219-
self.run_command("--config", self.cli_config_path, "test", lib=None)
225+
self.run_command("--config", self.cli_config_path, "test")
220226
assert config["anoption"].get() == "cli overwrite"
221227

222228
def test_cli_config_file_overwrites_beetsdir_defaults(self):
@@ -226,7 +232,7 @@ def test_cli_config_file_overwrites_beetsdir_defaults(self):
226232

227233
with open(self.cli_config_path, "w") as file:
228234
file.write("anoption: cli overwrite")
229-
self.run_command("--config", self.cli_config_path, "test", lib=None)
235+
self.run_command("--config", self.cli_config_path, "test")
230236
assert config["anoption"].get() == "cli overwrite"
231237

232238
# @unittest.skip('Difficult to implement with optparse')
@@ -241,7 +247,7 @@ def test_cli_config_file_overwrites_beetsdir_defaults(self):
241247
# file.write('second: value')
242248
#
243249
# self.run_command('--config', cli_config_path_1,
244-
# '--config', cli_config_path_2, 'test', lib=None)
250+
# '--config', cli_config_path_2, 'test')
245251
# assert config['first'].get() == 'value'
246252
# assert config['second'].get() == 'value'
247253
#
@@ -267,7 +273,7 @@ def test_cli_config_paths_resolve_relative_to_user_dir(self):
267273
file.write("library: beets.db\n")
268274
file.write("statefile: state")
269275

270-
self.run_command("--config", self.cli_config_path, "test", lib=None)
276+
self.run_command("--config", self.cli_config_path, "test")
271277
assert config["library"].as_path() == self.user_config_dir / "beets.db"
272278
assert config["statefile"].as_path() == self.user_config_dir / "state"
273279

@@ -278,22 +284,22 @@ def test_cli_config_paths_resolve_relative_to_beetsdir(self):
278284
file.write("library: beets.db\n")
279285
file.write("statefile: state")
280286

281-
self.run_command("--config", self.cli_config_path, "test", lib=None)
287+
self.run_command("--config", self.cli_config_path, "test")
282288
assert config["library"].as_path() == self.beetsdir / "beets.db"
283289
assert config["statefile"].as_path() == self.beetsdir / "state"
284290

285291
def test_command_line_option_relative_to_working_dir(self):
286292
config.read()
287293
os.chdir(syspath(self.temp_dir))
288-
self.run_command("--library", "foo.db", "test", lib=None)
294+
self.run_command("--library", "foo.db", "test")
289295
assert config["library"].as_path() == Path.cwd() / "foo.db"
290296

291297
def test_cli_config_file_loads_plugin_commands(self):
292298
with open(self.cli_config_path, "w") as file:
293299
file.write(f"pluginpath: {_common.PLUGINPATH}\n")
294300
file.write("plugins: test")
295301

296-
self.run_command("--config", self.cli_config_path, "plugin", lib=None)
302+
self.run_command("--config", self.cli_config_path, "plugin")
297303
plugs = plugins.find_plugins()
298304
assert len(plugs) == 1
299305
assert plugs[0].is_test_plugin
@@ -358,7 +364,7 @@ def test_custom_paths_prepend(self):
358364
@_common.slow_test()
359365
class PluginTest(TestPluginTestCase):
360366
def test_plugin_command_from_pluginpath(self):
361-
self.run_command("test", lib=None)
367+
self.run_command("test")
362368

363369

364370
class CommonOptionsParserCliTest(IOMixin, BeetsTestCase):

0 commit comments

Comments
 (0)