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)
+2 -1
View File
@@ -57,7 +57,8 @@ def test_kind_only_conflict(params, expected):
def test_api_rejects_a_conflict():
assert validate_download_parameters({**BASE, "audio_description_only": True, "no_audio": True}) == (
"Cannot use both audio_description_only and no_audio"
"--audio-description-only cannot be used with --no-audio: --no-audio drops the tracks that "
"--audio-description-only selects."
)
assert validate_download_parameters({**BASE, "audio_description_only": True, "audio_only": True}) is None
@@ -14,6 +14,7 @@ from langcodes import Language
from tests.lang_selection import test_kind_only_selection as harness
from tests.lang_selection.test_track_selection import audio, episode, selection, standard, video
from unshackle.core.run_plan import PlanError, check_options
from unshackle.core.tracks.selection import Kept, Skip
from unshackle.core.utilities import missing_required_langs
@@ -98,11 +99,9 @@ def test_every_kind_misses_in_one_reason() -> None:
({"require_audio": ["-en"]}, "--require-audio: en"),
],
)
def test_a_required_and_excluded_language_stops_the_run(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, flags: dict[str, Any], clash: str
) -> None:
assert harness.run(monkeypatch, caplog, {1: {}}, **flags) == 1
assert f"{clash} cannot be required and excluded at the same time." in caplog.text
def test_a_required_and_excluded_language_is_refused(flags: dict[str, Any], clash: str) -> None:
with pytest.raises(PlanError, match=f"^{clash} cannot be required and excluded at the same time.$"):
check_options(flags)
def test_a_language_override_does_not_inherit_the_lang_exclusions(
+6 -12
View File
@@ -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():
+17 -55
View File
@@ -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:
+1 -2
View File
@@ -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"] == {}
+14 -15
View File
@@ -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))
+5 -5
View File
@@ -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")
+1 -1
View File
@@ -296,7 +296,7 @@ def test_the_api_refuses_a_bad_sample_window(sample: object) -> None:
def test_the_api_refuses_sample_with_include_sample() -> None:
assert "include_sample" in (validate_download_parameters({"sample": True, "include_sample": True}) or "")
assert "--include-sample" in (validate_download_parameters({"sample": True, "include_sample": True}) or "")
def test_sample_name_uses_the_separator_of_the_template(monkeypatch: pytest.MonkeyPatch) -> None: