chore(release): promote 661be3ee to main

This commit is contained in:
imSp4rky
2026-11-23 19:20:21 -07:00
760 changed files with 74155 additions and 6855 deletions
@@ -15,7 +15,9 @@ from unshackle.core.utilities import find_missing_langs
(["fil"], ["en", "ja"], ["fil"]),
(["fil", "ko"], ["en"], ["fil", "ko"]),
(["es"], ["es-419"], []),
(["es-419"], ["es"], []),
(["es-419"], ["es"], ["es-419"]),
(["es-419"], ["es-MX", "es-ES"], ["es-419"]),
(["en-US"], ["en-GB"], ["en-US"]),
(["en"], ["en-US"], []),
(["all"], [], []),
(["best"], [], []),
@@ -34,7 +36,7 @@ from unshackle.core.utilities import find_missing_langs
(["zh"], ["zh-Hant"], ["zh"]),
(["zh-Hans"], ["zh-Hant"], ["zh-Hans"]),
(["zh-CN"], ["zh-TW"], ["zh-CN"]),
(["zh-HK"], ["zh-Hant"], []),
(["zh-HK"], ["zh-Hant"], ["zh-HK"]),
(["zh"], ["cmn"], []),
(["cmn"], ["zh"], []),
(["zh"], ["yue"], ["zh"]),
@@ -1,24 +0,0 @@
from __future__ import annotations
import pytest
from unshackle.core.utilities import keep_forced_subtitle
@pytest.mark.parametrize(
"forced,language,forced_s_lang,exact,expected",
[
(False, "en", [], False, True),
(False, "de", ["en"], False, True),
(True, "en", [], False, False),
(True, "en", ["en"], False, True),
(True, "en-US", ["en"], False, True),
(True, "de", ["en"], False, False),
(True, "de", ["en", "de"], False, True),
(True, "en-US", ["en"], True, True),
(True, "en", ["en"], True, True),
(True, "es-419", ["es-ES"], True, False),
],
)
def test_keep_forced_subtitle(forced: bool, language: str, forced_s_lang: list[str], exact: bool, expected: bool):
assert keep_forced_subtitle(forced, language, forced_s_lang, exact) is expected
@@ -9,12 +9,16 @@ from __future__ import annotations
import inspect
import logging
from typing import Any, cast
from pathlib import Path
from typing import Any, Optional, cast
import pytest
import requests
from unshackle.commands.dl import dl
from unshackle.core import binaries
from unshackle.core.api.handlers import DEFAULT_DOWNLOAD_PARAMS
from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY
from unshackle.core.service import Service
from unshackle.core.titles import Episode, Series
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
@@ -37,7 +41,7 @@ class Harness(dl):
class FakeService:
"""One episode per entry; ``ad`` adds a descriptive track, ``forced`` a forced subtitle."""
"""One episode per entry; ``ad`` adds a descriptive track, ``forced`` a forced subtitle, ``ko`` Korean audio."""
def __init__(self, episodes: dict[int, dict[str, bool]]) -> None:
self.episodes = episodes
@@ -61,6 +65,8 @@ class FakeService:
tracks.add(
Audio(id_="ad", url="https://x/ad", language="en", codec=Audio.Codec.AAC, bitrate=1, descriptive=True)
)
if kinds.get("ko"):
tracks.add(Audio(id_="ko", url="https://x/ko", language="ko", codec=Audio.Codec.AAC, bitrate=128_000))
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))
@@ -70,19 +76,41 @@ class FakeService:
return []
def __getattr__(self, name: str) -> Any:
if name.startswith("on_"):
if name.startswith(("on_", "get_")):
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)))
def stub_hybrid(monkeypatch: pytest.MonkeyPatch) -> None:
"""Let a hybrid run start without dovi_tool, and load the service's tracks with no probes."""
monkeypatch.setattr(binaries, "DoviTool", Path("/unused/dovi_tool"), raising=False)
monkeypatch.setattr(
"unshackle.commands.dl.load_tracks",
lambda service, title, **_: setattr(title, "tracks", service.get_tracks(title)),
)
def run(
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
episodes: dict,
service: Optional[FakeService] = None,
to_end: bool = False,
**flags: Any,
) -> Any:
"""Return the Selected ids, the exit code, or None for a run that completes; to_end runs past selection."""
if not to_end:
monkeypatch.setattr(Tracks, "tree", lambda self, *a, **k: (_ for _ in ()).throw(Selected(self)))
else:
monkeypatch.setattr("unshackle.commands.dl.download_tracks_in_passes", lambda *a, **k: None)
monkeypatch.setattr("unshackle.core.providers.search_metadata", lambda *a, **k: None)
cmd = Harness.__new__(Harness)
cmd.log = logging.getLogger("test_kind_only")
cmd.service = "FAKE"
cmd.tmdb_searched = True
cmd.completed_files = []
cmd.skipped_titles = []
cmd.skipped_subtitles = []
kwargs: dict[str, Any] = {}
for name, param in inspect.signature(dl.result).parameters.items():
if name in DEFAULT_DOWNLOAD_PARAMS:
@@ -92,12 +120,17 @@ def run(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, episo
kwargs.update(quality=[], vcodec=[], acodec=[], range_=[], wanted=[], cdm_only=None, downloads=1)
kwargs.update(flags)
caplog.set_level(logging.WARNING, logger="test_kind_only")
service = service or FakeService(episodes)
if to_end:
service.session = requests.Session()
try:
cmd.result(cast(Service, FakeService(episodes)), **kwargs)
cmd.result(cast(Service, service), **kwargs)
except Selected as sel:
return sel.ids
except SystemExit as exc:
return exc.code
finally:
DOWNLOAD_LICENCE_ONLY.clear()
return None
@@ -132,6 +165,15 @@ def test_a_single_title_with_no_such_track_exits(
assert "Skipping" not in caplog.text
def test_subs_only_with_no_matching_subtitle_exits_a_single_title_and_skips_in_a_season(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
assert run(monkeypatch, caplog, {1: {}}, subs_only=True, s_lang=["fr"]) == 1
assert run(monkeypatch, caplog, {1: {}, 2: {}}, subs_only=True, s_lang=["fr"]) == 1
assert caplog.text.count("Skipping Show S01E") == 2
assert "Skipping Show S01E02: There's no track left for the selected options." in caplog.text
def test_a_multi_title_run_skips_the_title_and_continues(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
@@ -140,8 +182,171 @@ def test_a_multi_title_run_skips_the_title_and_continues(
assert "Skipping Show S01E01" in caplog.text
def test_a_multi_title_run_with_every_title_skipped_completes(
def test_a_multi_title_run_with_every_title_skipped_fails(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
assert run(monkeypatch, caplog, {1: {}, 2: {}}, forced_subs_only=True) is None
assert run(monkeypatch, caplog, {1: {}, 2: {}}, forced_subs_only=True) == 1
assert caplog.text.count("Skipping Show S01E") == 2
def test_a_required_language_miss_stops_the_run_by_default(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
sink: list[dict] = []
assert run(monkeypatch, caplog, {1: {}, 2: {"ko": True}}, require_audio=["ko"], progress_sink=sink.append) == 1
assert "Skipping" not in caplog.text
assert "Show S01E01: Required audio language(s) not found: ko" in caplog.text
assert not any("skipped_titles" in event for event in sink)
def test_skip_missing_skips_the_title_and_reports_it(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
sink: list[dict] = []
ids = run(
monkeypatch,
caplog,
{1: {}, 2: {"ko": True}},
require_audio=["ko"],
skip_missing=True,
progress_sink=sink.append,
)
assert ids == {"video": ["v"], "audio": ["a"], "subs": ["s"]}
assert "Skipping Show S01E01: Required audio language(s) not found: ko" in caplog.text
assert {"skipped_titles": [{"title": "Show S01E01", "reason": "Required audio language(s) not found: ko"}]} in sink
def test_require_audio_video_and_subs_work_together(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, {1: {}}, require_audio=["en"], require_video=["en"], require_subs=["en"])
assert ids == {"video": ["v"], "audio": ["a"], "subs": ["s"]}
assert run(monkeypatch, caplog, {1: {}}, require_audio=["ko"], require_video=["ko"], require_subs=["ko"]) == 1
assert (
"Required audio language(s) not found: ko; Required video language(s) not found: ko; "
"Required subtitle language(s) not found: ko"
) in caplog.text
assert run(monkeypatch, caplog, {1: {}}, require_audio=["en"], require_video=["ko"], require_subs=["en"]) == 1
assert "Show S01E01: Required video language(s) not found: ko" in caplog.text
def test_skip_missing_skips_a_filter_miss_and_continues(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, {1: {}, 2: {"ko": True}}, a_lang=["ko"], skip_missing=True)
assert ids == {"video": ["v"], "audio": ["ko"], "subs": ["s"]}
assert "Skipping Show S01E01" in caplog.text
def test_skip_missing_still_fails_a_run_that_skips_every_title(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
assert run(monkeypatch, caplog, {1: {}, 2: {}}, require_audio=["ko"], skip_missing=True) == 1
assert "Skipped all 2 titles" in caplog.text
assert run(monkeypatch, caplog, {1: {}}, require_audio=["ko"], skip_missing=True) == 1
class LangService(FakeService):
"""Each episode names its original language and its audio languages; the video is in the original language."""
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=ep["orig"])
for n, ep in self.episodes.items()
)
def get_tracks(self, title: Episode) -> Tracks:
ep = self.episodes[title.number]
tracks = Tracks()
tracks.add(Video(id_="v", url="https://x/v", language=ep["orig"] or "en", codec=Video.Codec.AVC))
for lang in ep["audio"]:
tracks.add(Audio(id_=lang, url=f"https://x/{lang}", language=lang, codec=Audio.Codec.AAC, bitrate=128_000))
return tracks
JA_EN = {"orig": "ja", "audio": ["ja", "en"]}
FR = {"orig": "ja", "audio": ["fr"]}
EVERY = {"orig": "ja", "audio": ["ja", "ko", "en"]}
ORIG_KO_EN = ["orig", "ko", "en"]
@pytest.mark.parametrize(
"first,flags,outcome,logged",
[
(JA_EN, {}, 1, "Show S01E01: ko not found in audio tracks"),
(JA_EN, {"skip_missing": True}, ["ja", "ko", "en"], "Skipping Show S01E01: ko not found in audio tracks"),
({"orig": "ja", "audio": ["ko", "en"]}, {"skip_missing": True}, ["ja", "ko", "en"], "S01E01: orig not found"),
(JA_EN, {"best_available": True}, ["ja", "en"], "ko not found in audio tracks, continuing with: orig, en"),
(FR, {"best_available": True}, 1, "orig, ko, en not found in audio tracks and no fallback available"),
(FR, {"best_available": True, "skip_missing": True}, ["ja", "ko", "en"], "Skipping Show S01E01: orig, ko, en"),
(JA_EN, {"best_available": True, "require_audio": ["ko"]}, 1, "Required audio language(s) not found: ko"),
(
JA_EN,
{"best_available": True, "require_audio": ["ko"], "skip_missing": True},
["ja", "ko", "en"],
"Skipping Show S01E01: Required audio language(s) not found: ko",
),
],
)
def test_several_audio_languages_skip_an_episode_that_misses_one(
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
first: dict,
flags: dict[str, Any],
outcome: Any,
logged: str,
) -> None:
"""-al orig,ko,en on a season where only the second episode has all three."""
episodes = {1: first, 2: EVERY}
result = run(monkeypatch, caplog, episodes, service=LangService(episodes), a_lang=ORIG_KO_EN, **flags)
assert (result if outcome == 1 else result["audio"]) == outcome
assert logged in caplog.text
def test_several_audio_languages_fail_a_season_that_misses_one_everywhere(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
episodes = {1: JA_EN, 2: JA_EN}
assert run(monkeypatch, caplog, episodes, service=LangService(episodes), a_lang=ORIG_KO_EN, skip_missing=True) == 1
assert caplog.text.count("ko not found in audio tracks") == 2
assert "Skipped all 2 titles" in caplog.text
def test_a_partly_skipped_run_completes_and_lists_the_skips(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
episodes = {1: {}, 2: {"ko": True}}
assert run(monkeypatch, caplog, episodes, to_end=True, a_lang=["ko"], skip_missing=True, skip_dl=True) is None
assert "Skipped 1 of 2 titles: Show S01E01" in caplog.text
@pytest.mark.parametrize("no_mux,settled", [(False, 2), (True, 1)])
def test_a_skipped_title_settles_its_post_script_group(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, no_mux: bool, settled: int
) -> None:
"""The season event waits on every title of a group; a skipped title counts as settled, once at count time."""
import unshackle.commands.dl as dl_module
seen: list[str] = []
group = dl_module.post_script_group
monkeypatch.setattr(dl_module, "post_script_group", lambda t: seen.append(str(t)) or group(t))
run(monkeypatch, caplog, {1: {}, 2: {"ko": True}}, a_lang=["ko"], skip_missing=True, no_mux=no_mux)
assert seen.count("Show S01E01") == settled
class LcevcService(FakeService):
"""A 540p base video and the 1080p LCEVC enhancement layer that decodes on top of it."""
def get_tracks(self, title: Episode) -> Tracks:
tracks = super().get_tracks(title)
tracks.videos[0].height = 540
tracks.add(Video(id_="lcevc", url="https://x/l", language="en", codec=Video.Codec.LCEVC, height=1080))
return tracks
def test_an_lcevc_layer_is_left_out_unless_asked_for(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
assert run(monkeypatch, caplog, {1: {}}, service=LcevcService({1: {}}))["video"] == ["v"]
asked = run(monkeypatch, caplog, {1: {}}, service=LcevcService({1: {}}), vcodec=[Video.Codec.LCEVC])
assert asked["video"] == ["lcevc"]
@@ -4,7 +4,7 @@ from typing import Sequence
import pytest
from unshackle.core.utilities import matching_languages
from unshackle.core.utilities import ServiceTag, matching_languages
POOL = ["ar", "en", "en-GB", "en-US", "ja"]
@@ -12,10 +12,25 @@ POOL = ["ar", "en", "en-GB", "en-US", "ja"]
@pytest.mark.parametrize(
("language", "available", "exact", "expected"),
[
("en", POOL, False, {"en", "en-GB", "en-US"}),
("en", POOL, False, {"en"}),
("en", ["en-US", "en-GB"], False, {"en-US"}),
("pt", ["pt-PT", "pt-BR"], False, {"pt-BR"}),
("es", ["es-419", "es-ES"], False, {"es-ES"}),
("es", ["es-419", "es-MX"], False, {"es-419", "es-MX"}),
("es", ["es-419", "es-MX"], True, set()),
("en", POOL, True, {"en"}),
("en-GB", POOL, True, {"en-GB"}),
("zh", ["ar", "cmn", "ja"], True, {"cmn"}),
("en-US", POOL, False, {"en-US"}),
("en-US", ["en", "en-GB"], False, {"en"}),
("en-US", ["en-GB", "en-AU"], False, set()),
("es-419", ["es-419", "es-MX", "es-ES"], False, {"es-419"}),
("es-419", ["es-MX", "es-ES"], False, set()),
("es-419", ["es", "es-ES"], False, set()),
("pt-BR", ["pt", "pt-PT"], False, {"pt"}),
("pt-PT", ["pt", "pt-BR"], False, set()),
("zh-Hant", ["zh-TW", "zh-HK", "zh-Hans"], False, {"zh-TW"}),
("zh-Hant", ["zh-HK", "zh-Hans"], False, {"zh-HK"}),
("en", ["ar", "ja"], False, set()),
("en", [], False, set()),
("en", ["ar", None, "en"], True, {"en"}),
@@ -28,3 +43,23 @@ POOL = ["ar", "en", "en-GB", "en-US", "ja"]
)
def test_matching_languages(language: str, available: Sequence[str], exact: bool, expected: set[str]) -> None:
assert matching_languages(language, available, exact) == expected
@pytest.mark.parametrize(
("title", "available", "expected"),
[
("fr-CA", ["fr-FR", "fr-CA"], {"fr-CA"}),
("en-GB", ["en-US", "en-GB"], {"en-GB"}),
("zh-HK", ["zh-TW", "zh-HK", "zh-CN"], {"zh-HK"}),
("sr-ME", ["sr", "sr-ME"], {"sr-ME"}),
("en-US", ["en-GB", "fr"], {"en-GB"}),
("zh-TW", ["zh-HK", "zh-CN"], {"zh-HK"}),
],
)
def test_a_service_tag_prefers_its_own_variant(title: str, available: Sequence[str], expected: set[str]) -> None:
assert matching_languages(ServiceTag(title), available) == expected
def test_every_variant_returns_each_regional_form_of_a_bare_tag() -> None:
assert matching_languages("es", ["es-419", "es-ES", "en"], every_variant=True) == {"es-419", "es-ES"}
assert matching_languages("es-ES", ["es-419", "es-ES"], every_variant=True) == {"es-ES"}
@@ -27,6 +27,8 @@ class FakeTitle:
(["es"], ["es-ES", "es-419"], ["es-ES"]),
(["es"], ["es-419"], ["es-419"]),
(["fr"], ["fr-CA"], ["fr-CA"]),
(["en-US"], ["en-GB"], ["en-GB"]),
(["zh-HK"], ["zh-Hant", "zh-Hans"], ["zh-Hant"]),
(["zh"], ["cmn"], ["cmn"]),
(["en"], ["ja", "de"], []),
([None], ["en"], []),
@@ -0,0 +1,376 @@
"""Run regional language requests through the real dl.result() selection loop."""
from __future__ import annotations
from typing import Any
import pytest
from langcodes import Language
from tests.lang_selection import test_kind_only_selection as harness
from unshackle.commands.dl import hybrid_plan
from unshackle.core.titles import Episode
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
class RegionalService(harness.FakeService):
"""One episode in `title_lang`, with one video, one audio track per entry of `audio` and the given subtitles."""
def __init__(self, title_lang: str, audio: list[str], subs: list[tuple[str, str]]) -> None:
super().__init__({1: {}})
self.title_lang, self.audio, self.subs = title_lang, audio, subs
def get_titles_cached(self) -> Any:
title = super().get_titles_cached()
for episode in title:
episode.language = Language.get(self.title_lang)
return title
def get_tracks(self, title: Episode) -> Tracks:
tracks = Tracks()
lang = self.audio[0].split(":")[0]
tracks.add(Video(id_="v", url="https://x/v", language=lang, codec=Video.Codec.AVC, range_=Video.Range.SDR))
for entry in self.audio:
lang, _, codec = entry.partition(":")
tracks.add(
Audio(id_=entry, url=f"https://x/{entry}", language=lang, codec=Audio.Codec[codec or "AAC"], bitrate=1)
)
for lang, kind in self.subs:
sdh, forced = kind == "sdh", kind == "forced"
sub_id = f"{lang}{'-' + kind if kind else ''}"
tracks.add(
Subtitle(
id_=sub_id,
url=f"https://x/{sub_id}",
language=lang,
codec=Subtitle.Codec.WebVTT,
sdh=sdh,
forced=forced,
)
)
return tracks
def run(
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
service: RegionalService,
**flags: Any,
) -> Any:
return harness.run(monkeypatch, caplog, {1: {}}, service=service, **flags)
def test_orig_takes_another_region_of_the_title_language(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, RegionalService("en-US", ["en-GB", "fr-FR"], []))
assert ids["audio"] == ["en-GB"]
assert ids["video"] == ["v"]
def test_orig_keeps_the_script_the_title_region_implies(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
ids = run(monkeypatch, caplog, RegionalService("zh-TW", ["zh-HK", "zh-CN"], []))
assert ids["audio"] == ["zh-HK"]
def test_a_regional_audio_request_misses_rather_than_take_a_sibling(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
assert run(monkeypatch, caplog, RegionalService("fr-FR", ["fr-CA"], []), a_lang=["fr-FR"]) == 1
assert "fr-FR not found in audio tracks" in caplog.text
def test_a_regional_sdh_track_is_stripped_when_only_a_sibling_is_plain(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
service = RegionalService("en-US", ["en-US"], [("en-US", "sdh"), ("en-GB", "")])
ids = run(monkeypatch, caplog, service, s_lang=["en-US"])
assert sorted(ids["subs"]) == ["en-US-sdh", "en-US-sdh_stripped"]
def test_a_forced_track_does_not_hide_the_plain_track_a_region_means(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
service = RegionalService("ko", ["ko"], [("es", ""), ("es-ES", "forced"), ("fr", "")])
assert run(monkeypatch, caplog, service, s_lang=["es-ES"])["subs"] == ["es"]
def test_a_bare_sdh_track_is_stripped_when_only_another_variant_is_plain(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
service = RegionalService("en", ["en"], [("en", "sdh"), ("en-GB", "")])
assert sorted(run(monkeypatch, caplog, service, s_lang=["en"])["subs"]) == ["en-sdh", "en-sdh_stripped"]
def test_a_bare_audio_request_takes_the_variant_it_means(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
service = RegionalService("en", ["en", "pt-PT", "pt-BR"], [])
assert run(monkeypatch, caplog, service, a_lang=["pt"])["audio"] == ["pt-BR"]
def test_orig_takes_the_title_variant_over_the_one_a_bare_tag_means(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
assert run(monkeypatch, caplog, RegionalService("fr-CA", ["fr-FR", "fr-CA", "en"], []))["audio"] == ["fr-CA"]
@pytest.mark.parametrize(
("subs", "flags", "expected"),
[
([("en", "forced")], {"s_lang": ["en"], "forced_subs": True}, ["en-forced"]),
([("es", ""), ("es-ES", "forced")], {"s_lang": ["es-ES"], "forced_subs": True}, ["es", "es-ES-forced"]),
([("en-US", ""), ("en", "sdh")], {"s_lang": ["en"]}, ["en-US", "en-sdh"]),
([("es-ES", "forced"), ("es-419", "forced")], {"forced_s_lang": ["es"]}, ["es-ES-forced"]),
(
[("fr", ""), ("es-ES", "forced"), ("es-419", "forced")],
{"s_lang": ["fr"], "forced_s_lang": ["es"]},
["es-ES-forced", "fr"],
),
([("en-GB", ""), ("en-US", "")], {"s_lang": ["orig"]}, ["en-GB"]),
],
)
def test_subtitle_selection(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, subs: list, flags: dict, expected: list
) -> None:
ids = run(monkeypatch, caplog, RegionalService("en-GB", ["ja"], subs), lang=["ja"], **flags)
assert sorted(ids["subs"]) == expected
def test_a_forced_only_language_without_fs_is_reported_missing(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
service = RegionalService("en", ["ja"], [("en", ""), ("es-419", ""), ("es-ES", "forced")])
ids = run(monkeypatch, caplog, service, lang=["ja"], s_lang=["en", "es-ES"])
assert "es-ES not found in subtitle tracks, continuing with: en" in caplog.text
assert ids["subs"] == ["en"]
def test_a_missing_subtitle_language_continues_without_subtitles(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
service = RegionalService("en", ["ja"], [("en", "")])
ids = run(monkeypatch, caplog, service, lang=["ja"], s_lang=["fr"])
assert "fr not found in subtitle tracks, continuing without subtitles" in caplog.text
assert ids["subs"] == []
def test_a_missing_orig_subtitle_is_reported_as_orig(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
service = RegionalService("ja", ["ja"], [("en", "")])
ids = run(monkeypatch, caplog, service, s_lang=["orig", "en"])
assert "orig not found in subtitle tracks, continuing with: en" in caplog.text
assert ids["subs"] == ["en"]
def test_require_subs_fails_on_a_forced_track_that_is_dropped(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
service = RegionalService("ja", ["ja"], [("en", "forced")])
assert run(monkeypatch, caplog, service, require_subs=["en"]) == 1
def test_require_subs_counts_a_forced_track_that_fs_keeps(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
service = RegionalService("ja", ["ja"], [("en", "forced")])
assert run(monkeypatch, caplog, service, require_subs=["en"], forced_subs=True)["subs"] == ["en-forced"]
def test_an_exclusion_removes_every_regional_form(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
service = RegionalService("ja", ["ja", "es-419", "es-ES"], [])
assert run(monkeypatch, caplog, service, a_lang=["all", "-es"])["audio"] == ["ja"]
def test_the_meant_variant_does_not_depend_on_codec(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
service = RegionalService("ja", ["ja", "es-ES:EC3", "es-419"], [])
ids = run(monkeypatch, caplog, service, a_lang=["es"], acodec=[Audio.Codec.AAC, Audio.Codec.EC3])
assert ids["audio"] == ["es-ES:EC3"]
class RegionalVideoService(RegionalService):
"""A RegionalService whose one video is replaced by `videos`: SDR AVC tracks given as (id, language, height, kbps)."""
def __init__(self, title_lang: str, videos: list[tuple[Any, ...]]) -> None:
super().__init__(title_lang, [title_lang], [])
self.videos = videos
def get_tracks(self, title: Episode) -> Tracks:
tracks = super().get_tracks(title)
tracks.videos = [self.video(*row) for row in self.videos]
return tracks
def video(self, *row: Any) -> Video:
id_, lang, height, kbps = row
return Video(
id_=id_,
url=f"https://x/{id_}",
language=lang,
codec=Video.Codec.AVC,
range_=Video.Range.SDR,
width=height * 16 // 9,
height=height,
bitrate=kbps * 1000,
)
MIXED = [("au480", "en-AU", 480, 900), ("gb720", "en-GB", 720, 2000)]
SAME_HEIGHT = [("au720", "en-AU", 720, 900), ("gb720", "en-GB", 720, 2000)]
@pytest.mark.parametrize("request_", [{"v_lang": ["en"]}, {}], ids=["vl-en", "orig"])
@pytest.mark.parametrize(
("videos", "flags", "expected"),
[
(MIXED, {}, "gb720"),
(MIXED, {"quality": [1], "worst": True, "best_available": True}, "au480"),
(SAME_HEIGHT, {"quality": [720]}, "gb720"),
(SAME_HEIGHT, {"quality": [720], "worst": True}, "au720"),
],
ids=["best", "lowest-resolution", "best-at-720", "worst-at-720"],
)
def test_the_regional_forms_of_one_request_rank_as_one_language(
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
videos: list,
flags: dict,
expected: str,
request_: dict,
) -> None:
ids = run(monkeypatch, caplog, RegionalVideoService("en", videos), **request_, **flags)
assert ids["video"] == [expected]
@pytest.mark.parametrize(
("v_lang", "expected"),
[
(["en-AU"], ["au480"]),
(["en-GB", "en-AU"], ["gb720", "au480"]),
(["en-AU", "en-GB"], ["au480", "gb720"]),
(["all"], ["gb720", "au480"]),
],
)
def test_regional_tags_and_several_video_languages_keep_their_selection(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, v_lang: list, expected: list
) -> None:
assert run(monkeypatch, caplog, RegionalVideoService("en", MIXED), v_lang=v_lang)["video"] == expected
@pytest.mark.parametrize(
("flags", "expected"),
[
({"v_lang": ["en", "fr"]}, ["gb720", "fr720"]),
({"v_lang": ["en", "orig"]}, ["gb720"]),
({"v_lang": ["en", "de"], "best_available": True}, ["gb720"]),
],
ids=["two-languages", "orig-is-en", "missing-language-dropped"],
)
def test_each_video_request_gives_one_video_across_its_regional_tags(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, flags: dict, expected: list
) -> None:
service = RegionalVideoService("en", [*MIXED, ("fr720", "fr-FR", 720, 1500)])
assert run(monkeypatch, caplog, service, **flags)["video"] == expected
class HdrRegionalService(RegionalVideoService):
"""A RegionalVideoService of HEVC videos given as (id, language, range, width, height, kbps)."""
def video(self, *row: Any) -> Video:
id_, lang, range_, width, height, kbps = row
return Video(
id_=id_,
url=f"https://x/{id_}",
language=lang,
codec=Video.Codec.HEVC,
range_=Video.Range[range_],
width=width,
height=height,
bitrate=kbps * 1000,
)
class SelectedWithStandalone(harness.Selected):
def __init__(self, tracks: Tracks) -> None:
super().__init__(tracks)
self.ids["standalone"] = [t.id for t in tracks.videos if not t.hybrid_base_only]
def run_hdr(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, videos: list, ranges: list, **flags: Any
) -> Any:
harness.stub_hybrid(monkeypatch)
monkeypatch.setattr(harness, "Selected", SelectedWithStandalone)
service = HdrRegionalService("en", videos)
range_ = [Video.Range[r] for r in ranges]
return run(monkeypatch, caplog, service, quality=[2160], v_lang=["en"], range_=range_, **flags)
def test_hybrid_takes_the_best_dv_source_of_the_lowest_height_across_regional_tags(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
videos = [
("hdr", "en-AU", "HDR10", 3840, 2160, 8000),
("dv-au", "en-AU", "DV", 1920, 1080, 2000),
("dv-gb", "en-GB", "DV", 1920, 1080, 6000),
]
assert run_hdr(monkeypatch, caplog, videos, ["HYBRID"])["video"] == ["hdr", "dv-gb"]
def test_generated_dv_takes_the_best_base_across_regional_tags(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
videos = [("hdr-au", "en-AU", "HDR10", 3840, 1600, 8000), ("hdr-gb", "en-GB", "HDR10", 3840, 2160, 8000)]
assert run_hdr(monkeypatch, caplog, videos, ["HDR10"], generate_dv=True)["video"] == ["hdr-gb"]
@pytest.mark.parametrize(
("videos", "expected"),
[
(
[
("hdr-au", "en-AU", "HDR10", 3840, 1600, 8000),
("hdr-gb", "en-GB", "HDR10", 3840, 2160, 8000),
("dv", "en-AU", "DV", 1920, 1080, 2000),
],
["hdr-gb"],
),
(
[
("hdr10p", "en-AU", "HDR10P", 3840, 2160, 8000),
("hdr-crop", "en-AU", "HDR10", 3840, 1600, 9000),
("dv", "en-AU", "DV", 1920, 1080, 2000),
],
["hdr10p"],
),
],
ids=["regional-tags", "standalone-at-another-height"],
)
def test_a_standalone_range_beside_hybrid_does_not_add_a_hybrid_base(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, videos: list, expected: list
) -> None:
class Planned(BaseException):
def __init__(self, videos: list[Video], generate_dv: bool) -> None:
self.base_ids = [v.id for v in hybrid_plan(videos, generate_dv)[0]]
def stop_at_plan(videos: list[Video], generate_dv: bool) -> None:
raise Planned(videos, generate_dv)
monkeypatch.setattr("unshackle.commands.dl.hybrid_plan", stop_at_plan)
monkeypatch.setattr(Video, "normalize_vui", lambda self: None)
with pytest.raises(Planned) as planned:
run_hdr(monkeypatch, caplog, videos, ["HYBRID", "HDR10"], to_end=True, video_only=True)
assert planned.value.base_ids == expected
def test_the_fallback_from_a_failed_hybrid_ranks_regional_tags_as_one_language(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
videos = [("sdr-au", "en-AU", "SDR", 3840, 2160, 3000), ("sdr-gb", "en-GB", "SDR", 3840, 2160, 9000)]
assert run_hdr(monkeypatch, caplog, videos, ["HYBRID", "SDR"], best_available=True)["video"] == ["sdr-gb"]
+10 -5
View File
@@ -5,8 +5,7 @@ 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.api.handlers import DEFAULT_DOWNLOAD_PARAMS, cast_dl_params
from unshackle.core.utilities import missing_required_langs
@@ -40,10 +39,11 @@ def test_orig_resolves_to_the_title_language():
assert missing_required_langs(["orig"], ["en"], None) == []
def test_exact_lang_separates_a_regional_variant_from_its_base():
def test_a_regional_tag_never_matches_another_region():
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"]) == []
assert missing_required_langs(["en-US"], ["en-GB"]) == ["en-US"]
assert missing_required_langs(["orig"], ["en-GB"], "en-US") == []
def test_all_and_best_tokens_require_nothing():
@@ -101,7 +101,7 @@ def test_api_accepts_the_require_flags():
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)
assert cast_dl_params(dl.cli, {})[key] == default
@pytest.mark.parametrize(
@@ -137,3 +137,8 @@ def test_all_three_require_flags_share_one_gate():
for kind in ("audio", "video", "subtitle"):
assert f'"{kind}",' in source
assert "missing_required_langs(required, available, title.language, exact=exact_lang)" in source
def test_exact_lang_turns_off_the_bare_tag_fallback():
assert missing_required_langs(["en"], ["en-GB"]) == []
assert missing_required_langs(["en"], ["en-GB"], exact=True) == ["en"]
@@ -5,7 +5,7 @@ from typing import Optional, Sequence
import pytest
from langcodes import Language
from unshackle.core.utilities import resolve_sort_langs
from unshackle.core.utilities import ServiceTag, resolve_sort_langs
@pytest.mark.parametrize(
@@ -14,6 +14,7 @@ from unshackle.core.utilities import resolve_sort_langs
(["orig", "en", "es"], "ja", ["ja", "en", "es"]),
(["orig", "en", "es"], None, ["en", "es"]),
(["orig"], Language.get("pt-BR"), ["pt-BR"]),
(["orig"], "zh-Hant-TW", ["zh-Hant-TW"]),
(["en", "orig"], "en", ["en"]),
(["en", "es", "en", "fr"], None, ["en", "es", "fr"]),
(["all", "best", "en"], "ja", ["all", "best", "en"]),
@@ -22,3 +23,8 @@ from unshackle.core.utilities import resolve_sort_langs
)
def test_resolve_sort_langs(tokens: Sequence[str], original: Optional[str], expected: list[str]) -> None:
assert resolve_sort_langs(tokens, original) == expected
def test_orig_is_a_service_tag_outside_exact_mode() -> None:
assert isinstance(resolve_sort_langs(["orig"], "pt-BR")[0], ServiceTag)
assert not isinstance(resolve_sort_langs(["orig"], "pt-BR", exact=True)[0], ServiceTag)