mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-02 22:15:12 +00:00
195 lines
7.4 KiB
Python
195 lines
7.4 KiB
Python
"""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 hold_session, 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: hold_session(client, "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()
|