| 1 |
# TODO: Tests in this fire are very bad. Stop using Mocks in this module. |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import os |
| 5 |
from typing import TYPE_CHECKING |
| 6 |
from unittest.mock import MagicMock, Mock, PropertyMock |
| 7 |
|
| 8 |
import pytest |
| 9 |
|
| 10 |
from beets import config |
| 11 |
from beets.dbcore.sort import FixedFieldSort, MultipleSort, NullSort |
| 12 |
from beets.library import Album, Item, parse_query_string |
| 13 |
from beets.test._common import item |
| 14 |
from beets.test.helper import BeetsTestCase, IOMixin, PathsMixin, PluginTestCase |
| 15 |
from beets.ui import UserError |
| 16 |
from beets.util import CHAR_REPLACE |
| 17 |
from beetsplug.smartplaylist import SmartPlaylistPlugin |
| 18 |
|
| 19 |
if TYPE_CHECKING: |
| 20 |
from pathlib import Path |
| 21 |
|
| 22 |
_p = pytest.param |
| 23 |
|
| 24 |
|
| 25 |
class PlaylistDirMixin(PathsMixin): |
| 26 |
@property |
| 27 |
def playlist_dir(self) -> Path: |
| 28 |
return self.temp_path / "playlists" |
| 29 |
|
| 30 |
|
| 31 |
class SmartPlaylistTest(PlaylistDirMixin, BeetsTestCase): |
| 32 |
def test_build_queries(self): |
| 33 |
spl = SmartPlaylistPlugin() |
| 34 |
assert spl._matched_playlists == set() |
| 35 |
assert spl._unmatched_playlists == set() |
| 36 |
|
| 37 |
config["smartplaylist"]["playlists"].set([]) |
| 38 |
spl.build_queries() |
| 39 |
assert spl._matched_playlists == set() |
| 40 |
assert spl._unmatched_playlists == set() |
| 41 |
|
| 42 |
config["smartplaylist"]["playlists"].set( |
| 43 |
[ |
| 44 |
{"name": "foo", "query": "FOO foo"}, |
| 45 |
{"name": "bar", "album_query": ["BAR bar1", "BAR bar2"]}, |
| 46 |
{"name": "baz", "query": "BAZ baz", "album_query": "BAZ baz"}, |
| 47 |
] |
| 48 |
) |
| 49 |
spl.build_queries() |
| 50 |
assert spl._matched_playlists == set() |
| 51 |
foo_foo = parse_query_string("FOO foo", Item) |
| 52 |
baz_baz = parse_query_string("BAZ baz", Item) |
| 53 |
baz_baz2 = parse_query_string("BAZ baz", Album) |
| 54 |
# Multiple queries are now stored as a tuple of (query, sort) tuples |
| 55 |
bar_queries = tuple( |
| 56 |
[ |
| 57 |
parse_query_string("BAR bar1", Album), |
| 58 |
parse_query_string("BAR bar2", Album), |
| 59 |
] |
| 60 |
) |
| 61 |
assert spl._unmatched_playlists == { |
| 62 |
("foo", foo_foo, (None, None)), |
| 63 |
("baz", baz_baz, baz_baz2), |
| 64 |
("bar", (None, None), (bar_queries, None)), |
| 65 |
} |
| 66 |
|
| 67 |
def test_build_queries_with_sorts(self): |
| 68 |
spl = SmartPlaylistPlugin() |
| 69 |
config["smartplaylist"]["playlists"].set( |
| 70 |
[ |
| 71 |
{"name": "no_sort", "query": "foo"}, |
| 72 |
{"name": "one_sort", "query": "foo year+"}, |
| 73 |
{"name": "only_empty_sorts", "query": ["foo", "bar"]}, |
| 74 |
{"name": "one_non_empty_sort", "query": ["foo year+", "bar"]}, |
| 75 |
{ |
| 76 |
"name": "multiple_sorts", |
| 77 |
"query": ["foo year+", "bar genres-"], |
| 78 |
}, |
| 79 |
{ |
| 80 |
"name": "mixed", |
| 81 |
"query": ["foo year+", "bar", "baz genres+ id-"], |
| 82 |
}, |
| 83 |
] |
| 84 |
) |
| 85 |
|
| 86 |
spl.build_queries() |
| 87 |
|
| 88 |
# Multiple queries now return a tuple of (query, sort) tuples, not combined |
| 89 |
sorts = {} |
| 90 |
for name, (query_data, sort), _ in spl._unmatched_playlists: |
| 91 |
if isinstance(query_data, tuple): |
| 92 |
# Tuple of queries - each has its own sort |
| 93 |
sorts[name] = [s for _, s in query_data] |
| 94 |
else: |
| 95 |
sorts[name] = sort |
| 96 |
|
| 97 |
sort = FixedFieldSort # short cut since we're only dealing with this |
| 98 |
assert sorts["no_sort"] == NullSort() |
| 99 |
assert sorts["one_sort"] == sort("year") |
| 100 |
# Multiple queries store individual sorts in the tuple |
| 101 |
assert all(isinstance(x, NullSort) for x in sorts["only_empty_sorts"]) |
| 102 |
assert sorts["one_non_empty_sort"] == [sort("year"), NullSort()] |
| 103 |
assert sorts["multiple_sorts"] == [sort("year"), sort("genres", False)] |
| 104 |
assert sorts["mixed"] == [ |
| 105 |
sort("year"), |
| 106 |
NullSort(), |
| 107 |
MultipleSort([sort("genres"), sort("id", False)]), |
| 108 |
] |
| 109 |
|
| 110 |
def test_matches(self): |
| 111 |
spl = SmartPlaylistPlugin() |
| 112 |
|
| 113 |
a = MagicMock(Album) |
| 114 |
i = MagicMock(Item) |
| 115 |
|
| 116 |
assert not spl.matches(i, None, None) |
| 117 |
assert not spl.matches(a, None, None) |
| 118 |
|
| 119 |
query = Mock() |
| 120 |
query.match.side_effect = {i: True}.__getitem__ |
| 121 |
assert spl.matches(i, query, None) |
| 122 |
assert not spl.matches(a, query, None) |
| 123 |
|
| 124 |
a_query = Mock() |
| 125 |
a_query.match.side_effect = {a: True}.__getitem__ |
| 126 |
assert not spl.matches(i, None, a_query) |
| 127 |
assert spl.matches(a, None, a_query) |
| 128 |
|
| 129 |
assert spl.matches(i, query, a_query) |
| 130 |
assert spl.matches(a, query, a_query) |
| 131 |
|
| 132 |
# Test with list of queries |
| 133 |
q1 = Mock() |
| 134 |
q1.match.return_value = False |
| 135 |
q2 = Mock() |
| 136 |
q2.match.side_effect = {i: True}.__getitem__ |
| 137 |
queries_list = [(q1, None), (q2, None)] |
| 138 |
assert spl.matches(i, queries_list, None) |
| 139 |
assert not spl.matches(a, queries_list, None) |
| 140 |
|
| 141 |
def test_db_changes(self): |
| 142 |
spl = SmartPlaylistPlugin() |
| 143 |
|
| 144 |
nones = None, None |
| 145 |
pl1 = "1", ("q1", None), nones |
| 146 |
pl2 = "2", ("q2", None), nones |
| 147 |
pl3 = "3", ("q3", None), nones |
| 148 |
|
| 149 |
spl._unmatched_playlists = {pl1, pl2, pl3} |
| 150 |
spl._matched_playlists = set() |
| 151 |
|
| 152 |
spl.matches = Mock(return_value=False) |
| 153 |
spl.db_change(None, "nothing") |
| 154 |
assert spl._unmatched_playlists == {pl1, pl2, pl3} |
| 155 |
assert spl._matched_playlists == set() |
| 156 |
|
| 157 |
spl.matches.side_effect = lambda _, q, __: q == "q3" |
| 158 |
spl.db_change(None, "matches 3") |
| 159 |
assert spl._unmatched_playlists == {pl1, pl2} |
| 160 |
assert spl._matched_playlists == {pl3} |
| 161 |
|
| 162 |
spl.matches.side_effect = lambda _, q, __: q == "q1" |
| 163 |
spl.db_change(None, "matches 3") |
| 164 |
assert spl._matched_playlists == {pl1, pl3} |
| 165 |
assert spl._unmatched_playlists == {pl2} |
| 166 |
|
| 167 |
def test_playlist_update(self): |
| 168 |
spl = SmartPlaylistPlugin() |
| 169 |
|
| 170 |
i = Mock(path=b"/tagada.mp3") |
| 171 |
i.evaluate_template.side_effect = lambda pl, **__: os.fsdecode( |
| 172 |
pl |
| 173 |
).replace("$title", "ta:ga:da") |
| 174 |
|
| 175 |
lib = Mock() |
| 176 |
lib.replacements = CHAR_REPLACE |
| 177 |
lib.items.return_value = [i] |
| 178 |
lib.albums.return_value = [] |
| 179 |
|
| 180 |
q = Mock() |
| 181 |
a_q = Mock() |
| 182 |
pl = b"$title-my<playlist>.m3u", (q, None), (a_q, None) |
| 183 |
spl._matched_playlists = {pl} |
| 184 |
|
| 185 |
config["smartplaylist"]["relative_to"] = False |
| 186 |
config["smartplaylist"]["playlist_dir"] = str(self.playlist_dir) |
| 187 |
spl.update_playlists(lib) |
| 188 |
|
| 189 |
lib.items.assert_called_once_with(q, None) |
| 190 |
lib.albums.assert_called_once_with(a_q, None) |
| 191 |
|
| 192 |
m3u_filepath = self.playlist_dir / "ta_ga_da-my_playlist_.m3u" |
| 193 |
assert m3u_filepath.exists() |
| 194 |
content = m3u_filepath.read_bytes() |
| 195 |
|
| 196 |
assert content == b"/tagada.mp3\n" |
| 197 |
|
| 198 |
def test_playlist_update_output_extm3u(self): |
| 199 |
spl = SmartPlaylistPlugin() |
| 200 |
|
| 201 |
i = MagicMock() |
| 202 |
type(i).artist = PropertyMock(return_value="fake artist") |
| 203 |
type(i).title = PropertyMock(return_value="fake title") |
| 204 |
type(i).length = PropertyMock(return_value=300.123) |
| 205 |
type(i).path = PropertyMock(return_value=b"/tagada.mp3") |
| 206 |
i.evaluate_template.side_effect = lambda pl, **__: os.fsdecode( |
| 207 |
pl |
| 208 |
).replace("$title", "ta:ga:da") |
| 209 |
|
| 210 |
lib = Mock() |
| 211 |
lib.replacements = CHAR_REPLACE |
| 212 |
lib.items.return_value = [i] |
| 213 |
lib.albums.return_value = [] |
| 214 |
|
| 215 |
q = Mock() |
| 216 |
a_q = Mock() |
| 217 |
pl = b"$title-my<playlist>.m3u", (q, None), (a_q, None) |
| 218 |
spl._matched_playlists = {pl} |
| 219 |
|
| 220 |
config["smartplaylist"]["output"] = "extm3u" |
| 221 |
config["smartplaylist"]["prefix"] = "http://beets:8337/files" |
| 222 |
config["smartplaylist"]["relative_to"] = False |
| 223 |
config["smartplaylist"]["playlist_dir"] = str(self.playlist_dir) |
| 224 |
spl.update_playlists(lib) |
| 225 |
|
| 226 |
lib.items.assert_called_once_with(q, None) |
| 227 |
lib.albums.assert_called_once_with(a_q, None) |
| 228 |
|
| 229 |
m3u_filepath = self.playlist_dir / "ta_ga_da-my_playlist_.m3u" |
| 230 |
assert m3u_filepath.exists() |
| 231 |
content = m3u_filepath.read_bytes() |
| 232 |
|
| 233 |
assert content == ( |
| 234 |
b"#EXTM3U\n" |
| 235 |
b"#EXTINF:300,fake artist - fake title\n" |
| 236 |
b"http://beets:8337/files/tagada.mp3\n" |
| 237 |
) |
| 238 |
|
| 239 |
def test_playlist_update_output_extm3u_fields(self): |
| 240 |
spl = SmartPlaylistPlugin() |
| 241 |
|
| 242 |
i = MagicMock() |
| 243 |
type(i).artist = PropertyMock(return_value="Fake Artist") |
| 244 |
type(i).title = PropertyMock(return_value="fake Title") |
| 245 |
type(i).length = PropertyMock(return_value=300.123) |
| 246 |
type(i).path = PropertyMock(return_value=b"/tagada.mp3") |
| 247 |
a = {"id": 456, "genres": ["Rock", "Pop"]} |
| 248 |
i.__getitem__.side_effect = a.__getitem__ |
| 249 |
i.evaluate_template.side_effect = lambda pl, **__: os.fsdecode( |
| 250 |
pl |
| 251 |
).replace("$title", "ta:ga:da") |
| 252 |
|
| 253 |
lib = Mock() |
| 254 |
lib.replacements = CHAR_REPLACE |
| 255 |
lib.items.return_value = [i] |
| 256 |
lib.albums.return_value = [] |
| 257 |
|
| 258 |
q = Mock() |
| 259 |
a_q = Mock() |
| 260 |
pl = b"$title-my<playlist>.m3u", (q, None), (a_q, None) |
| 261 |
spl._matched_playlists = {pl} |
| 262 |
|
| 263 |
config["smartplaylist"]["output"] = "extm3u" |
| 264 |
config["smartplaylist"]["relative_to"] = False |
| 265 |
config["smartplaylist"]["playlist_dir"] = str(self.playlist_dir) |
| 266 |
config["smartplaylist"]["fields"] = ["id", "genres"] |
| 267 |
spl.update_playlists(lib) |
| 268 |
|
| 269 |
lib.items.assert_called_once_with(q, None) |
| 270 |
lib.albums.assert_called_once_with(a_q, None) |
| 271 |
|
| 272 |
m3u_filepath = self.playlist_dir / "ta_ga_da-my_playlist_.m3u" |
| 273 |
assert m3u_filepath.exists() |
| 274 |
content = m3u_filepath.read_bytes() |
| 275 |
|
| 276 |
assert content == ( |
| 277 |
b"#EXTM3U\n" |
| 278 |
b'#EXTINF:300 id="456" genres="Rock%3B%20Pop",Fake Artist - fake Title\n' |
| 279 |
b"/tagada.mp3\n" |
| 280 |
) |
| 281 |
|
| 282 |
def test_get_playlist_items(self): |
| 283 |
"""Test get playlist items. |
| 284 |
|
| 285 |
- Items preserve their order in the playlist |
| 286 |
- There are no duplicates when items match multiple queries |
| 287 |
""" |
| 288 |
self.add_item(path=b"/item1.mp3", id=1) |
| 289 |
self.add_item(path=b"/item2.mp3", id=2) |
| 290 |
self.add_item(path=b"/item3.mp3", id=3) |
| 291 |
queries_and_sorts = (("path::item id-", None), ("path::item3", None)) |
| 292 |
|
| 293 |
actual_items = SmartPlaylistPlugin.get_playlist_items( |
| 294 |
self.lib, (queries_and_sorts, None), (None, None) |
| 295 |
) |
| 296 |
|
| 297 |
assert [i.id for i in actual_items] == [3, 2, 1] |
| 298 |
|
| 299 |
|
| 300 |
class TestGetItemURI: |
| 301 |
@pytest.fixture |
| 302 |
def plugin(self, config, plugin_config): |
| 303 |
plugin_config = {"prefix": "http://beets:8337/files", **plugin_config} |
| 304 |
config["smartplaylist"].set(plugin_config) |
| 305 |
|
| 306 |
return SmartPlaylistPlugin() |
| 307 |
|
| 308 |
@pytest.fixture(autouse=True) |
| 309 |
def _setup(self, monkeypatch): |
| 310 |
monkeypatch.setattr(Item, "destination", lambda _: b"/tagada.mp3") |
| 311 |
|
| 312 |
@pytest.fixture |
| 313 |
def item(self): |
| 314 |
return item( |
| 315 |
id=3, |
| 316 |
artist="fake artist", |
| 317 |
title="fake title", |
| 318 |
length=300.123, |
| 319 |
path=b"/imported/path/with/dont/move/tagada.mp3", |
| 320 |
) |
| 321 |
|
| 322 |
@pytest.mark.parametrize( |
| 323 |
"plugin_config, expected_uri", |
| 324 |
[ |
| 325 |
_p( |
| 326 |
{}, |
| 327 |
b"http://beets:8337/files/imported/path/with/dont/move/tagada.mp3", |
| 328 |
id="path by default", |
| 329 |
), |
| 330 |
_p( |
| 331 |
{"dest_regen": True}, |
| 332 |
b"http://beets:8337/files/tagada.mp3", |
| 333 |
id="dest_regen uses item destination", |
| 334 |
), |
| 335 |
_p( |
| 336 |
{ |
| 337 |
"uri_format": "http://beets:8337/item/$id/file", |
| 338 |
"dest_regen": True, |
| 339 |
}, |
| 340 |
b"http://beets:8337/item/3/file", |
| 341 |
id="uri_format takes precedence", |
| 342 |
), |
| 343 |
], |
| 344 |
) |
| 345 |
def test_get_item_uri(self, plugin, item, expected_uri): |
| 346 |
assert plugin.get_item_uri(item) == expected_uri |
| 347 |
|
| 348 |
|
| 349 |
class SmartPlaylistCLITest(PlaylistDirMixin, IOMixin, PluginTestCase): |
| 350 |
plugin = "smartplaylist" |
| 351 |
|
| 352 |
def setUp(self): |
| 353 |
super().setUp() |
| 354 |
|
| 355 |
self.item = self.add_item() |
| 356 |
config["smartplaylist"]["playlists"].set( |
| 357 |
[ |
| 358 |
{"name": "my_playlist.m3u", "query": self.item.title}, |
| 359 |
{"name": "all.m3u", "query": ""}, |
| 360 |
] |
| 361 |
) |
| 362 |
config["smartplaylist"]["playlist_dir"] = str(self.playlist_dir) |
| 363 |
|
| 364 |
def test_splupdate(self): |
| 365 |
with pytest.raises(UserError): |
| 366 |
self.run_with_output("splupdate", "tagada") |
| 367 |
|
| 368 |
self.run_with_output("splupdate", "my_playlist") |
| 369 |
m3u_path = self.playlist_dir / "my_playlist.m3u" |
| 370 |
assert m3u_path.exists() |
| 371 |
assert m3u_path.read_bytes() == self.item.path + b"\n" |
| 372 |
m3u_path.unlink() |
| 373 |
|
| 374 |
self.run_with_output("splupdate", "my_playlist.m3u") |
| 375 |
assert m3u_path.read_bytes() == self.item.path + b"\n" |
| 376 |
m3u_path.unlink() |
| 377 |
|
| 378 |
self.run_with_output("splupdate") |
| 379 |
for name in ("my_playlist.m3u", "all.m3u"): |
| 380 |
assert ( |
| 381 |
self.playlist_dir / name |
| 382 |
).read_bytes() == self.item.path + b"\n" |
| 383 |
|
| 384 |
def test_splupdate_unknown_playlist_error_is_sorted_and_quoted(self): |
| 385 |
config["smartplaylist"]["playlists"].set( |
| 386 |
[ |
| 387 |
{"name": "z last.m3u", "query": self.item.title}, |
| 388 |
{"name": "rock'n roll.m3u", "query": self.item.title}, |
| 389 |
{"name": "a one.m3u", "query": self.item.title}, |
| 390 |
] |
| 391 |
) |
| 392 |
|
| 393 |
with pytest.raises(UserError) as exc_info: |
| 394 |
self.run_with_output("splupdate", "tagada") |
| 395 |
|
| 396 |
assert str(exc_info.value) == ( |
| 397 |
"No playlist matching any of " |
| 398 |
"'a one.m3u' 'rock'\"'\"'n roll.m3u' 'z last.m3u' found" |
| 399 |
) |
| 400 |
|
| 401 |
def test_splupdate_log_output(self): |
| 402 |
with self.assertLogs("beets.smartplaylist", level="INFO") as logs: |
| 403 |
self.run_with_output("splupdate", "my_playlist") |
| 404 |
|
| 405 |
output = "\n".join(logs.output) |
| 406 |
assert "Updating 1 smart playlists..." in output |
| 407 |
assert "Creating playlist my_playlist.m3u: 1 tracks." in output |
| 408 |
assert "1 playlists updated" in output |
| 409 |
|
| 410 |
def test_splupdate_verbose_log_output(self): |
| 411 |
with self.assertLogs("beets.smartplaylist", level="DEBUG") as logs: |
| 412 |
self.run_with_output("splupdate", "my_playlist") |
| 413 |
|
| 414 |
output = "\n".join(logs.output) |
| 415 |
assert "Updating 1 smart playlists..." in output |
| 416 |
assert "Creating playlist my_playlist.m3u: 1 tracks." in output |
| 417 |
assert "the ärtist - " in output |
| 418 |
assert "1 playlists updated" in output |
| 419 |
|
| 420 |
def test_splupdate_pretend_log_output(self): |
| 421 |
with self.assertLogs("beets.smartplaylist", level="INFO") as logs: |
| 422 |
self.run_with_output("splupdate", "--pretend", "my_playlist") |
| 423 |
|
| 424 |
output = "\n".join(logs.output) |
| 425 |
assert "Updating 1 smart playlists..." in output |
| 426 |
assert "Creating playlist my_playlist.m3u: 1 tracks." in output |
| 427 |
assert "1 playlists would be updated" in output |