| 1 |
"""Tests for the 'lastgenre' plugin.""" |
| 2 |
|
| 3 |
import re |
| 4 |
from collections import defaultdict |
| 5 |
from unittest.mock import Mock, patch |
| 6 |
|
| 7 |
import confuse |
| 8 |
import pytest |
| 9 |
|
| 10 |
from beets.library import Album |
| 11 |
from beets.test import _common |
| 12 |
from beets.test.helper import IOMixin, PluginTestCase |
| 13 |
from beetsplug import lastgenre |
| 14 |
from beetsplug.lastgenre.utils import is_ignored, normalize_genre |
| 15 |
|
| 16 |
_p = pytest.param |
| 17 |
|
| 18 |
|
| 19 |
class LastGenrePluginTest(IOMixin, PluginTestCase): |
| 20 |
plugin = "lastgenre" |
| 21 |
|
| 22 |
def setUp(self): |
| 23 |
super().setUp() |
| 24 |
self.plugin = lastgenre.LastGenrePlugin() |
| 25 |
|
| 26 |
def _setup_config( |
| 27 |
self, whitelist=False, canonical=False, count=1, prefer_specific=False |
| 28 |
): |
| 29 |
self.config["lastgenre"]["canonical"] = canonical |
| 30 |
self.config["lastgenre"]["count"] = count |
| 31 |
self.config["lastgenre"]["prefer_specific"] = prefer_specific |
| 32 |
if isinstance(whitelist, (bool, (str,))): |
| 33 |
# Filename, default, or disabled. |
| 34 |
self.config["lastgenre"]["whitelist"] = whitelist |
| 35 |
self.plugin.setup() |
| 36 |
if not isinstance(whitelist, (bool, (str,))): |
| 37 |
# Explicit list of genres. |
| 38 |
self.plugin.whitelist = whitelist |
| 39 |
|
| 40 |
def test_default(self): |
| 41 |
"""Fetch genres with whitelist and c14n deactivated""" |
| 42 |
self._setup_config() |
| 43 |
assert self.plugin._resolve_genres(["delta blues"]) == ["delta blues"] |
| 44 |
|
| 45 |
def test_c14n_only(self): |
| 46 |
"""Default c14n tree funnels up to most common genre except for *wrong* |
| 47 |
genres that stay unchanged. |
| 48 |
""" |
| 49 |
self._setup_config(canonical=True, count=99) |
| 50 |
assert self.plugin._resolve_genres(["delta blues"]) == ["blues"] |
| 51 |
assert self.plugin._resolve_genres(["iota blues"]) == ["iota blues"] |
| 52 |
|
| 53 |
def test_whitelist_only(self): |
| 54 |
"""Default whitelist rejects *wrong* (non existing) genres.""" |
| 55 |
self._setup_config(whitelist=True) |
| 56 |
assert self.plugin._resolve_genres(["iota blues"]) == [] |
| 57 |
|
| 58 |
def test_whitelist_c14n(self): |
| 59 |
"""Default whitelist and c14n both activated result in all parents |
| 60 |
genres being selected (from specific to common). |
| 61 |
""" |
| 62 |
self._setup_config(canonical=True, whitelist=True, count=99) |
| 63 |
assert self.plugin._resolve_genres(["delta blues"]) == [ |
| 64 |
"delta blues", |
| 65 |
"blues", |
| 66 |
] |
| 67 |
|
| 68 |
def test_whitelist_custom(self): |
| 69 |
"""Keep only genres that are in the whitelist.""" |
| 70 |
self._setup_config(whitelist={"blues", "rock", "jazz"}, count=2) |
| 71 |
assert self.plugin._resolve_genres(["pop", "blues"]) == ["blues"] |
| 72 |
|
| 73 |
self._setup_config(canonical="", whitelist={"rock"}) |
| 74 |
assert self.plugin._resolve_genres(["delta blues"]) == [] |
| 75 |
|
| 76 |
def test_format_genres(self): |
| 77 |
"""Format genres list.""" |
| 78 |
self._setup_config(count=2) |
| 79 |
assert self.plugin._format_genres(["jazz", "pop", "rock", "blues"]) == [ |
| 80 |
"Jazz", |
| 81 |
"Pop", |
| 82 |
"Rock", |
| 83 |
"Blues", |
| 84 |
] |
| 85 |
|
| 86 |
def test_count_c14n(self): |
| 87 |
"""Keep the n first genres, after having applied c14n when necessary""" |
| 88 |
self._setup_config( |
| 89 |
whitelist={"blues", "rock", "jazz"}, canonical=True, count=2 |
| 90 |
) |
| 91 |
# thanks to c14n, 'blues' superseeds 'country blues' and takes the |
| 92 |
# second slot |
| 93 |
assert self.plugin._resolve_genres( |
| 94 |
["jazz", "pop", "country blues", "rock"] |
| 95 |
) == ["jazz", "blues"] |
| 96 |
|
| 97 |
def test_c14n_whitelist(self): |
| 98 |
"""Genres first pass through c14n and are then filtered""" |
| 99 |
self._setup_config(canonical=True, whitelist={"rock"}) |
| 100 |
assert self.plugin._resolve_genres(["delta blues"]) == [] |
| 101 |
|
| 102 |
def test_empty_string_enables_canonical(self): |
| 103 |
"""For backwards compatibility, setting the `canonical` option |
| 104 |
to the empty string enables it using the default tree. |
| 105 |
""" |
| 106 |
self._setup_config(canonical="", count=99) |
| 107 |
assert self.plugin._resolve_genres(["delta blues"]) == ["blues"] |
| 108 |
|
| 109 |
def test_empty_string_enables_whitelist(self): |
| 110 |
"""Again for backwards compatibility, setting the `whitelist` |
| 111 |
option to the empty string enables the default set of genres. |
| 112 |
""" |
| 113 |
self._setup_config(whitelist="") |
| 114 |
assert self.plugin._resolve_genres(["iota blues"]) == [] |
| 115 |
|
| 116 |
def test_prefer_specific_loads_tree(self): |
| 117 |
"""When prefer_specific is enabled but canonical is not the |
| 118 |
tree still has to be loaded. |
| 119 |
""" |
| 120 |
self._setup_config(prefer_specific=True, canonical=False) |
| 121 |
assert self.plugin.c14n_branches != [] |
| 122 |
|
| 123 |
def test_prefer_specific_without_canonical(self): |
| 124 |
"""Prefer_specific works without canonical.""" |
| 125 |
self._setup_config(prefer_specific=True, canonical=False, count=4) |
| 126 |
assert self.plugin._resolve_genres(["math rock", "post-rock"]) == [ |
| 127 |
"post-rock", |
| 128 |
"math rock", |
| 129 |
] |
| 130 |
|
| 131 |
@patch("beets.ui.should_write", Mock(return_value=True)) |
| 132 |
@patch( |
| 133 |
"beetsplug.lastgenre.LastGenrePlugin._get_genre", |
| 134 |
Mock(return_value=("Mock Genre", "mock stage")), |
| 135 |
) |
| 136 |
def test_pretend_option_skips_library_updates(self): |
| 137 |
item = self.create_item( |
| 138 |
album="Pretend Album", |
| 139 |
albumartist="Pretend Artist", |
| 140 |
artist="Pretend Artist", |
| 141 |
title="Pretend Track", |
| 142 |
genres=["Original Genre"], |
| 143 |
) |
| 144 |
album = self.lib.add_album([item]) |
| 145 |
|
| 146 |
def unexpected_store(*_, **__): |
| 147 |
raise AssertionError("Unexpected store call") |
| 148 |
|
| 149 |
# Verify that try_write was never called (file operations skipped) |
| 150 |
with patch("beetsplug.lastgenre.Item.store", unexpected_store): |
| 151 |
output = self.run_with_output("lastgenre", "--pretend") |
| 152 |
|
| 153 |
assert "genres:" in output |
| 154 |
album.load() |
| 155 |
assert album.genres == ["Original Genre"] |
| 156 |
assert album.items()[0].genres == ["Original Genre"] |
| 157 |
|
| 158 |
def test_no_duplicate(self): |
| 159 |
"""Remove duplicated genres.""" |
| 160 |
self._setup_config(count=99) |
| 161 |
assert self.plugin._resolve_genres(["blues", "blues"]) == ["blues"] |
| 162 |
|
| 163 |
def test_fetch_va_genres_picks_most_popular_track_genre(self): |
| 164 |
"""Among fetched track genres, the most common one wins.""" |
| 165 |
self._setup_config() |
| 166 |
self.config["lastgenre"]["source"] = "track" |
| 167 |
self.plugin.setup() |
| 168 |
item1 = self.add_item(artist="Artist A") |
| 169 |
item2 = self.add_item(artist="Artist B") |
| 170 |
item3 = self.add_item(artist="Artist C") |
| 171 |
album = self.lib.add_album([item1, item2, item3]) |
| 172 |
|
| 173 |
track_genres = { |
| 174 |
"Artist A": ["Rock"], |
| 175 |
"Artist B": ["Rock"], |
| 176 |
"Artist C": ["Jazz"], |
| 177 |
} |
| 178 |
self.plugin.client.fetch = lambda kind, obj, *args: ( |
| 179 |
track_genres[obj.artist] if kind == "track" else [] |
| 180 |
) |
| 181 |
|
| 182 |
assert self.plugin._fetch_va_genres(album) == ["Rock"] |
| 183 |
|
| 184 |
def test_fetch_va_genres_falls_back_to_artist_genre(self): |
| 185 |
"""When a track has no genre, fall back to its artist's genre.""" |
| 186 |
self._setup_config() |
| 187 |
item = self.add_item(artist="Artist A") |
| 188 |
album = self.lib.add_album([item]) |
| 189 |
|
| 190 |
self.plugin.client.fetch = lambda kind, obj, *args: ( |
| 191 |
["Jazz"] if kind == "artist" else [] |
| 192 |
) |
| 193 |
|
| 194 |
assert self.plugin._fetch_va_genres(album) == ["Jazz"] |
| 195 |
|
| 196 |
def test_fetch_va_genres_empty_when_nothing_found(self): |
| 197 |
"""Return an empty list when neither track nor artist genres exist.""" |
| 198 |
self._setup_config() |
| 199 |
item = self.add_item(artist="Artist A") |
| 200 |
album = self.lib.add_album([item]) |
| 201 |
|
| 202 |
self.plugin.client.fetch = lambda kind, obj, *args: [] |
| 203 |
|
| 204 |
assert self.plugin._fetch_va_genres(album) == [] |
| 205 |
|
| 206 |
def test_fetch_genre(self): |
| 207 |
class MockPylastElem: |
| 208 |
def __init__(self, name): |
| 209 |
self.name = name |
| 210 |
|
| 211 |
def get_name(self): |
| 212 |
return self.name |
| 213 |
|
| 214 |
class MockPylastObj: |
| 215 |
def get_top_tags(self): |
| 216 |
tag1 = Mock() |
| 217 |
tag1.weight = 90 |
| 218 |
tag1.item = MockPylastElem("Pop") |
| 219 |
tag2 = Mock() |
| 220 |
tag2.weight = 40 |
| 221 |
tag2.item = MockPylastElem("Rap") |
| 222 |
return [tag1, tag2] |
| 223 |
|
| 224 |
plugin = lastgenre.LastGenrePlugin() |
| 225 |
res = plugin.client.fetch_genres(MockPylastObj()) |
| 226 |
assert res == ["pop", "rap"] |
| 227 |
|
| 228 |
plugin.client.min_weight = 50 |
| 229 |
res = plugin.client.fetch_genres(MockPylastObj()) |
| 230 |
assert res == ["pop"] |
| 231 |
|
| 232 |
def test_sort_by_depth(self): |
| 233 |
self._setup_config(canonical=True) |
| 234 |
# Normal case. |
| 235 |
tags = ("electronic", "ambient", "post-rock", "downtempo") |
| 236 |
res = lastgenre.sort_by_depth(tags, self.plugin.c14n_branches) |
| 237 |
assert res == ["post-rock", "downtempo", "ambient", "electronic"] |
| 238 |
# Non-canonical tag ('chill out') present. |
| 239 |
tags = ("electronic", "ambient", "chill out") |
| 240 |
res = lastgenre.sort_by_depth(tags, self.plugin.c14n_branches) |
| 241 |
assert res == ["ambient", "electronic"] |
| 242 |
|
| 243 |
# Ignorelist tests in resolve_genres and _is_ignored |
| 244 |
|
| 245 |
def test_ignorelist_filters_genres_in_resolve(self): |
| 246 |
"""Ignored genres are stripped by _resolve_genres (no c14n). |
| 247 |
|
| 248 |
Artist-specific and global patterns are both applied. |
| 249 |
""" |
| 250 |
self._setup_config(whitelist=False, canonical=False) |
| 251 |
self.plugin.ignore_patterns = defaultdict( |
| 252 |
list, |
| 253 |
{ |
| 254 |
"the artist": [re.compile(r"^metal$", re.IGNORECASE)], |
| 255 |
"*": [re.compile(r"^rock$", re.IGNORECASE)], |
| 256 |
}, |
| 257 |
) |
| 258 |
result = self.plugin._resolve_genres( |
| 259 |
["metal", "rock", "jazz"], artist="the artist" |
| 260 |
) |
| 261 |
assert "metal" not in result, ( |
| 262 |
"artist-specific ignored genre must be removed" |
| 263 |
) |
| 264 |
assert "rock" not in result, "globally ignored genre must be removed" |
| 265 |
assert "jazz" in result, "non-ignored genre must survive" |
| 266 |
|
| 267 |
def test_ignorelist_stops_c14n_ancestry_walk(self): |
| 268 |
"""An ignored tag's c14n parents don't bleed into the result. |
| 269 |
|
| 270 |
Without ignorelist, 'delta blues' canonicalizes to 'blues'. |
| 271 |
With 'delta blues' ignored the tag is skipped entirely in the |
| 272 |
c14n loop, so 'blues' must not appear either. |
| 273 |
""" |
| 274 |
self._setup_config(whitelist=False, canonical=True, count=99) |
| 275 |
self.plugin.ignore_patterns = defaultdict( |
| 276 |
list, {"the artist": [re.compile(r"^delta blues$", re.IGNORECASE)]} |
| 277 |
) |
| 278 |
result = self.plugin._resolve_genres( |
| 279 |
["delta blues"], artist="the artist" |
| 280 |
) |
| 281 |
assert result == [], ( |
| 282 |
"ignored tag must not contribute c14n parents to the result" |
| 283 |
) |
| 284 |
|
| 285 |
def test_ignorelist_c14n_no_whitelist_keeps_oldest_ancestor(self): |
| 286 |
"""With c14n on and whitelist off, ignorelist must not change the |
| 287 |
parent-selection rule: only the oldest ancestor is returned. |
| 288 |
""" |
| 289 |
self._setup_config(whitelist=False, canonical=True, count=99) |
| 290 |
# ignorelist targets an unrelated genre — must not affect parent walking |
| 291 |
self.plugin.ignore_patterns = defaultdict( |
| 292 |
list, {"*": [re.compile(r"^jazz$", re.IGNORECASE)]} |
| 293 |
) |
| 294 |
result = self.plugin._resolve_genres(["delta blues"]) |
| 295 |
assert result == ["blues"], ( |
| 296 |
"oldest ancestor only must be returned, not the full parent chain" |
| 297 |
) |
| 298 |
|
| 299 |
def test_ignorelist_c14n_no_whitelist_drops_ignored_ancestor(self): |
| 300 |
"""With c14n on and whitelist off, if the oldest ancestor itself is |
| 301 |
ignored it must be dropped and the tag contributes nothing. |
| 302 |
""" |
| 303 |
self._setup_config(whitelist=False, canonical=True, count=99) |
| 304 |
self.plugin.ignore_patterns = defaultdict( |
| 305 |
list, {"*": [re.compile(r"^blues$", re.IGNORECASE)]} |
| 306 |
) |
| 307 |
result = self.plugin._resolve_genres(["delta blues"]) |
| 308 |
assert result == [], ( |
| 309 |
"ignored oldest ancestor must not appear in the result" |
| 310 |
) |
| 311 |
|
| 312 |
# _filter_valid tests |
| 313 |
|
| 314 |
def test_filter_valid_no_whitelist_no_ignorelist_returns_all(self): |
| 315 |
"""With neither whitelist nor ignorelist, all non-empty genres pass.""" |
| 316 |
self._setup_config(whitelist=False) |
| 317 |
self.plugin.ignore_patterns = defaultdict(list) |
| 318 |
result = self.plugin._filter_valid(["rock", "jazz", "blues"]) |
| 319 |
assert result == ["rock", "jazz", "blues"] |
| 320 |
|
| 321 |
def test_filter_valid_strips_empty_and_whitespace(self): |
| 322 |
"""Empty strings and whitespace-only strings are always removed.""" |
| 323 |
self._setup_config(whitelist=False) |
| 324 |
self.plugin.ignore_patterns = defaultdict(list) |
| 325 |
result = self.plugin._filter_valid(["rock", "", " ", "blues"]) |
| 326 |
assert result == ["rock", "blues"] |
| 327 |
|
| 328 |
def test_filter_valid_whitelist_drops_unknown_genres(self): |
| 329 |
"""Genres not in the whitelist are removed.""" |
| 330 |
self._setup_config(whitelist={"rock", "blues"}) |
| 331 |
result = self.plugin._filter_valid(["rock", "jazz", "blues"]) |
| 332 |
assert result == ["rock", "blues"] |
| 333 |
|
| 334 |
def test_filter_valid_whitelist_is_case_insensitive(self): |
| 335 |
"""Whitelist lookup is lowercased, so genre case doesn't matter.""" |
| 336 |
self._setup_config(whitelist={"rock"}) |
| 337 |
result = self.plugin._filter_valid(["Rock", "ROCK", "rock"]) |
| 338 |
assert result == ["Rock", "ROCK", "rock"] |
| 339 |
|
| 340 |
def test_filter_valid_ignorelist_drops_matched_genres(self): |
| 341 |
"""Genres matching ignorelist patterns are removed.""" |
| 342 |
self._setup_config(whitelist=False) |
| 343 |
self.plugin.ignore_patterns = defaultdict( |
| 344 |
list, {"*": [re.compile(r"^metal$", re.IGNORECASE)]} |
| 345 |
) |
| 346 |
result = self.plugin._filter_valid(["rock", "metal", "jazz"]) |
| 347 |
assert result == ["rock", "jazz"] |
| 348 |
|
| 349 |
def test_filter_valid_ignorelist_artist_specific(self): |
| 350 |
"""Artist-specific ignorelist patterns apply only for that artist.""" |
| 351 |
self._setup_config(whitelist=False) |
| 352 |
self.plugin.ignore_patterns = defaultdict( |
| 353 |
list, {"the artist": [re.compile(r"^noise$", re.IGNORECASE)]} |
| 354 |
) |
| 355 |
assert self.plugin._filter_valid( |
| 356 |
["noise", "rock"], artist="the artist" |
| 357 |
) == ["rock"] |
| 358 |
assert self.plugin._filter_valid(["noise", "rock"], artist="other") == [ |
| 359 |
"noise", |
| 360 |
"rock", |
| 361 |
] |
| 362 |
|
| 363 |
def test_filter_valid_whitelist_and_ignorelist_combined(self): |
| 364 |
"""Whitelist is applied first; ignorelist further filters the remainder.""" |
| 365 |
self._setup_config(whitelist={"rock", "metal", "jazz"}) |
| 366 |
self.plugin.ignore_patterns = defaultdict( |
| 367 |
list, {"*": [re.compile(r"^metal$", re.IGNORECASE)]} |
| 368 |
) |
| 369 |
result = self.plugin._filter_valid(["rock", "metal", "pop", "jazz"]) |
| 370 |
assert result == ["rock", "jazz"] |
| 371 |
|
| 372 |
|
| 373 |
@pytest.mark.parametrize( |
| 374 |
"config_values, item_genre, mock_genres, expected_result", |
| 375 |
[ |
| 376 |
_p( |
| 377 |
{ |
| 378 |
"force": True, |
| 379 |
"keep_existing": True, |
| 380 |
"source": "album", # means album or artist genre |
| 381 |
"whitelist": True, |
| 382 |
"canonical": False, |
| 383 |
"prefer_specific": False, |
| 384 |
"count": 10, |
| 385 |
}, |
| 386 |
["Blues"], |
| 387 |
{"album": ["Jazz"]}, |
| 388 |
(["Blues", "Jazz"], "keep + album, whitelist"), |
| 389 |
id="force-keep-whitelisted", |
| 390 |
), |
| 391 |
_p( |
| 392 |
{ |
| 393 |
"force": True, |
| 394 |
"keep_existing": True, |
| 395 |
"source": "album", |
| 396 |
"whitelist": True, |
| 397 |
"canonical": False, |
| 398 |
"prefer_specific": False, |
| 399 |
"count": 10, |
| 400 |
}, |
| 401 |
["original unknown", "Blues"], |
| 402 |
{"album": ["Jazz"]}, |
| 403 |
(["Blues", "Jazz"], "keep + album, whitelist"), |
| 404 |
id="force-keep-whitelisted-unknown-original", |
| 405 |
), |
| 406 |
_p( |
| 407 |
{ |
| 408 |
"force": True, |
| 409 |
"keep_existing": True, |
| 410 |
"source": "album", |
| 411 |
"whitelist": True, |
| 412 |
"canonical": False, |
| 413 |
"prefer_specific": False, |
| 414 |
}, |
| 415 |
[], |
| 416 |
{"album": ["Jazz"]}, |
| 417 |
(["Jazz"], "album, whitelist"), |
| 418 |
id="force-keep-whitelisted-empty-tag", |
| 419 |
), |
| 420 |
_p( |
| 421 |
{ |
| 422 |
"force": True, |
| 423 |
"keep_existing": True, |
| 424 |
"source": "artist", # means artist genre, original or fallback |
| 425 |
"whitelist": True, |
| 426 |
"canonical": False, |
| 427 |
"prefer_specific": False, |
| 428 |
"count": 10, |
| 429 |
}, |
| 430 |
["original unknown", "Blues"], |
| 431 |
{"album": ["Jazz"], "artist": ["Pop"]}, |
| 432 |
(["Blues", "Pop"], "keep + artist, whitelist"), |
| 433 |
id="force-keep-artist-configured", |
| 434 |
), |
| 435 |
_p( |
| 436 |
{ |
| 437 |
"force": False, |
| 438 |
"keep_existing": False, |
| 439 |
"source": "album", |
| 440 |
"whitelist": False, |
| 441 |
"canonical": False, |
| 442 |
"prefer_specific": False, |
| 443 |
}, |
| 444 |
["any genre"], |
| 445 |
{"album": ["Jazz"]}, |
| 446 |
(["any genre"], "keep any, no-force"), |
| 447 |
id="no-force-whitelist-disabled", |
| 448 |
), |
| 449 |
_p( |
| 450 |
{ |
| 451 |
"force": False, |
| 452 |
"keep_existing": False, |
| 453 |
"source": "album", |
| 454 |
"whitelist": False, |
| 455 |
"canonical": False, |
| 456 |
"prefer_specific": False, |
| 457 |
}, |
| 458 |
[], |
| 459 |
{"album": ["Jazzin"]}, |
| 460 |
(["Jazzin"], "album, any"), |
| 461 |
id="no-force-empty-tag-no-whitelist", |
| 462 |
), |
| 463 |
# Canonicalize original genre when force is **off** and |
| 464 |
# whitelist, canonical and cleanup_existing are on. |
| 465 |
# "Cosmic Disco" is not in the default whitelist, thus gets resolved "up" in the |
| 466 |
# tree to "Disco" and "Electronic". |
| 467 |
_p( |
| 468 |
{ |
| 469 |
"force": False, |
| 470 |
"keep_existing": False, |
| 471 |
"source": "artist", |
| 472 |
"whitelist": True, |
| 473 |
"canonical": True, |
| 474 |
"cleanup_existing": True, |
| 475 |
"prefer_specific": False, |
| 476 |
"count": 10, |
| 477 |
}, |
| 478 |
["Cosmic Disco"], |
| 479 |
{"artist": []}, |
| 480 |
(["Disco", "Electronic"], "keep + cleanup, whitelist"), |
| 481 |
id="canonicalize-existing-genre-with-cleanup", |
| 482 |
), |
| 483 |
_p( |
| 484 |
{ |
| 485 |
"force": True, |
| 486 |
"keep_existing": True, |
| 487 |
"source": "track", # means track,album,artist,... |
| 488 |
"whitelist": False, |
| 489 |
"canonical": False, |
| 490 |
"prefer_specific": False, |
| 491 |
"count": 10, |
| 492 |
}, |
| 493 |
["unknown genre"], |
| 494 |
{"track": None, "album": None, "artist": ["Jazz"]}, |
| 495 |
(["Unknown Genre", "Jazz"], "keep + artist, any"), |
| 496 |
id="fallback-through-stages-until-found", |
| 497 |
), |
| 498 |
_p( |
| 499 |
{ |
| 500 |
"force": True, |
| 501 |
"keep_existing": True, |
| 502 |
"source": "track", |
| 503 |
"whitelist": False, |
| 504 |
"fallback": "fallback genre", |
| 505 |
"canonical": False, |
| 506 |
"prefer_specific": False, |
| 507 |
}, |
| 508 |
["any existing"], |
| 509 |
{"track": None, "album": None, "artist": None}, |
| 510 |
(["any existing"], "original fallback"), |
| 511 |
id="keep-original-with-keep-existing-without-whitelist", |
| 512 |
), |
| 513 |
_p( |
| 514 |
{ |
| 515 |
"force": True, |
| 516 |
"keep_existing": True, |
| 517 |
"source": "track", |
| 518 |
"whitelist": True, |
| 519 |
"fallback": "fallback genre", |
| 520 |
"canonical": False, |
| 521 |
"prefer_specific": False, |
| 522 |
}, |
| 523 |
["Jazz"], |
| 524 |
{"track": None, "album": None, "artist": None}, |
| 525 |
(["Jazz"], "original fallback"), |
| 526 |
id="keep-valid-original-with-keep-existing-with-whitelist", |
| 527 |
), |
| 528 |
_p( |
| 529 |
{ |
| 530 |
"force": True, |
| 531 |
"keep_existing": False, |
| 532 |
"source": "track", |
| 533 |
"whitelist": True, |
| 534 |
"fallback": "fallback genre", |
| 535 |
"canonical": False, |
| 536 |
"prefer_specific": False, |
| 537 |
}, |
| 538 |
["Jazz"], |
| 539 |
{"track": None, "album": None, "artist": None}, |
| 540 |
(["fallback genre"], "fallback"), |
| 541 |
id="fallback-without-keep-existing", |
| 542 |
), |
| 543 |
_p( |
| 544 |
{ |
| 545 |
"force": True, |
| 546 |
"keep_existing": True, |
| 547 |
"source": "track", |
| 548 |
"whitelist": True, |
| 549 |
"fallback": "fallback genre", |
| 550 |
"canonical": False, |
| 551 |
"prefer_specific": False, |
| 552 |
}, |
| 553 |
[], |
| 554 |
{"track": None, "album": None, "artist": None}, |
| 555 |
(["fallback genre"], "fallback"), |
| 556 |
id="fallback-when-no-original-genre", |
| 557 |
), |
| 558 |
_p( |
| 559 |
{ |
| 560 |
"force": True, |
| 561 |
"keep_existing": True, |
| 562 |
"source": "album", |
| 563 |
"whitelist": True, |
| 564 |
"count": 5, |
| 565 |
"canonical": False, |
| 566 |
"prefer_specific": False, |
| 567 |
}, |
| 568 |
["original unknown", "Blues", "Rock", "Folk", "Metal"], |
| 569 |
{"album": ["Jazz", "Bebop", "Hardbop"]}, |
| 570 |
( |
| 571 |
["Blues", "Rock", "Metal", "Jazz", "Bebop"], |
| 572 |
"keep + album, whitelist", |
| 573 |
), |
| 574 |
id="limit-many-results", |
| 575 |
), |
| 576 |
# fallback to next stage (artist) if no allowed original present |
| 577 |
# and no album genre were fetched. |
| 578 |
_p( |
| 579 |
{ |
| 580 |
"force": True, |
| 581 |
"keep_existing": True, |
| 582 |
"source": "album", |
| 583 |
"whitelist": True, |
| 584 |
"fallback": "fallback genre", |
| 585 |
"canonical": False, |
| 586 |
"prefer_specific": False, |
| 587 |
}, |
| 588 |
["not whitelisted original"], |
| 589 |
{"track": None, "album": None, "artist": ["Jazz"]}, |
| 590 |
(["Jazz"], "keep + artist, whitelist"), |
| 591 |
id="fallback-to-artist-when-original-and-album-invalid", |
| 592 |
), |
| 593 |
# canonicalization transforms non-whitelisted genres to canonical forms |
| 594 |
# |
| 595 |
# "Acid Techno" is not in the default whitelist, thus gets resolved "up" in the |
| 596 |
# tree to "Techno" and "Electronic". |
| 597 |
_p( |
| 598 |
{ |
| 599 |
"force": True, |
| 600 |
"keep_existing": False, |
| 601 |
"source": "album", |
| 602 |
"whitelist": True, |
| 603 |
"canonical": True, |
| 604 |
"prefer_specific": False, |
| 605 |
"count": 10, |
| 606 |
}, |
| 607 |
[], |
| 608 |
{"album": ["acid techno"]}, |
| 609 |
(["Techno", "Electronic"], "album, whitelist"), |
| 610 |
id="canonicalize-non-whitelisted-fetched-genre", |
| 611 |
), |
| 612 |
# canonicalization transforms whitelisted genres to canonical forms and |
| 613 |
# includes originals |
| 614 |
# |
| 615 |
# "Detroit Techno" is in the default whitelist, thus it stays and and also gets |
| 616 |
# resolved "up" in the tree to "Techno" and "Electronic". The same happens for |
| 617 |
# newly fetched genre "Acid House". |
| 618 |
_p( |
| 619 |
{ |
| 620 |
"force": True, |
| 621 |
"keep_existing": True, |
| 622 |
"source": "album", |
| 623 |
"whitelist": True, |
| 624 |
"canonical": True, |
| 625 |
"prefer_specific": False, |
| 626 |
"count": 10, |
| 627 |
"extended_debug": True, |
| 628 |
}, |
| 629 |
["detroit techno"], |
| 630 |
{"album": ["acid house"]}, |
| 631 |
( |
| 632 |
[ |
| 633 |
"Detroit Techno", |
| 634 |
"Techno", |
| 635 |
"Electronic", |
| 636 |
"Acid House", |
| 637 |
"House", |
| 638 |
], |
| 639 |
"keep + album, whitelist", |
| 640 |
), |
| 641 |
id="canonicalize-whitelisted-original-and-fetched-genres", |
| 642 |
), |
| 643 |
# canonicalization transforms non-whitelisted original genres to canonical |
| 644 |
# forms and deduplication works. |
| 645 |
# |
| 646 |
# "Cosmic Disco" is not in the default whitelist, thus gets resolved "up" in the |
| 647 |
# tree to "Disco" and "Electronic". New genre "Detroit Techno" resolves to |
| 648 |
# "Techno". Both resolve to "Electronic" which gets deduplicated. |
| 649 |
_p( |
| 650 |
{ |
| 651 |
"force": True, |
| 652 |
"keep_existing": True, |
| 653 |
"source": "album", |
| 654 |
"whitelist": True, |
| 655 |
"canonical": True, |
| 656 |
"prefer_specific": False, |
| 657 |
"count": 10, |
| 658 |
}, |
| 659 |
["Cosmic Disco"], |
| 660 |
{"album": ["Detroit Techno"]}, |
| 661 |
( |
| 662 |
["Disco", "Electronic", "Detroit Techno", "Techno"], |
| 663 |
"keep + album, whitelist", |
| 664 |
), |
| 665 |
id="canonicalize-and-deduplicate-original-and-fetched-genres", |
| 666 |
), |
| 667 |
# canonicalization transforms non-whitelisted original genres to canonical |
| 668 |
# forms and deduplication works, **even** when no new genres are found online. |
| 669 |
# |
| 670 |
# "Cosmic Disco" is not in the default whitelist, thus gets resolved "up" in the |
| 671 |
# tree to "Disco" and "Electronic". |
| 672 |
_p( |
| 673 |
{ |
| 674 |
"force": True, |
| 675 |
"keep_existing": True, |
| 676 |
"source": "album", |
| 677 |
"whitelist": True, |
| 678 |
"canonical": True, |
| 679 |
"prefer_specific": False, |
| 680 |
"count": 10, |
| 681 |
}, |
| 682 |
["Cosmic Disco"], |
| 683 |
{"album": [], "artist": []}, |
| 684 |
(["Disco", "Electronic"], "keep + original fallback, whitelist"), |
| 685 |
id="canonicalize-and-deduplicate-without-new-genres", |
| 686 |
), |
| 687 |
# Semicolon-delimited genre tag from an external mediafile |
| 688 |
# ("Jazz; Funk; Soul" as a single element) is split by |
| 689 |
# DelimitedString.normalize() on assignment and returned as three |
| 690 |
# individual genres via the "original fallback" path when all Last.fm |
| 691 |
# stages return empty. |
| 692 |
_p( |
| 693 |
{ |
| 694 |
"force": True, |
| 695 |
"keep_existing": True, |
| 696 |
"source": "album", |
| 697 |
"whitelist": False, |
| 698 |
"canonical": False, |
| 699 |
"prefer_specific": False, |
| 700 |
"count": 10, |
| 701 |
}, |
| 702 |
["Jazz; Funk; Soul"], |
| 703 |
{"album": [], "artist": []}, |
| 704 |
(["Jazz", "Funk", "Soul"], "original fallback"), |
| 705 |
id="split-semicolon-delimited-original-genres", |
| 706 |
), |
| 707 |
# Multiple whitelisted genres in the multi-valued `genres` field must |
| 708 |
# NOT be wiped when Last.fm returns no tags — whether the album is not |
| 709 |
# found at all or exists but has no tags. Both scenarios produce an |
| 710 |
# empty list from the fetcher and must be preserved via "original |
| 711 |
# fallback". |
| 712 |
_p( |
| 713 |
{ |
| 714 |
"force": True, |
| 715 |
"keep_existing": True, |
| 716 |
"source": "album", |
| 717 |
"whitelist": True, |
| 718 |
"canonical": False, |
| 719 |
"prefer_specific": False, |
| 720 |
}, |
| 721 |
["Baroque", "Classical"], |
| 722 |
{"album": [], "artist": []}, |
| 723 |
(["Baroque", "Classical"], "original fallback"), |
| 724 |
id="preserve-multiple-whitelisted-genres-on-empty-fetch", |
| 725 |
), |
| 726 |
], |
| 727 |
) |
| 728 |
@pytest.mark.usefixtures("config") |
| 729 |
def test_get_genre( |
| 730 |
monkeypatch, config_values, item_genre, mock_genres, expected_result |
| 731 |
): |
| 732 |
"""Test _get_genre with various configurations.""" |
| 733 |
# Mock the last.fm fetchers. When whitelist enabled, we can assume only |
| 734 |
# whitelisted genres get returned, the plugin's _resolve_genre method |
| 735 |
# ensures it. |
| 736 |
monkeypatch.setattr( |
| 737 |
"beetsplug.lastgenre.client.LastFmClient.fetch", |
| 738 |
lambda _, kind, __: mock_genres[kind], |
| 739 |
) |
| 740 |
# Initialize plugin instance and item |
| 741 |
plugin = lastgenre.LastGenrePlugin() |
| 742 |
# Configure |
| 743 |
plugin.config.set(config_values) |
| 744 |
plugin.setup() # Loads default whitelist and canonicalization tree |
| 745 |
|
| 746 |
item = _common.item() |
| 747 |
item.genres = item_genre |
| 748 |
|
| 749 |
# Run |
| 750 |
assert plugin._get_genre(item) == expected_result |
| 751 |
|
| 752 |
|
| 753 |
class TestIgnorelist: |
| 754 |
"""Ignorelist pattern matching tests independent of resolve_genres.""" |
| 755 |
|
| 756 |
@pytest.mark.parametrize( |
| 757 |
"ignorelist_dict, artist, genre, expected_forbidden", |
| 758 |
[ |
| 759 |
# Global ignorelist - simple word |
| 760 |
({"*": ["spoken word"]}, "Any Artist", "spoken word", True), |
| 761 |
({"*": ["spoken word"]}, "Any Artist", "jazz", False), |
| 762 |
# Global ignorelist - regex pattern |
| 763 |
( |
| 764 |
{"*": [".*electronic.*"]}, |
| 765 |
"Any Artist", |
| 766 |
"ambient electronic", |
| 767 |
True, |
| 768 |
), |
| 769 |
({"*": [".*electronic.*"]}, "Any Artist", "jazz", False), |
| 770 |
# Artist-specific ignorelist |
| 771 |
({"metallica": ["metal"]}, "Metallica", "metal", True), |
| 772 |
({"metallica": ["metal"]}, "Iron Maiden", "metal", False), |
| 773 |
# Case insensitive matching |
| 774 |
({"metallica": ["metal"]}, "METALLICA", "METAL", True), |
| 775 |
# Full-match behavior: plain "metal" must not match "heavy metal" |
| 776 |
({"metallica": ["metal"]}, "Metallica", "heavy metal", False), |
| 777 |
# Regex behavior: explicit pattern ".*metal.*" may match "heavy metal" |
| 778 |
({"metallica": [".*metal.*"]}, "Metallica", "heavy metal", True), |
| 779 |
# Artist-specific ignorelist - exact match |
| 780 |
( |
| 781 |
{"metallica": ["^Heavy Metal$"]}, |
| 782 |
"Metallica", |
| 783 |
"classic metal", |
| 784 |
False, |
| 785 |
), |
| 786 |
# Combined global and artist-specific |
| 787 |
( |
| 788 |
{"*": ["spoken word"], "metallica": ["metal"]}, |
| 789 |
"Metallica", |
| 790 |
"spoken word", |
| 791 |
True, |
| 792 |
), |
| 793 |
( |
| 794 |
{"*": ["spoken word"], "metallica": ["metal"]}, |
| 795 |
"Metallica", |
| 796 |
"metal", |
| 797 |
True, |
| 798 |
), |
| 799 |
# Complex regex pattern with multiple features (raw string) |
| 800 |
( |
| 801 |
{ |
| 802 |
"fracture": [ |
| 803 |
r"^(heavy|black|power|death)?\s?(metal|rock)$|\w+-metal\d*$" |
| 804 |
] |
| 805 |
}, |
| 806 |
"Fracture", |
| 807 |
"power metal", |
| 808 |
True, |
| 809 |
), |
| 810 |
# Complex regex pattern with multiple features (regular string) |
| 811 |
( |
| 812 |
{"amon tobin": ["d(rum)?[ n/]*b(ass)?"]}, |
| 813 |
"Amon Tobin", |
| 814 |
"dnb", |
| 815 |
True, |
| 816 |
), |
| 817 |
# Empty ignorelist |
| 818 |
({}, "Any Artist", "any genre", False), |
| 819 |
], |
| 820 |
) |
| 821 |
def test_ignorelist_patterns( |
| 822 |
self, ignorelist_dict, artist, genre, expected_forbidden |
| 823 |
): |
| 824 |
"""Test ignorelist pattern matching logic directly.""" |
| 825 |
|
| 826 |
logger = Mock() |
| 827 |
|
| 828 |
# Set up compiled patterns directly (skipping file parsing) |
| 829 |
ignore_patterns = defaultdict(list) |
| 830 |
for artist_name, patterns in ignorelist_dict.items(): |
| 831 |
ignore_patterns[artist_name.lower()] = [ |
| 832 |
re.compile(pattern, re.IGNORECASE) for pattern in patterns |
| 833 |
] |
| 834 |
|
| 835 |
result = is_ignored(logger, ignore_patterns, genre, artist) |
| 836 |
assert result == expected_forbidden |
| 837 |
|
| 838 |
@pytest.mark.parametrize( |
| 839 |
"ignorelist_config, expected_ignorelist", |
| 840 |
[ |
| 841 |
# Basic artist with single pattern |
| 842 |
({"metallica": ["metal"]}, {"metallica": ["metal"]}), |
| 843 |
# Global ignorelist with '*' key |
| 844 |
({"*": ["spoken word"]}, {"*": ["spoken word"]}), |
| 845 |
# Multiple patterns per artist |
| 846 |
( |
| 847 |
{"metallica": ["metal", ".*rock.*"]}, |
| 848 |
{"metallica": ["metal", ".*rock.*"]}, |
| 849 |
), |
| 850 |
# Combined global and artist-specific |
| 851 |
( |
| 852 |
{"*": ["spoken word"], "metallica": ["metal"]}, |
| 853 |
{"*": ["spoken word"], "metallica": ["metal"]}, |
| 854 |
), |
| 855 |
# Invalid regex pattern that gets escaped (full-match literal fallback) |
| 856 |
( |
| 857 |
{"artist": ["[invalid(regex"]}, |
| 858 |
{"artist": ["\\[invalid\\(regex"]}, |
| 859 |
), |
| 860 |
# Disabled via False / empty dict — both produce empty dict |
| 861 |
(False, {}), |
| 862 |
({}, {}), |
| 863 |
], |
| 864 |
) |
| 865 |
def test_ignorelist_config_format( |
| 866 |
self, ignorelist_config, expected_ignorelist |
| 867 |
): |
| 868 |
"""Test ignorelist parsing/compilation with isolated config state.""" |
| 869 |
cfg = confuse.Configuration("test", read=False) |
| 870 |
cfg.set({"lastgenre": {"ignorelist": ignorelist_config}}) |
| 871 |
|
| 872 |
# Mimic the plugin loader behavior in isolation to avoid global config bleed. |
| 873 |
if not cfg["lastgenre"]["ignorelist"].get(): |
| 874 |
ignore_patterns = {} |
| 875 |
else: |
| 876 |
raw_strs = cfg["lastgenre"]["ignorelist"].get( |
| 877 |
confuse.MappingValues(confuse.Sequence(str)) |
| 878 |
) |
| 879 |
ignore_patterns = {} |
| 880 |
for artist, patterns in raw_strs.items(): |
| 881 |
compiled_patterns = [] |
| 882 |
for pattern in patterns: |
| 883 |
try: |
| 884 |
compiled_patterns.append( |
| 885 |
re.compile(pattern, re.IGNORECASE).pattern |
| 886 |
) |
| 887 |
except re.error: |
| 888 |
compiled_patterns.append( |
| 889 |
re.compile( |
| 890 |
re.escape(pattern), re.IGNORECASE |
| 891 |
).pattern |
| 892 |
) |
| 893 |
ignore_patterns[artist.lower()] = compiled_patterns |
| 894 |
|
| 895 |
assert ignore_patterns == expected_ignorelist |
| 896 |
|
| 897 |
@pytest.mark.parametrize( |
| 898 |
"invalid_config, expected_error_message", |
| 899 |
[ |
| 900 |
# A plain string (e.g. accidental file path) instead of a mapping |
| 901 |
("/path/to/ignorelist.txt", "must be a dict"), |
| 902 |
# An integer instead of a mapping |
| 903 |
(42, "must be a dict"), |
| 904 |
# A list of strings instead of a mapping |
| 905 |
(["spoken word", "comedy"], "must be a dict"), |
| 906 |
# A mapping with a non-list value |
| 907 |
({"metallica": "metal"}, "must be a list"), |
| 908 |
], |
| 909 |
) |
| 910 |
def test_ignorelist_config_format_errors( |
| 911 |
self, invalid_config, expected_error_message |
| 912 |
): |
| 913 |
"""Test ignorelist config validation errors in isolated config.""" |
| 914 |
cfg = confuse.Configuration("test", read=False) |
| 915 |
cfg.set({"lastgenre": {"ignorelist": invalid_config}}) |
| 916 |
|
| 917 |
with pytest.raises(confuse.ConfigTypeError) as exc_info: |
| 918 |
_ = cfg["lastgenre"]["ignorelist"].get( |
| 919 |
confuse.MappingValues(confuse.Sequence(str)) |
| 920 |
) |
| 921 |
|
| 922 |
assert expected_error_message in str(exc_info.value) |
| 923 |
|
| 924 |
def test_ignorelist_multivalued_album_artist_fallback( |
| 925 |
self, monkeypatch, config |
| 926 |
): |
| 927 |
"""`stage_artist=None` fallback must not re-drop per-artist results.""" |
| 928 |
config["lastgenre"]["ignorelist"] = { |
| 929 |
"Artist A": ["Metal"], |
| 930 |
"Artist Group": ["Metal"], |
| 931 |
} |
| 932 |
config["lastgenre"]["whitelist"] = False |
| 933 |
config["lastgenre"]["count"] = 10 |
| 934 |
|
| 935 |
plugin = lastgenre.LastGenrePlugin() |
| 936 |
plugin.setup() |
| 937 |
|
| 938 |
def fake_fetch(_, kind, obj, *args): |
| 939 |
if kind == "album_artist" and args: |
| 940 |
album_artist = args[0] |
| 941 |
return {"Artist A": ["Rock"], "Artist B": ["Metal", "Jazz"]}[ |
| 942 |
album_artist |
| 943 |
] |
| 944 |
return [] |
| 945 |
|
| 946 |
monkeypatch.setattr( |
| 947 |
"beetsplug.lastgenre.client.LastFmClient.fetch", fake_fetch |
| 948 |
) |
| 949 |
|
| 950 |
obj = Album() |
| 951 |
obj.albumartist = "Artist Group" |
| 952 |
obj.album = "Album Title" |
| 953 |
obj.albumartists = ["Artist A", "Artist B"] |
| 954 |
|
| 955 |
genres, label = plugin._get_genre(obj) |
| 956 |
|
| 957 |
assert "multi-valued album artist" in label |
| 958 |
assert "Metal" in genres |
| 959 |
|
| 960 |
|
| 961 |
class TestAliases: |
| 962 |
"""Alias pattern matching and loading tests.""" |
| 963 |
|
| 964 |
@pytest.mark.parametrize( |
| 965 |
"aliases_dict, genre, expected", |
| 966 |
[ |
| 967 |
# Static replacement |
| 968 |
({"foo bar": ["foobar"]}, "foobar", "foo bar"), |
| 969 |
# Template with back-reference |
| 970 |
({r"\1 music": [r"(fake)[ /-]*music"]}, "fake-music", "fake music"), |
| 971 |
# Template with multiple back-references |
| 972 |
({r"\1-\2": [r"(x)[ /-]*(y)"]}, "x y", "x-y"), |
| 973 |
# Case-insensitive matching |
| 974 |
({"foo bar": ["foobar"]}, "FOOBAR", "foo bar"), |
| 975 |
# No match — genre returned as-is (lowercased) |
| 976 |
({"foo bar": ["foobar"]}, "jazz", "jazz"), |
| 977 |
# Empty alias list → no-op |
| 978 |
({}, "something", "something"), |
| 979 |
], |
| 980 |
) |
| 981 |
def test_normalize_genre( |
| 982 |
self, aliases_dict: dict[str, list[str]], genre: str, expected: str |
| 983 |
) -> None: |
| 984 |
"""Test normalize_genre() with static and template canonical names.""" |
| 985 |
alias_patterns = [ |
| 986 |
(re.compile(pat, re.IGNORECASE), template.lower()) |
| 987 |
for template, patterns in aliases_dict.items() |
| 988 |
for pat in patterns |
| 989 |
] |
| 990 |
assert normalize_genre(Mock(), alias_patterns, genre) == expected |
| 991 |
|
| 992 |
def test_normalize_genre_invalid_template_does_not_crash(self) -> None: |
| 993 |
"""Invalid replacement templates are skipped instead of crashing.""" |
| 994 |
logger = Mock() |
| 995 |
alias_patterns = [ |
| 996 |
(re.compile(r"(hip)[ /-]*hop", re.IGNORECASE), r"\g<2> hop") |
| 997 |
] |
| 998 |
|
| 999 |
assert normalize_genre(logger, alias_patterns, "hip-hop") == "hip-hop" |
| 1000 |
logger.warning.assert_called_once() |
| 1001 |
|
| 1002 |
def test_aliases_config_format(self, config): |
| 1003 |
"""Test _load_aliases() loading from inline config dict.""" |
| 1004 |
# Multi-pattern list: proves all patterns are loaded, not just the first |
| 1005 |
config["lastgenre"]["aliases"] = {"hip hop": ["hip-hop", "hiphop"]} |
| 1006 |
plugin = lastgenre.LastGenrePlugin() |
| 1007 |
assert ( |
| 1008 |
normalize_genre(plugin._log, plugin.alias_patterns, "hip-hop") |
| 1009 |
== "hip hop" |
| 1010 |
) |
| 1011 |
assert ( |
| 1012 |
normalize_genre(plugin._log, plugin.alias_patterns, "hiphop") |
| 1013 |
== "hip hop" |
| 1014 |
) |
| 1015 |
|
| 1016 |
@pytest.mark.parametrize( |
| 1017 |
"invalid_config, expected_error", |
| 1018 |
[ |
| 1019 |
# Plain string instead of mapping |
| 1020 |
("/path/to/aliases.txt", "must be a dict"), |
| 1021 |
# Integer |
| 1022 |
(42, "must be a dict"), |
| 1023 |
# Mapping with non-list value |
| 1024 |
({"hip hop": "hip-hop"}, "must be a list"), |
| 1025 |
], |
| 1026 |
) |
| 1027 |
def test_aliases_config_format_errors( |
| 1028 |
self, config, invalid_config, expected_error |
| 1029 |
): |
| 1030 |
"""Test that invalid aliases config values raise confuse.ConfigTypeError.""" |
| 1031 |
config["lastgenre"]["aliases"] = invalid_config |
| 1032 |
with pytest.raises(confuse.ConfigTypeError) as exc_info: |
| 1033 |
lastgenre.LastGenrePlugin() |
| 1034 |
assert expected_error in str(exc_info.value) |
| 1035 |
|
| 1036 |
def test_normalize_before_whitelist(self, config): |
| 1037 |
"""Aliases normalize BEFORE whitelist filtering. |
| 1038 |
|
| 1039 |
'hip-hop' is not on the whitelist but 'hip hop' is. With aliases |
| 1040 |
enabled the tag must survive whitelist filtering. |
| 1041 |
""" |
| 1042 |
config["lastgenre"]["aliases"] = {"hip hop": ["hip-hop", "hiphop"]} |
| 1043 |
plugin = lastgenre.LastGenrePlugin() |
| 1044 |
plugin.setup() |
| 1045 |
# Inject only 'hip hop' into the whitelist to prove the alias fired. |
| 1046 |
plugin.whitelist = {"hip hop"} |
| 1047 |
|
| 1048 |
result = plugin._resolve_genres(["hip-hop"]) |
| 1049 |
assert result == ["hip hop"], ( |
| 1050 |
"alias must normalize 'hip-hop' → 'hip hop' before whitelist check" |
| 1051 |
) |
| 1052 |
|
| 1053 |
def test_normalize_before_ignorelist(self, config): |
| 1054 |
"""Aliases normalize BEFORE ignorelist filtering. |
| 1055 |
|
| 1056 |
If 'hip hop' is ignored but 'hip-hop' is fed in, the alias fires first |
| 1057 |
so the result is empty (correctly ignored). |
| 1058 |
""" |
| 1059 |
config["lastgenre"]["aliases"] = {"hip hop": ["hip-hop"]} |
| 1060 |
plugin = lastgenre.LastGenrePlugin() |
| 1061 |
plugin.setup() |
| 1062 |
plugin.ignore_patterns = {"*": [re.compile("hip hop", re.IGNORECASE)]} |
| 1063 |
|
| 1064 |
result = plugin._resolve_genres(["hip-hop"]) |
| 1065 |
assert result == [], ( |
| 1066 |
"alias must normalize 'hip-hop' before ignorelist check drops it" |
| 1067 |
) |
| 1068 |
|
| 1069 |
def test_disabled(self, config): |
| 1070 |
"""With aliases: false, no normalization is performed.""" |
| 1071 |
config["lastgenre"]["aliases"] = False |
| 1072 |
plugin = lastgenre.LastGenrePlugin() |
| 1073 |
assert plugin.alias_patterns == [] |
| 1074 |
# normalize_genre with an empty list must return the genre unchanged. |
| 1075 |
assert ( |
| 1076 |
normalize_genre(plugin._log, plugin.alias_patterns, "hip-hop") |
| 1077 |
== "hip-hop" |
| 1078 |
) |
| 1079 |
|
| 1080 |
@pytest.mark.parametrize( |
| 1081 |
"input_genre, expected_genre", |
| 1082 |
[ |
| 1083 |
("dnb", "drum and bass"), |
| 1084 |
("drum n bass", "drum and bass"), |
| 1085 |
("r&b", "r&b"), |
| 1086 |
("rnb", "r&b"), |
| 1087 |
("rock & roll", "rock and roll"), |
| 1088 |
("rock'n'roll", "rock and roll"), |
| 1089 |
("kpop", "k-pop"), |
| 1090 |
("k -pop", "k-pop"), |
| 1091 |
("j rock", "j-rock"), |
| 1092 |
("post rock", "post-rock"), |
| 1093 |
("lofi", "lo-fi"), |
| 1094 |
("lo fi", "lo-fi"), |
| 1095 |
("p funk", "p-funk"), |
| 1096 |
("synth funk", "synth funk"), |
| 1097 |
("synth pop", "synth-pop"), |
| 1098 |
("synth-wave", "synthwave"), |
| 1099 |
("avantgarde", "avant-garde"), |
| 1100 |
("avant gard", "avant-garde"), |
| 1101 |
("nu-jazz", "nu jazz"), |
| 1102 |
("nu-metal", "nu metal"), |
| 1103 |
("nu-soul", "nu soul"), |
| 1104 |
("nu-disco", "nu disco"), |
| 1105 |
("nu - disco", "nu disco"), |
| 1106 |
("electronic music", "electronic"), |
| 1107 |
("world", "world music"), |
| 1108 |
("chill", "chill"), |
| 1109 |
("chill out", "chillout"), |
| 1110 |
("chill-out", "chillout"), |
| 1111 |
("dark wave", "dark wave"), |
| 1112 |
("dark-wave", "dark wave"), |
| 1113 |
("blues rock", "blues rock"), |
| 1114 |
("blues-rock", "blues rock"), |
| 1115 |
("folk-rock", "folk rock"), |
| 1116 |
("downbeat", "downtempo"), |
| 1117 |
("shoegazer", "shoegaze"), |
| 1118 |
("shoegazing", "shoegaze"), |
| 1119 |
("hip-hop", "hip hop"), |
| 1120 |
("triphop", "trip hop"), |
| 1121 |
("punk", "punk rock"), |
| 1122 |
("alt", "alt"), |
| 1123 |
("alt rock", "alternative rock"), |
| 1124 |
("alternative", "alternative"), |
| 1125 |
("goth", "gothic rock"), |
| 1126 |
("goth rock", "gothic rock"), |
| 1127 |
("gothic rock", "gothic rock"), |
| 1128 |
("prog", "progressive rock"), |
| 1129 |
("prog rock", "progressive rock"), |
| 1130 |
("progressive rock", "progressive rock"), |
| 1131 |
("trad", "trad"), |
| 1132 |
("traditional", "traditional"), |
| 1133 |
("indie", "indie"), |
| 1134 |
("indie rock", "indie rock"), |
| 1135 |
("juke/footwork", "juke/footwork"), |
| 1136 |
("Funk / Soul", "funk / soul"), |
| 1137 |
("psy-trance", "psytrance"), |
| 1138 |
("psy rock", "psychedelic rock"), |
| 1139 |
("psych-pop", "psychedelic pop"), |
| 1140 |
("disney", "disney"), |
| 1141 |
("old-school death-metal", "old school death metal"), |
| 1142 |
("old-skool-hip-hop", "old school hip hop"), |
| 1143 |
("old school-jungle", "old school jungle"), |
| 1144 |
], |
| 1145 |
) |
| 1146 |
def test_default_alias_patterns(self, config, input_genre, expected_genre): |
| 1147 |
"""Verify that bundled aliases.yaml correctly handles common variants.""" |
| 1148 |
plugin = lastgenre.LastGenrePlugin() |
| 1149 |
result = normalize_genre( |
| 1150 |
plugin._log, plugin.alias_patterns, input_genre |
| 1151 |
) |
| 1152 |
assert result == expected_genre |
| 1153 |
|
| 1154 |
def test_client_normalizes_in_last_lookup(self): |
| 1155 |
"""LastFmClient._last_lookup applies alias normalization then ignorelist.""" |
| 1156 |
alias_patterns = [(re.compile(r"hip-hop", re.IGNORECASE), "hip hop")] |
| 1157 |
ignore_patterns = {"*": [re.compile("hip hop", re.IGNORECASE)]} |
| 1158 |
client = lastgenre.client.LastFmClient( |
| 1159 |
Mock(), 0, ignore_patterns, alias_patterns |
| 1160 |
) |
| 1161 |
|
| 1162 |
mock_lastfm_obj = Mock() |
| 1163 |
mock_lastfm_obj.get_top_tags.return_value = [] |
| 1164 |
# Seed the cache directly to avoid a real network call. |
| 1165 |
client.genre_cache["track.artist-title"] = ["hip-hop"] |
| 1166 |
|
| 1167 |
result = client._last_lookup("track", Mock(), "artist", "title") |
| 1168 |
assert result == [], ( |
| 1169 |
"'hip-hop' must be normalized to 'hip hop' then filtered by ignorelist" |
| 1170 |
) |