mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-26 19:05:13 +00:00
refactor(dl): check dl options once in a run plan shared by the CLI and the REST download job
This commit is contained in:
@@ -11,7 +11,6 @@ from unshackle.commands.dl import dl
|
||||
from unshackle.core.api import routes
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from unshackle.core.dl_options import (
|
||||
API_SHAPED_DL_PARAMS,
|
||||
DEFAULT_DOWNLOAD_PARAMS,
|
||||
DL_OPTION_ALIASES,
|
||||
DL_OPTIONS,
|
||||
@@ -54,15 +53,10 @@ def test_the_server_reads_back_what_a_remote_client_forwards():
|
||||
|
||||
|
||||
def test_api_defaults_cast_to_the_dl_defaults():
|
||||
"""An API-shaped option keeps its own empty default, which perform_download normalizes."""
|
||||
"""``wanted`` keeps its API default of no keys, which dl reads as every title, like the CLI's None."""
|
||||
ctx = click.Context(dl.cli)
|
||||
expected = {
|
||||
p.name: p.type_cast_value(ctx, p.get_default(ctx))
|
||||
for p in dl.cli.params
|
||||
if p.name not in CLI_ONLY | API_SHAPED_DL_PARAMS
|
||||
}
|
||||
cast = cast_dl_params(dl.cli, {})
|
||||
assert {k: v for k, v in cast.items() if k not in API_SHAPED_DL_PARAMS} == expected
|
||||
expected = {p.name: p.type_cast_value(ctx, p.get_default(ctx)) for p in dl.cli.params if p.name not in CLI_ONLY}
|
||||
assert cast_dl_params(dl.cli, {}) == {**expected, "wanted": []}
|
||||
|
||||
|
||||
def test_cli_only_options_never_reach_dl():
|
||||
@@ -107,7 +101,7 @@ def test_values_are_cast_by_the_dl_click_types():
|
||||
assert cast["acodec"] == [Audio.Codec.EC3]
|
||||
assert cast["range_"] == [Video.Range.HDR10P, Video.Range.DV]
|
||||
assert cast["lang"] == ["en"]
|
||||
assert (cast["slow"], cast["wanted"]) == ("20-40", ["S01E01"])
|
||||
assert (cast["slow"], cast["wanted"]) == ((20, 40), ["1x1"])
|
||||
assert (cast["downloads"], cast["sample"], cast["tvdb_order"]) == (3, (0, 60), "dvd")
|
||||
assert cast["sub_format"] is Subtitle.Codec.SubRip
|
||||
assert (cast["output_dir"], cast["cdm_only"], cast["s_lang"]) == (None, False, ["all"])
|
||||
@@ -186,8 +180,8 @@ def test_api_refuses_a_value_the_dl_option_cannot_take(data, error):
|
||||
|
||||
|
||||
def test_no_dl_option_needs_a_parse_step_the_cast_skips():
|
||||
"""type_cast_value runs no callback and no required check, so neither may appear on a dl option."""
|
||||
assert not [p.name for p in dl.cli.params if p.callback or p.required]
|
||||
"""type_cast_value runs no callback, required check or envvar lookup, so none may appear on a dl option."""
|
||||
assert not [p.name for p in dl.cli.params if p.callback or p.required or getattr(p, "envvar", None)]
|
||||
|
||||
|
||||
def test_null_takes_the_api_default():
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Covers serialize_title's conditional `part` key, the list-tracks wanted filter
|
||||
routing through Episode.matches_wanted, the discrete season/episode/part request
|
||||
fields, and download_manager's already-internal wanted sniff.
|
||||
fields, and SeasonRange.convert passing already-parsed wanted keys through.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,6 +17,7 @@ import pytest
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.titles.episode import Episode
|
||||
from unshackle.core.utils.click_types import SEASON_RANGE
|
||||
from unshackle.core.wire import build_title, serialize_title
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
@@ -202,68 +203,29 @@ def test_rest_multi_episode_order_is_stable_across_parts(monkeypatch) -> None:
|
||||
assert selected(result) == ["1x1.1", "1x1.2", "1x1.3", "1x2"]
|
||||
|
||||
|
||||
SNIFF = r"^!?\d+x\d+(\.\d+)?$"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"wanted, internal",
|
||||
("wanted", "parsed"),
|
||||
[
|
||||
(["1x1"], True), # today's pre-parsed form
|
||||
(["1x1", "1x2"], True),
|
||||
(["1x1.2"], True), # part key
|
||||
(["!1x1.2"], True), # negative part key
|
||||
(["1x1", "!1x1.2"], True),
|
||||
(["S01E01"], False),
|
||||
(["s1e1.2"], False),
|
||||
(["S01"], False),
|
||||
(["1x1", "S01E02"], False),
|
||||
(["1x1"], ["1x1"]),
|
||||
(["1x1.2"], ["1x1.2"]),
|
||||
(["!1x1.2"], ["!1x1.2"]),
|
||||
(["1x1", "!1x1.2"], ["1x1", "!1x1.2"]),
|
||||
("1x1, 1x2", ["1x1", "1x2"]),
|
||||
(["1x01"], ["1x1"]),
|
||||
],
|
||||
)
|
||||
def test_download_manager_sniff_regex(wanted: List[str], internal: bool) -> None:
|
||||
needs_conversion = any(not re.match(SNIFF, w) for w in wanted)
|
||||
assert needs_conversion is (not internal)
|
||||
def test_parsed_keys_pass_unchanged(wanted: Any, parsed: List[str]) -> None:
|
||||
"""A pre-parsed part or negative key never reaches parse_tokens, which cannot read it."""
|
||||
assert SEASON_RANGE.convert(wanted) == parsed
|
||||
|
||||
|
||||
def test_sniff_regex_matches_the_one_in_download_manager() -> None:
|
||||
"""Guard the copy above against drift from the production regex."""
|
||||
from pathlib import Path
|
||||
|
||||
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
|
||||
@pytest.mark.parametrize("wanted", [["S01E01"], "S01E01", ["s1e1"], "s1e1; S01E01"])
|
||||
def test_tokens_parse_from_a_list_or_a_separated_string(wanted: Any) -> None:
|
||||
assert SEASON_RANGE.convert(wanted) == ["1x1"]
|
||||
|
||||
|
||||
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.utils.click_types import SeasonRange
|
||||
|
||||
calls = []
|
||||
monkeypatch.setattr(SeasonRange, "parse_tokens", lambda self, *t: calls.append(t) or [])
|
||||
|
||||
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)
|
||||
|
||||
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.utils.click_types import SeasonRange
|
||||
|
||||
calls = []
|
||||
monkeypatch.setattr(SeasonRange, "parse_tokens", lambda self, *t: calls.append(t) or ["1x1"])
|
||||
|
||||
params: Dict[str, Any] = {"wanted": "S01E01"}
|
||||
with pytest.raises(BaseException):
|
||||
perform_download("job-2", "NoSuchServiceXYZ", "t1", params)
|
||||
|
||||
assert calls == [("S01E01",)]
|
||||
assert params["wanted"] == ["1x1"]
|
||||
def test_a_mixed_list_parses_every_token() -> None:
|
||||
assert sorted(SEASON_RANGE.convert(["1x1", "S01E02"])) == ["1x1", "1x2"]
|
||||
|
||||
|
||||
def test_dl_and_handlers_share_the_one_match_helper() -> None:
|
||||
|
||||
@@ -36,8 +36,7 @@ def test_a_rest_job_converts_quality_and_passes_cdm_only(tmp_path: Path, monkeyp
|
||||
raise _Captured(self.ctx.params["quality"], kwargs["quality"], self.ctx.params["cdm_only"])
|
||||
|
||||
class FakeService:
|
||||
def __init__(self, ctx: click.Context) -> None:
|
||||
pass
|
||||
cli = click.Command("svc", callback=lambda title: object())
|
||||
|
||||
monkeypatch.setattr(dl_module, "dl", FakeDl)
|
||||
monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path))
|
||||
|
||||
@@ -109,7 +109,7 @@ def test_client_sent_keys_without_stamp_counts_all_keys():
|
||||
assert dm.client_sent_keys({"workers": 1, "quality": None}) == {"workers", "quality"}
|
||||
|
||||
|
||||
def test_service_defaults_and_options_travel_nested(env, monkeypatch):
|
||||
def test_service_options_travel_nested_without_their_defaults(env, monkeypatch):
|
||||
@click.command()
|
||||
@click.option("--profile", type=int, default=1)
|
||||
@click.option("--device", default="chrome")
|
||||
@@ -119,8 +119,8 @@ def test_service_defaults_and_options_travel_nested(env, monkeypatch):
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda service: SimpleNamespace(cli=cli))
|
||||
params = env(body={"profile": "work", "service_params": {"profile": 2}})
|
||||
assert params["profile"] == "work"
|
||||
assert params["service_params"] == {"profile": 2, "device": "chrome"}
|
||||
assert env(body={"device": "tv"})["service_params"] == {"profile": 1, "device": "tv"}
|
||||
assert params["service_params"] == {"profile": 2}
|
||||
assert env(body={"device": "tv"})["service_params"] == {"device": "tv"}
|
||||
|
||||
|
||||
def use_cli(monkeypatch, *options):
|
||||
@@ -157,4 +157,4 @@ def test_a_json_shape_click_cannot_convert_is_a_400(env, monkeypatch, name, valu
|
||||
|
||||
def test_a_flat_dl_key_never_fills_a_service_option_of_the_same_name(env, monkeypatch):
|
||||
use_cli(monkeypatch, click.Option(["--quality"], type=click.Choice(["SD", "HD"]), default="HD"))
|
||||
assert env(body={"quality": [1080]})["service_params"] == {"quality": "HD"}
|
||||
assert env(body={"quality": [1080]})["service_params"] == {}
|
||||
|
||||
@@ -241,8 +241,7 @@ def test_perform_download_passes_latest_episodes_to_dl_result(tmp_path: Path, mo
|
||||
raise _CapturedCtx(kwargs)
|
||||
|
||||
class FakeService:
|
||||
def __init__(self, ctx: click.Context) -> None:
|
||||
pass
|
||||
cli = click.Command("svc", callback=lambda title: object())
|
||||
|
||||
monkeypatch.setattr(dl_module, "dl", FakeDl)
|
||||
monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path))
|
||||
@@ -277,8 +276,9 @@ def test_perform_download_gives_dl_the_defaults_for_null_and_empty_values(
|
||||
raise RuntimeError("stop")
|
||||
|
||||
class FakeService:
|
||||
def __init__(self, ctx: click.Context) -> None:
|
||||
seen["parent"] = dict(ctx.parent.params)
|
||||
cli = click.Command(
|
||||
"svc", callback=click.pass_context(lambda ctx, title: seen.update(parent=dict(ctx.parent.params)))
|
||||
)
|
||||
|
||||
monkeypatch.setattr(dl_module, "dl", FakeDl)
|
||||
monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path))
|
||||
@@ -307,14 +307,16 @@ def test_perform_download_casts_service_options(tmp_path: Path, monkeypatch: pyt
|
||||
def __init__(self, ctx: click.Context, **kwargs: object) -> None:
|
||||
pass
|
||||
|
||||
def build(title: str, episodes: object, tag: object) -> None:
|
||||
raise _CapturedCtx(episodes, tag)
|
||||
|
||||
class FakeService:
|
||||
cli = click.Command(
|
||||
"svc", params=[click.Option(["--episodes"], type=int), click.Option(["--tag"], multiple=True)]
|
||||
"svc",
|
||||
params=[click.Option(["--episodes"], type=int), click.Option(["--tag"], multiple=True)],
|
||||
callback=build,
|
||||
)
|
||||
|
||||
def __init__(self, ctx: click.Context, episodes: object = None, tag: object = ()) -> None:
|
||||
raise _CapturedCtx(episodes, tag)
|
||||
|
||||
monkeypatch.setattr(dl_module, "dl", FakeDl)
|
||||
monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path))
|
||||
monkeypatch.setattr(Services, "load", staticmethod(lambda s: FakeService))
|
||||
@@ -669,28 +671,25 @@ async def test_a_skip_written_just_before_the_worker_exits_reaches_the_job(
|
||||
|
||||
|
||||
def test_a_stopped_run_names_its_reason_in_the_job_error(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
import sys
|
||||
|
||||
import click
|
||||
|
||||
import unshackle.commands.dl as dl_module
|
||||
from unshackle.core.api import download_manager, handlers
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.run_plan import RunStopped
|
||||
from unshackle.core.services import Services
|
||||
|
||||
class FakeDl:
|
||||
cli = dl_module.dl.cli
|
||||
|
||||
def __init__(self, ctx: click.Context, **kwargs: object) -> None:
|
||||
self.stop_reason = None
|
||||
pass
|
||||
|
||||
def result(self, **kwargs: object) -> None:
|
||||
self.stop_reason = "Show S01E01: Required audio language(s) not found: ko"
|
||||
sys.exit(1)
|
||||
raise RunStopped("Show S01E01: Required audio language(s) not found: ko")
|
||||
|
||||
class FakeService:
|
||||
def __init__(self, ctx: click.Context) -> None:
|
||||
pass
|
||||
cli = click.Command("svc", callback=lambda title: object())
|
||||
|
||||
monkeypatch.setattr(dl_module, "dl", FakeDl)
|
||||
monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path))
|
||||
|
||||
@@ -301,17 +301,17 @@ def test_validate_download_params_accepts_defaults() -> None:
|
||||
({"vbitrate": -1}, "vbitrate"),
|
||||
({"abitrate": "no"}, "abitrate"),
|
||||
({"vbitrate_range": "no-dash-but-letters"}, "MIN-MAX"),
|
||||
({"vbitrate": 5000, "vbitrate_range": "1-2"}, "vbitrate and vbitrate_range"),
|
||||
({"abitrate": 128, "abitrate_range": "96-256"}, "abitrate and abitrate_range"),
|
||||
({"vbitrate": 5000, "vbitrate_range": "1-2"}, "--vbitrate and --vbitrate-range"),
|
||||
({"abitrate": 128, "abitrate_range": "96-256"}, "--abitrate and --abitrate-range"),
|
||||
({"abitrate_range": "1-2-3"}, "MIN-MAX"),
|
||||
({"quality": "4k"}, "Invalid quality"),
|
||||
({"quality": [0]}, "above 0"),
|
||||
({"channels": -3}, "channels"),
|
||||
({"workers": 0}, "workers"),
|
||||
({"downloads": 0}, "downloads"),
|
||||
({"video_only": True, "audio_only": True}, "exclusive"),
|
||||
({"no_subs": True, "subs_only": True}, "no_subs and subs_only"),
|
||||
({"no_audio": True, "audio_only": True}, "no_audio and audio_only"),
|
||||
({"video_only": True, "audio_only": True}, None),
|
||||
({"no_subs": True, "subs_only": True}, "--subs-only cannot be used with --no-subs"),
|
||||
({"no_audio": True, "audio_only": True}, "--audio-only cannot be used with --no-audio"),
|
||||
({"require_subs": "en"}, "require_subs must be an array"),
|
||||
({"range": "UHD"}, "Invalid range"),
|
||||
({"range": ["SDR", "UHD"]}, "Invalid range"),
|
||||
|
||||
@@ -335,7 +335,7 @@ def test_a_service_click_default_stays_out_of_the_download_gate(monkeypatch):
|
||||
monkeypatch.setattr(dm, "get_download_manager", Manager)
|
||||
body = {"service": "EXAMPLE1", "title_id": "t1", "quality": [1080]}
|
||||
asyncio.run(handlers.download_handler(body, request("flat")))
|
||||
assert jobs[0]["service_params"] == {"best_available": True}
|
||||
assert jobs[0]["service_params"] == {}
|
||||
assert not jobs[0].get("best_available")
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user