forked from kenzuya/unshackle
feat(music): list and select playlist songs by their position
This commit is contained in:
@@ -125,3 +125,14 @@ def test_songs_separator_survives_a_config_without_a_songs_template(reset_folder
|
||||
"""A user config with output_template but no `songs` key used to raise a KeyError."""
|
||||
reset_folder_config.output_template = {"movies": "{title}.{year}"}
|
||||
assert reset_folder_config.get_template_separator("songs") == "."
|
||||
|
||||
|
||||
def test_a_playlist_position_changes_no_output_name(reset_folder_config):
|
||||
"""The file name, the folder and the text form of a song come from its own album."""
|
||||
reset_folder_config.output_template = {"songs": "{disc?}-{track_number}. {title}"}
|
||||
reset_folder_config.folder_templates = {"albums": "{album} {disc?} {track_number}"}
|
||||
song = make_song(track=6, disc=2, position=9)
|
||||
|
||||
assert song.get_filename(StubMediaInfo()) == "02-06.Example.Track"
|
||||
assert song.get_filename(StubMediaInfo(), folder=True) == "Example Album 02 06"
|
||||
assert str(song) == "Example Artist - Example Album (2025) / 06. Example Track"
|
||||
|
||||
@@ -7,12 +7,19 @@ click type makes of them, and the titles the download loop keeps.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import click
|
||||
import jsonpickle
|
||||
import pytest
|
||||
|
||||
from tests.lang_selection.test_kind_only_selection import FakeService, run
|
||||
from unshackle.commands.dl import title_wanted
|
||||
from unshackle.core.console import console
|
||||
from unshackle.core.music.renderer import MusicRenderer
|
||||
from unshackle.core.music.tagger import build_tag_values
|
||||
from unshackle.core.titles.movie import Movie
|
||||
from unshackle.core.titles.music import Song
|
||||
from unshackle.core.titles.music import Album, Song
|
||||
from unshackle.core.utils.click_types import SeasonRange
|
||||
|
||||
|
||||
@@ -20,15 +27,16 @@ class DummyService:
|
||||
pass
|
||||
|
||||
|
||||
def make_song(track: int = 1, disc: int = 1) -> Song:
|
||||
def make_song(track: int = 1, disc: int = 1, position: int | None = None, album: str = "Example Album") -> Song:
|
||||
return Song(
|
||||
id_=f"track-{disc:02}{track:04}",
|
||||
service=DummyService,
|
||||
name=f"Example Track {track}",
|
||||
artist="Example Artist",
|
||||
album="Example Album",
|
||||
album=album,
|
||||
track=track,
|
||||
disc=disc,
|
||||
position=position,
|
||||
year=2025,
|
||||
album_artist="Example Artist",
|
||||
)
|
||||
@@ -124,3 +132,55 @@ def test_song_matches_only_its_own_key():
|
||||
song = make_song(track=3, disc=2)
|
||||
assert song.matches_wanted(["2x3"]) is True
|
||||
assert song.matches_wanted(["1x3", "2x4"]) is False
|
||||
|
||||
|
||||
def test_a_playlist_lists_and_selects_by_position_but_tags_by_album_track():
|
||||
songs = [make_song(1, position=1, album="Z"), make_song(6, 2, 2, "B"), make_song(1, position=3, album="A")]
|
||||
playlist = Album(reversed(songs), kind="playlist")
|
||||
|
||||
assert list(playlist) == songs
|
||||
assert select("2", playlist) == [6]
|
||||
assert not songs[1].matches_wanted(["2x6"])
|
||||
assert [MusicRenderer().song_line(s, playlist).plain[:2] for s in playlist] == ["01", "02", "03"]
|
||||
tags = build_tag_values(songs[1])
|
||||
assert (tags["TRACKNUMBER"], tags["DISCNUMBER"]) == ("6", "2")
|
||||
|
||||
|
||||
def test_a_playlist_shows_no_disc_count():
|
||||
playlist = Album([make_song(6, 2, position=1), make_song(1, 3, position=2)], kind="playlist")
|
||||
assert "Discs" not in list(MusicRenderer().render_header(playlist).columns[0].cells)
|
||||
assert "Discs" in list(MusicRenderer().render_header(Album([make_song(6, 2)])).columns[0].cells)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("position", "key", "rule"), [(9, "1x9", "Track 09"), (None, "2x6", "Track 06")])
|
||||
def test_the_download_loop_names_the_number_that_selected_the_song(monkeypatch, caplog, position, key, rule):
|
||||
service = FakeService({1: {}})
|
||||
tracks = service.get_tracks(service.get_titles()[0])
|
||||
service.get_titles = lambda: Album([make_song(6, 2, position, "B"), make_song(1)])
|
||||
service.get_tracks = lambda title: tracks
|
||||
|
||||
with console.capture() as out:
|
||||
run(monkeypatch, caplog, {}, service=service, wanted=[key])
|
||||
|
||||
assert re.findall(r"Track \d+: Example Track \d+", out.get()) == [f"{rule}: Example Track 6"]
|
||||
|
||||
|
||||
def test_a_release_without_positions_keeps_its_order_and_numbers():
|
||||
songs = [make_song(1, album="A"), make_song(6, 2, album="B"), make_song(1, album="Z")]
|
||||
release = Album(reversed(songs))
|
||||
|
||||
assert list(release) == songs
|
||||
assert [MusicRenderer().song_line(s, release).plain[:4].strip() for s in release] == ["01", "2.06", "01"]
|
||||
|
||||
|
||||
def test_a_release_from_an_older_title_cache_reads_as_having_no_positions():
|
||||
"""jsonpickle restores a Song without its __init__, so an older entry has no 'position' key."""
|
||||
songs = [make_song(6, 2, album="B"), make_song(1, album="Z")]
|
||||
for song in songs:
|
||||
del song.__dict__["position"]
|
||||
|
||||
restored = jsonpickle.loads(jsonpickle.dumps(songs))
|
||||
|
||||
assert ["position" in vars(song) for song in restored] == [False, False]
|
||||
assert [song.listing_number for song in restored] == [(2, 6), (1, 1)]
|
||||
assert [song.album for song in Album(reversed(restored))] == ["B", "Z"]
|
||||
|
||||
@@ -146,6 +146,7 @@ def song() -> Song:
|
||||
artwork_url="https://img.example/song.jpg",
|
||||
synced_lyrics="[00:01.00]la",
|
||||
lyrics_suffix=".lrc",
|
||||
position=7,
|
||||
)
|
||||
|
||||
|
||||
@@ -398,6 +399,7 @@ REST_SONG = {
|
||||
"synced_lyrics": "[00:01.00]la",
|
||||
"lyrics_suffix": ".lrc",
|
||||
"artwork_url": "https://img.example/song.jpg",
|
||||
"position": 7,
|
||||
"music_data": {"release_date": "2022-01-02", "composer": "Example Composer", "comment": "nested"},
|
||||
}
|
||||
|
||||
@@ -783,6 +785,23 @@ def test_build_title_from_rest_song() -> None:
|
||||
}
|
||||
|
||||
|
||||
def test_a_song_of_an_older_server_has_no_position() -> None:
|
||||
rebuilt = build_title({k: v for k, v in REST_SONG.items() if k != "position"}, "EXAMPLE", "fallback-id")
|
||||
assert (rebuilt.position, rebuilt.listing_number) == (None, (1, 3))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("position", [0, -1, "7", 7.5, True, [7]])
|
||||
def test_build_title_refuses_a_bad_song_position(position: Any) -> None:
|
||||
with pytest.raises((TypeError, ValueError), match="position"):
|
||||
build_title({**REST_SONG, "position": position}, "EXAMPLE", "fallback-id")
|
||||
|
||||
|
||||
def test_apply_title_fields_keeps_the_song_position() -> None:
|
||||
title = song()
|
||||
apply_title_fields(title, {"position": 9, "genre": "Jazz"})
|
||||
assert (title.position, title.genre) == (7, "Jazz")
|
||||
|
||||
|
||||
def test_build_title_from_export_meta() -> None:
|
||||
title = build_title(json_copy(META_EPISODE), "EXAMPLE", "fallback-id")
|
||||
assert title_fields(title) == {**EPISODE_FIELDS, "data": None, "description": None}
|
||||
|
||||
@@ -177,6 +177,20 @@ def test_list_tracks_stamps_the_service_flags(monkeypatch: pytest.MonkeyPatch, w
|
||||
assert all((t["anime"], t["daily"]) == (True, True) for t in titles)
|
||||
|
||||
|
||||
def test_list_tracks_selects_a_playlist_song_by_position(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
songs = [
|
||||
Song(f"song-{album}", _FakeSvc, "Track", "Artist", album, track, disc, position=position)
|
||||
for album, track, disc, position in (("Z", 1, 1, 1), ("B", 6, 2, 2), ("A", 2, 1, 3))
|
||||
]
|
||||
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "FAKE")
|
||||
monkeypatch.setattr(handlers, "launch_served", lambda *a, **kw: handlers.Launched(_FakeService(songs), None, None))
|
||||
|
||||
response = asyncio.run(handlers.list_tracks_handler({"service": "FAKE", "title_id": "t1", "wanted": "2"}))
|
||||
|
||||
title = json.loads(response.body)["title"]
|
||||
assert (title["id"], title["position"], title["track"]) == ("song-B", 2, 6)
|
||||
|
||||
|
||||
def test_list_titles_stamps_the_service_flags(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "FAKE")
|
||||
monkeypatch.setattr(handlers, "launch_served", lambda *a, **kw: handlers.Launched(_FakeService([ep()]), None, None))
|
||||
|
||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
import json
|
||||
import logging
|
||||
from threading import Lock
|
||||
from typing import Any
|
||||
|
||||
import click
|
||||
import pytest
|
||||
@@ -87,6 +88,63 @@ def test_a_lost_session_reopens_and_replays_the_call_under_the_new_ids(monkeypat
|
||||
assert service._title_alias == {"ep3-aaaa": "ep3-bbbb"}
|
||||
|
||||
|
||||
def rest_song(id_: str, album: str, position: Any = None, track: int = 1) -> dict:
|
||||
return {"type": "song", "id": id_, "name": "N", "artist": "A", "album": album, "track": track, "position": position}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("before", "after", "alias"),
|
||||
[
|
||||
pytest.param(
|
||||
[rest_song("song-z", "Z", 1), rest_song("song-b", "B", 2)],
|
||||
[rest_song("song-b", "B", 1), rest_song("song-z", "Z", 2)],
|
||||
{},
|
||||
id="reordered-playlist",
|
||||
),
|
||||
pytest.param(
|
||||
[rest_song("song-clean", "Z", 1), rest_song("song-explicit", "Z", 2)],
|
||||
[rest_song("song-explicit", "Z", 1)],
|
||||
{},
|
||||
id="two-versions-of-one-single",
|
||||
),
|
||||
pytest.param(
|
||||
[rest_song("song-z", "Z"), rest_song("song-b", "B")],
|
||||
[rest_song("song-z", "Z", 1), rest_song("song-b", "B", 2)],
|
||||
{},
|
||||
id="server-updated",
|
||||
),
|
||||
pytest.param(
|
||||
[rest_song("song-x-old", "X"), rest_song("song-y-old", "X", track=2)],
|
||||
[rest_song("song-x-new", "X"), rest_song("song-y-new", "X", track=2)],
|
||||
{"song-x-old": "song-x-new", "song-y-old": "song-y-new"},
|
||||
id="album-without-positions",
|
||||
),
|
||||
],
|
||||
)
|
||||
@responses.activate
|
||||
def test_a_reopened_session_never_takes_another_song_for_a_playlist_song(monkeypatch, before, after, alias):
|
||||
service = make_service()
|
||||
service._titles = [build_title(info, "TEST", "x") for info in before]
|
||||
monkeypatch.setattr(service, "authenticate", lambda credential=None: setattr(service, "_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": after})
|
||||
|
||||
assert service.reopen()
|
||||
assert service._title_alias == alias
|
||||
|
||||
|
||||
@responses.activate
|
||||
def test_a_malformed_song_position_on_reopen_is_one_error_line(monkeypatch):
|
||||
service = make_service()
|
||||
monkeypatch.setattr(service, "authenticate", lambda credential=None: setattr(service, "_session_id", "s2"))
|
||||
responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok", "draining": False})
|
||||
listing = {"titles": [rest_song("song-z", "Z", "x")]}
|
||||
responses.add(responses.GET, f"{SERVER}/api/session/s2/titles", json=listing)
|
||||
|
||||
with pytest.raises(RemoteError, match="The remote server sent malformed titles: Expected position"):
|
||||
service.reopen()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"broken",
|
||||
[
|
||||
|
||||
Reference in New Issue
Block a user