refactor(core)!: drop leading underscores from internal definitions

Renames 314 defs and 41 module/class-level constants. Keeps 11 names underscored where the stripped form collides in scope, plus 5.5.0 shims for the three symbols external service repos call.
This commit is contained in:
imSp4rky
2026-08-15 22:07:41 -06:00
parent db4f0b39f9
commit 21d5f1c5e1
116 changed files with 1671 additions and 1492 deletions
+42 -42
View File
@@ -26,7 +26,7 @@ class _FakeSvc:
pass
def _ep(season: int = 1, number: int = 1, part: Optional[int] = None, **overrides: Any) -> Episode:
def ep(season: int = 1, number: int = 1, part: Optional[int] = None, **overrides: Any) -> Episode:
base: Dict[str, Any] = dict(
id_=f"ep-{season}-{number}-{part or 0}",
service=_FakeSvc,
@@ -58,7 +58,7 @@ class _FakeService:
return _FakeTracks()
def _run_list_tracks(monkeypatch: pytest.MonkeyPatch, titles: List[Episode], **data: Any) -> Dict[str, Any]:
def run_list_tracks(monkeypatch: pytest.MonkeyPatch, titles: List[Episode], **data: Any) -> Dict[str, Any]:
"""Drive list_tracks_handler end to end with the service layer stubbed out."""
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "FAKE")
monkeypatch.setattr(handlers, "setup_list_service", lambda *a, **kw: _FakeService(titles))
@@ -71,7 +71,7 @@ def _run_list_tracks(monkeypatch: pytest.MonkeyPatch, titles: List[Episode], **d
return json.loads(response.body)
def _selected(result: Dict[str, Any]) -> List[str]:
def selected(result: Dict[str, Any]) -> List[str]:
"""Selection-syntax keys of whatever the handler returned, single or multi."""
entries = result["episodes"] if "episodes" in result else [{"title": result["title"]}]
keys = []
@@ -86,7 +86,7 @@ def _selected(result: Dict[str, Any]) -> List[str]:
def test_partless_episode_json_has_no_part_key() -> None:
d = serialize_title(_ep(part=None))
d = serialize_title(ep(part=None))
assert "part" not in d
assert list(d.keys()) == [
"type",
@@ -105,26 +105,26 @@ def test_partless_episode_json_has_no_part_key() -> None:
def test_partful_episode_json_carries_part_last() -> None:
d = serialize_title(_ep(part=2))
d = serialize_title(ep(part=2))
assert d["part"] == 2
# additive: `part` is appended, every pre-existing key keeps its position
assert list(d.keys())[:11] == list(serialize_title(_ep(part=None)).keys())
assert list(d.keys())[:11] == list(serialize_title(ep(part=None)).keys())
assert list(d.keys())[11] == "part"
def test_part_stays_out_of_the_name_field() -> None:
"""`name` is a reconstruction input for _build_title, not a display string."""
assert serialize_title(_ep(part=2))["name"] == "Pilot"
assert serialize_title(_ep(part=3, name=None))["name"] == "Episode 01"
"""`name` is a reconstruction input for build_title, not a display string."""
assert serialize_title(ep(part=2))["name"] == "Pilot"
assert serialize_title(ep(part=3, name=None))["name"] == "Episode 01"
def test_remote_build_title_round_trip() -> None:
from unshackle.core.remote_service import _build_title
from unshackle.core.remote_service import build_title
rebuilt = _build_title(serialize_title(_ep(1, 4, 2)), "FAKE", "fallback-id")
rebuilt = build_title(serialize_title(ep(1, 4, 2)), "FAKE", "fallback-id")
assert (rebuilt.season, rebuilt.number, rebuilt.part, rebuilt.name) == (1, 4, 2, "Pilot")
partless = _build_title(serialize_title(_ep(1, 4, None)), "FAKE", "fallback-id")
partless = build_title(serialize_title(ep(1, 4, None)), "FAKE", "fallback-id")
assert partless.part is None
@@ -143,32 +143,32 @@ def test_movie_json_unaffected() -> None:
@pytest.fixture
def split_titles() -> List[Episode]:
"""E1 split into three parts, E2 unsplit."""
return [_ep(1, 1, 1), _ep(1, 1, 2), _ep(1, 1, 3), _ep(1, 2, None)]
return [ep(1, 1, 1), ep(1, 1, 2), ep(1, 1, 3), ep(1, 2, None)]
def test_rest_bare_episode_key_selects_every_part(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, wanted="S01E01")
assert _selected(result) == ["1x1.1", "1x1.2", "1x1.3"]
result = run_list_tracks(monkeypatch, split_titles, wanted="S01E01")
assert selected(result) == ["1x1.1", "1x1.2", "1x1.3"]
def test_rest_part_key_selects_exactly_one(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, wanted="S01E01.2")
assert _selected(result) == ["1x1.2"]
result = run_list_tracks(monkeypatch, split_titles, wanted="S01E01.2")
assert selected(result) == ["1x1.2"]
def test_rest_negative_part_key_excludes_only_that_part(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, wanted=["S01", "-S01E01.2"])
assert _selected(result) == ["1x1.1", "1x1.3", "1x2"]
result = run_list_tracks(monkeypatch, split_titles, wanted=["S01", "-S01E01.2"])
assert selected(result) == ["1x1.1", "1x1.3", "1x2"]
def test_rest_partless_episode_unchanged(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, wanted="S01E02")
assert _selected(result) == ["1x2"]
result = run_list_tracks(monkeypatch, split_titles, wanted="S01E02")
assert selected(result) == ["1x2"]
assert "part" not in result["title"]
def test_rest_part_of_unsplit_episode_selects_nothing(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, wanted="S01E02.1")
result = run_list_tracks(monkeypatch, split_titles, wanted="S01E02.1")
assert result["status"] == 404
@@ -176,28 +176,28 @@ def test_rest_part_of_unsplit_episode_selects_nothing(monkeypatch, split_titles)
def test_discrete_fields_without_part_select_every_part(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, season=1, episode=1)
assert _selected(result) == ["1x1.1", "1x1.2", "1x1.3"]
result = run_list_tracks(monkeypatch, split_titles, season=1, episode=1)
assert selected(result) == ["1x1.1", "1x1.2", "1x1.3"]
def test_discrete_fields_with_part_select_one(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, season=1, episode=1, part=3)
assert _selected(result) == ["1x1.3"]
result = run_list_tracks(monkeypatch, split_titles, season=1, episode=1, part=3)
assert selected(result) == ["1x1.3"]
def test_discrete_part_accepts_string(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, season=1, episode=1, part="3")
assert _selected(result) == ["1x1.3"]
result = run_list_tracks(monkeypatch, split_titles, season=1, episode=1, part="3")
assert selected(result) == ["1x1.3"]
def test_discrete_no_match_error_reports_the_part_qualified_key(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, season=1, episode=1, part=9)
result = run_list_tracks(monkeypatch, split_titles, season=1, episode=1, part=9)
assert result["status"] == 404
assert result["details"]["wanted"] == "1x1.9"
def test_discrete_partless_error_key_unchanged(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, season=9, episode=9)
result = run_list_tracks(monkeypatch, split_titles, season=9, episode=9)
assert result["details"]["wanted"] == "9x9"
@@ -211,15 +211,15 @@ def test_part_is_a_transport_key_not_a_service_option() -> None:
def test_rest_multi_episode_order_is_stable_across_parts(monkeypatch) -> None:
titles = [_ep(1, 2, None), _ep(1, 1, 3), _ep(1, 1, 1), _ep(1, 1, 2)]
result = _run_list_tracks(monkeypatch, titles, wanted="S01")
assert _selected(result) == ["1x1.1", "1x1.2", "1x1.3", "1x2"]
titles = [ep(1, 2, None), ep(1, 1, 3), ep(1, 1, 1), ep(1, 1, 2)]
result = run_list_tracks(monkeypatch, titles, wanted="S01")
assert selected(result) == ["1x1.1", "1x1.2", "1x1.3", "1x2"]
# ---------- download_manager: already-internal wanted sniff ----------
_SNIFF = r"^!?\d+x\d+(\.\d+)?$"
SNIFF = r"^!?\d+x\d+(\.\d+)?$"
@pytest.mark.parametrize(
@@ -237,7 +237,7 @@ _SNIFF = r"^!?\d+x\d+(\.\d+)?$"
],
)
def test_download_manager_sniff_regex(wanted: List[str], internal: bool) -> None:
needs_conversion = any(not re.match(_SNIFF, w) for w in wanted)
needs_conversion = any(not re.match(SNIFF, w) for w in wanted)
assert needs_conversion is (not internal)
@@ -248,12 +248,12 @@ def test_sniff_regex_matches_the_one_in_download_manager() -> None:
import unshackle.core.api.download_manager as dm
source = Path(dm.__file__).read_text(encoding="utf8")
assert f'needs_conversion = any(not re.match(r"{_SNIFF}", w) for w in wanted_raw)' in source
assert f'needs_conversion = any(not re.match(r"{SNIFF}", w) for w in wanted_raw)' in source
def test_perform_download_skips_reconversion_for_preparsed_part_keys(monkeypatch) -> None:
"""A pre-parsed list with part and negative keys must not reach parse_tokens."""
from unshackle.core.api.download_manager import _perform_download
from unshackle.core.api.download_manager import perform_download
from unshackle.core.utils.click_types import SeasonRange
calls = []
@@ -262,14 +262,14 @@ def test_perform_download_skips_reconversion_for_preparsed_part_keys(monkeypatch
params: Dict[str, Any] = {"wanted": ["1x1", "1x1.2", "!1x1.3"]}
with pytest.raises(BaseException):
# blows up later on the unknown service; the wanted block runs first
_perform_download("job-1", "NoSuchServiceXYZ", "t1", params)
perform_download("job-1", "NoSuchServiceXYZ", "t1", params)
assert calls == []
assert params["wanted"] == ["1x1", "1x1.2", "!1x1.3"]
def test_perform_download_still_converts_cli_style_tokens(monkeypatch) -> None:
from unshackle.core.api.download_manager import _perform_download
from unshackle.core.api.download_manager import perform_download
from unshackle.core.utils.click_types import SeasonRange
calls = []
@@ -277,7 +277,7 @@ def test_perform_download_still_converts_cli_style_tokens(monkeypatch) -> None:
params: Dict[str, Any] = {"wanted": "S01E01"}
with pytest.raises(BaseException):
_perform_download("job-2", "NoSuchServiceXYZ", "t1", params)
perform_download("job-2", "NoSuchServiceXYZ", "t1", params)
assert calls == [("S01E01",)]
assert params["wanted"] == ["1x1"]
@@ -325,7 +325,7 @@ def test_rest_filter_agrees_with_cli_filter(monkeypatch, split_titles, wanted_to
if t.matches_wanted(wanted)
]
result = _run_list_tracks(monkeypatch, split_titles, wanted=list(wanted_tokens))
rest_selected = [] if result.get("status") == 404 else _selected(result)
result = run_list_tracks(monkeypatch, split_titles, wanted=list(wanted_tokens))
rest_selected = [] if result.get("status") == 404 else selected(result)
assert sorted(rest_selected) == sorted(cli_selected)
+31 -31
View File
@@ -1,7 +1,7 @@
"""The title fields that cross the remote wire: air_date, absolute, anime and daily.
Covers serialize_title's conditional keys, the service-class ANIME/DAILY stamp, and the
serialize_title / title_to_meta round trips through remote_service._build_title.
serialize_title / title_to_meta round trips through remote_service.build_title.
"""
from __future__ import annotations
@@ -16,8 +16,8 @@ from langcodes import Language
from unshackle.commands.dl import dl
from unshackle.core.api import handlers
from unshackle.core.api.handlers import _stamp_service_flags, serialize_title
from unshackle.core.remote_service import _build_title
from unshackle.core.api.handlers import serialize_title, stamp_service_flags
from unshackle.core.remote_service import build_title
from unshackle.core.titles.episode import Episode
from unshackle.core.titles.movie import Movie
@@ -28,7 +28,7 @@ class _FakeSvc:
pass
def _ep(**overrides: Any) -> Episode:
def ep(**overrides: Any) -> Episode:
base: Dict[str, Any] = dict(
id_="ep-0001",
service=_FakeSvc,
@@ -56,7 +56,7 @@ NEW_KEYS = ("air_date", "absolute", "daily", "anime")
def test_a_plain_episode_gains_no_new_keys() -> None:
d = serialize_title(_ep())
d = serialize_title(ep())
assert not [k for k in NEW_KEYS if k in d]
@@ -66,20 +66,20 @@ def test_a_plain_movie_gains_no_new_keys() -> None:
def test_air_date_is_serialized_as_an_iso_string() -> None:
assert serialize_title(_ep(air_date=date(2026, 8, 11)))["air_date"] == "2026-08-11"
assert serialize_title(ep(air_date=date(2026, 8, 11)))["air_date"] == "2026-08-11"
def test_an_unparseable_air_date_is_serialized_as_text() -> None:
assert serialize_title(_ep(air_date="soon"))["air_date"] == "soon"
assert serialize_title(ep(air_date="soon"))["air_date"] == "soon"
def test_absolute_is_serialized() -> None:
assert serialize_title(_ep(absolute=57))["absolute"] == 57
assert serialize_title(ep(absolute=57))["absolute"] == 57
@pytest.mark.parametrize("value", [True, False])
def test_per_title_daily_and_anime_are_serialized_both_ways(value: bool) -> None:
episode = _ep()
episode = ep()
episode.daily = value
episode.anime = value
d = serialize_title(episode)
@@ -107,25 +107,25 @@ class _PlainSvc:
def test_the_stamp_fills_both_flags_from_the_service_class() -> None:
d = _stamp_service_flags(serialize_title(_ep()), _AnimeDailySvc())
d = stamp_service_flags(serialize_title(ep()), _AnimeDailySvc())
assert (d["anime"], d["daily"]) == (True, True)
def test_the_stamp_never_overrides_a_per_title_false() -> None:
episode = _ep()
episode = ep()
episode.anime = False
episode.daily = False
d = _stamp_service_flags(serialize_title(episode), _AnimeDailySvc())
d = stamp_service_flags(serialize_title(episode), _AnimeDailySvc())
assert (d["anime"], d["daily"]) == (False, False)
def test_a_plain_service_stamps_nothing() -> None:
d = _stamp_service_flags(serialize_title(_ep()), _PlainSvc())
d = stamp_service_flags(serialize_title(ep()), _PlainSvc())
assert not [k for k in NEW_KEYS if k in d]
def test_a_movie_is_never_stamped_daily() -> None:
d = _stamp_service_flags(serialize_title(_movie()), _AnimeDailySvc())
d = stamp_service_flags(serialize_title(_movie()), _AnimeDailySvc())
assert d["anime"] is True
assert "daily" not in d
@@ -143,55 +143,55 @@ class _FakeService:
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, "setup_list_service", lambda *a, **kw: _FakeService([_ep()]))
monkeypatch.setattr(handlers, "setup_list_service", lambda *a, **kw: _FakeService([ep()]))
response = asyncio.run(handlers.list_titles_handler({"service": "FAKE", "title_id": "t1"}))
title = json.loads(response.body)["titles"][0]
assert (title["anime"], title["daily"]) == (True, True)
# ---------- round trips through _build_title ----------
# ---------- round trips through build_title ----------
def _round_trip(episode: Episode, stamp: Optional[Any] = None) -> Episode:
def round_trip(episode: Episode, stamp: Optional[Any] = None) -> Episode:
info = serialize_title(episode)
if stamp is not None:
info = _stamp_service_flags(info, stamp)
return _build_title(info, "FAKE", "fallback-id")
info = stamp_service_flags(info, stamp)
return build_title(info, "FAKE", "fallback-id")
def test_serialize_round_trip_keeps_the_new_fields() -> None:
episode = _ep(air_date=date(2026, 8, 11), absolute=57)
episode = ep(air_date=date(2026, 8, 11), absolute=57)
episode.daily = True
episode.anime = True
rebuilt = _round_trip(episode)
rebuilt = round_trip(episode)
assert rebuilt.air_date == date(2026, 8, 11)
assert rebuilt.absolute == 57
assert (rebuilt.daily, rebuilt.anime) == (True, True)
def test_serialize_round_trip_leaves_unset_flags_inheriting() -> None:
rebuilt = _round_trip(_ep())
rebuilt = round_trip(ep())
assert rebuilt.air_date is None
assert rebuilt.absolute is None
assert (rebuilt.daily, rebuilt.anime) == (None, None)
def test_the_stamped_service_flags_survive_the_round_trip() -> None:
rebuilt = _round_trip(_ep(), stamp=_AnimeDailySvc())
rebuilt = round_trip(ep(), stamp=_AnimeDailySvc())
assert (rebuilt.daily, rebuilt.anime) == (True, True)
def test_a_per_title_false_survives_the_round_trip() -> None:
episode = _ep()
episode = ep()
episode.daily = False
rebuilt = _round_trip(episode)
rebuilt = round_trip(episode)
assert rebuilt.daily is False
def test_a_movie_round_trip_keeps_the_anime_flag() -> None:
movie = _movie()
movie.anime = True
rebuilt = _build_title(serialize_title(movie), "FAKE", "fallback-id")
rebuilt = build_title(serialize_title(movie), "FAKE", "fallback-id")
assert isinstance(rebuilt, Movie)
assert rebuilt.anime is True
@@ -200,22 +200,22 @@ def test_a_movie_round_trip_keeps_the_anime_flag() -> None:
def test_title_to_meta_omits_the_new_keys_for_a_plain_episode() -> None:
meta = dl.title_to_meta(_ep())
meta = dl.title_to_meta(ep())
assert not [k for k in ("absolute", "daily", "anime") if k in meta]
def test_title_to_meta_round_trip_keeps_the_new_fields() -> None:
episode = _ep(air_date=date(2026, 8, 11), absolute=57)
episode = ep(air_date=date(2026, 8, 11), absolute=57)
episode.daily = True
episode.anime = True
rebuilt = _build_title(dl.title_to_meta(episode), "FAKE", "fallback-id")
rebuilt = build_title(dl.title_to_meta(episode), "FAKE", "fallback-id")
assert rebuilt.air_date == date(2026, 8, 11)
assert rebuilt.absolute == 57
assert (rebuilt.daily, rebuilt.anime) == (True, True)
def test_title_to_meta_round_trip_leaves_unset_flags_inheriting() -> None:
rebuilt = _build_title(dl.title_to_meta(_ep()), "FAKE", "fallback-id")
rebuilt = build_title(dl.title_to_meta(ep()), "FAKE", "fallback-id")
assert rebuilt.absolute is None
assert (rebuilt.daily, rebuilt.anime) == (None, None)
@@ -223,5 +223,5 @@ def test_title_to_meta_round_trip_leaves_unset_flags_inheriting() -> None:
def test_title_to_meta_round_trip_keeps_the_movie_anime_flag() -> None:
movie = _movie()
movie.anime = True
rebuilt = _build_title(dl.title_to_meta(movie), "FAKE", "fallback-id")
rebuilt = build_title(dl.title_to_meta(movie), "FAKE", "fallback-id")
assert rebuilt.anime is True
+5 -5
View File
@@ -19,7 +19,7 @@ class _FakeReq:
self.headers = {"Accept-Encoding": accept_encoding}
def _run(coro):
def run(coro):
return asyncio.run(coro)
@@ -30,7 +30,7 @@ def test_skips_when_client_does_not_accept_gzip() -> None:
return web.json_response({"data": "x" * 4096})
req = _FakeReq(accept_encoding="identity")
resp = _run(compression_middleware(req, handler))
resp = run(compression_middleware(req, handler))
assert resp.headers.get("Content-Encoding") != "gzip"
assert resp.body == body_json or len(resp.body) >= len(body_json) - 8
@@ -39,7 +39,7 @@ def test_skips_when_body_below_threshold() -> None:
async def handler(req): # noqa: ARG001
return web.json_response({"hi": "x"})
resp = _run(compression_middleware(_FakeReq(), handler))
resp = run(compression_middleware(_FakeReq(), handler))
assert resp.headers.get("Content-Encoding") != "gzip"
@@ -47,7 +47,7 @@ def test_skips_non_json_response() -> None:
async def handler(req): # noqa: ARG001
return web.Response(body=b"x" * 4096, content_type="text/plain")
resp = _run(compression_middleware(_FakeReq(), handler))
resp = run(compression_middleware(_FakeReq(), handler))
assert resp.headers.get("Content-Encoding") != "gzip"
@@ -57,7 +57,7 @@ def test_compresses_large_json_when_accepted() -> None:
async def handler(req): # noqa: ARG001
return web.json_response(big)
resp = _run(compression_middleware(_FakeReq(), handler))
resp = run(compression_middleware(_FakeReq(), handler))
assert resp.headers.get("Content-Encoding") == "gzip"
decompressed = gzip.decompress(resp.body)
assert json.loads(decompressed) == big
@@ -12,9 +12,9 @@ from unshackle.core.api import handlers
from unshackle.core.api.download_manager import (
DownloadJob,
JobStatus,
_redact_parameters,
_redact_text,
_secret_values,
redact_parameters,
secret_values,
)
from unshackle.core.api.errors import APIError, APIErrorCode
@@ -34,7 +34,7 @@ def test_redact_parameters_masks_secrets_and_proxy_userinfo():
"proxy": "http://bob:secret@proxy.example:8080",
"quality": "1080p",
}
red = _redact_parameters(params)
red = redact_parameters(params)
assert red["credential"] == "***"
assert red["password"] == "***"
assert red["token"] == "***"
@@ -45,11 +45,11 @@ def test_redact_parameters_masks_secrets_and_proxy_userinfo():
def test_redact_parameters_masks_credentials_dict():
assert _redact_parameters({"credentials": {"default": "u:p"}})["credentials"] == "***"
assert redact_parameters({"credentials": {"default": "u:p"}})["credentials"] == "***"
def test_secret_values_includes_password_half_and_dict_values():
secrets = _secret_values({"credential": "user:hunter2", "credentials": {"d": "alice:wonder"}})
secrets = secret_values({"credential": "user:hunter2", "credentials": {"d": "alice:wonder"}})
assert "user:hunter2" in secrets # full credential
assert "hunter2" in secrets # password half of user:pass
assert "alice:wonder" in secrets # value from the credentials map
@@ -98,10 +98,10 @@ def stub_handler(monkeypatch):
forbidden request raises APIError *before* the try block and an allowed one is caught inside it."""
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: tag)
def _boom(*_args, **_kwargs):
def boom(*_args, **_kwargs):
raise _PastGate()
monkeypatch.setattr(handlers.Services, "load", _boom)
monkeypatch.setattr(handlers.Services, "load", boom)
return monkeypatch
+26 -7
View File
@@ -5,8 +5,10 @@ from __future__ import annotations
import pytest
from langcodes import Language
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.api.handlers import (
sanitize_log,
search_handler,
serialize_audio_track,
serialize_drm,
serialize_subtitle_track,
@@ -27,7 +29,7 @@ class _FakeSvc:
pass
def _video(**overrides) -> Video:
def video(**overrides) -> Video:
base = dict(
url="https://example.com/v.mpd",
language=Language.get("en"),
@@ -44,7 +46,7 @@ def _video(**overrides) -> Video:
return Video(**base)
def _audio(**overrides) -> Audio:
def audio(**overrides) -> Audio:
base = dict(
url="https://example.com/a.mpd",
language=Language.get("en"),
@@ -60,7 +62,7 @@ def _audio(**overrides) -> Audio:
return Audio(**base)
def _subtitle(**overrides) -> Subtitle:
def subtitle(**overrides) -> Subtitle:
base = dict(
url="https://example.com/s.vtt",
language=Language.get("en"),
@@ -142,7 +144,7 @@ def test_serialize_title_episode_unnamed_falls_back_to_number() -> None:
def test_serialize_video_track_basic() -> None:
d = serialize_video_track(_video())
d = serialize_video_track(video())
assert d["id"] == "video-001"
assert d["codec"] == "AVC"
assert d["bitrate"] == 5000 # kbps
@@ -155,12 +157,12 @@ def test_serialize_video_track_basic() -> None:
def test_serialize_video_track_include_url() -> None:
d = serialize_video_track(_video(), include_url=True)
d = serialize_video_track(video(), include_url=True)
assert d["url"] == "https://example.com/v.mpd"
def test_serialize_audio_track_basic() -> None:
d = serialize_audio_track(_audio())
d = serialize_audio_track(audio())
assert d["id"] == "audio-001"
assert d["codec"] == "AAC"
assert d["bitrate"] == 128
@@ -169,7 +171,7 @@ def test_serialize_audio_track_basic() -> None:
def test_serialize_subtitle_track_basic() -> None:
d = serialize_subtitle_track(_subtitle(forced=True))
d = serialize_subtitle_track(subtitle(forced=True))
assert d["id"] == "sub-001"
assert d["codec"] == "WebVTT"
assert d["forced"] is True
@@ -287,3 +289,20 @@ def test_validate_download_params_accepts_valid_values() -> None:
)
is None
)
async def test_search_missing_service_raises_invalid_input() -> None:
# MISSING_SERVICE was never an APIErrorCode member, so this raised AttributeError
# and routes.py surfaced a 500 instead of the intended 400.
with pytest.raises(APIError) as exc:
await search_handler({"query": "dune"}, None)
assert exc.value.error_code == APIErrorCode.INVALID_INPUT
assert APIError.default_http_status(exc.value.error_code) == 400
async def test_search_unknown_service_raises_invalid_service() -> None:
# get_tag echoes unknown tags back, so the old `not normalized_service` guard
# never fired and Services.get_path leaked a KeyError as a 500.
with pytest.raises(APIError) as exc:
await search_handler({"service": "NOPE_THIS_IS_NOT_REAL_", "query": "x"}, None)
assert exc.value.error_code == APIErrorCode.INVALID_SERVICE
+6 -6
View File
@@ -45,7 +45,7 @@ class Subtitle:
self.bitrate = None
def _noop(**kwargs):
def noop(**kwargs):
pass
@@ -66,7 +66,7 @@ def test_weight_video_over_audio_over_subtitle():
def test_weighting_makes_video_dominate_progress():
updates: list[dict] = []
video, sub = Video(bitrate=4_000_000), Subtitle()
cbs = build_job_progress_callables([video, sub], [_noop, _noop], updates.append)
cbs = build_job_progress_callables([video, sub], [noop, noop], updates.append)
# subtitle fully done, video untouched -> progress is tiny (subtitle barely weighted)
cbs[1](downloaded="Downloaded")
@@ -80,7 +80,7 @@ def test_weighting_makes_video_dominate_progress():
def test_active_tracks_labels_reported_and_cleared_on_done():
updates: list[dict] = []
cbs = build_job_progress_callables([Video(2160, "DV"), Audio("en-US", "2.0")], [_noop, _noop], updates.append)
cbs = build_job_progress_callables([Video(2160, "DV"), Audio("en-US", "2.0")], [noop, noop], updates.append)
cbs[0](total=100, completed=10) # video downloading
assert updates[-1]["active_tracks"] == ["video 2160p DV"]
@@ -121,7 +121,7 @@ def test_aggregate_progress_is_monotonic_with_counts():
def test_all_tracks_done_reaches_download_ceiling():
# Downloads fill up to the ceiling; dl.result drives muxing the rest of the way to 100.
updates: list[dict] = []
cbs = build_job_progress_callables([Audio(bitrate=1000), Audio(bitrate=1000)], [_noop, _noop], updates.append)
cbs = build_job_progress_callables([Audio(bitrate=1000), Audio(bitrate=1000)], [noop, noop], updates.append)
cbs[0](total=10, completed=10, downloaded="Downloaded")
assert updates[-1]["progress"] < DOWNLOAD_PROGRESS_CEILING
@@ -136,7 +136,7 @@ def test_finished_track_does_not_dip_when_callable_reused_for_decrypt():
"""A track hits 100% (then decrypt reuses the callable with completed=0); the aggregate must
hold, never dip - even before the terminal 'Downloaded'/'Decrypted' string arrives."""
updates: list[dict] = []
cbs = build_job_progress_callables([Video(bitrate=1000), Video(bitrate=1000)], [_noop, _noop], updates.append)
cbs = build_job_progress_callables([Video(bitrate=1000), Video(bitrate=1000)], [noop, noop], updates.append)
cbs[0](total=100, completed=100) # download hits 100% BEFORE any terminal string -> 50%
cbs[0](total=200, completed=0) # decrypt phase resets counts, still no terminal string
@@ -151,7 +151,7 @@ def test_finished_track_does_not_dip_when_callable_reused_for_decrypt():
def test_skipped_subtitle_counts_as_done():
updates: list[dict] = []
cbs = build_job_progress_callables([Subtitle()], [_noop], updates.append)
cbs = build_job_progress_callables([Subtitle()], [noop], updates.append)
cbs[0](downloaded="[yellow]SKIPPED")
assert updates[-1]["completed_tracks"] == 1
assert updates[-1]["progress"] == pytest.approx(DOWNLOAD_PROGRESS_CEILING)
+6 -6
View File
@@ -1,11 +1,11 @@
"""Unit tests for resolve_server / _resolve_proxy in unshackle.core.remote_service."""
"""Unit tests for resolve_server / resolve_proxy_arg in unshackle.core.remote_service."""
from __future__ import annotations
import click
import pytest
from unshackle.core.remote_service import _resolve_proxy, resolve_server
from unshackle.core.remote_service import resolve_proxy_arg, resolve_server
pytestmark = pytest.mark.unit
@@ -126,8 +126,8 @@ def test_resolve_server_multi_with_name(multi_remote_services) -> None:
def test_resolve_proxy_none_returns_none() -> None:
assert _resolve_proxy(None) is None
assert _resolve_proxy("") is None
assert resolve_proxy_arg(None) is None
assert resolve_proxy_arg("") is None
def test_resolve_proxy_passes_through_value(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -136,7 +136,7 @@ def test_resolve_proxy_passes_through_value(monkeypatch: pytest.MonkeyPatch) ->
monkeypatch.setattr(resolve_mod, "initialize_proxy_providers", lambda: [])
monkeypatch.setattr(resolve_mod, "resolve_proxy", lambda arg, providers: f"http://proxy/{arg}")
assert _resolve_proxy("us") == "http://proxy/us"
assert resolve_proxy_arg("us") == "http://proxy/us"
def test_resolve_proxy_value_error_becomes_click(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -150,5 +150,5 @@ def test_resolve_proxy_value_error_becomes_click(monkeypatch: pytest.MonkeyPatch
monkeypatch.setattr(resolve_mod, "resolve_proxy", boom)
with pytest.raises(click.ClickException) as exc:
_resolve_proxy("xx")
resolve_proxy_arg("xx")
assert "no such country" in str(exc.value.message)
@@ -7,14 +7,14 @@ from enum import Enum
import pytest
from unshackle.core.remote_service import (
_build_title,
_build_tracks,
_deserialize_audio,
_deserialize_subtitle,
_deserialize_video,
_enum_get,
_match_track,
_reconstruct_drm,
build_title,
build_tracks,
deserialize_audio,
deserialize_subtitle,
deserialize_video,
enum_get,
match_track,
reconstruct_drm,
)
from unshackle.core.titles.episode import Episode
from unshackle.core.titles.movie import Movie
@@ -29,19 +29,19 @@ class _Color(Enum):
def test_enum_get_known() -> None:
assert _enum_get(_Color, "RED") is _Color.RED
assert enum_get(_Color, "RED") is _Color.RED
def test_enum_get_unknown_returns_default() -> None:
assert _enum_get(_Color, "PURPLE", default=_Color.BLUE) is _Color.BLUE
assert enum_get(_Color, "PURPLE", default=_Color.BLUE) is _Color.BLUE
def test_enum_get_none_returns_default() -> None:
assert _enum_get(_Color, None, default=_Color.RED) is _Color.RED
assert enum_get(_Color, None, default=_Color.RED) is _Color.RED
def test_deserialize_video_minimal() -> None:
v = _deserialize_video({"id": "video-1", "codec": "AVC", "width": 1920, "height": 1080, "bitrate": 5000})
v = deserialize_video({"id": "video-1", "codec": "AVC", "width": 1920, "height": 1080, "bitrate": 5000})
assert isinstance(v, Video)
assert v.id == "video-1"
assert v.codec is Video.Codec.AVC
@@ -52,12 +52,12 @@ def test_deserialize_video_minimal() -> None:
def test_deserialize_video_unknown_codec_falls_back_to_none() -> None:
v = _deserialize_video({"id": "v2", "codec": "MADE_UP", "width": 0, "height": 0})
v = deserialize_video({"id": "v2", "codec": "MADE_UP", "width": 0, "height": 0})
assert v.codec is None
def test_deserialize_audio_atmos_flag_sets_joc() -> None:
a = _deserialize_audio({"id": "a1", "codec": "AAC", "atmos": True, "channels": 6, "bitrate": 256})
a = deserialize_audio({"id": "a1", "codec": "AAC", "atmos": True, "channels": 6, "bitrate": 256})
assert isinstance(a, Audio)
assert a.joc == 1
assert a.channels == 6
@@ -65,34 +65,34 @@ def test_deserialize_audio_atmos_flag_sets_joc() -> None:
def test_deserialize_audio_no_atmos() -> None:
a = _deserialize_audio({"id": "a2", "codec": "AAC", "channels": 2})
a = deserialize_audio({"id": "a2", "codec": "AAC", "channels": 2})
assert a.joc == 0
def test_deserialize_subtitle_forced_flag() -> None:
s = _deserialize_subtitle({"id": "s1", "codec": "WebVTT", "language": "en", "forced": True})
s = deserialize_subtitle({"id": "s1", "codec": "WebVTT", "language": "en", "forced": True})
assert isinstance(s, Subtitle)
assert s.forced is True
assert s.sdh is False
def test_deserialize_subtitle_sdh_flag() -> None:
s = _deserialize_subtitle({"id": "s2", "codec": "WebVTT", "language": "en", "sdh": True})
s = deserialize_subtitle({"id": "s2", "codec": "WebVTT", "language": "en", "sdh": True})
assert s.sdh is True
assert s.forced is False
def test_reconstruct_drm_empty() -> None:
assert _reconstruct_drm(None) == []
assert _reconstruct_drm([]) == []
assert reconstruct_drm(None) == []
assert reconstruct_drm([]) == []
def test_reconstruct_drm_skips_entries_without_pssh() -> None:
assert _reconstruct_drm([{"type": "widevine"}]) == []
assert reconstruct_drm([{"type": "widevine"}]) == []
def test_reconstruct_drm_invalid_pssh_silently_dropped() -> None:
assert _reconstruct_drm([{"type": "widevine", "pssh": "not-real-pssh"}]) == []
assert reconstruct_drm([{"type": "widevine", "pssh": "not-real-pssh"}]) == []
def test_build_tracks_aggregates() -> None:
@@ -102,33 +102,33 @@ def test_build_tracks_aggregates() -> None:
"subtitles": [{"id": "s", "codec": "WebVTT", "language": "en"}],
"attachments": [],
}
t = _build_tracks(data)
t = build_tracks(data)
assert len(t.videos) == 1
assert len(t.audio) == 1
assert len(t.subtitles) == 1
def test_match_track_by_id() -> None:
a = _deserialize_video({"id": "v1", "codec": "AVC", "width": 1920, "height": 1080})
b = _deserialize_video({"id": "v2", "codec": "AVC", "width": 1280, "height": 720})
remote = _deserialize_video({"id": "v2", "codec": "AVC", "width": 1280, "height": 720})
assert _match_track(remote, [a, b]) is b
a = deserialize_video({"id": "v1", "codec": "AVC", "width": 1920, "height": 1080})
b = deserialize_video({"id": "v2", "codec": "AVC", "width": 1280, "height": 720})
remote = deserialize_video({"id": "v2", "codec": "AVC", "width": 1280, "height": 720})
assert match_track(remote, [a, b]) is b
def test_match_track_by_attributes_when_id_missing() -> None:
local = _deserialize_video({"id": "X", "codec": "AVC", "width": 1920, "height": 1080, "language": "en"})
remote = _deserialize_video({"id": "Y", "codec": "AVC", "width": 1920, "height": 1080, "language": "en"})
assert _match_track(remote, [local]) is local
local = deserialize_video({"id": "X", "codec": "AVC", "width": 1920, "height": 1080, "language": "en"})
remote = deserialize_video({"id": "Y", "codec": "AVC", "width": 1920, "height": 1080, "language": "en"})
assert match_track(remote, [local]) is local
def test_match_track_no_candidates_returns_none() -> None:
remote = _deserialize_video({"id": "X", "codec": "AVC", "width": 1, "height": 1})
assert _match_track(remote, []) is None
remote = deserialize_video({"id": "X", "codec": "AVC", "width": 1, "height": 1})
assert match_track(remote, []) is None
def test_build_title_movie() -> None:
info = {"type": "movie", "id": "movie-0001", "name": "Foo", "year": 2024, "language": "en"}
title = _build_title(info, "ATV", "fallback")
title = build_title(info, "ATV", "fallback")
assert isinstance(title, Movie)
assert title.id == "movie-0001"
assert title.name == "Foo"
@@ -145,7 +145,7 @@ def test_build_title_episode() -> None:
"year": 2024,
"language": "en",
}
title = _build_title(info, "ATV", "fallback")
title = build_title(info, "ATV", "fallback")
assert isinstance(title, Episode)
assert title.season == 1
assert title.number == 2
@@ -153,5 +153,5 @@ def test_build_title_episode() -> None:
def test_build_title_falls_back_to_id_when_missing() -> None:
title = _build_title({"type": "movie", "name": "x"}, "ATV", "fallback-id")
title = build_title({"type": "movie", "name": "x"}, "ATV", "fallback-id")
assert title.id == "fallback-id"
+12 -12
View File
@@ -21,20 +21,20 @@ pytestmark = pytest.mark.unit
def make_app():
"""Factory that builds an aiohttp app for tests."""
def _factory(remote_only: bool = False, with_auth_middleware: bool = False):
def factory(remote_only: bool = False, with_auth_middleware: bool = False):
middlewares = [cors_middleware, compression_middleware]
if with_auth_middleware:
middlewares.insert(1, _no_key_required_auth())
middlewares.insert(1, no_key_required_auth())
app = web.Application(middlewares=middlewares)
app["config"] = {"users": {}}
app["debug_api"] = False
setup_routes(app, remote_only=remote_only)
return app
return _factory
return factory
def _no_key_required_auth():
def no_key_required_auth():
"""Mirror serve.py's api_key_authentication middleware: required X-Secret-Key
on every endpoint except /api/health."""
@@ -52,13 +52,13 @@ def _no_key_required_auth():
return mw
def _collect_paths(app: web.Application) -> list[tuple[str, str]]:
def collect_paths(app: web.Application) -> list[tuple[str, str]]:
return sorted({(r.method, r.resource.canonical) for r in app.router.routes()})
def test_setup_routes_full_mode_wires_all_endpoints(make_app) -> None:
app = make_app(remote_only=False)
paths = _collect_paths(app)
paths = collect_paths(app)
expected = {
("GET", "/api/health"),
("GET", "/api/services"),
@@ -84,7 +84,7 @@ def test_setup_routes_full_mode_wires_all_endpoints(make_app) -> None:
def test_setup_routes_remote_only_excludes_list_and_download(make_app) -> None:
app = make_app(remote_only=True)
paths = set(_collect_paths(app))
paths = set(collect_paths(app))
assert ("POST", "/api/list-titles") not in paths
assert ("POST", "/api/list-tracks") not in paths
assert ("POST", "/api/download") not in paths
@@ -121,7 +121,7 @@ async def test_api_handler_maps_apierror(aiohttp_client) -> None:
client = await aiohttp_client(app)
resp = await client.get("/boom")
assert resp.status == 404 # NOT_FOUND -> 404 per errors.APIError._default_http_status
assert resp.status == 404 # NOT_FOUND -> 404 per errors.APIError.default_http_status
body = await resp.json()
assert body["status"] == "error"
assert body["error_code"] == "NOT_FOUND"
@@ -142,10 +142,10 @@ async def test_cors_preflight_returns_headers(make_app, aiohttp_client) -> None:
async def test_health_endpoint_responds_ok(make_app, aiohttp_client, monkeypatch: pytest.MonkeyPatch) -> None:
from unshackle.core.api import routes as routes_mod
async def _no_update(_):
async def no_update(_):
return None
monkeypatch.setattr(routes_mod.UpdateChecker, "check_for_updates", _no_update)
monkeypatch.setattr(routes_mod.UpdateChecker, "check_for_updates", no_update)
app = make_app(remote_only=True)
client = await aiohttp_client(app)
resp = await client.get("/api/health")
@@ -158,10 +158,10 @@ async def test_health_endpoint_responds_ok(make_app, aiohttp_client, monkeypatch
async def test_health_bypasses_api_key_auth_middleware(make_app, aiohttp_client, monkeypatch) -> None:
from unshackle.core.api import routes as routes_mod
async def _no_update(_):
async def no_update(_):
return None
monkeypatch.setattr(routes_mod.UpdateChecker, "check_for_updates", _no_update)
monkeypatch.setattr(routes_mod.UpdateChecker, "check_for_updates", no_update)
app = make_app(remote_only=True, with_auth_middleware=True)
client = await aiohttp_client(app)
+4 -4
View File
@@ -28,13 +28,13 @@ def serve_users(monkeypatch):
monkeypatch.setattr(handlers, "request_secret_key", lambda request: request.headers.get("X-Secret-Key"))
def _request(key):
def request(key):
return SimpleNamespace(headers={"X-Secret-Key": key} if key else {})
@pytest.mark.parametrize(("key", "allowed"), ENTITLEMENTS)
def test_server_cdm_allowed(serve_users, key, allowed):
assert handlers.server_cdm_allowed(_request(key)) is allowed
assert handlers.server_cdm_allowed(request(key)) is allowed
def test_no_request_allows(serve_users):
@@ -45,10 +45,10 @@ def test_no_request_allows(serve_users):
def test_download_gate_follows_entitlement(serve_users, key, allowed):
# A download job licenses with the server CDM, so submission obeys the same gate.
if allowed:
handlers.enforce_download_gates({}, _request(key))
handlers.enforce_download_gates({}, request(key))
else:
with pytest.raises(APIError) as ei:
handlers.enforce_download_gates({}, _request(key))
handlers.enforce_download_gates({}, request(key))
assert ei.value.error_code == APIErrorCode.FORBIDDEN
+2 -2
View File
@@ -69,7 +69,7 @@ async def test_cleanup_expired_drops_old_authenticated(store: SessionStore, monk
from datetime import datetime, timedelta, timezone
entry = await store.create("ATV", _FakeService())
entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store._ttl + 100)
entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 100)
removed = await store.cleanup_expired()
assert removed == 1
assert store.session_count == 0
@@ -118,7 +118,7 @@ async def test_get_session_store_returns_singleton() -> None:
async def test_max_sessions_evicts_oldest(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(type(store), "_max_sessions", property(lambda _: 2))
monkeypatch.setattr(type(store), "max_sessions", property(lambda _: 2))
await store.create("A", _FakeService(), session_id="a")
await asyncio.sleep(0.01)