chore(release): promote 6.0.0 to main

This commit is contained in:
imSp4rky
2026-11-23 18:11:04 -07:00
425 changed files with 52275 additions and 12006 deletions
@@ -0,0 +1,53 @@
from types import SimpleNamespace
from langcodes import Language
from unshackle.core.utilities import apply_original_language
class FakeTracks(SimpleNamespace):
def __iter__(self):
return iter([*self.videos, *self.audio])
def track(lang, original=False):
return SimpleNamespace(language=Language.get(lang) if lang else None, is_original_lang=original)
def title(language, videos=(), audio=()):
return SimpleNamespace(
language=Language.get(language) if language else None,
tracks=FakeTracks(videos=list(videos), audio=list(audio)),
)
def test_overrides_the_service_guess_and_its_videos():
t = title("es", videos=[track("es"), track("es")])
apply_original_language(t, Language.get("it"))
assert str(t.language) == "it"
assert [str(v.language) for v in t.tracks.videos] == ["it", "it"]
def test_videos_in_another_language_keep_it():
t = title("es", videos=[track("es"), track("ja"), track(None)])
apply_original_language(t, Language.get("it"))
assert [v.language and str(v.language) for v in t.tracks.videos] == ["it", "ja", None]
def test_no_service_language_keeps_video_tags():
t = title(None, videos=[track("en")])
apply_original_language(t, Language.get("it"))
assert str(t.language) == "it"
assert str(t.tracks.videos[0].language) == "en"
def test_original_flag_moves_to_the_enrich_language():
t = title("es", audio=[track("es-419", original=True), track("it-IT")])
apply_original_language(t, Language.get("it"))
assert [a.is_original_lang for a in t.tracks.audio] == [False, True]
def test_same_language_leaves_flags_alone():
t = title("it", videos=[track(None, original=True)])
apply_original_language(t, Language.get("it"))
assert t.tracks.videos[0].is_original_lang is True
@@ -10,10 +10,8 @@ from unshackle.core.utilities import as_requested
@pytest.mark.parametrize(
"tokens,orig_token,expected",
[
# the user passed no -l, so orig resolved to en behind their back; report orig
(["en"], "en", "orig"),
(["en", "ja"], "en", "orig, ja"),
# the user named en, so report en
(["en"], None, "en"),
(["ja"], "en", "ja"),
(["en", "ja"], None, "en, ja"),
@@ -28,5 +28,4 @@ def test_every_declaring_video_counts():
@pytest.mark.parametrize("videos", [[video(audio_language="zh-CN")], [video(audio_language="zh-CN"), video()]])
def test_dropping_the_video_drops_its_audio(videos):
# --audio-only / --no-video discard the track the audio lives in, so nothing is embedded
assert embedded_audio_langs(videos, False) == []
@@ -15,7 +15,6 @@ from unshackle.core.utilities import keep_forced_subtitle
(True, "en-US", ["en"], False, True),
(True, "de", ["en"], False, False),
(True, "de", ["en", "de"], False, True),
# CLDR rates paradigm-regional pairs (en/en-US) distance 0, so exact still matches
(True, "en-US", ["en"], True, True),
(True, "en", ["en"], True, True),
(True, "es-419", ["es-ES"], True, False),
@@ -0,0 +1,85 @@
"""The kind-only flags: --audio-description-only and --forced-subs-only.
The filters in dl.result are not extractable without executing the whole download loop, so
their wiring is pinned against the source, the same way test_required_langs_gate does it.
"""
from __future__ import annotations
import inspect
import pytest
from unshackle.commands.dl import dl
from unshackle.core.api.handlers import validate_download_parameters
from unshackle.core.utilities import kind_only_conflict
KEYS = ["audio_description_only", "forced_subs_only"]
BASE = {"service": "EXAMPLE", "title": "x"}
@pytest.mark.parametrize(
"args,only_key,base_key,expected",
[
(["-ado"], "audio_description_only", "audio_description", (True, False)),
(["-ad"], "audio_description_only", "audio_description", (False, True)),
([], "audio_description_only", "audio_description", (False, False)),
(["-fso"], "forced_subs_only", "forced_subs", (True, False)),
(["-fs"], "forced_subs_only", "forced_subs", (False, True)),
],
)
def test_only_flag_does_not_parse_as_its_base_flag(args, only_key, base_key, expected):
params = dl.cli.make_context("dl", args, resilient_parsing=True).params
assert (params[only_key], params[base_key]) == expected
@pytest.mark.parametrize(
"params,expected",
[
({"audio_description_only": True, "audio_only": True}, None),
({"audio_description_only": True}, None),
({"audio_description_only": True, "no_audio": True}, ("audio_description_only", "no_audio")),
({"audio_description_only": True, "video_only": True}, ("audio_description_only", "video_only")),
({"forced_subs_only": True, "subs_only": True}, None),
({"forced_subs_only": True, "no_subs": True}, ("forced_subs_only", "no_subs")),
({"forced_subs_only": True, "audio_only": True}, ("forced_subs_only", "audio_only")),
({"no_audio": True, "video_only": True}, None),
({"audio_description_only": True, "audio_only": True, "subs_only": True}, None),
({"forced_subs_only": True, "subs_only": True, "audio_only": True}, None),
({"audio_description_only": True, "subs_only": True}, ("audio_description_only", "subs_only")),
],
)
def test_kind_only_conflict(params, expected):
assert 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"
)
assert validate_download_parameters({**BASE, "audio_description_only": True, "audio_only": True}) is None
@pytest.mark.parametrize("key", [*KEYS, "audio_description", "audio_only"])
def test_api_rejects_a_non_boolean_flag(key):
assert validate_download_parameters({**BASE, key: "false"}) == f"{key} must be a boolean"
assert validate_download_parameters({**BASE, key: None}) is None
class TestFilterWiring:
source = inspect.getsource(dl.result)
def test_ado_runs_when_the_title_has_no_separate_audio(self):
ado = self.source.index("if keep_audio and audio_description_only:")
guard = self.source.index("if keep_audio and len(title.tracks.audio) > 0:")
assert ado < guard
def test_ado_does_not_count_embedded_audio(self):
assert self.source.count("keep_videos and not audio_description_only") == 2
def test_only_filters_keep_one_kind(self):
assert "title.tracks.select_audio(lambda x: x.descriptive)" in self.source
assert "title.tracks.select_subtitles(lambda x: x.forced)" in self.source
def test_fso_implies_forced_subs(self):
assert "if forced_s_lang or fsl_excl or forced_subs_only:" in self.source
@@ -0,0 +1,147 @@
"""Run the kind-only filters through the real dl.result() selection loop.
A fake service hands in-memory tracks to the loop, and the run stops at the first
title that reaches ``Tracks.tree``, the step right after selection. A title with no
track of the kind never gets there, so what the hook records is what the run kept.
"""
from __future__ import annotations
import inspect
import logging
from typing import Any, cast
import pytest
from unshackle.commands.dl import dl
from unshackle.core.api.handlers import DEFAULT_DOWNLOAD_PARAMS
from unshackle.core.service import Service
from unshackle.core.titles import Episode, Series
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
class Selected(BaseException):
"""Carries the kept track ids out of the loop."""
def __init__(self, tracks: Tracks) -> None:
self.ids = {
"video": [t.id for t in tracks.videos],
"audio": [t.id for t in tracks.audio],
"subs": [t.id for t in tracks.subtitles],
}
class Harness(dl):
def __getattr__(self, name: str) -> None:
return None
class FakeService:
"""One episode per entry; ``ad`` adds a descriptive track, ``forced`` a forced subtitle."""
def __init__(self, episodes: dict[int, dict[str, bool]]) -> None:
self.episodes = episodes
self.session = None
def authenticate(self, cookies: Any = None, credential: Any = None) -> None:
pass
def get_titles_cached(self) -> Series:
return Series(
Episode(id_=f"show-s01-e{n:03}", service=FakeService, title="Show", season=1, number=n, language="en")
for n in self.episodes
)
def get_tracks(self, title: Episode) -> Tracks:
kinds = self.episodes[title.number]
tracks = Tracks()
tracks.add(Video(id_="v", url="https://x/v", language="en", codec=Video.Codec.AVC, range_=Video.Range.SDR))
tracks.add(Audio(id_="a", url="https://x/a", language="en", codec=Audio.Codec.AAC, bitrate=128_000))
if kinds.get("ad"):
tracks.add(
Audio(id_="ad", url="https://x/ad", language="en", codec=Audio.Codec.AAC, bitrate=1, descriptive=True)
)
tracks.add(Subtitle(id_="s", url="https://x/s", language="en", codec=Subtitle.Codec.WebVTT))
if kinds.get("forced"):
tracks.add(Subtitle(id_="sf", url="https://x/sf", language="en", codec=Subtitle.Codec.WebVTT, forced=True))
return tracks
def get_chapters(self, title: Episode) -> list:
return []
def __getattr__(self, name: str) -> Any:
if name.startswith("on_"):
return lambda *a, **k: None
raise AttributeError(name)
def run(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, episodes: dict, **flags: Any) -> Any:
"""Return the Selected ids, the exit code, or None for a run that completes."""
monkeypatch.setattr(Tracks, "tree", lambda self, *a, **k: (_ for _ in ()).throw(Selected(self)))
cmd = Harness.__new__(Harness)
cmd.log = logging.getLogger("test_kind_only")
cmd.service = "FAKE"
cmd.tmdb_searched = True
cmd.completed_files = []
kwargs: dict[str, Any] = {}
for name, param in inspect.signature(dl.result).parameters.items():
if name in DEFAULT_DOWNLOAD_PARAMS:
kwargs[name] = DEFAULT_DOWNLOAD_PARAMS[name]
elif name not in ("self", "service"):
kwargs[name] = None if param.default is inspect.Parameter.empty else param.default
kwargs.update(quality=[], vcodec=[], acodec=[], range_=[], wanted=[], cdm_only=None, downloads=1)
kwargs.update(flags)
caplog.set_level(logging.WARNING, logger="test_kind_only")
try:
cmd.result(cast(Service, FakeService(episodes)), **kwargs)
except Selected as sel:
return sel.ids
except SystemExit as exc:
return exc.code
return None
def test_ado_keeps_the_descriptive_track_and_the_other_types(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, {1: {"ad": True, "forced": True}}, audio_description_only=True)
assert ids == {"video": ["v"], "audio": ["ad"], "subs": ["s"]}
def test_fso_keeps_the_forced_track_and_the_other_types(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, {1: {"ad": True, "forced": True}}, forced_subs_only=True)
assert ids == {"video": ["v"], "audio": ["a"], "subs": ["sf"]}
def test_only_flags_with_their_type_flags_give_a_single_kind(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, {1: {"ad": True, "forced": True}}, audio_description_only=True, audio_only=True)
assert ids == {"video": [], "audio": ["ad"], "subs": []}
ids = run(monkeypatch, caplog, {1: {"ad": True, "forced": True}}, forced_subs_only=True, subs_only=True)
assert ids == {"video": [], "audio": [], "subs": ["sf"]}
@pytest.mark.parametrize("flag", ["audio_description_only", "forced_subs_only"])
def test_a_single_title_with_no_such_track_exits(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, flag: str
) -> None:
assert run(monkeypatch, caplog, {1: {}}, **{flag: True}) == 1
assert "Skipping" not in caplog.text
def test_a_multi_title_run_skips_the_title_and_continues(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, {1: {}, 2: {"ad": True}}, audio_description_only=True)
assert ids["audio"] == ["ad"]
assert "Skipping Show S01E01" in caplog.text
def test_a_multi_title_run_with_every_title_skipped_completes(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
assert run(monkeypatch, caplog, {1: {}, 2: {}}, forced_subs_only=True) is None
assert caplog.text.count("Skipping Show S01E") == 2
@@ -13,15 +13,12 @@ POOL = ["ar", "en", "en-GB", "en-US", "ja"]
("language", "available", "exact", "expected"),
[
("en", POOL, False, {"en", "en-GB", "en-US"}),
# CLDR rates en/en-US at distance 0, so exact mode leans on the RFC 4647 string preference
("en", POOL, True, {"en"}),
("en-GB", POOL, True, {"en-GB"}),
# no string-equal tag, so exact mode falls back to the distance match
("zh", ["ar", "cmn", "ja"], True, {"cmn"}),
("en", ["ar", "ja"], False, set()),
("en", [], False, set()),
("en", ["ar", None, "en"], True, {"en"}),
# unparseable tags (config typos) must match nothing, never raise
("engrish", POOL, False, set()),
("engrish", POOL, True, set()),
("", POOL, False, set()),
@@ -21,18 +21,13 @@ class FakeTitle:
@pytest.mark.parametrize(
"title_language,track_languages,expected",
[
# paradigm collapse: CLDR calls these the same language, RFC 4647 picks the specific one
(["en"], ["en", "en-US"], ["en"]),
(["en"], ["en-US", "en-GB"], ["en-US"]),
(["pt"], ["pt-BR", "pt-PT"], ["pt-BR"]),
(["es"], ["es-ES", "es-419"], ["es-ES"]),
# non-paradigm regionals: exact mode drops them, so the fuzzy fallback catches
# them and the flag still matches what a default 'orig' download selects
(["es"], ["es-419"], ["es-419"]),
(["fr"], ["fr-CA"], ["fr-CA"]),
# alias
(["zh"], ["cmn"], ["cmn"]),
# nothing in the original language, and no language on the title at all
(["en"], ["ja", "de"], []),
([None], ["en"], []),
],
@@ -21,8 +21,6 @@ from unshackle.core.tracks import Audio
from unshackle.core.tracks.tracks import Tracks
from unshackle.core.utilities import is_exact_match
# Base language vs regional variant that CLDR rates at distance 0 (paradigm locales). These are
# the pairs that collapse under naive exact matching.
COLLAPSING_PAIRS = [
("ar", "ar-EG"),
("en", "en-US"),
@@ -32,8 +30,6 @@ COLLAPSING_PAIRS = [
("de", "de-DE"),
("it", "it-IT"),
]
# Pairs CLDR rates at distance >0, which exact matching already separates. Never collapsed.
# Includes two-regional splits (no bare base) as services more commonly ship them.
DISTINCT_PAIRS = [
("es", "es-419"),
("fr", "fr-CA"),
@@ -47,9 +43,6 @@ DISTINCT_PAIRS = [
("no", "nn"),
]
# A full real-world audio language set for one title, the kind of mix a streaming manifest ships,
# which must resolve 1:1 with no collision or loss. Tags are drawn from published streaming
# language references (Warner Bros. Discovery / Netflix) and include regional and script variants.
REAL_WORLD_AUDIO_LANGS = [
"ar",
"ar-EG",
@@ -101,79 +94,67 @@ REAL_WORLD_AUDIO_LANGS = [
]
def _mk(*tags):
def mk(*tags):
return [Audio("https://x", language=t, id_=t) for t in tags]
def _select(tags, pool, exact=True):
def select(tags, pool, exact=True):
return [(t.id, str(t.language)) for t in Tracks.by_language(pool, tags, per_language=1, exact_match=exact)]
@pytest.mark.parametrize("base,reg", COLLAPSING_PAIRS)
def test_collapsing_pairs_are_distance_zero(base, reg):
# Root cause: the regional variant exact-matches the base request (CLDR paradigm data).
assert is_exact_match(base, [reg]) is True
@pytest.mark.parametrize("base,reg", DISTINCT_PAIRS)
def test_distinct_pairs_are_not_distance_zero(base, reg):
# Contrast: these never collapse, which is why the bug was language-specific.
assert is_exact_match(base, [reg]) is False
@pytest.mark.parametrize("base,reg", COLLAPSING_PAIRS)
def test_exact_lang_selects_distinct_collapsing_variants(base, reg):
# Both tracks present + both tags requested: each tag must route to its own track.
assert _select([base, reg], _mk(base, reg)) == [(base, base), (reg, reg)]
assert select([base, reg], mk(base, reg)) == [(base, base), (reg, reg)]
@pytest.mark.parametrize("base,reg", DISTINCT_PAIRS)
def test_exact_lang_distinct_regionals_still_work(base, reg):
assert _select([base, reg], _mk(base, reg)) == [(base, base), (reg, reg)]
assert select([base, reg], mk(base, reg)) == [(base, base), (reg, reg)]
def test_exact_lang_lenient_base_to_regional_fallback():
# Only the regional present; a base request must still find it when CLDR rates them equal.
assert _select(["en"], _mk("en-US")) == [("en-US", "en-US")]
# Alias with no string-equal track must still resolve (zh -> cmn).
assert _select(["zh"], _mk("cmn")) == [("cmn", "cmn")]
assert select(["en"], mk("en-US")) == [("en-US", "en-US")]
assert select(["zh"], mk("cmn")) == [("cmn", "cmn")]
def test_exact_lang_stays_strict_for_nonzero_distance():
# `es` does NOT accept `es-419` in exact mode (distance 5), but fuzzy mode does.
assert _select(["es"], _mk("es-419")) == []
assert _select(["es"], _mk("es-419"), exact=False) == [("es-419", "es-419")]
assert select(["es"], mk("es-419")) == []
assert select(["es"], mk("es-419"), exact=False) == [("es-419", "es-419")]
@pytest.mark.parametrize("base,reg", COLLAPSING_PAIRS)
def test_overlapping_tags_never_duplicate_in_fuzzy_mode(base, reg):
# Non-exact still collapses base/regional, but must dedupe rather than return a track twice.
selected = Tracks.by_language(_mk(base, reg), [base, reg], per_language=1, exact_match=False)
selected = Tracks.by_language(mk(base, reg), [base, reg], per_language=1, exact_match=False)
assert len({t.id for t in selected}) == len(selected)
def test_exact_lang_three_way_base_and_two_regionals():
# fr (base, dist 0 to fr-FR) + fr-FR + fr-CA (dist 4): all three must resolve distinctly.
assert _select(["fr", "fr-FR", "fr-CA"], _mk("fr", "fr-FR", "fr-CA")) == [
assert select(["fr", "fr-FR", "fr-CA"], mk("fr", "fr-FR", "fr-CA")) == [
("fr", "fr"),
("fr-FR", "fr-FR"),
("fr-CA", "fr-CA"),
]
# Base request with no bare-tag track falls back to its paradigm regional, without stealing
# the sibling regional (fr -> fr-FR, not fr-CA).
assert _select(["fr", "fr-CA"], _mk("fr-FR", "fr-CA")) == [("fr-FR", "fr-FR"), ("fr-CA", "fr-CA")]
assert select(["fr", "fr-CA"], mk("fr-FR", "fr-CA")) == [("fr-FR", "fr-FR"), ("fr-CA", "fr-CA")]
@pytest.mark.parametrize("tag", REAL_WORLD_AUDIO_LANGS)
def test_full_language_set_each_tag_resolves_to_itself(tag):
# Against a full real-world language pool, every exact request must return its own track, so
# that no tag captures another's: ar-EG must resolve to ar-EG, never to ar.
pool = _mk(*REAL_WORLD_AUDIO_LANGS)
assert _select([tag], pool) == [(tag, tag)]
pool = mk(*REAL_WORLD_AUDIO_LANGS)
assert select([tag], pool) == [(tag, tag)]
def test_full_language_set_selects_every_track_once():
pool = _mk(*REAL_WORLD_AUDIO_LANGS)
pool = mk(*REAL_WORLD_AUDIO_LANGS)
selected = Tracks.by_language(pool, REAL_WORLD_AUDIO_LANGS, per_language=1, exact_match=True)
assert len(selected) == len(REAL_WORLD_AUDIO_LANGS)
assert {t.id for t in selected} == set(REAL_WORLD_AUDIO_LANGS)
+139
View File
@@ -0,0 +1,139 @@
from __future__ import annotations
import inspect
import pytest
from unshackle.commands.dl import dl
from unshackle.core.api import download_manager
from unshackle.core.api.handlers import DEFAULT_DOWNLOAD_PARAMS
from unshackle.core.utilities import missing_required_langs
@pytest.mark.parametrize(
"required,available,expected",
[
(["en"], ["en", "de"], []),
(["en"], ["fr", "de"], ["en"]),
(["en", "fr"], ["en"], ["fr"]),
(["en", "fr"], [], ["en", "fr"]),
([], ["de"], []),
(["en"], ["en-US"], []),
(["es"], ["es-419"], []),
(["zh"], ["zh-Hans"], []),
(["en"], [None], ["en"]),
(["-fr"], ["en"], []),
],
)
def test_missing_required_langs(required, available, expected):
assert missing_required_langs(required, available) == expected
def test_exclusion_token_is_not_a_required_language():
assert missing_required_langs(["en", "-fr"], ["en", "ja"]) == []
assert missing_required_langs(["en", "-fr"], ["ja"]) == ["en"]
def test_orig_resolves_to_the_title_language():
assert missing_required_langs(["orig"], ["ja"], "ja") == []
assert missing_required_langs(["orig"], ["en"], "ja") == ["ja"]
assert missing_required_langs(["orig"], ["en"], None) == []
def test_exact_lang_separates_a_regional_variant_from_its_base():
assert missing_required_langs(["en-US"], ["en-US"], exact=True) == []
assert missing_required_langs(["en-US"], ["en-GB"], exact=True) == ["en-US"]
assert missing_required_langs(["en-US"], ["en-GB"]) == []
def test_all_and_best_tokens_require_nothing():
assert missing_required_langs(["all"], []) == []
assert missing_required_langs(["best"], []) == []
@pytest.mark.parametrize("flag", ["--require-audio", "--require-video", "--best-available", "--warn-only"])
def test_flag_is_registered_on_the_dl_command(flag):
assert any(flag in param.opts for param in dl.cli.params)
@pytest.mark.parametrize(
"flag,expected_param",
[
("--require-audio", "require_audio"),
("--require-video", "require_video"),
("--warn-only", "best_available"),
("--best-available", "best_available"),
],
)
def test_flag_maps_to_its_param_name(flag, expected_param):
param = next(p for p in dl.cli.params if flag in p.opts)
assert param.name == expected_param
@pytest.mark.parametrize("flag", ["--require-audio", "--require-video"])
def test_require_flags_parse_a_comma_list(flag):
param = next(p for p in dl.cli.params if flag in p.opts)
assert param.default == []
assert param.type.convert("en,ja", param, None) == ["en", "ja"]
@pytest.mark.parametrize("key", ["require_audio", "require_video"])
def test_api_passes_the_flags_through(key):
assert DEFAULT_DOWNLOAD_PARAMS[key] == []
assert key in inspect.signature(dl.result).parameters
def test_api_accepts_the_require_flags():
from unshackle.core.api.handlers import validate_download_parameters
assert (
validate_download_parameters(
{"service": "EXAMPLE", "title": "x", "require_audio": ["en"], "require_video": ["en"], "lang": ["en", "fr"]}
)
is None
)
@pytest.mark.parametrize(
"key,default",
[("require_audio", []), ("require_video", []), ("audio_description_only", False), ("forced_subs_only", False)],
)
def test_api_reaches_dl_result(key, default):
assert DEFAULT_DOWNLOAD_PARAMS[key] == default
assert key in inspect.signature(dl.result).parameters
assert f'{key}=params.get("{key}", {default!r})' in inspect.getsource(download_manager)
@pytest.mark.parametrize(
"value",
["en,fr", "en", {"lang": "en"}, [1], ["en", None]],
)
@pytest.mark.parametrize("key", ["require_audio", "require_video"])
def test_api_rejects_a_non_array_require_value(key, value):
from unshackle.core.api.handlers import validate_download_parameters
error = validate_download_parameters({"service": "EXAMPLE", "title": "x", key: value})
assert error == f"{key} must be an array of language strings"
def test_require_subs_no_longer_conflicts_with_s_lang():
from unshackle.core.api.handlers import validate_download_parameters
assert (
validate_download_parameters(
{"service": "EXAMPLE", "title": "x", "s_lang": ["en", "ko", "ja"], "require_subs": ["en"]}
)
is None
)
def test_all_three_require_flags_share_one_gate():
import inspect as _inspect
from unshackle.commands import dl as dl_module
source = _inspect.getsource(dl_module.dl.result)
assert "downloading all available subtitles" not in source
for kind in ("audio", "video", "subtitle"):
assert f'"{kind}",' in source
assert "missing_required_langs(required, available, title.language, exact=exact_lang)" in source
@@ -0,0 +1,62 @@
"""The dl.result call site of missing_required_langs, and inputs the unit tests skip.
The gate in dl.result is not extractable without executing the whole download loop, so
its wiring is pinned the same way test_required_langs pins download_manager: against the
source. The value inputs cover what the helper's own tests leave out — real tracks carry
langcodes.Language objects, not strings.
"""
from __future__ import annotations
import inspect
from langcodes import Language
from unshackle.commands.dl import dl
from unshackle.core.utilities import missing_required_langs
def test_language_objects_satisfy_a_requirement():
assert missing_required_langs(["en"], [Language.get("en")]) == []
assert missing_required_langs(["en"], [Language.get("en-US")]) == []
assert missing_required_langs(["en"], [Language.get("fr")]) == ["en"]
def test_orig_accepts_a_language_object_title_language():
assert missing_required_langs(["orig"], ["ja"], Language.get("ja")) == []
assert missing_required_langs(["orig"], ["en"], Language.get("ja")) == ["ja"]
def test_requirement_checks_the_catalogue_not_the_selection():
assert missing_required_langs(["en"], ["en", "ko", "ja", "fr"]) == []
assert missing_required_langs(["fr"], ["en", "ko", "ja", "fr"]) == []
class TestGateWiring:
"""Pin the dl.result gate's shape; a silent rewire is otherwise invisible to tests."""
source = inspect.getsource(dl.result)
def test_gate_is_disabled_with_the_track_kind(self):
assert "require_audio if keep_audio else []" in self.source
assert "require_video if keep_videos else []" in self.source
def test_gate_counts_audio_embedded_in_kept_video(self):
assert "embedded_audio_langs(title.tracks.videos, keep_videos and not audio_description_only)" in self.source
def test_gate_honours_exact_lang(self):
assert "missing_required_langs(required, available, title.language, exact=exact_lang)" in self.source
def test_gate_reads_tracks_before_the_keep_flags_empty_them(self):
gate = self.source.index("missing_required_langs(required")
reset = self.source.index("if not keep_videos:")
assert gate < reset
def test_require_and_exclude_clash_is_rejected_per_flag(self):
assert "cannot be required and excluded at the same time" in self.source
for pair in (
'("--require-audio", require_audio, audio_excl)',
'("--require-video", require_video, video_excl)',
'("--require-subs", require_subs, s_lang_excl)',
):
assert pair in self.source