refactor(dl): check dl options once in a run plan shared by the CLI and the REST download job

This commit is contained in:
imSp4rky
2026-11-25 16:16:43 -07:00
parent 7838226590
commit 4d3df8e74f
23 changed files with 501 additions and 524 deletions
+7 -4
View File
@@ -18,7 +18,6 @@ import pytest
import unshackle.commands.dl as dl_module
from tests.remote.unit.test_remote_service_helpers import _sent_create_data
from unshackle.commands.dl import generated_dv_ranges
from unshackle.core import mux_step
from unshackle.core.api import download_manager, handlers
from unshackle.core.api.handlers import validate_download_parameters
@@ -37,7 +36,12 @@ from unshackle.core.tracks.hybrid import (
nits_to_pq,
pq_to_nits,
)
from unshackle.core.tracks.selection import hybrid_gate_failure, keep_generated_dv_bases, select_hybrid_bases
from unshackle.core.tracks.selection import (
generated_dv_ranges,
hybrid_gate_failure,
keep_generated_dv_bases,
select_hybrid_bases,
)
pytestmark = pytest.mark.unit
@@ -803,8 +807,7 @@ def test_a_rest_job_gives_the_flag_to_the_service_ctx_and_to_dl(
raise _Captured(self.ctx.params["generate_dv"], kwargs["generate_dv"])
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))
+20 -14
View File
@@ -2,12 +2,11 @@
from __future__ import annotations
import click
import pytest
from unshackle.commands.dl import validate_metadata_ids
from unshackle.core.api.handlers import validate_download_parameters
from unshackle.core.config import config
from unshackle.core.run_plan import PlanError, validate_metadata_ids
@pytest.fixture(autouse=True)
@@ -25,7 +24,7 @@ def with_keys(monkeypatch: pytest.MonkeyPatch, **keys: str) -> None:
[(27205, "tt1375666", None), (27205, None, 73871), (None, "tt1375666", 73871), (27205, "tt1375666", 73871)],
)
def test_two_ids_are_refused(tmdb: int | None, imdb: str | None, tvdb: int | None) -> None:
with pytest.raises(click.UsageError) as exc:
with pytest.raises(PlanError) as exc:
validate_metadata_ids(tmdb, imdb, tvdb)
assert "cannot be used together" in str(exc.value)
@@ -41,14 +40,14 @@ def test_imdb_alone_passes_on_the_keyless_provider(monkeypatch: pytest.MonkeyPat
def test_tmdb_without_its_key_names_the_key(monkeypatch: pytest.MonkeyPatch) -> None:
with_keys(monkeypatch)
with pytest.raises(click.UsageError) as exc:
with pytest.raises(PlanError) as exc:
validate_metadata_ids(27205, None, None)
assert "--tmdb" in str(exc.value) and "tmdb_api_key" in str(exc.value)
def test_tvdb_without_its_key_names_the_key(monkeypatch: pytest.MonkeyPatch) -> None:
with_keys(monkeypatch)
with pytest.raises(click.UsageError) as exc:
with pytest.raises(PlanError) as exc:
validate_metadata_ids(None, None, 73871)
assert "--tvdb" in str(exc.value) and "tvdb_api_key" in str(exc.value)
@@ -61,7 +60,7 @@ def test_tmdb_with_its_key_passes(monkeypatch: pytest.MonkeyPatch) -> None:
def test_a_provider_filtered_out_of_the_order_points_at_the_config(monkeypatch: pytest.MonkeyPatch) -> None:
with_keys(monkeypatch, tmdb_api_key="k")
monkeypatch.setattr(config, "metadata_providers", ["imdb", "omdb"])
with pytest.raises(click.UsageError) as exc:
with pytest.raises(PlanError) as exc:
validate_metadata_ids(27205, None, None)
assert "metadata_providers" in str(exc.value)
@@ -69,7 +68,7 @@ def test_a_provider_filtered_out_of_the_order_points_at_the_config(monkeypatch:
def test_imdb_is_unresolvable_when_the_order_drops_both_of_its_providers(monkeypatch: pytest.MonkeyPatch) -> None:
with_keys(monkeypatch)
monkeypatch.setattr(config, "metadata_providers", ["tmdb", "tvdb"])
with pytest.raises(click.UsageError) as exc:
with pytest.raises(PlanError) as exc:
validate_metadata_ids(None, "tt1375666", None)
assert "metadata_providers" in str(exc.value)
assert "imdb" in str(exc.value) and "omdb" in str(exc.value)
@@ -92,7 +91,7 @@ def test_one_kind_keeping_the_provider_is_enough(monkeypatch: pytest.MonkeyPatch
)
def test_api_refuses_two_ids(payload: dict) -> None:
err = validate_download_parameters(payload)
assert err and "multiple external IDs" in err
assert err and "cannot be used together" in err
@pytest.mark.parametrize("payload", [{"tmdb_id": 27205}, {"imdb_id": "tt1375666"}, {"tvdb_id": 73871}, {}])
@@ -118,7 +117,7 @@ def test_anilist_pairs_with_one_other_id(monkeypatch: pytest.MonkeyPatch) -> Non
def test_anilist_does_not_excuse_two_western_ids(monkeypatch: pytest.MonkeyPatch) -> None:
with_keys(monkeypatch)
with pytest.raises(click.UsageError) as exc:
with pytest.raises(PlanError) as exc:
validate_metadata_ids(27205, "tt1375666", None, 21)
assert "cannot be used together" in str(exc.value)
@@ -126,7 +125,7 @@ def test_anilist_does_not_excuse_two_western_ids(monkeypatch: pytest.MonkeyPatch
@pytest.mark.parametrize("value", ["tt1375666", "anilist:21", "mal:", "abc", "-3"])
def test_a_malformed_anilist_value_is_refused(monkeypatch: pytest.MonkeyPatch, value: str) -> None:
with_keys(monkeypatch)
with pytest.raises(click.UsageError) as exc:
with pytest.raises(PlanError) as exc:
validate_metadata_ids(None, None, None, value)
assert "--anilist" in str(exc.value)
@@ -142,19 +141,19 @@ def test_api_accepts_anilist_alongside_one_western_id() -> None:
def test_api_still_refuses_two_western_ids_with_anilist() -> None:
err = validate_download_parameters({"tmdb_id": 27205, "imdb_id": "tt1375666", "anilist_id": 21})
assert err and "multiple external IDs" in err
assert err and "cannot be used together" in err
@pytest.mark.parametrize("value", [0, -3, True, "mal:", "tt1375666", "anilist:21", 1.5])
def test_api_refuses_a_malformed_anilist_id(value: object) -> None:
err = validate_download_parameters({"anilist_id": value})
assert err and "anilist_id" in err
assert err and "anilist" in err
@pytest.mark.parametrize("value", ["0", "mal:0", "²", "21.5"])
def test_a_non_positive_or_non_decimal_anilist_value_is_refused(monkeypatch: pytest.MonkeyPatch, value: str) -> None:
with_keys(monkeypatch)
with pytest.raises(click.UsageError) as exc:
with pytest.raises(PlanError) as exc:
validate_metadata_ids(None, None, None, value)
assert "--anilist" in str(exc.value)
@@ -168,4 +167,11 @@ def test_api_accepts_what_the_cli_accepts(payload: dict) -> None:
@pytest.mark.parametrize("value", ["0", "mal:0", "²"])
def test_api_refuses_what_the_cli_refuses(value: str) -> None:
err = validate_download_parameters({"anilist_id": value})
assert err and "anilist_id" in err
assert err and "anilist" in err
def test_api_refuses_an_id_no_configured_provider_can_find(monkeypatch: pytest.MonkeyPatch) -> None:
with_keys(monkeypatch)
assert validate_download_parameters({"tmdb_id": 27205}) == (
"--tmdb needs the tmdb provider: set tmdb_api_key in your config"
)
+106
View File
@@ -0,0 +1,106 @@
"""The run plan: one check of the dl options for the CLI and the REST download job."""
from __future__ import annotations
from typing import Any
import click
import pytest
from click.core import ParameterSource
from unshackle.commands.dl import dl
from unshackle.core.api.errors import categorize_exception
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.run_plan import PlanError, api_plan, bitrate_range, check_options
from unshackle.core.tracks import Video
def cli_params(*args: str) -> dict[str, Any]:
"""The dl params a CLI parse of ``args`` gives, with the service subcommand left out."""
ctx = dl.cli.make_context("dl", [*args, "EXAMPLE"], resilient_parsing=True)
return ctx.params
@pytest.mark.parametrize(
("args", "data", "message"),
[
(["--sample", "--include-sample"], {"sample": True, "include_sample": True}, "--sample and --include-sample"),
(["--vbitrate", "5000", "--vbitrate-range", "1-2"], {"vbitrate": 5000, "vbitrate_range": "1-2"}, "--vbitrate"),
(["--abitrate-range", "1-2-3"], {"abitrate_range": "1-2-3"}, "Invalid --abitrate-range"),
(["-l", "all,-all"], {"lang": ["all", "-all"]}, "'all' cannot be excluded"),
(["--require-audio", "-en"], {"require_audio": ["-en"]}, "--require-audio: en cannot be required"),
(["-ado", "--no-audio"], {"audio_description_only": True, "no_audio": True}, "--audio-description-only"),
(["--enrich"], {"enrich": True}, "--enrich requires"),
(["-S", "--no-subs"], {"subs_only": True, "no_subs": True}, "--subs-only cannot be used with --no-subs"),
(["-V", "-A"], {"video_only": True, "audio_only": True}, None),
(["--tvdb-order", "official"], {"tvdb_order": "absolute", "tvdb_id": 1}, None),
],
)
def test_the_cli_and_the_api_refuse_the_same_run(args: list[str], data: dict, message: str | None) -> None:
"""Both front doors go through check_options, so a run dl refuses is a submit-time refusal over the API."""
if message is None:
check_options(cli_params(*args))
return
with pytest.raises(PlanError, match=message):
check_options(cli_params(*args))
with pytest.raises(PlanError, match=message):
api_plan(data)
def test_select_titles_and_wanted_are_refused() -> None:
with pytest.raises(PlanError, match="--select-titles"):
check_options({"select_titles": True, "wanted": ["1x1"]})
def test_hybrid_needs_dovi_tool(monkeypatch: pytest.MonkeyPatch) -> None:
import unshackle.core.binaries as binaries
monkeypatch.setattr(binaries, "DoviTool", None)
with pytest.raises(PlanError, match="dovi_tool"):
check_options({"range_": [Video.Range.HDR10], "generate_dv": True})
check_options({"range_": [Video.Range.HDR10]})
def test_a_plan_error_exits_1_without_a_usage_block() -> None:
assert PlanError("x").exit_code == 1
assert not isinstance(PlanError("x"), click.UsageError)
def test_a_plan_error_is_an_invalid_parameters_api_error() -> None:
error = categorize_exception(PlanError("--sample and --include-sample cannot be used together."))
assert error.error_code is APIErrorCode.INVALID_PARAMETERS
assert error.message == "--sample and --include-sample cannot be used together."
@pytest.mark.parametrize(("value", "expected"), [("6000-7000", (6000, 7000)), ("7000-6000", (6000, 7000)), ("", None)])
def test_bitrate_range_orders_its_ends(value: str, expected: Any) -> None:
assert bitrate_range(value, "--vbitrate-range", "6000-7000") == expected
def test_the_api_plan_shapes_wanted_and_slow() -> None:
plan = api_plan({"wanted": "S01E01, S01E02", "slow": [20, 40]})
assert sorted(plan.params["wanted"]) == ["1x1", "1x2"]
assert plan.params["slow"] == (20, 40)
assert api_plan({"slow": True}).params["slow"] == (60, 120)
with pytest.raises(PlanError, match="slow"):
api_plan({"slow": [1, 2]})
with pytest.raises(PlanError, match="wanted"):
api_plan({"wanted": [1]})
def test_the_api_plan_records_where_each_value_came_from() -> None:
plan = api_plan({"workers": 4, "quality": [1080], "cdm": "dev", "remote": "box"}, client_keys={"workers", "cdm"})
assert plan.sources["workers"] is ParameterSource.COMMANDLINE
assert plan.sources["cdm_name"] is ParameterSource.COMMANDLINE
assert plan.sources["quality"] is ParameterSource.DEFAULT
assert plan.sources["server"] is ParameterSource.DEFAULT
assert (plan.params["cdm_name"], plan.params["remote"], plan.params["server"]) == ("dev", True, "box")
ctx = plan.context(dl.cli, "EXAMPLE")
assert ctx.invoked_subcommand == "EXAMPLE"
assert ctx.get_parameter_source("workers") is ParameterSource.COMMANDLINE
assert ctx.params == plan.params
def test_dl_checks_the_plan_before_the_service_loads() -> None:
with pytest.raises(PlanError, match="--sample and --include-sample"):
dl.cli.main(["--sample", "--include-sample", "EXAMPLE", "t"], standalone_mode=False)