mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-01 21:45:10 +00:00
fix(music): show a collection's own facts in the listing and over --remote
This commit is contained in:
@@ -79,6 +79,7 @@ def test_first_text(values: tuple[Any, ...], default: str, expected: str) -> Non
|
||||
(("abc", 7), 7.0),
|
||||
((None, ""), None),
|
||||
((), None),
|
||||
((10**400, "Infinity", float("nan"), 7), 7.0),
|
||||
],
|
||||
)
|
||||
def test_first_number(values: tuple[Any, ...], expected: float | None) -> None:
|
||||
@@ -126,6 +127,7 @@ def test_duration_seconds(value: Any, expected: float | None) -> None:
|
||||
(-5, "0:00"),
|
||||
(None, ""),
|
||||
("bad", ""),
|
||||
(float("inf"), ""),
|
||||
],
|
||||
)
|
||||
def test_format_duration(value: Any, expected: str) -> None:
|
||||
@@ -189,6 +191,7 @@ def test_build_music_from_songs() -> None:
|
||||
year=2019,
|
||||
album="Greatest",
|
||||
artist="Band",
|
||||
album_artist="The Band",
|
||||
total_tracks=2,
|
||||
total_discs=1,
|
||||
data={"duration": 100},
|
||||
@@ -224,6 +227,19 @@ def test_build_music_from_songs_overrides() -> None:
|
||||
assert music.description == "best of"
|
||||
|
||||
|
||||
def test_build_music_from_songs_of_different_releases_takes_no_fact_from_a_song() -> None:
|
||||
songs = [
|
||||
make_song(album="A", album_artist="Band A", total_tracks=30, artwork_url="http://art/a.jpg"),
|
||||
make_song(track=12, disc=4, album="B", album_artist="Band B", total_discs=4, data={"duration": 60}),
|
||||
]
|
||||
music = build_music_from_songs(songs, kind="playlist")
|
||||
assert (music.title, music.artist, music.year, music.artwork_url) == (None, None, None, None)
|
||||
assert (music.total_tracks, music.total_discs, music.total_duration) == (2, None, 60)
|
||||
|
||||
named = build_music_from_songs(songs, kind="playlist", title="My Mix", artist="Various")
|
||||
assert str(named) == "Various - My Mix"
|
||||
|
||||
|
||||
def test_build_music_from_songs_empty_raises() -> None:
|
||||
with pytest.raises(ValueError, match="nothing here"):
|
||||
build_music_from_songs([], kind="album", empty_error="nothing here")
|
||||
|
||||
@@ -1,6 +1,211 @@
|
||||
from typing import Any
|
||||
|
||||
import jsonpickle
|
||||
import pytest
|
||||
|
||||
from tests.lang_selection.test_kind_only_selection import FakeService, run
|
||||
from unshackle.core.console import console
|
||||
from unshackle.core.music.renderer import MusicRenderer
|
||||
from unshackle.core.titles.music import Album, Music, Song
|
||||
|
||||
|
||||
class DummyService:
|
||||
pass
|
||||
|
||||
|
||||
def song(number: int, album: str, album_artist: str | None, **fields: Any) -> Song:
|
||||
values: dict[str, Any] = {
|
||||
"artist": f"Song Artist {number}",
|
||||
"year": 2000 + number,
|
||||
"genre": f"Genre {number}",
|
||||
"label": f"Label {number}",
|
||||
"data": {"release_date": f"200{number}-10-14", "quality": "FLAC 24-bit/96kHz", "duration": 60},
|
||||
**fields,
|
||||
}
|
||||
return Song(
|
||||
f"song-{number}", DummyService, f"Name {number}", album=album, album_artist=album_artist, track=number, **values
|
||||
)
|
||||
|
||||
|
||||
def mixed(**facts: Any) -> Album:
|
||||
"""Songs of two releases that share no fact with each other."""
|
||||
return Album([song(1, "Album 1", "Album Artist 1", explicit=True), song(2, "Album 2", "Album Artist 2")], **facts)
|
||||
|
||||
|
||||
def header(music: Music) -> list[tuple[str, str]]:
|
||||
grid = MusicRenderer().render_header(music)
|
||||
assert grid is not None
|
||||
labels, values = (list(column.cells) for column in grid.columns)
|
||||
return [(str(label), str(value)) for label, value in zip(labels, values, strict=True)]
|
||||
|
||||
|
||||
OWN_FACTS = {"kind": "playlist", "title": "Own Title", "artist": "Own Artist", "year": 1990, "total_tracks": 9}
|
||||
OWN_ROWS = [
|
||||
("Title", "Own Title"),
|
||||
("Artist", "Own Artist"),
|
||||
("Type", "Playlist Explicit"),
|
||||
("Year", "1990"),
|
||||
("Tracks", "9"),
|
||||
("Length", "2m 00s"),
|
||||
]
|
||||
|
||||
|
||||
def test_a_collection_of_different_releases_shows_only_its_own_facts() -> None:
|
||||
assert header(mixed(**OWN_FACTS)) == OWN_ROWS
|
||||
assert str(mixed(**OWN_FACTS)) == "Own Artist - Own Title (1990)"
|
||||
|
||||
|
||||
def test_a_collection_of_different_releases_shows_the_date_and_quality_set_on_it() -> None:
|
||||
music = mixed(**OWN_FACTS)
|
||||
vars(music).update(release_date="1990-02-03", quality="MP3")
|
||||
rows = dict(header(music))
|
||||
assert (rows["Released"], rows["Quality"]) == ("February 3, 1990", "MP3")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("facts", "line"),
|
||||
[
|
||||
({}, "2 songs"),
|
||||
({"total_tracks": 9}, "2 songs"),
|
||||
({"title": "Own Title"}, "Own Title"),
|
||||
({"artist": "Own Artist"}, "Own Artist"),
|
||||
({"year": 1990}, "(1990)"),
|
||||
({"title": "Own Title", "year": 1990}, "Own Title (1990)"),
|
||||
({"title": "Own Title", "artist": "Own Artist"}, "Own Artist - Own Title"),
|
||||
],
|
||||
)
|
||||
def test_a_fact_that_a_collection_of_different_releases_lacks_has_no_row_and_no_placeholder(
|
||||
facts: dict[str, Any], line: str
|
||||
) -> None:
|
||||
assert str(mixed(**facts)) == line
|
||||
shown = [label for label, _ in header(mixed(**facts)) if label not in ("Type", "Tracks", "Length")]
|
||||
assert shown == [label for label in ("Title", "Artist", "Year") if label.lower() in facts]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"other", [("Album 1", "Album Artist 2"), ("Album 2", "Album Artist 1"), ("Album 1", None)], ids=str
|
||||
)
|
||||
def test_the_album_and_its_artist_together_make_one_release(other: tuple[str, str | None]) -> None:
|
||||
music = Album([song(1, "Album 1", "Album Artist 1"), song(2, *other)], title="Own Title")
|
||||
assert [label for label, _ in header(music)] == ["Title", "Type", "Tracks", "Length"]
|
||||
assert str(music) == "Own Title"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("album_artist", "artist"), [("Album Artist", "Album Artist"), (None, "Song Artist 1")])
|
||||
def test_a_collection_of_one_release_shows_the_facts_of_its_first_song(album_artist: str | None, artist: str) -> None:
|
||||
music = Album([song(n, "Album 1", album_artist) for n in (1, 2)], kind="playlist")
|
||||
assert header(music) == [
|
||||
("Title", "Album 1"),
|
||||
("Artist", artist),
|
||||
("Type", "Playlist"),
|
||||
("Released", "October 14, 2001"),
|
||||
("Year", "2001"),
|
||||
("Tracks", "2"),
|
||||
("Length", "2m 00s"),
|
||||
("Quality", "Hi-Res Lossless"),
|
||||
("Genre", "Genre 1"),
|
||||
("Label", "Label 1"),
|
||||
]
|
||||
assert str(music) == f"{artist} - Album 1 (2001)"
|
||||
assert str(Album([song(1, "Album 1", album_artist, year=None)])) == f"{artist} - Album 1 (?)"
|
||||
|
||||
|
||||
def test_a_collection_of_one_release_shows_its_own_facts_before_those_of_a_song() -> None:
|
||||
facts = {**OWN_FACTS, "total_discs": 3, "total_duration": 4000}
|
||||
music = Album([song(n, "Album 1", "Album Artist", explicit=True) for n in (1, 2)], **facts)
|
||||
vars(music).update(released="1990-02-03", quality="MP3")
|
||||
assert dict(header(music)) == {
|
||||
"Title": "Own Title",
|
||||
"Artist": "Own Artist",
|
||||
"Type": "Playlist Explicit",
|
||||
"Released": "February 3, 1990",
|
||||
"Year": "1990",
|
||||
"Tracks": "9",
|
||||
"Discs": "3",
|
||||
"Length": "1h 06m 40s",
|
||||
"Quality": "MP3",
|
||||
"Genre": "Genre 1",
|
||||
"Label": "Label 1",
|
||||
}
|
||||
assert str(music) == "Own Artist - Own Title (1990)"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("nested", [False, True])
|
||||
def test_the_first_song_of_one_release_gives_the_quality_flags(nested: bool) -> None:
|
||||
data = {"lossless": True, "hires": True, "release_date": "2001-10-14"}
|
||||
music = Album([song(1, "Album 1", None, data={"metadata": data} if nested else data)])
|
||||
assert (dict(header(music))["Quality"], dict(header(music))["Released"]) == ("Hi-Res Lossless", "October 14, 2001")
|
||||
|
||||
|
||||
def test_a_blank_album_of_one_release_keeps_its_row() -> None:
|
||||
music = Album([song(1, " ", "Album Artist")])
|
||||
assert str(music) == "Album Artist - (2001)"
|
||||
assert header(music)[0] == ("Title", "")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("duration", [10**400, float("inf"), "Infinity"], ids=["huge", "infinite", "text"])
|
||||
def test_a_song_duration_too_large_to_convert_does_not_count(duration: Any) -> None:
|
||||
music = Album([song(1, "Album 1", None), song(2, "Album 1", None, data={"duration": duration})])
|
||||
assert dict(header(music))["Length"] == "1m 00s"
|
||||
with console.capture() as out:
|
||||
console.print(music.tree())
|
||||
assert "Name 2" in out.get()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["title", "artist", "kind"])
|
||||
def test_a_fact_is_text_and_not_markup(field: str) -> None:
|
||||
with console.capture() as out:
|
||||
console.print(MusicRenderer().render_header(mixed(**{field: "[red]x[/y] :cd:"})))
|
||||
assert "[red]x[/y] :cd:" in out.get().lower()
|
||||
|
||||
|
||||
def test_a_collection_from_the_title_cache_shows_only_its_own_facts() -> None:
|
||||
restored = jsonpickle.loads(jsonpickle.dumps(mixed(**OWN_FACTS)))
|
||||
assert header(restored) == OWN_ROWS
|
||||
assert str(restored) == "Own Artist - Own Title (1990)"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["year", "total_tracks", "total_discs", "total_duration"])
|
||||
def test_a_collection_number_is_never_a_bool(field: str) -> None:
|
||||
with pytest.raises(TypeError, match=f"Expected {field} to be an int, not True"):
|
||||
Album([], **{field: True})
|
||||
|
||||
|
||||
def test_a_total_duration_too_large_to_convert_is_shown_as_given() -> None:
|
||||
assert MusicRenderer.format_total_duration(10**400) == str(10**400)
|
||||
|
||||
|
||||
NOT_MARKUP = pytest.mark.parametrize("name", ["Live [red]set[/red]", "Live [/x]", "Live :cd:", "Live \\"])
|
||||
|
||||
|
||||
@NOT_MARKUP
|
||||
def test_the_title_line_shows_the_collection_as_given(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, name: str
|
||||
) -> None:
|
||||
service = FakeService({})
|
||||
service.get_titles = lambda: mixed(artist="Own Artist", title=name) # type: ignore[assignment]
|
||||
|
||||
with console.capture() as out:
|
||||
run(monkeypatch, caplog, {}, service=service, list_titles=True)
|
||||
|
||||
assert f" Album: Own Artist - {name} " in out.get()
|
||||
|
||||
|
||||
@NOT_MARKUP
|
||||
def test_the_track_line_shows_the_song_as_given(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, name: str
|
||||
) -> None:
|
||||
music = mixed()
|
||||
music[0].name = name
|
||||
service = FakeService({1: {}})
|
||||
tracks = service.get_tracks(service.get_titles()[0])
|
||||
service.get_titles = lambda: music # type: ignore[assignment]
|
||||
service.get_tracks = lambda title: tracks # type: ignore[method-assign]
|
||||
|
||||
with console.capture() as out:
|
||||
run(monkeypatch, caplog, {}, service=service)
|
||||
|
||||
assert f" Track 01: {name} " in out.get()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
"""The facts of a music collection reach a --remote client through the titles route, with its songs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import responses
|
||||
|
||||
from tests.core.test_music_renderer import OWN_FACTS, OWN_ROWS, header, mixed
|
||||
from tests.remote.sessions import session_entry
|
||||
from tests.remote.unit.test_session_reopen import SERVER, make_service
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.remote_service import RemoteError, RemoteService
|
||||
from unshackle.core.titles import Movie, Movies
|
||||
from unshackle.core.titles.music import MUSIC_FIELDS, Album, Music, Song
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
FACTS: dict[str, Any] = {
|
||||
**OWN_FACTS,
|
||||
"total_discs": 7,
|
||||
"artwork_url": "https://img.example/own.jpg",
|
||||
"total_duration": 120,
|
||||
"owner": "Own Owner",
|
||||
"description": "Own Description",
|
||||
}
|
||||
|
||||
|
||||
def facts_of(music: Any) -> dict[str, Any]:
|
||||
return {field: getattr(music, field) for field in FACTS}
|
||||
|
||||
|
||||
def titles_reply(monkeypatch: pytest.MonkeyPatch, service: Any) -> dict[str, Any]:
|
||||
"""The answer of the titles route of a server whose remote session runs ``service``."""
|
||||
session = session_entry(service_instance=service)
|
||||
|
||||
async def validated(*_: Any) -> Any:
|
||||
return session
|
||||
|
||||
monkeypatch.setattr(handlers, "get_validated_session", validated)
|
||||
response = asyncio.run(handlers.session_titles_handler("sid"))
|
||||
assert response.status == 200
|
||||
return json.loads(response.body)
|
||||
|
||||
|
||||
def client_of(answer: dict[str, Any]) -> RemoteService:
|
||||
"""A client that gets ``answer`` from the titles route."""
|
||||
service = make_service()
|
||||
service.session_call = lambda call: answer # type: ignore[method-assign]
|
||||
service.drain_server_logs = lambda: None # type: ignore[method-assign]
|
||||
return service
|
||||
|
||||
|
||||
def served(titles: Any) -> Any:
|
||||
return SimpleNamespace(get_titles=lambda: titles)
|
||||
|
||||
|
||||
def over_remote(monkeypatch: pytest.MonkeyPatch, titles: Any) -> Any:
|
||||
return client_of(titles_reply(monkeypatch, served(titles))).get_titles()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("collection", [Album, Music])
|
||||
def test_a_client_gets_the_facts_of_the_collection(monkeypatch: pytest.MonkeyPatch, collection: type[Music]) -> None:
|
||||
titles = over_remote(monkeypatch, collection(mixed(), **FACTS))
|
||||
|
||||
assert type(titles) is Album
|
||||
assert facts_of(titles) == FACTS
|
||||
assert [song.name for song in titles] == ["Name 1", "Name 2"]
|
||||
|
||||
|
||||
def test_the_remote_listing_is_the_local_one(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
local = mixed(**{**FACTS, "total_discs": None})
|
||||
titles = over_remote(monkeypatch, local)
|
||||
|
||||
assert header(titles) == header(local) == OWN_ROWS
|
||||
assert str(titles) == str(local) == "Own Artist - Own Title (1990)"
|
||||
|
||||
|
||||
def test_each_fact_the_constructor_takes_crosses_the_wire() -> None:
|
||||
assert set(MUSIC_FIELDS) == set(FACTS) == set(vars(Album([]))) & set(Music.__init__.__annotations__)
|
||||
|
||||
|
||||
def test_the_reply_names_only_the_facts_the_collection_has(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
reply = titles_reply(monkeypatch, served(mixed(kind="artist", title="Own Title")))
|
||||
assert reply["collection"] == {"kind": "artist", "title": "Own Title"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value", ["1990", 0, True, 12.5, float("nan"), b"1990", date(1990, 1, 2), " ", {1}, ""], ids=repr
|
||||
)
|
||||
@pytest.mark.parametrize("field", ["year", "total_tracks", "total_discs", "kind", "artwork_url"])
|
||||
def test_a_fact_the_client_would_refuse_never_stops_the_listing(
|
||||
monkeypatch: pytest.MonkeyPatch, field: str, value: Any
|
||||
) -> None:
|
||||
music = mixed(**FACTS)
|
||||
setattr(music, field, value)
|
||||
|
||||
titles = over_remote(monkeypatch, music)
|
||||
|
||||
assert len(titles) == 2
|
||||
assert {**facts_of(titles), field: None} == {**FACTS, field: None}
|
||||
|
||||
|
||||
def test_a_listing_that_is_not_a_collection_sends_no_facts(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
movies = Movies([Movie("movie-1", Song, "Name", 2024)])
|
||||
for titles in (movies, list(mixed(**FACTS))):
|
||||
assert list(titles_reply(monkeypatch, served(titles))) == ["session_id", "titles"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kept", [{}, {"collection": None}], ids=["missing", "null"])
|
||||
def test_a_reply_with_no_facts_gives_a_plain_album(monkeypatch: pytest.MonkeyPatch, kept: dict[str, Any]) -> None:
|
||||
reply = titles_reply(monkeypatch, served(mixed(**FACTS)))
|
||||
del reply["collection"]
|
||||
|
||||
titles = client_of({**reply, **kept}).get_titles()
|
||||
|
||||
assert type(titles) is Album
|
||||
assert facts_of(titles) == facts_of(Album([]))
|
||||
assert len(titles) == 2
|
||||
|
||||
|
||||
def test_a_relaying_server_forwards_the_facts(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
upstream = titles_reply(monkeypatch, served(mixed(**FACTS)))
|
||||
relayed = titles_reply(monkeypatch, client_of(upstream))
|
||||
assert facts_of(client_of(relayed).get_titles()) == FACTS
|
||||
|
||||
|
||||
def test_the_title_map_keeps_the_facts(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
client = client_of(titles_reply(monkeypatch, served(mixed(**FACTS))))
|
||||
monkeypatch.setattr("unshackle.core.remote_service.config.services", {"TEST": {"title_map": {"Name 1": "New"}}})
|
||||
|
||||
titles = client.get_titles_cached()
|
||||
|
||||
assert facts_of(titles) == FACTS
|
||||
assert [song.name for song in titles] == ["New", "Name 2"]
|
||||
|
||||
|
||||
@responses.activate
|
||||
def test_a_reopened_session_keeps_the_facts(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
client = client_of(titles_reply(monkeypatch, served(mixed(**FACTS))))
|
||||
client.get_titles()
|
||||
monkeypatch.setattr(client, "authenticate", lambda credential=None: setattr(client, "_session_id", "s2"))
|
||||
responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok", "draining": False})
|
||||
responses.add(
|
||||
responses.GET,
|
||||
f"{SERVER}/api/session/s2/titles",
|
||||
json=titles_reply(monkeypatch, served(mixed(title="Replaced"))),
|
||||
)
|
||||
|
||||
assert client.reopen()
|
||||
assert facts_of(client.get_titles()) == FACTS
|
||||
|
||||
|
||||
def test_an_unknown_key_of_the_facts_is_dropped(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
reply = titles_reply(monkeypatch, served(mixed(**FACTS)))
|
||||
reply["collection"] |= {"iterable": [], "quality": "MP3", "x": [1]}
|
||||
|
||||
titles = client_of(reply).get_titles()
|
||||
|
||||
assert facts_of(titles) == FACTS
|
||||
assert len(titles) == 2
|
||||
assert not {"iterable", "quality", "x"} & set(vars(titles))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"collection",
|
||||
[
|
||||
pytest.param([], id="list"),
|
||||
pytest.param("kind", id="text"),
|
||||
pytest.param(5, id="number"),
|
||||
pytest.param(False, id="bool"),
|
||||
pytest.param({"kind": None}, id="no-kind"),
|
||||
pytest.param({"kind": " "}, id="blank-kind"),
|
||||
pytest.param({"title": ["x"]}, id="title-list"),
|
||||
pytest.param({"artist": 5}, id="artist-number"),
|
||||
pytest.param({"year": "1990"}, id="year-text"),
|
||||
pytest.param({"year": True}, id="year-bool"),
|
||||
pytest.param({"year": 0}, id="year-zero"),
|
||||
pytest.param({"total_tracks": -1}, id="negative-tracks"),
|
||||
pytest.param({"total_discs": True}, id="discs-bool"),
|
||||
pytest.param({"total_duration": 1.5}, id="duration-float"),
|
||||
pytest.param({"artwork_url": {}}, id="artwork-object"),
|
||||
pytest.param({"description": 1}, id="description-number"),
|
||||
],
|
||||
)
|
||||
def test_malformed_facts_are_one_remote_error(monkeypatch: pytest.MonkeyPatch, collection: Any) -> None:
|
||||
reply = titles_reply(monkeypatch, served(mixed()))
|
||||
with pytest.raises(RemoteError, match="^The remote server sent malformed titles: [^\n]+$"):
|
||||
client_of({**reply, "collection": collection}).get_titles()
|
||||
Reference in New Issue
Block a user