| 1 |
import importlib |
| 2 |
import itertools |
| 3 |
import logging |
| 4 |
import pkgutil |
| 5 |
import sys |
| 6 |
from typing import ClassVar |
| 7 |
from unittest.mock import ANY, Mock, patch |
| 8 |
|
| 9 |
import pytest |
| 10 |
from mediafile import MediaFile |
| 11 |
|
| 12 |
from beets import config, plugins, ui |
| 13 |
from beets.dbcore import types |
| 14 |
from beets.importer import Action, SingletonImportTask |
| 15 |
from beets.library import Item |
| 16 |
from beets.test.helper import ( |
| 17 |
RUNNING_IN_CI, |
| 18 |
AutotagStub, |
| 19 |
ImportHelper, |
| 20 |
IOMixin, |
| 21 |
PluginMixin, |
| 22 |
PluginTestHelper, |
| 23 |
TerminalImportMixin, |
| 24 |
) |
| 25 |
from beets.util import PromptChoice, displayable_path |
| 26 |
|
| 27 |
|
| 28 |
class TestPluginRegistration(IOMixin, PluginTestHelper): |
| 29 |
class RatingPlugin(plugins.BeetsPlugin): |
| 30 |
item_types: ClassVar[dict[str, types.Type]] = { |
| 31 |
"rating": types.Float(), |
| 32 |
"multi_value": types.MULTI_VALUE_DSV, |
| 33 |
} |
| 34 |
|
| 35 |
def __init__(self): |
| 36 |
super().__init__() |
| 37 |
self.register_listener("write", self.on_write) |
| 38 |
|
| 39 |
@staticmethod |
| 40 |
def on_write(item=None, path=None, tags=None): |
| 41 |
if tags["artist"] == "XXX": |
| 42 |
tags["artist"] = "YYY" |
| 43 |
|
| 44 |
@pytest.fixture(autouse=True) |
| 45 |
def _setup(self): |
| 46 |
self.register_plugin(self.RatingPlugin) |
| 47 |
|
| 48 |
def test_field_type_registered(self): |
| 49 |
assert isinstance(Item._types.get("rating"), types.Float) |
| 50 |
|
| 51 |
def test_duplicate_type(self): |
| 52 |
class DuplicateTypePlugin(plugins.BeetsPlugin): |
| 53 |
item_types: ClassVar[dict[str, types.Type]] = { |
| 54 |
"rating": types.INTEGER |
| 55 |
} |
| 56 |
|
| 57 |
self.register_plugin(DuplicateTypePlugin) |
| 58 |
with pytest.raises( |
| 59 |
plugins.PluginConflictError, match="already been defined" |
| 60 |
): |
| 61 |
Item._types |
| 62 |
|
| 63 |
def test_listener_registered(self): |
| 64 |
self.RatingPlugin() |
| 65 |
item = self.add_item_fixture(artist="XXX") |
| 66 |
|
| 67 |
item.write() |
| 68 |
|
| 69 |
assert MediaFile(item.filepath).artist == "YYY" |
| 70 |
|
| 71 |
def test_multi_value_flex_field_type(self): |
| 72 |
item = Item(path="apath", artist="aaa") |
| 73 |
item.multi_value = ["one", "two", "three"] |
| 74 |
item.add(self.lib) |
| 75 |
|
| 76 |
out = self.run_with_output("ls", "-f", "$multi_value") |
| 77 |
assert out == "one; two; three\n" |
| 78 |
|
| 79 |
|
| 80 |
class PluginImportHelper(PluginMixin, ImportHelper): |
| 81 |
def setup_beets(self): |
| 82 |
super().setup_beets() |
| 83 |
self.prepare_album_for_import(2) |
| 84 |
|
| 85 |
|
| 86 |
class TestEvents(PluginImportHelper): |
| 87 |
def test_import_task_created(self, caplog): |
| 88 |
self.importer = self.setup_importer(pretend=True) |
| 89 |
|
| 90 |
with caplog.at_level("DEBUG"): |
| 91 |
self.importer.run() |
| 92 |
|
| 93 |
# Exactly one event should have been imported (for the album). |
| 94 |
# Sentinels do not get emitted. |
| 95 |
assert caplog.text.count("Sending event: import_task_created") == 1 |
| 96 |
|
| 97 |
logs = [ |
| 98 |
msg |
| 99 |
for msg in caplog.messages |
| 100 |
if not msg.startswith("Sending event:") |
| 101 |
] |
| 102 |
assert logs == [ |
| 103 |
f"Album: {self.import_path / 'album'}", |
| 104 |
f" {displayable_path(self.import_media[0].path)}", |
| 105 |
f" {displayable_path(self.import_media[1].path)}", |
| 106 |
] |
| 107 |
|
| 108 |
def test_import_task_created_with_plugin(self, caplog): |
| 109 |
class ToSingletonPlugin(plugins.BeetsPlugin): |
| 110 |
def __init__(self): |
| 111 |
super().__init__() |
| 112 |
|
| 113 |
self.register_listener( |
| 114 |
"import_task_created", self.import_task_created_event |
| 115 |
) |
| 116 |
|
| 117 |
def import_task_created_event(self, session, task): |
| 118 |
return [ |
| 119 |
SingletonImportTask(task.toppath, i) for i in task.items |
| 120 |
] |
| 121 |
|
| 122 |
to_singleton_plugin = ToSingletonPlugin |
| 123 |
self.register_plugin(to_singleton_plugin) |
| 124 |
|
| 125 |
self.importer = self.setup_importer(pretend=True) |
| 126 |
|
| 127 |
with caplog.at_level("DEBUG"): |
| 128 |
self.importer.run() |
| 129 |
|
| 130 |
# Exactly one event should have been imported (for the album). |
| 131 |
# Sentinels do not get emitted. |
| 132 |
assert caplog.text.count("Sending event: import_task_created") == 1 |
| 133 |
|
| 134 |
logs = [ |
| 135 |
msg |
| 136 |
for msg in caplog.messages |
| 137 |
if not msg.startswith("Sending event:") |
| 138 |
] |
| 139 |
assert logs == [ |
| 140 |
f"Singleton: {displayable_path(self.import_media[0].path)}", |
| 141 |
f"Singleton: {displayable_path(self.import_media[1].path)}", |
| 142 |
] |
| 143 |
|
| 144 |
|
| 145 |
class TestListeners(PluginTestHelper): |
| 146 |
def test_register(self): |
| 147 |
class DummyPlugin(plugins.BeetsPlugin): |
| 148 |
def __init__(self): |
| 149 |
super().__init__() |
| 150 |
self.register_listener("cli_exit", self.dummy) |
| 151 |
self.register_listener("cli_exit", self.dummy) |
| 152 |
|
| 153 |
def dummy(self): |
| 154 |
pass |
| 155 |
|
| 156 |
d = DummyPlugin() |
| 157 |
assert DummyPlugin._raw_listeners["cli_exit"] == [d.dummy] |
| 158 |
|
| 159 |
d2 = DummyPlugin() |
| 160 |
assert DummyPlugin._raw_listeners["cli_exit"] == [d.dummy, d2.dummy] |
| 161 |
|
| 162 |
d.register_listener("cli_exit", d2.dummy) |
| 163 |
assert DummyPlugin._raw_listeners["cli_exit"] == [d.dummy, d2.dummy] |
| 164 |
|
| 165 |
def test_events_called(self): |
| 166 |
class DummyPlugin(plugins.BeetsPlugin): |
| 167 |
def __init__(self): |
| 168 |
super().__init__() |
| 169 |
self.foo = Mock(__name__="foo") |
| 170 |
self.register_listener("event_foo", self.foo) |
| 171 |
self.bar = Mock(__name__="bar") |
| 172 |
self.register_listener("event_bar", self.bar) |
| 173 |
|
| 174 |
d = DummyPlugin() |
| 175 |
|
| 176 |
plugins.send("event") |
| 177 |
d.foo.assert_has_calls([]) |
| 178 |
d.bar.assert_has_calls([]) |
| 179 |
|
| 180 |
plugins.send("event_foo", var="tagada") |
| 181 |
d.foo.assert_called_once_with(var="tagada") |
| 182 |
d.bar.assert_has_calls([]) |
| 183 |
|
| 184 |
def test_listener_params(self): |
| 185 |
class DummyPlugin(plugins.BeetsPlugin): |
| 186 |
def __init__(self): |
| 187 |
super().__init__() |
| 188 |
for i in itertools.count(1): |
| 189 |
try: |
| 190 |
meth = getattr(self, f"dummy{i}") |
| 191 |
except AttributeError: |
| 192 |
break |
| 193 |
self.register_listener(f"event{i}", meth) |
| 194 |
|
| 195 |
def dummy1(self, foo): |
| 196 |
assert foo == 5 |
| 197 |
|
| 198 |
def dummy2(self, foo=None): |
| 199 |
assert foo == 5 |
| 200 |
|
| 201 |
def dummy3(self): |
| 202 |
# argument cut off |
| 203 |
pass |
| 204 |
|
| 205 |
def dummy4(self, bar=None): |
| 206 |
# argument cut off |
| 207 |
pass |
| 208 |
|
| 209 |
def dummy5(self, bar): |
| 210 |
assert not True |
| 211 |
|
| 212 |
# more complex examples |
| 213 |
|
| 214 |
def dummy6(self, foo, bar=None): |
| 215 |
assert foo == 5 |
| 216 |
assert bar is None |
| 217 |
|
| 218 |
def dummy7(self, foo, **kwargs): |
| 219 |
assert foo == 5 |
| 220 |
assert kwargs == {} |
| 221 |
|
| 222 |
def dummy8(self, foo, bar, **kwargs): |
| 223 |
assert not True |
| 224 |
|
| 225 |
def dummy9(self, **kwargs): |
| 226 |
assert kwargs == {"foo": 5} |
| 227 |
|
| 228 |
DummyPlugin() |
| 229 |
|
| 230 |
plugins.send("event1", foo=5) |
| 231 |
plugins.send("event2", foo=5) |
| 232 |
plugins.send("event3", foo=5) |
| 233 |
plugins.send("event4", foo=5) |
| 234 |
|
| 235 |
with pytest.raises(TypeError): |
| 236 |
plugins.send("event5", foo=5) |
| 237 |
|
| 238 |
plugins.send("event6", foo=5) |
| 239 |
plugins.send("event7", foo=5) |
| 240 |
|
| 241 |
with pytest.raises(TypeError): |
| 242 |
plugins.send("event8", foo=5) |
| 243 |
|
| 244 |
plugins.send("event9", foo=5) |
| 245 |
|
| 246 |
|
| 247 |
class TestPromptChoices(TerminalImportMixin, PluginImportHelper): |
| 248 |
@pytest.fixture(autouse=True) |
| 249 |
def setup_prompt_choice(self, io): |
| 250 |
self.setup_importer() |
| 251 |
self.matcher = AutotagStub(AutotagStub.IDENT).install() |
| 252 |
# keep track of ui.input_option() calls |
| 253 |
self.input_options_patcher = patch( |
| 254 |
"beets.ui.input_options", side_effect=ui.input_options |
| 255 |
) |
| 256 |
self.mock_input_options = self.input_options_patcher.start() |
| 257 |
yield |
| 258 |
self.input_options_patcher.stop() |
| 259 |
self.matcher.restore() |
| 260 |
|
| 261 |
def test_plugin_choices_in_ui_input_options_album(self): |
| 262 |
"""Test the presence of plugin choices on the prompt (album).""" |
| 263 |
|
| 264 |
class DummyPlugin(plugins.BeetsPlugin): |
| 265 |
def __init__(self): |
| 266 |
super().__init__() |
| 267 |
self.register_listener( |
| 268 |
"before_choose_candidate", self.return_choices |
| 269 |
) |
| 270 |
|
| 271 |
def return_choices(self, session, task): |
| 272 |
return [ |
| 273 |
PromptChoice("f", "Foo", None), |
| 274 |
PromptChoice("z", "baZ", None), |
| 275 |
] |
| 276 |
|
| 277 |
self.register_plugin(DummyPlugin) |
| 278 |
# Default options + extra choices by the plugin ('Foo', 'Bar') |
| 279 |
opts = ( |
| 280 |
"Apply", |
| 281 |
"More candidates", |
| 282 |
"Skip", |
| 283 |
"Use as-is", |
| 284 |
"as Tracks", |
| 285 |
"Group albums", |
| 286 |
"Rescan directory", |
| 287 |
"Enter search", |
| 288 |
"enter Id", |
| 289 |
"aBort", |
| 290 |
"Foo", |
| 291 |
"baZ", |
| 292 |
) |
| 293 |
|
| 294 |
self.importer.add_choice(Action.SKIP) |
| 295 |
self.importer.run() |
| 296 |
self.mock_input_options.assert_called_once_with( |
| 297 |
opts, default="a", require=ANY |
| 298 |
) |
| 299 |
|
| 300 |
def test_plugin_choices_in_ui_input_options_singleton(self): |
| 301 |
"""Test the presence of plugin choices on the prompt (singleton).""" |
| 302 |
|
| 303 |
class DummyPlugin(plugins.BeetsPlugin): |
| 304 |
def __init__(self): |
| 305 |
super().__init__() |
| 306 |
self.register_listener( |
| 307 |
"before_choose_candidate", self.return_choices |
| 308 |
) |
| 309 |
|
| 310 |
def return_choices(self, session, task): |
| 311 |
return [ |
| 312 |
PromptChoice("f", "Foo", None), |
| 313 |
PromptChoice("r", "baR", None), |
| 314 |
] |
| 315 |
|
| 316 |
self.register_plugin(DummyPlugin) |
| 317 |
# Default options + extra choices by the plugin ('Foo', 'Bar') |
| 318 |
opts = ( |
| 319 |
"Apply", |
| 320 |
"More candidates", |
| 321 |
"Skip", |
| 322 |
"Use as-is", |
| 323 |
"Enter search", |
| 324 |
"enter Id", |
| 325 |
"aBort", |
| 326 |
"Foo", |
| 327 |
"baR", |
| 328 |
) |
| 329 |
|
| 330 |
config["import"]["singletons"] = True |
| 331 |
self.importer.add_choice(Action.SKIP) |
| 332 |
self.importer.run() |
| 333 |
self.mock_input_options.assert_called_with( |
| 334 |
opts, default="a", require=ANY |
| 335 |
) |
| 336 |
|
| 337 |
def test_choices_conflicts(self): |
| 338 |
"""Test the short letter conflict solving.""" |
| 339 |
|
| 340 |
class DummyPlugin(plugins.BeetsPlugin): |
| 341 |
def __init__(self): |
| 342 |
super().__init__() |
| 343 |
self.register_listener( |
| 344 |
"before_choose_candidate", self.return_choices |
| 345 |
) |
| 346 |
|
| 347 |
def return_choices(self, session, task): |
| 348 |
return [ |
| 349 |
PromptChoice("a", "A foo", None), # dupe |
| 350 |
PromptChoice("z", "baZ", None), # ok |
| 351 |
PromptChoice("z", "Zupe", None), # dupe |
| 352 |
PromptChoice("z", "Zoo", None), |
| 353 |
] # dupe |
| 354 |
|
| 355 |
self.register_plugin(DummyPlugin) |
| 356 |
# Default options + not dupe extra choices by the plugin ('baZ') |
| 357 |
opts = ( |
| 358 |
"Apply", |
| 359 |
"More candidates", |
| 360 |
"Skip", |
| 361 |
"Use as-is", |
| 362 |
"as Tracks", |
| 363 |
"Group albums", |
| 364 |
"Rescan directory", |
| 365 |
"Enter search", |
| 366 |
"enter Id", |
| 367 |
"aBort", |
| 368 |
"baZ", |
| 369 |
) |
| 370 |
self.importer.add_choice(Action.SKIP) |
| 371 |
self.importer.run() |
| 372 |
self.mock_input_options.assert_called_once_with( |
| 373 |
opts, default="a", require=ANY |
| 374 |
) |
| 375 |
|
| 376 |
def test_plugin_callback(self): |
| 377 |
"""Test that plugin callbacks are being called upon user choice.""" |
| 378 |
|
| 379 |
class DummyPlugin(plugins.BeetsPlugin): |
| 380 |
def __init__(self): |
| 381 |
super().__init__() |
| 382 |
self.register_listener( |
| 383 |
"before_choose_candidate", self.return_choices |
| 384 |
) |
| 385 |
|
| 386 |
def return_choices(self, session, task): |
| 387 |
return [PromptChoice("f", "Foo", self.foo)] |
| 388 |
|
| 389 |
def foo(self, session, task): |
| 390 |
pass |
| 391 |
|
| 392 |
self.register_plugin(DummyPlugin) |
| 393 |
# Default options + extra choices by the plugin ('Foo', 'Bar') |
| 394 |
opts = ( |
| 395 |
"Apply", |
| 396 |
"More candidates", |
| 397 |
"Skip", |
| 398 |
"Use as-is", |
| 399 |
"as Tracks", |
| 400 |
"Group albums", |
| 401 |
"Rescan directory", |
| 402 |
"Enter search", |
| 403 |
"enter Id", |
| 404 |
"aBort", |
| 405 |
"Foo", |
| 406 |
) |
| 407 |
|
| 408 |
# DummyPlugin.foo() should be called once |
| 409 |
with patch.object(DummyPlugin, "foo", autospec=True) as mock_foo: |
| 410 |
self.io.addinput("f") |
| 411 |
self.io.addinput("n") |
| 412 |
self.importer.run() |
| 413 |
assert mock_foo.call_count == 1 |
| 414 |
|
| 415 |
# input_options should be called twice, as foo() returns None |
| 416 |
assert self.mock_input_options.call_count == 2 |
| 417 |
self.mock_input_options.assert_called_with( |
| 418 |
opts, default="a", require=ANY |
| 419 |
) |
| 420 |
|
| 421 |
def test_plugin_callback_return(self): |
| 422 |
"""Test that plugin callbacks that return a value exit the loop.""" |
| 423 |
|
| 424 |
class DummyPlugin(plugins.BeetsPlugin): |
| 425 |
def __init__(self): |
| 426 |
super().__init__() |
| 427 |
self.register_listener( |
| 428 |
"before_choose_candidate", self.return_choices |
| 429 |
) |
| 430 |
|
| 431 |
def return_choices(self, session, task): |
| 432 |
return [PromptChoice("f", "Foo", self.foo)] |
| 433 |
|
| 434 |
def foo(self, session, task): |
| 435 |
return Action.SKIP |
| 436 |
|
| 437 |
self.register_plugin(DummyPlugin) |
| 438 |
# Default options + extra choices by the plugin ('Foo', 'Bar') |
| 439 |
opts = ( |
| 440 |
"Apply", |
| 441 |
"More candidates", |
| 442 |
"Skip", |
| 443 |
"Use as-is", |
| 444 |
"as Tracks", |
| 445 |
"Group albums", |
| 446 |
"Rescan directory", |
| 447 |
"Enter search", |
| 448 |
"enter Id", |
| 449 |
"aBort", |
| 450 |
"Foo", |
| 451 |
) |
| 452 |
|
| 453 |
# DummyPlugin.foo() should be called once |
| 454 |
self.io.addinput("f") |
| 455 |
self.importer.run() |
| 456 |
|
| 457 |
# input_options should be called once, as foo() returns SKIP |
| 458 |
self.mock_input_options.assert_called_once_with( |
| 459 |
opts, default="a", require=ANY |
| 460 |
) |
| 461 |
|
| 462 |
|
| 463 |
def get_available_plugins(): |
| 464 |
"""Get all available plugins in the beetsplug namespace.""" |
| 465 |
namespace_pkg = importlib.import_module("beetsplug") |
| 466 |
|
| 467 |
return [ |
| 468 |
m.name |
| 469 |
for m in pkgutil.iter_modules(namespace_pkg.__path__) |
| 470 |
if not m.name.startswith("_") |
| 471 |
] |
| 472 |
|
| 473 |
|
| 474 |
class TestImportPlugin(PluginMixin): |
| 475 |
@pytest.fixture(params=get_available_plugins()) |
| 476 |
def plugin_name(self, request): |
| 477 |
"""Fixture to provide the name of each available plugin.""" |
| 478 |
name = request.param |
| 479 |
|
| 480 |
# skip gstreamer plugins on windows |
| 481 |
gstreamer_plugins = {"bpd", "replaygain"} |
| 482 |
if sys.platform == "win32" and name in gstreamer_plugins: |
| 483 |
pytest.skip(f"GStreamer is not available on Windows: {name}") |
| 484 |
|
| 485 |
return name |
| 486 |
|
| 487 |
def unload_plugins(self): |
| 488 |
"""Unimport plugins before each test to avoid conflicts.""" |
| 489 |
super().unload_plugins() |
| 490 |
for mod in list(sys.modules): |
| 491 |
if mod.startswith("beetsplug."): |
| 492 |
del sys.modules[mod] |
| 493 |
|
| 494 |
@pytest.fixture(autouse=True) |
| 495 |
def cleanup(self): |
| 496 |
"""Ensure plugins are unimported before and after each test.""" |
| 497 |
self.unload_plugins() |
| 498 |
yield |
| 499 |
self.unload_plugins() |
| 500 |
|
| 501 |
@pytest.mark.skipif( |
| 502 |
not RUNNING_IN_CI, |
| 503 |
reason=( |
| 504 |
"Requires all dependencies to be installed, which we can't" |
| 505 |
" guarantee in the local environment." |
| 506 |
), |
| 507 |
) |
| 508 |
def test_import_plugin(self, caplog, plugin_name): |
| 509 |
"""Test that a plugin is importable without an error.""" |
| 510 |
caplog.set_level(logging.WARNING) |
| 511 |
self.load_plugins(plugin_name) |
| 512 |
|
| 513 |
assert "PluginImportError" not in caplog.text, ( |
| 514 |
f"Plugin '{plugin_name}' has issues during import." |
| 515 |
) |
| 516 |
|
| 517 |
|
| 518 |
class TestDeprecationCopy: |
| 519 |
# TODO: remove this test in Beets 3.0.0 |
| 520 |
def test_legacy_metadata_plugin_deprecation(self): |
| 521 |
"""Test that a MetadataSourcePlugin with 'legacy' data_source |
| 522 |
raises a deprecation warning and all function and properties are |
| 523 |
copied from the base class. |
| 524 |
""" |
| 525 |
with pytest.warns(DeprecationWarning, match="LegacyMetadataPlugin"): |
| 526 |
|
| 527 |
class LegacyMetadataPlugin(plugins.BeetsPlugin): |
| 528 |
data_source = "legacy" |
| 529 |
|
| 530 |
# Assert all methods are present |
| 531 |
assert hasattr(LegacyMetadataPlugin, "albums_for_ids") |
| 532 |
assert hasattr(LegacyMetadataPlugin, "tracks_for_ids") |
| 533 |
assert hasattr(LegacyMetadataPlugin, "data_source_mismatch_penalty") |
| 534 |
assert hasattr(LegacyMetadataPlugin, "_extract_id") |
| 535 |
assert hasattr(LegacyMetadataPlugin, "get_artist") |
| 536 |
|
| 537 |
|
| 538 |
class TestMusicBrainzPluginLoading: |
| 539 |
@pytest.fixture(autouse=True) |
| 540 |
def config(self): |
| 541 |
_config = config |
| 542 |
_config.sources = [] |
| 543 |
_config.read(user=False, defaults=True) |
| 544 |
return _config |
| 545 |
|
| 546 |
def test_default(self): |
| 547 |
assert "musicbrainz" in plugins.get_plugin_names() |
| 548 |
|
| 549 |
def test_other_plugin_enabled(self, config): |
| 550 |
config["plugins"] = ["anything"] |
| 551 |
|
| 552 |
assert "musicbrainz" not in plugins.get_plugin_names() |
| 553 |
|
| 554 |
def test_deprecated_enabled(self, config, caplog): |
| 555 |
config["plugins"] = ["anything"] |
| 556 |
config["musicbrainz"]["enabled"] = True |
| 557 |
|
| 558 |
assert "musicbrainz" in plugins.get_plugin_names() |
| 559 |
assert ( |
| 560 |
"musicbrainz.enabled' configuration option is deprecated" |
| 561 |
in caplog.text |
| 562 |
) |
| 563 |
|
| 564 |
def test_deprecated_disabled(self, config, caplog): |
| 565 |
config["musicbrainz"]["enabled"] = False |
| 566 |
|
| 567 |
assert "musicbrainz" not in plugins.get_plugin_names() |
| 568 |
assert ( |
| 569 |
"musicbrainz.enabled' configuration option is deprecated" |
| 570 |
in caplog.text |
| 571 |
) |