refactor(core)!: drop leading underscores from internal definitions

Renames 314 defs and 41 module/class-level constants. Keeps 11 names underscored where the stripped form collides in scope, plus 5.5.0 shims for the three symbols external service repos call.
This commit is contained in:
imSp4rky
2026-08-15 22:07:41 -06:00
parent db4f0b39f9
commit 21d5f1c5e1
116 changed files with 1671 additions and 1492 deletions
+3 -3
View File
@@ -50,7 +50,7 @@ def _provider(monkeypatch: pytest.MonkeyPatch, body: dict) -> tuple[AniListProvi
@pytest.fixture(autouse=True)
def _default_title_language(monkeypatch: pytest.MonkeyPatch) -> None:
def default_title_language(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "anilist_title_language", "english")
@@ -263,12 +263,12 @@ def test_the_provider_needs_no_api_key() -> None:
def test_a_cached_node_rebuilds_with_the_read_time_title_language(monkeypatch: pytest.MonkeyPatch) -> None:
"""The raw node is cached; which title variant it yields follows the config at read time."""
from unshackle.core.providers import _cached_to_result
from unshackle.core.providers import cached_to_result
node = {**ONE_PIECE, "title": {"romaji": "WAN PIISU", "english": "One Piece", "native": "ワンピース"}}
monkeypatch.setattr(config, "anilist_title_language", "native")
result = _cached_to_result(node, "anilist", "tv")
result = cached_to_result(node, "anilist", "tv")
assert result is not None
assert result.title == "ワンピース"
+7 -7
View File
@@ -24,7 +24,7 @@ from unshackle.core.cdm.detect import (
is_remote_widevine_cdm,
is_widevine_cdm,
)
from unshackle.core.cdm.loader import _stamp_remote
from unshackle.core.cdm.loader import stamp_remote
pytestmark = pytest.mark.unit
@@ -125,7 +125,7 @@ def test_custom_remote_cdm_classification(device, expect_pr):
def test_stamp_remote_sets_attrs_and_returns_same_object():
obj = SimpleNamespace()
out = _stamp_remote(obj, "playready")
out = stamp_remote(obj, "playready")
assert out is obj
assert obj.drm == "playready"
assert obj.is_remote_cdm is True
@@ -136,14 +136,14 @@ def test_stamp_remote_is_best_effort_on_unsettable_object():
__slots__ = ()
obj = Slotted()
out = _stamp_remote(obj, "widevine") # must not raise
out = stamp_remote(obj, "widevine") # must not raise
assert out is obj
assert not hasattr(obj, "drm")
def test_load_remote_decryptlabs_playready_is_stamped():
cdm_api = {"name": "dl-pr", "type": "decrypt_labs", "secret": "x", "device_name": "SL3000"}
cdm = loader_mod._load_remote_cdm(dict(cdm_api), "dl-pr", "AMZN", None)
cdm = loader_mod.load_remote_cdm(dict(cdm_api), "dl-pr", "AMZN", None)
assert cdm.drm == "playready"
assert cdm.is_remote_cdm is True
assert is_remote_playready_cdm(cdm)
@@ -151,7 +151,7 @@ def test_load_remote_decryptlabs_playready_is_stamped():
def test_load_remote_decryptlabs_widevine_is_stamped():
cdm_api = {"name": "dl-wv", "type": "decrypt_labs", "secret": "x", "device_name": "ChromeCDM"}
cdm = loader_mod._load_remote_cdm(dict(cdm_api), "dl-wv", "AMZN", None)
cdm = loader_mod.load_remote_cdm(dict(cdm_api), "dl-wv", "AMZN", None)
assert cdm.drm == "widevine"
assert is_remote_widevine_cdm(cdm)
@@ -165,7 +165,7 @@ def test_load_remote_native_playready_is_stamped(monkeypatch):
monkeypatch.setattr(prmod, "RemoteCdm", FakePlayReadyRemote)
cdm_api = {"name": "pr", "Device Type": "PLAYREADY", "host": "h", "secret": "s", "device_name": "d"}
cdm = loader_mod._load_remote_cdm(dict(cdm_api), "pr", "AMZN", None)
cdm = loader_mod.load_remote_cdm(dict(cdm_api), "pr", "AMZN", None)
assert isinstance(cdm, FakePlayReadyRemote)
assert cdm.drm == "playready"
assert cdm.is_remote_cdm is True
@@ -181,7 +181,7 @@ def test_load_remote_native_widevine_is_stamped(monkeypatch):
monkeypatch.setattr(wvmod, "RemoteCdm", FakeWidevineRemote)
cdm_api = {"name": "wv", "Device Type": "ANDROID", "host": "h", "secret": "s", "device_name": "d"}
cdm = loader_mod._load_remote_cdm(dict(cdm_api), "wv", "AMZN", None)
cdm = loader_mod.load_remote_cdm(dict(cdm_api), "wv", "AMZN", None)
assert isinstance(cdm, FakeWidevineRemote)
assert cdm.drm == "widevine"
assert is_remote_widevine_cdm(cdm)
+5 -5
View File
@@ -88,7 +88,7 @@ def test_warns_once_per_instance(tmp_path, caplog) -> None:
assert len(warnings) == 1
def _data_key(raw: bytes, base64_encoded: bool = True) -> Key:
def data_key(raw: bytes, base64_encoded: bool = True) -> Key:
if base64_encoded:
uri = "data:text/plain;base64," + base64.b64encode(raw).decode("ascii")
else:
@@ -97,24 +97,24 @@ def _data_key(raw: bytes, base64_encoded: bool = True) -> Key:
def test_data_uri_key_decodes_and_validates_length() -> None:
drm = ClearKey.from_m3u_key(_data_key(KEY))
drm = ClearKey.from_m3u_key(data_key(KEY))
assert drm.key == KEY
def test_data_uri_key_wrong_length_rejected() -> None:
with pytest.raises(ValueError, match="Unexpected Length"):
ClearKey.from_m3u_key(_data_key(b"\x00" * 8))
ClearKey.from_m3u_key(data_key(b"\x00" * 8))
def test_raw_data_uri_key_materialises_and_validates() -> None:
# A raw (non-base64) data: payload must be taken as literal key bytes, not hex-parsed.
drm = ClearKey.from_m3u_key(_data_key(KEY, base64_encoded=False))
drm = ClearKey.from_m3u_key(data_key(KEY, base64_encoded=False))
assert drm.key == KEY
def test_raw_data_uri_key_wrong_length_rejected() -> None:
with pytest.raises(ValueError, match="Unexpected Length"):
ClearKey.from_m3u_key(_data_key(b"\x01" * 8, base64_encoded=False))
ClearKey.from_m3u_key(data_key(b"\x01" * 8, base64_encoded=False))
def test_data_uri_split_tolerates_commas_in_payload() -> None:
+1 -1
View File
@@ -70,5 +70,5 @@ def test_unreadable_source_yields_empty_string() -> None:
def test_unwalkable_source_yields_empty_string(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""A dir os.walk cannot enter must yield "", not a valid-looking hash of fewer files."""
(tmp_path / "__main__.py").write_bytes(b"")
monkeypatch.setattr(unshackle.core, "_PKG", tmp_path)
monkeypatch.setattr(unshackle.core, "PKG", tmp_path)
assert code_hash() == ""
+1 -1
View File
@@ -35,7 +35,7 @@ class FakeProvider(MetadataProvider):
@pytest.fixture(autouse=True)
def _disabled(monkeypatch: pytest.MonkeyPatch) -> None:
def disabled(monkeypatch: pytest.MonkeyPatch) -> None:
"""Turn metadata off and keep every test off the network."""
monkeypatch.setattr(config, "disable_metadata", True)
monkeypatch.setattr(config, "metadata_providers", [])
+1 -1
View File
@@ -47,7 +47,7 @@ def count_mode(monkeypatch):
def ctx(language, languages) -> dict:
return make_movie(language)._build_base_template_context(make_media_info(languages))
return make_movie(language).build_base_template_context(make_media_info(languages))
def test_strict_dual_with_original(strict_mode):
+13 -13
View File
@@ -90,15 +90,15 @@ def test_old_cache_entry_reads_as_absolute_less():
def test_absolute_token_is_three_wide(reset_template):
assert make_episode(absolute=7)._build_template_context(StubMediaInfo())["absolute"] == "007"
assert make_episode(absolute=7).build_template_context(StubMediaInfo())["absolute"] == "007"
def test_absolute_token_does_not_truncate_past_three_digits(reset_template):
assert make_episode(absolute=1042)._build_template_context(StubMediaInfo())["absolute"] == "1042"
assert make_episode(absolute=1042).build_template_context(StubMediaInfo())["absolute"] == "1042"
def test_absolute_token_is_empty_without_a_value(reset_template):
assert make_episode()._build_template_context(StubMediaInfo())["absolute"] == ""
assert make_episode().build_template_context(StubMediaInfo())["absolute"] == ""
def test_filename_renders_the_absolute_number(reset_template):
@@ -112,7 +112,7 @@ def test_optional_absolute_token_drops_out(reset_template):
def test_absolute_is_a_known_template_variable(reset_template, recwarn):
reset_template._validate_output_templates()
reset_template.validate_output_templates()
assert not [w for w in recwarn.list if "absolute" in str(w.message)]
@@ -139,7 +139,7 @@ class _FakeProvider:
return self.mapping
def _fill(
def fill(
monkeypatch: pytest.MonkeyPatch, episodes: list, mapping: dict, tvdb_id=73871, provider=True, order="official"
):
from unshackle.commands.dl import dl
@@ -163,7 +163,7 @@ MAPPING = {(1, 1): (1, 1, "One"), (1, 2): (1, 2, "Two"), (2, 1): (1, 3, "Three")
def test_fill_populates_missing_absolute_numbers(monkeypatch: pytest.MonkeyPatch) -> None:
episodes = [make_episode(season=1, number=1), make_episode(season=1, number=2), make_episode(season=2, number=1)]
titles, fake, _ = _fill(monkeypatch, episodes, MAPPING)
titles, fake, _ = fill(monkeypatch, episodes, MAPPING)
assert [t.absolute for t in titles] == [1, 2, 3]
assert fake.orders == ["absolute"]
@@ -171,45 +171,45 @@ def test_fill_populates_missing_absolute_numbers(monkeypatch: pytest.MonkeyPatch
def test_a_service_already_in_absolute_order_fills_from_its_own_numbers(monkeypatch: pytest.MonkeyPatch) -> None:
"""get_order_map returns {} for the same-order case; the numbers are their own fill."""
episodes = [make_episode(season=1, number=26), make_episode(season=1, number=27)]
titles, fake, _ = _fill(monkeypatch, episodes, {}, order="absolute")
titles, fake, _ = fill(monkeypatch, episodes, {}, order="absolute")
assert [t.absolute for t in titles] == [26, 27]
assert fake.orders == []
def test_fill_never_touches_season_or_number(monkeypatch: pytest.MonkeyPatch) -> None:
episodes = [make_episode(season=2, number=1)]
titles, _, _ = _fill(monkeypatch, episodes, MAPPING)
titles, _, _ = fill(monkeypatch, episodes, MAPPING)
assert [(t.season, t.number) for t in titles] == [(2, 1)]
def test_a_service_set_absolute_number_wins(monkeypatch: pytest.MonkeyPatch) -> None:
episodes = [make_episode(season=1, number=1, absolute=99), make_episode(season=1, number=2)]
titles, _, _ = _fill(monkeypatch, episodes, MAPPING)
titles, _, _ = fill(monkeypatch, episodes, MAPPING)
assert [t.absolute for t in titles] == [99, 2]
def test_an_unmapped_episode_keeps_no_absolute_number(monkeypatch: pytest.MonkeyPatch) -> None:
episodes = [make_episode(season=9, number=9)]
titles, _, _ = _fill(monkeypatch, episodes, MAPPING)
titles, _, _ = fill(monkeypatch, episodes, MAPPING)
assert titles[0].absolute is None
def test_fill_skips_silently_without_an_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
episodes = [make_episode(season=1, number=1)]
titles, _, logged = _fill(monkeypatch, episodes, MAPPING, provider=False)
titles, _, logged = fill(monkeypatch, episodes, MAPPING, provider=False)
assert titles[0].absolute is None
assert [level for level, _ in logged] == ["debug"]
def test_fill_skips_silently_without_a_tvdb_id(monkeypatch: pytest.MonkeyPatch) -> None:
episodes = [make_episode(season=1, number=1)]
titles, _, logged = _fill(monkeypatch, episodes, MAPPING, tvdb_id=None)
titles, _, logged = fill(monkeypatch, episodes, MAPPING, tvdb_id=None)
assert titles[0].absolute is None
assert [level for level, _ in logged] == ["debug"]
def test_fill_skips_silently_when_tvdb_has_no_absolute_order(monkeypatch: pytest.MonkeyPatch) -> None:
episodes = [make_episode(season=1, number=1)]
titles, _, logged = _fill(monkeypatch, episodes, {})
titles, _, logged = fill(monkeypatch, episodes, {})
assert titles[0].absolute is None
assert [level for level, _ in logged] == ["debug"]
+7 -7
View File
@@ -47,7 +47,7 @@ def reset_template():
def test_air_date_replaces_season_episode_dotted(reset_template):
ep = make_episode(air_date=date(2024, 6, 30))
ctx = ep._build_template_context(StubMediaInfo())
ctx = ep.build_template_context(StubMediaInfo())
assert ctx["season_episode"] == "2024.06.30"
assert ctx["season"] == "2024.06.30"
assert ctx["episode"] == ""
@@ -58,19 +58,19 @@ def test_air_date_replaces_season_episode_dotted(reset_template):
def test_air_date_uses_space_separator(reset_template):
reset_template.output_template = {"series": "{title} {season_episode} {quality}-{tag}"}
ep = make_episode(air_date=date(2024, 6, 30))
assert ep._build_template_context(StubMediaInfo())["season_episode"] == "2024 06 30"
assert ep.build_template_context(StubMediaInfo())["season_episode"] == "2024 06 30"
def test_iso_string_air_date_coerced(reset_template):
ep = make_episode(air_date="2024-06-30")
assert isinstance(ep.air_date, date)
assert ep._build_template_context(StubMediaInfo())["season_episode"] == "2024.06.30"
assert ep.build_template_context(StubMediaInfo())["season_episode"] == "2024.06.30"
def test_year_always_dropped_in_file_when_dated(reset_template):
"""The air date is the sole date in the filename; a distinct year is dropped too (deterministic)."""
ep = make_episode(year=2010, air_date=date(2013, 10, 30))
ctx = ep._build_template_context(StubMediaInfo())
ctx = ep.build_template_context(StubMediaInfo())
assert ctx["year"] == ""
assert ctx["season_episode"] == "2013.10.30"
@@ -78,7 +78,7 @@ def test_year_always_dropped_in_file_when_dated(reset_template):
def test_yearless_title_takes_year_from_date(reset_template):
"""A title with no year still names cleanly; the date supplies the year."""
ep = make_episode(year=None, air_date=date(2026, 6, 28))
ctx = ep._build_template_context(StubMediaInfo())
ctx = ep.build_template_context(StubMediaInfo())
assert ctx["year"] == ""
assert ctx["season_episode"] == "2026.06.28"
@@ -87,13 +87,13 @@ def test_datetime_normalized_to_date(reset_template):
"""A datetime (subclass of date) must not leak its time into the {date} token."""
ep = make_episode(air_date=datetime(2024, 6, 30, 13, 0, 0))
assert type(ep.air_date) is date
assert ep._build_template_context(StubMediaInfo())["date"] == "2024-06-30"
assert ep.build_template_context(StubMediaInfo())["date"] == "2024-06-30"
def test_no_air_date_is_unchanged(reset_template):
"""Regression: without air_date, naming is exactly as before (presentation-only field)."""
ep = make_episode()
ctx = ep._build_template_context(StubMediaInfo())
ctx = ep.build_template_context(StubMediaInfo())
assert ctx["season_episode"] == "S2024E181"
assert ctx["season"] == "S2024"
assert ctx["episode"] == "E181"
+2 -2
View File
@@ -144,7 +144,7 @@ def test_spaced_template_uses_spaces(reset_template):
def test_template_context_leaves_the_season_token_alone(reset_template):
ctx = make_episode(part=2)._build_template_context(StubMediaInfo())
ctx = make_episode(part=2).build_template_context(StubMediaInfo())
assert ctx["season"] == "S01"
assert ctx["episode"] == "E01.Part.2"
assert ctx["season_episode"] == "S01E01.Part.2"
@@ -152,7 +152,7 @@ def test_template_context_leaves_the_season_token_alone(reset_template):
def test_part_token_is_empty_without_a_part(reset_template):
assert make_episode()._build_template_context(StubMediaInfo())["part"] == ""
assert make_episode().build_template_context(StubMediaInfo())["part"] == ""
def test_parts_share_one_season_folder(reset_template):
+17 -17
View File
@@ -39,7 +39,7 @@ class _FakeProvider:
return self.episodes
def _fill(
def fill(
monkeypatch: pytest.MonkeyPatch,
titles: list,
episodes: list,
@@ -74,93 +74,93 @@ LISTING = [tvdb_episode(1, 1, "2026-08-10"), tvdb_episode(1, 2, "2026-08-11")]
def test_fill_populates_missing_air_dates(monkeypatch: pytest.MonkeyPatch) -> None:
episodes = [make_episode(number=1), make_episode(number=2)]
series, logged = _fill(monkeypatch, episodes, LISTING)
series, logged = fill(monkeypatch, episodes, LISTING)
assert [t.air_date for t in series] == [date(2026, 8, 10), date(2026, 8, 11)]
assert [level for level, _ in logged] == ["info"]
def test_a_service_set_air_date_wins(monkeypatch: pytest.MonkeyPatch) -> None:
episodes = [make_episode(number=1, air_date="1999-01-02"), make_episode(number=2)]
series, _ = _fill(monkeypatch, episodes, LISTING)
series, _ = fill(monkeypatch, episodes, LISTING)
assert [t.air_date for t in series] == [date(1999, 1, 2), date(2026, 8, 11)]
def test_fill_never_touches_season_or_number(monkeypatch: pytest.MonkeyPatch) -> None:
series, _ = _fill(monkeypatch, [make_episode(number=2)], LISTING)
series, _ = fill(monkeypatch, [make_episode(number=2)], LISTING)
assert [(t.season, t.number) for t in series] == [(1, 2)]
def test_an_unmapped_episode_keeps_no_air_date(monkeypatch: pytest.MonkeyPatch) -> None:
series, _ = _fill(monkeypatch, [make_episode(season=9, number=9)], LISTING)
series, _ = fill(monkeypatch, [make_episode(season=9, number=9)], LISTING)
assert series[0].air_date is None
@pytest.mark.parametrize("aired", [None, "", "not-a-date", "2026-13-40"])
def test_an_unusable_aired_value_is_skipped(monkeypatch: pytest.MonkeyPatch, aired) -> None:
series, _ = _fill(monkeypatch, [make_episode(number=1)], [tvdb_episode(1, 1, aired)])
series, _ = fill(monkeypatch, [make_episode(number=1)], [tvdb_episode(1, 1, aired)])
assert series[0].air_date is None
def test_a_pre_1970_date_is_skipped(monkeypatch: pytest.MonkeyPatch) -> None:
series, _ = _fill(monkeypatch, [make_episode(number=1)], [tvdb_episode(1, 1, "1900-01-01")])
series, _ = fill(monkeypatch, [make_episode(number=1)], [tvdb_episode(1, 1, "1900-01-01")])
assert series[0].air_date is None
def test_a_future_placeholder_date_is_skipped(monkeypatch: pytest.MonkeyPatch) -> None:
future = (date.today() + timedelta(days=30)).isoformat()
series, _ = _fill(monkeypatch, [make_episode(number=1)], [tvdb_episode(1, 1, future)])
series, _ = fill(monkeypatch, [make_episode(number=1)], [tvdb_episode(1, 1, future)])
assert series[0].air_date is None
def test_tomorrow_still_fills(monkeypatch: pytest.MonkeyPatch) -> None:
tomorrow = date.today() + timedelta(days=1)
series, _ = _fill(monkeypatch, [make_episode(number=1)], [tvdb_episode(1, 1, tomorrow.isoformat())])
series, _ = fill(monkeypatch, [make_episode(number=1)], [tvdb_episode(1, 1, tomorrow.isoformat())])
assert series[0].air_date == tomorrow
def test_a_datetime_stamped_aired_value_keeps_the_date(monkeypatch: pytest.MonkeyPatch) -> None:
series, _ = _fill(monkeypatch, [make_episode(number=1)], [tvdb_episode(1, 1, "2026-08-10T20:00:00Z")])
series, _ = fill(monkeypatch, [make_episode(number=1)], [tvdb_episode(1, 1, "2026-08-10T20:00:00Z")])
assert series[0].air_date == date(2026, 8, 10)
def test_fill_skips_silently_without_an_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
series, logged = _fill(monkeypatch, [make_episode(number=1)], LISTING, provider=False)
series, logged = fill(monkeypatch, [make_episode(number=1)], LISTING, provider=False)
assert series[0].air_date is None
assert [level for level, _ in logged] == ["debug"]
def test_fill_skips_silently_without_a_tvdb_id(monkeypatch: pytest.MonkeyPatch) -> None:
series, logged = _fill(monkeypatch, [make_episode(number=1)], LISTING, tvdb_id=None)
series, logged = fill(monkeypatch, [make_episode(number=1)], LISTING, tvdb_id=None)
assert series[0].air_date is None
assert [level for level, _ in logged] == ["debug"]
def test_fill_skips_silently_when_tvdb_lists_no_episodes(monkeypatch: pytest.MonkeyPatch) -> None:
series, logged = _fill(monkeypatch, [make_episode(number=1)], [])
series, logged = fill(monkeypatch, [make_episode(number=1)], [])
assert series[0].air_date is None
assert [level for level, _ in logged] == ["debug"]
def test_nothing_is_filled_when_no_title_is_daily(monkeypatch: pytest.MonkeyPatch) -> None:
series, logged = _fill(monkeypatch, [make_episode(number=1)], LISTING, daily=False)
series, logged = fill(monkeypatch, [make_episode(number=1)], LISTING, daily=False)
assert series[0].air_date is None
assert logged == []
def test_the_service_daily_flag_fills_without_the_cli_flag(monkeypatch: pytest.MonkeyPatch) -> None:
series, _ = _fill(monkeypatch, [make_episode(number=1)], LISTING, daily=False, service_daily=True)
series, _ = fill(monkeypatch, [make_episode(number=1)], LISTING, daily=False, service_daily=True)
assert series[0].air_date == date(2026, 8, 10)
def test_a_per_title_daily_false_is_skipped_while_others_fill(monkeypatch: pytest.MonkeyPatch) -> None:
first, second = make_episode(number=1), make_episode(number=2)
first.daily = False
series, _ = _fill(monkeypatch, [first, second], LISTING, daily=False, service_daily=True)
series, _ = fill(monkeypatch, [first, second], LISTING, daily=False, service_daily=True)
assert [t.air_date for t in series] == [None, date(2026, 8, 11)]
def test_the_cli_flag_overrides_a_per_title_daily_false(monkeypatch: pytest.MonkeyPatch) -> None:
episode = make_episode(number=1)
episode.daily = False
series, _ = _fill(monkeypatch, [episode], LISTING, daily=True)
series, _ = fill(monkeypatch, [episode], LISTING, daily=True)
assert series[0].air_date == date(2026, 8, 10)
+17 -17
View File
@@ -18,7 +18,7 @@ class _Response:
return self._payload
def _node(
def node(
imdb_id: str = "tt3581920",
text: str = "The Last of Us",
year: Optional[int] = 2023,
@@ -67,14 +67,14 @@ def test_is_available_without_any_key() -> None:
def test_cache_hit_uses_one_get(monkeypatch: pytest.MonkeyPatch) -> None:
p, session = _provider(monkeypatch, [{"data": {"title": _node()}}])
p, session = _provider(monkeypatch, [{"data": {"title": node()}}])
result = p.get_by_id("tt3581920", "tv")
assert result is not None and result.title == "The Last of Us"
assert len(session.gets) == 1 and session.posts == []
def test_persisted_query_miss_falls_back_to_one_post(monkeypatch: pytest.MonkeyPatch) -> None:
p, session = _provider(monkeypatch, [NOT_FOUND, {"data": {"title": _node()}}])
p, session = _provider(monkeypatch, [NOT_FOUND, {"data": {"title": node()}}])
result = p.get_by_id("tt3581920", "tv")
assert result is not None and result.external_ids.imdb_id == "tt3581920"
assert len(session.gets) == 1 and len(session.posts) == 1
@@ -86,14 +86,14 @@ def test_persisted_query_miss_falls_back_to_one_post(monkeypatch: pytest.MonkeyP
def test_get_params_carry_no_spaces(monkeypatch: pytest.MonkeyPatch) -> None:
"""IMDb's GraphQL gateway decodes "+" literally, so spaced JSON would come back as a 400."""
p, session = _provider(monkeypatch, [{"data": {"title": _node()}}])
p, session = _provider(monkeypatch, [{"data": {"title": node()}}])
p.get_by_id("tt3581920", "tv")
assert " " not in session.gets[0]["extensions"]
assert " " not in session.gets[0]["variables"]
def test_get_by_id_maps_every_field(monkeypatch: pytest.MonkeyPatch) -> None:
p, _ = _provider(monkeypatch, [{"data": {"title": _node()}}])
p, _ = _provider(monkeypatch, [{"data": {"title": node()}}])
result = p.get_by_id("tt3581920", "tv")
assert result is not None
assert (result.title, result.year, result.kind) == ("The Last of Us", 2023, "tv")
@@ -105,7 +105,7 @@ def test_get_by_id_maps_every_field(monkeypatch: pytest.MonkeyPatch) -> None:
@pytest.mark.parametrize("title_type", ["movie", "tvSeries", "videoGame"])
def test_caller_kind_wins_over_the_response_title_type(monkeypatch: pytest.MonkeyPatch, title_type: str) -> None:
"""kind stays the caller's, so it cannot desync from the tmdb_kind resolve_by_ids seeds."""
p, _ = _provider(monkeypatch, [{"data": {"title": _node(title_type=title_type)}}])
p, _ = _provider(monkeypatch, [{"data": {"title": node(title_type=title_type)}}])
result = p.get_by_id("tt1375666", "tv")
assert result is not None and result.kind == "tv"
@@ -116,12 +116,12 @@ def test_get_by_id_returns_none_on_no_answer(monkeypatch: pytest.MonkeyPatch, pa
assert p.get_by_id("tt3581920", "tv") is None
def _edges(*nodes: dict) -> dict:
def edges(*nodes: dict) -> dict:
return {"data": {"advancedTitleSearch": {"edges": [{"node": {"title": n}} for n in nodes]}}}
def test_search_uses_its_own_operation_and_one_get_on_a_cache_hit(monkeypatch: pytest.MonkeyPatch) -> None:
p, session = _provider(monkeypatch, [_edges(_node())])
p, session = _provider(monkeypatch, [edges(node())])
result = p.search("The Last of Us", 2023, "tv")
assert result is not None and result.external_ids.imdb_id == "tt3581920"
assert session.gets[0]["operationName"] == "UnshackleTitleSearch"
@@ -129,7 +129,7 @@ def test_search_uses_its_own_operation_and_one_get_on_a_cache_hit(monkeypatch: p
def test_search_query_text_carries_the_constraints(monkeypatch: pytest.MonkeyPatch) -> None:
p, session = _provider(monkeypatch, [NOT_FOUND, _edges(_node())])
p, session = _provider(monkeypatch, [NOT_FOUND, edges(node())])
p.search("The Last of Us", 2023, "tv")
query = session.posts[0]["query"]
assert 'searchTerm: "The Last of Us"' in query
@@ -138,7 +138,7 @@ def test_search_query_text_carries_the_constraints(monkeypatch: pytest.MonkeyPat
def test_search_omits_the_year_range_when_unknown(monkeypatch: pytest.MonkeyPatch) -> None:
p, session = _provider(monkeypatch, [NOT_FOUND, _edges(_node(title_type="movie"))])
p, session = _provider(monkeypatch, [NOT_FOUND, edges(node(title_type="movie"))])
p.search("Inception", None, "movie")
query = session.posts[0]["query"]
assert "releaseDateConstraint" not in query
@@ -146,26 +146,26 @@ def test_search_omits_the_year_range_when_unknown(monkeypatch: pytest.MonkeyPatc
def test_search_picks_the_closest_title_not_the_first(monkeypatch: pytest.MonkeyPatch) -> None:
noise = _node(imdb_id="tt27478132", text="Making of: The Last of Us")
exact = _node()
p, _ = _provider(monkeypatch, [_edges(noise, exact)])
noise = node(imdb_id="tt27478132", text="Making of: The Last of Us")
exact = node()
p, _ = _provider(monkeypatch, [edges(noise, exact)])
result = p.search("The Last of Us", 2023, "tv")
assert result is not None and result.external_ids.imdb_id == "tt3581920"
def test_search_rejects_a_title_that_is_not_a_close_match(monkeypatch: pytest.MonkeyPatch) -> None:
p, _ = _provider(monkeypatch, [_edges(_node(imdb_id="tt999", text="Something Else Entirely"))])
p, _ = _provider(monkeypatch, [edges(node(imdb_id="tt999", text="Something Else Entirely"))])
assert p.search("The Last of Us", 2023, "tv") is None
def test_search_survives_a_null_language_block(monkeypatch: pytest.MonkeyPatch) -> None:
p, _ = _provider(monkeypatch, [_edges(_node(languages=None))])
p, _ = _provider(monkeypatch, [edges(node(languages=None))])
result = p.search("The Last of Us", 2023, "tv")
assert result is not None and result.original_language is None
def test_search_returns_none_when_nothing_comes_back(monkeypatch: pytest.MonkeyPatch) -> None:
p, _ = _provider(monkeypatch, [_edges()])
p, _ = _provider(monkeypatch, [edges()])
assert p.search("The Last of Us", 2023, "tv") is None
@@ -174,7 +174,7 @@ def test_escape_graphql_closes_the_string_injection() -> None:
def test_search_term_with_a_quote_stays_inside_the_string(monkeypatch: pytest.MonkeyPatch) -> None:
p, session = _provider(monkeypatch, [NOT_FOUND, _edges(_node(text='The "Best" Show'))])
p, session = _provider(monkeypatch, [NOT_FOUND, edges(node(text='The "Best" Show'))])
p.search('The "Best" Show', None, "tv")
assert 'searchTerm: "The \\"Best\\" Show"' in session.posts[0]["query"]
+55
View File
@@ -0,0 +1,55 @@
"""ProtectionHeader SystemID parsing.
MS-SSTR manifests commonly write the GUID in registry format
("{EDEF8BA9-...}"); a bare-GUID comparison silently drops the DRM.
"""
from __future__ import annotations
from uuid import UUID
import pytest
from pywidevine import PSSH
from unshackle.core.drm import Widevine
from unshackle.core.manifests.ism import ISM
WIDEVINE_PSSH_B64 = PSSH.new(key_ids=["00112233445566778899aabbccddeeff"], system_id=PSSH.SystemId.Widevine).dumps()
MANIFEST = """<?xml version="1.0" encoding="utf-8"?>
<SmoothStreamingMedia MajorVersion="2" MinorVersion="2" Duration="600000000" TimeScale="10000000">
<Protection>
<ProtectionHeader SystemID="{system_id}">{pssh}</ProtectionHeader>
</Protection>
<StreamIndex Type="video" QualityLevels="1" Chunks="1" Url="QualityLevels({{bitrate}})/Fragments(video={{start time}})">
<QualityLevel Index="0" Bitrate="1000000" FourCC="H264" MaxWidth="1280" MaxHeight="720"
CodecPrivateData="00000001674d401e9a6602800b76020000003e90000bb800f18311200000000168ebccb22c"/>
<c t="0" d="20000000"/>
</StreamIndex>
</SmoothStreamingMedia>
"""
@pytest.mark.parametrize(
"system_id",
[
"EDEF8BA9-79D6-4ACE-A3C8-27DCD51D21ED",
"{EDEF8BA9-79D6-4ACE-A3C8-27DCD51D21ED}",
],
)
def test_get_drm_resolves_braced_and_bare_system_ids(system_id):
manifest = MANIFEST.format(system_id=system_id, pssh=WIDEVINE_PSSH_B64)
ism = ISM.from_text(manifest, "https://example.test/Manifest")
drm = ISM.get_drm(ism.manifest.xpath(".//ProtectionHeader"))
assert len(drm) == 1
assert isinstance(drm[0], Widevine)
assert drm[0].kid == UUID("00112233-4455-6677-8899-aabbccddeeff")
def test_get_drm_warns_on_unparseable_header(caplog):
manifest = MANIFEST.format(system_id="EDEF8BA9-79D6-4ACE-A3C8-27DCD51D21ED", pssh="!!!not-base64!!!")
ism = ISM.from_text(manifest, "https://example.test/Manifest")
with caplog.at_level("WARNING", logger="ISM"):
drm = ISM.get_drm(ism.manifest.xpath(".//ProtectionHeader"))
assert drm == []
assert any("unparseable Widevine" in r.message for r in caplog.records)
+12 -12
View File
@@ -581,7 +581,7 @@ def test_hvcc_profile_tier_level_is_nonzero():
assert level_idc != 0
def _piff_fragment(flags: int = 0x0, override: bool = False) -> bytes:
def piff_fragment(flags: int = 0x0, override: bool = False) -> bytes:
"""Minimal moof+mdat fragment carrying sample encryption in the PIFF uuid box."""
ivs = b"".join(bytes([i]) * 8 for i in range(1, 3))
senc_payload = struct.pack(">I", 2) + ivs
@@ -599,7 +599,7 @@ def _piff_fragment(flags: int = 0x0, override: bool = False) -> bytes:
def test_piff_senc_rewritten_to_cenc_senc():
frag = _piff_fragment()
frag = piff_fragment()
out = piff_senc_to_cenc(frag)
# trun's data_offset is moof-relative; shrinking the box misaims decryption
assert len(out) == len(frag)
@@ -612,7 +612,7 @@ def test_piff_senc_rewritten_to_cenc_senc():
def test_piff_senc_override_header_stripped():
frag = _piff_fragment(override=True)
frag = piff_fragment(override=True)
out = piff_senc_to_cenc(frag)
assert len(out) == len(frag)
assert PIFF_SENC_UUID not in out
@@ -624,7 +624,7 @@ def test_piff_senc_override_header_stripped():
def test_piff_subsample_flag_survives_override_strip():
# losing 0x2 is silent: no subsample map, so clear NAL headers get encrypted too
frag = _piff_fragment(flags=0x2, override=True)
frag = piff_fragment(flags=0x2, override=True)
out = piff_senc_to_cenc(frag)
senc = out.index(b"senc")
flags = int.from_bytes(out[senc + 5 : senc + 8], "big")
@@ -648,7 +648,7 @@ def test_piff_rewrite_skips_traf_that_already_has_senc():
def test_piff_rewrite_covers_every_moof_and_traf():
frag = _piff_fragment() + _piff_fragment()
frag = piff_fragment() + piff_fragment()
out = piff_senc_to_cenc(frag)
assert len(out) == len(frag)
assert PIFF_SENC_UUID not in out
@@ -683,8 +683,8 @@ def traf_children_tile_exactly(frag: bytes) -> bool:
def test_piff_rewrite_keeps_traf_children_tiling_exactly():
# a mis-sized senc still "decrypts", just off the wrong bytes, so assert the sizes too
assert traf_children_tile_exactly(_piff_fragment())
for frag in (_piff_fragment(), _piff_fragment(flags=0x2), _piff_fragment(flags=0x2, override=True)):
assert traf_children_tile_exactly(piff_fragment())
for frag in (piff_fragment(), piff_fragment(flags=0x2), piff_fragment(flags=0x2, override=True)):
assert traf_children_tile_exactly(piff_senc_to_cenc(frag)), "rewritten traf no longer tiles"
@@ -700,7 +700,7 @@ def test_piff_rewrite_refuses_override_iv_size_mismatch():
def test_piff_rewrite_never_grows_output_on_malformed_boxes():
# A declared size running past the buffer would extend the output over the mdat.
good = _piff_fragment()
good = piff_fragment()
truncations = [good[:n] for n in range(8, len(good), 7)]
oversized = bytearray(good)
struct.pack_into(">I", oversized, 0, len(good) + 4096) # moof claims more than exists
@@ -709,7 +709,7 @@ def test_piff_rewrite_never_grows_output_on_malformed_boxes():
assert len(out) == len(frag), f"output grew: {len(frag)} -> {len(out)}"
def _text_fragment(seq: int, begin: str, end: str, text: str, sdi: int) -> bytes:
def text_fragment(seq: int, begin: str, end: str, text: str, sdi: int) -> bytes:
"""A single-sample fTTML moof+mdat, mirroring what a Smooth text stream serves."""
payload = (
"<?xml version='1.0' encoding='utf-8'?>"
@@ -771,7 +771,7 @@ def test_pymp4_consumes_whole_init_and_reaches_fragments():
init = build_init_segment(
stream_type="text", fourcc="TTML", codec_private_data="", duration=6_000_000_000, language="eng"
)
data = init + _text_fragment(1, "00:00:01.000", "00:00:02.000", "first", sdi=1)
data = init + text_fragment(1, "00:00:01.000", "00:00:02.000", "first", sdi=1)
types = [b.type for b in MP4.parse_stream(BytesIO(data))]
assert types == [b"ftyp", b"moov", b"moof", b"mdat"]
@@ -784,8 +784,8 @@ def test_fttml_subtitle_parse_yields_cues():
)
data = (
init
+ _text_fragment(1, "00:00:01.000", "00:00:02.000", "first", sdi=1)
+ _text_fragment(2, "00:00:03.000", "00:00:04.000", "second", sdi=2)
+ text_fragment(1, "00:00:01.000", "00:00:02.000", "first", sdi=1)
+ text_fragment(2, "00:00:03.000", "00:00:04.000", "second", sdi=2)
)
caption_set = Subtitle.parse(data, Subtitle.Codec.fTTML)
cues = [c for lang in caption_set.get_languages() for c in caption_set.get_captions(lang)]
+11
View File
@@ -28,6 +28,17 @@ def test_placeholder_spellings_repeat_and_audiotag_fallback() -> None:
assert audio.codec == Audio.Codec.AAC # AudioTag 255 means AACL
def test_duration_fallback_when_next_fragment_omits_time() -> None:
# A d-less <c> whose successor also omits t must fall back to the manifest
# duration (int(None) used to raise TypeError past the except clause).
sparse = MANIFEST.replace('<c t="0" d="20000000" r="2"/>', '<c t="0"/>')
tracks = ISM.from_text(sparse, "https://cdn.example/x.ism/manifest").to_tracks()
assert tracks.audio[0].data["ism"]["segments"] == [
"https://cdn.example/x.ism/QualityLevels(128000)/Fragments(audio=0)",
"https://cdn.example/x.ism/QualityLevels(128000)/Fragments(audio=60000000)",
]
def test_missing_language_without_fallback_raises() -> None:
# MS-SSTR Language is optional; video StreamIndexes commonly omit it.
no_lang = MANIFEST.replace(' Language="en"', "")
+14 -14
View File
@@ -11,11 +11,11 @@ from unshackle.core.config import config
@pytest.fixture(autouse=True)
def _default_order(monkeypatch: pytest.MonkeyPatch) -> None:
def default_order(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "metadata_providers", [])
def _with_keys(monkeypatch: pytest.MonkeyPatch, **keys: str) -> None:
def with_keys(monkeypatch: pytest.MonkeyPatch, **keys: str) -> None:
for name in ("tmdb_api_key", "tvdb_api_key", "omdb_api_key", "simkl_client_id"):
monkeypatch.setattr(config, name, keys.get(name, ""))
@@ -38,7 +38,7 @@ def test_no_ids_is_fine() -> None:
def test_imdb_alone_passes_on_the_keyless_provider(monkeypatch: pytest.MonkeyPatch) -> None:
_with_keys(monkeypatch)
with_keys(monkeypatch)
assert validate_metadata_ids(None, "tt1375666", None) is None
@@ -46,26 +46,26 @@ 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_keys(monkeypatch)
with pytest.raises(click.UsageError) 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_keys(monkeypatch)
with pytest.raises(click.UsageError) as exc:
validate_metadata_ids(None, None, 73871)
assert "--tvdb" in str(exc.value) and "tvdb_api_key" in str(exc.value)
def test_tmdb_with_its_key_passes(monkeypatch: pytest.MonkeyPatch) -> None:
_with_keys(monkeypatch, tmdb_api_key="k")
with_keys(monkeypatch, tmdb_api_key="k")
assert validate_metadata_ids(27205, None, None) is 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")
with_keys(monkeypatch, tmdb_api_key="k")
monkeypatch.setattr(config, "metadata_providers", ["imdb", "omdb"])
with pytest.raises(click.UsageError) as exc:
validate_metadata_ids(27205, None, None)
@@ -73,7 +73,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)
with_keys(monkeypatch)
monkeypatch.setattr(config, "metadata_providers", ["tmdb", "tvdb"])
with pytest.raises(click.UsageError) as exc:
validate_metadata_ids(None, "tt1375666", None)
@@ -83,7 +83,7 @@ def test_imdb_is_unresolvable_when_the_order_drops_both_of_its_providers(monkeyp
def test_one_kind_keeping_the_provider_is_enough(monkeypatch: pytest.MonkeyPatch) -> None:
"""A per-kind order can drop tvdb for movies and keep it for tv, so this must not error."""
_with_keys(monkeypatch, tvdb_api_key="k")
with_keys(monkeypatch, tvdb_api_key="k")
monkeypatch.setattr(config, "metadata_providers", {"tv": ["tvdb"], "movie": ["tmdb"]})
assert validate_metadata_ids(None, None, 73871) is None
@@ -119,17 +119,17 @@ def test_api_still_reports_a_malformed_id_first() -> None:
@pytest.mark.parametrize("value", [21, "21", "mal:21"])
def test_anilist_alone_passes_without_any_key(monkeypatch: pytest.MonkeyPatch, value: object) -> None:
_with_keys(monkeypatch)
with_keys(monkeypatch)
assert validate_metadata_ids(None, None, None, value) is None
def test_anilist_pairs_with_one_other_id(monkeypatch: pytest.MonkeyPatch) -> None:
_with_keys(monkeypatch)
with_keys(monkeypatch)
assert validate_metadata_ids(None, "tt1375666", None, 21) is None
def test_anilist_does_not_excuse_two_western_ids(monkeypatch: pytest.MonkeyPatch) -> None:
_with_keys(monkeypatch)
with_keys(monkeypatch)
with pytest.raises(click.UsageError) as exc:
validate_metadata_ids(27205, "tt1375666", None, 21)
assert "cannot be used together" in str(exc.value)
@@ -137,7 +137,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_keys(monkeypatch)
with pytest.raises(click.UsageError) as exc:
validate_metadata_ids(None, None, None, value)
assert "--anilist" in str(exc.value)
@@ -165,7 +165,7 @@ def test_api_refuses_a_malformed_anilist_id(value: object) -> None:
@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_keys(monkeypatch)
with pytest.raises(click.UsageError) as exc:
validate_metadata_ids(None, None, None, value)
assert "--anilist" in str(exc.value)
+16 -16
View File
@@ -38,7 +38,7 @@ class FakeProvider(MetadataProvider):
@pytest.fixture(autouse=True)
def _isolate(monkeypatch: pytest.MonkeyPatch) -> None:
def isolate(monkeypatch: pytest.MonkeyPatch) -> None:
"""Keep every test off the network and on the default provider order."""
monkeypatch.setattr(config, "metadata_providers", [])
monkeypatch.setattr(providers, "fetch_external_ids", lambda *a, **kw: ExternalIds())
@@ -50,7 +50,7 @@ def _isolate(monkeypatch: pytest.MonkeyPatch) -> None:
)
def _patch_providers(monkeypatch: pytest.MonkeyPatch, available: dict[str, FakeProvider]) -> None:
def patch_providers(monkeypatch: pytest.MonkeyPatch, available: dict[str, FakeProvider]) -> None:
monkeypatch.setattr(providers, "get_provider", lambda name: available.get(name))
@@ -60,7 +60,7 @@ def test_supplied_ids_survive_a_providers_own_answer(monkeypatch: pytest.MonkeyP
"tmdb",
MetadataResult(title="Inception", year=2010, kind="movie", external_ids=ExternalIds(imdb_id="tt9999999")),
)
_patch_providers(monkeypatch, {"tmdb": tmdb})
patch_providers(monkeypatch, {"tmdb": tmdb})
result = providers.resolve_by_ids(27205, "tt1375666", kind="movie")
@@ -73,7 +73,7 @@ def test_supplied_ids_survive_a_providers_own_answer(monkeypatch: pytest.MonkeyP
def test_imdb_falls_through_to_omdb(monkeypatch: pytest.MonkeyPatch) -> None:
imdb = FakeProvider("imdb", raises=True)
omdb = FakeProvider("omdb", MetadataResult(title="Inception", year=2010, kind="movie"))
_patch_providers(monkeypatch, {"imdb": imdb, "omdb": omdb})
patch_providers(monkeypatch, {"imdb": imdb, "omdb": omdb})
result = providers.resolve_by_ids(imdb_id="tt1375666", kind="movie")
@@ -84,7 +84,7 @@ def test_imdb_falls_through_to_omdb(monkeypatch: pytest.MonkeyPatch) -> None:
def test_all_providers_down_synthesizes_a_result(monkeypatch: pytest.MonkeyPatch) -> None:
_patch_providers(monkeypatch, {})
patch_providers(monkeypatch, {})
result = providers.resolve_by_ids(tvdb_id=73871, title="Futurama", year=1999, kind="tv")
@@ -97,7 +97,7 @@ def test_all_providers_down_synthesizes_a_result(monkeypatch: pytest.MonkeyPatch
def test_no_ids_searches(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[tuple] = []
monkeypatch.setattr(providers, "search_metadata", lambda *a, **kw: calls.append(a) or None)
_patch_providers(monkeypatch, {})
patch_providers(monkeypatch, {})
providers.resolve_by_ids(title="Futurama", year=1999, kind="tv")
@@ -105,7 +105,7 @@ def test_no_ids_searches(monkeypatch: pytest.MonkeyPatch) -> None:
def test_no_ids_and_no_title_returns_none(monkeypatch: pytest.MonkeyPatch) -> None:
_patch_providers(monkeypatch, {})
patch_providers(monkeypatch, {})
assert providers.resolve_by_ids(kind="tv") is None
@@ -113,7 +113,7 @@ def test_per_kind_order_puts_tvdb_first_for_tv(monkeypatch: pytest.MonkeyPatch)
monkeypatch.setattr(config, "metadata_providers", {"tv": ["tvdb", "tmdb", "imdb", "omdb"]})
tvdb = FakeProvider("tvdb", MetadataResult(title="Futurama", year=1999, kind="tv"))
tmdb = FakeProvider("tmdb", MetadataResult(title="Wrong Show", year=2020, kind="tv"))
_patch_providers(monkeypatch, {"tvdb": tvdb, "tmdb": tmdb})
patch_providers(monkeypatch, {"tvdb": tvdb, "tmdb": tmdb})
result = providers.resolve_by_ids(615, tvdb_id=73871, kind="tv")
@@ -140,7 +140,7 @@ def test_an_anilist_id_reaches_the_anilist_provider(monkeypatch: pytest.MonkeyPa
MetadataResult(title="One Piece", year=1999, kind="tv", external_ids=ExternalIds(anilist_id=21)),
)
tmdb = FakeProvider("tmdb", MetadataResult(title="Wrong Show", year=2020, kind="tv"))
_patch_providers(monkeypatch, {"anilist": anilist, "tmdb": tmdb})
patch_providers(monkeypatch, {"anilist": anilist, "tmdb": tmdb})
result = providers.resolve_by_ids(anilist_id=21, kind="tv")
@@ -152,7 +152,7 @@ def test_an_anilist_id_reaches_the_anilist_provider(monkeypatch: pytest.MonkeyPa
def test_a_supplied_anilist_id_survives_a_provider_miss(monkeypatch: pytest.MonkeyPatch) -> None:
_patch_providers(monkeypatch, {})
patch_providers(monkeypatch, {})
result = providers.resolve_by_ids(anilist_id="21", title="One Piece", kind="tv")
@@ -162,7 +162,7 @@ def test_a_supplied_anilist_id_survives_a_provider_miss(monkeypatch: pytest.Monk
def test_a_mal_reference_carries_only_what_the_lookup_answered(monkeypatch: pytest.MonkeyPatch) -> None:
anilist = FakeProvider("anilist", MetadataResult(title="One Piece", external_ids=ExternalIds(anilist_id=21)))
_patch_providers(monkeypatch, {"anilist": anilist})
patch_providers(monkeypatch, {"anilist": anilist})
result = providers.resolve_by_ids(anilist_id="mal:21", kind="tv")
@@ -172,7 +172,7 @@ def test_a_mal_reference_carries_only_what_the_lookup_answered(monkeypatch: pyte
def test_a_mal_reference_that_misses_leaves_no_anilist_id(monkeypatch: pytest.MonkeyPatch) -> None:
_patch_providers(monkeypatch, {})
patch_providers(monkeypatch, {})
result = providers.resolve_by_ids(anilist_id="mal:21", title="One Piece", kind="tv")
@@ -183,7 +183,7 @@ def test_a_mal_reference_that_misses_leaves_no_anilist_id(monkeypatch: pytest.Mo
def test_anilist_combines_with_a_western_id(monkeypatch: pytest.MonkeyPatch) -> None:
tmdb = FakeProvider("tmdb", MetadataResult(title="One Piece", year=1999, kind="tv"))
anilist = FakeProvider("anilist", MetadataResult(title="One Piece", external_ids=ExternalIds(anilist_id=21)))
_patch_providers(monkeypatch, {"tmdb": tmdb, "anilist": anilist})
patch_providers(monkeypatch, {"tmdb": tmdb, "anilist": anilist})
result = providers.resolve_by_ids(37854, anilist_id=21, kind="tv")
@@ -215,7 +215,7 @@ def test_an_anime_hint_falls_through_to_the_normal_order_on_a_miss(monkeypatch:
"""anilist is asked first but knows no imdb ids, so imdb still answers."""
anilist = FakeProvider("anilist", None)
imdb = FakeProvider("imdb", MetadataResult(title="One Piece", year=1999, kind="tv"))
_patch_providers(monkeypatch, {"anilist": anilist, "imdb": imdb})
patch_providers(monkeypatch, {"anilist": anilist, "imdb": imdb})
result = providers.resolve_by_ids(imdb_id="tt0388629", kind="tv", anime=True)
@@ -229,7 +229,7 @@ def test_an_anime_hint_falls_through_to_the_normal_order_on_a_miss(monkeypatch:
def test_the_anime_hint_reaches_search(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[dict] = []
monkeypatch.setattr(providers, "search_metadata", lambda *a, **kw: calls.append({"args": a}) or None)
_patch_providers(monkeypatch, {})
patch_providers(monkeypatch, {})
providers.resolve_by_ids(title="One Piece", year=1999, kind="tv", anime=True)
@@ -242,7 +242,7 @@ def test_all_supplied_ids_survive_together(monkeypatch: pytest.MonkeyPatch) -> N
"tvdb",
MetadataResult(title="One Piece", year=1999, kind="tv", external_ids=ExternalIds(tvdb_id=81797)),
)
_patch_providers(monkeypatch, {"tvdb": tvdb})
patch_providers(monkeypatch, {"tvdb": tvdb})
result = providers.resolve_by_ids(tvdb_id=81797, anilist_id="mal:21", imdb_id="tt0388629", kind="tv")
+15 -15
View File
@@ -66,11 +66,11 @@ def test_repos_base_uses_configured_local_dir(monkeypatch, tmp_path):
def test_is_stale(tmp_path):
stamp = tmp_path / "stamp"
assert service_repo._is_stale(stamp, ttl=10) is True # missing → stale
assert service_repo.is_stale(stamp, ttl=10) is True # missing → stale
stamp.write_text(str(time.time()))
assert service_repo._is_stale(stamp, ttl=10) is False # fresh
assert service_repo.is_stale(stamp, ttl=10) is False # fresh
stamp.write_text(str(time.time() - 100))
assert service_repo._is_stale(stamp, ttl=10) is True # old
assert service_repo.is_stale(stamp, ttl=10) is True # old
def test_clone_invokes_git(monkeypatch, tmp_path):
@@ -110,7 +110,7 @@ def test_fresh_clone_skips_pull(monkeypatch, tmp_path):
assert service_repo.resolve_service_repo("a/b") == dest
def _git_stub(porcelain=b"", ahead=b"0"):
def git_stub(porcelain=b"", ahead=b"0"):
"""Fake subprocess.run for git: dirty checks return given output, pull succeeds."""
def run(args, **kw):
@@ -126,20 +126,20 @@ def _git_stub(porcelain=b"", ahead=b"0"):
def test_is_dirty_uncommitted(monkeypatch):
monkeypatch.setattr(service_repo.binaries, "Git", "git")
monkeypatch.setattr(service_repo.subprocess, "run", _git_stub(porcelain=b" M EXAMPLE/__init__.py\n"))
assert service_repo._is_dirty(Path("/x")) is True
monkeypatch.setattr(service_repo.subprocess, "run", git_stub(porcelain=b" M EXAMPLE/__init__.py\n"))
assert service_repo.is_dirty(Path("/x")) is True
def test_is_dirty_commits_ahead(monkeypatch):
monkeypatch.setattr(service_repo.binaries, "Git", "git")
monkeypatch.setattr(service_repo.subprocess, "run", _git_stub(porcelain=b"", ahead=b"2"))
assert service_repo._is_dirty(Path("/x")) is True
monkeypatch.setattr(service_repo.subprocess, "run", git_stub(porcelain=b"", ahead=b"2"))
assert service_repo.is_dirty(Path("/x")) is True
def test_is_dirty_clean(monkeypatch):
monkeypatch.setattr(service_repo.binaries, "Git", "git")
monkeypatch.setattr(service_repo.subprocess, "run", _git_stub(porcelain=b"", ahead=b"0"))
assert service_repo._is_dirty(Path("/x")) is False
monkeypatch.setattr(service_repo.subprocess, "run", git_stub(porcelain=b"", ahead=b"0"))
assert service_repo.is_dirty(Path("/x")) is False
def test_is_dirty_ignores_untracked_files(monkeypatch):
@@ -153,7 +153,7 @@ def test_is_dirty_ignores_untracked_files(monkeypatch):
return subprocess.CompletedProcess(args, 0, out, b"")
monkeypatch.setattr(service_repo.subprocess, "run", run)
service_repo._is_dirty(Path("/x"))
service_repo.is_dirty(Path("/x"))
status_args = next(a for a in seen if a[3] == "status")
assert "--untracked-files=no" in status_args
@@ -165,7 +165,7 @@ def test_auto_refresh_refuses_dirty_clone(monkeypatch, tmp_path):
service_repo.stamp_for(dest).write_text("0") # stale → refresh due
monkeypatch.setattr(service_repo, "repos_base", lambda: tmp_path)
monkeypatch.setattr(service_repo.binaries, "Git", "git")
monkeypatch.setattr(service_repo.subprocess, "run", _git_stub(porcelain=b" M f\n"))
monkeypatch.setattr(service_repo.subprocess, "run", git_stub(porcelain=b" M f\n"))
with pytest.raises(service_repo.DirtyServiceRepo) as ei:
service_repo.resolve_service_repo("a/b")
assert ei.value.path == dest
@@ -201,7 +201,7 @@ def test_changed_services_groups_by_top_dir(monkeypatch):
return subprocess.CompletedProcess(args, 0, out, b"")
monkeypatch.setattr(service_repo.subprocess, "run", run)
lines = service_repo._changed_services(Path("/x"), "aaa", "bbb")
lines = service_repo.changed_services(Path("/x"), "aaa", "bbb")
assert "+ NEW (added)" in lines
assert "~ OLD (modified)" in lines
assert "- GONE (removed)" in lines
@@ -215,7 +215,7 @@ def test_local_dirty_services_lists_edited_dirs(monkeypatch):
"run",
lambda *a, **k: subprocess.CompletedProcess(a, 0, b"CR/__init__.py\nCR/config.yaml\nNF/__init__.py\n", b""),
)
assert service_repo._local_dirty_services(Path("/x")) == ["CR", "NF"]
assert service_repo.local_dirty_services(Path("/x")) == ["CR", "NF"]
def test_refresh_reports_discarded_local_edits(monkeypatch, tmp_path):
@@ -241,7 +241,7 @@ def test_changed_services_up_to_date(monkeypatch):
monkeypatch.setattr(service_repo.binaries, "Git", "git")
# same HEAD before/after → no diff computed at all
monkeypatch.setattr(service_repo.subprocess, "run", lambda *a, **k: pytest.fail("no git diff when HEAD unchanged"))
assert service_repo._changed_services(Path("/x"), "same", "same") == []
assert service_repo.changed_services(Path("/x"), "same", "same") == []
@pytest.mark.parametrize("order", [["a", "b"], ["b", "a"]])
+3 -3
View File
@@ -61,7 +61,7 @@ def clean_config(monkeypatch: pytest.MonkeyPatch) -> None:
def context_for(rules: list[dict[str, Any]], monkeypatch: pytest.MonkeyPatch) -> dict:
monkeypatch.setattr(config, "tag_rules", rules)
return make_movie()._build_base_template_context(make_media_info(["en"]))
return make_movie().build_base_template_context(make_media_info(["en"]))
def test_matching_rule_replaces_the_tag(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -90,7 +90,7 @@ def test_rules_run_after_lang_tag(monkeypatch: pytest.MonkeyPatch) -> None:
movie = make_movie()
movie.tracks = TrackStub(audio=[types.SimpleNamespace(language=Language.get("ja"))], subtitles=[]) # type: ignore[assignment]
context = movie._build_base_template_context(make_media_info(["ja"]))
context = movie.build_base_template_context(make_media_info(["ja"]))
assert context["lang_tag"] == "SUBBED"
assert context["tag"] == "SUBGRP"
@@ -113,7 +113,7 @@ def test_a_quality_rule_matches_the_built_context(monkeypatch: pytest.MonkeyPatc
)
media_info = types.SimpleNamespace(video_tracks=[video], audio_tracks=[make_audio("en")])
context = make_movie()._build_base_template_context(media_info)
context = make_movie().build_base_template_context(media_info)
assert context["quality"] == "2160p"
assert context["video"] == "H.265"
+27 -27
View File
@@ -6,8 +6,8 @@ import pytest
from unshackle.core import providers
from unshackle.core.config import config
from unshackle.core.providers.tvdb import TVDBProvider, _ids_from_remote, _pick_match
from unshackle.core.utils.tags import _build_tags_from_ids
from unshackle.core.providers.tvdb import TVDBProvider, ids_from_remote, pick_match
from unshackle.core.utils.tags import build_tags_from_ids
REMOTE_IDS = [
{"id": "tt0149460", "type": 2, "sourceName": "IMDB"},
@@ -31,19 +31,19 @@ DVD = [
def test_ids_from_remote() -> None:
ext = _ids_from_remote(REMOTE_IDS, 73871)
ext = ids_from_remote(REMOTE_IDS, 73871)
assert ext.imdb_id == "tt0149460"
assert ext.tmdb_id == 615
assert ext.tvdb_id == 73871
def _stub(p: TVDBProvider, monkeypatch: pytest.MonkeyPatch) -> None:
def stub(p: TVDBProvider, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(p, "get_episodes", lambda _id, order: {"official": AIRED, "dvd": DVD}.get(order, []))
def test_order_map_joins_on_episode_id(monkeypatch: pytest.MonkeyPatch) -> None:
p = TVDBProvider()
_stub(p, monkeypatch)
stub(p, monkeypatch)
mapping = p.get_order_map(73871, "dvd")
assert mapping[(1, 9)] == (1, 9, "Hell Is Other Robots")
@@ -55,7 +55,7 @@ def test_order_map_joins_on_episode_id(monkeypatch: pytest.MonkeyPatch) -> None:
def test_order_map_reverses_with_source_order(monkeypatch: pytest.MonkeyPatch) -> None:
p = TVDBProvider()
_stub(p, monkeypatch)
stub(p, monkeypatch)
mapping = p.get_order_map(73871, "official", source_order="dvd")
assert mapping[(1, 10)] == (2, 1, "A Flight to Remember")
@@ -67,13 +67,13 @@ def test_order_map_is_noop_when_orders_match() -> None:
def test_order_map_empty_when_order_missing(monkeypatch: pytest.MonkeyPatch) -> None:
p = TVDBProvider()
_stub(p, monkeypatch)
stub(p, monkeypatch)
assert p.get_order_map(73871, "alternate") == {}
def test_detect_order_picks_the_order_the_numbering_matches(monkeypatch: pytest.MonkeyPatch) -> None:
p = TVDBProvider()
_stub(p, monkeypatch)
stub(p, monkeypatch)
# a service may number a series in a non-aired order, so detection must not assume aired
assert p.detect_order(73871, [(1, 10), (1, 11)]) == "dvd"
assert p.detect_order(73871, [(2, 1), (2, 2), (2, 3)]) == "official"
@@ -94,27 +94,27 @@ BSG = [
def test_pick_match_prefers_the_right_era() -> None:
# exact title match on the 1978 series must not beat the era the caller asked for
best, _, _ = _pick_match(BSG, "Battlestar Galactica", 2004)
best, _, _ = pick_match(BSG, "Battlestar Galactica", 2004)
assert best["tvdb_id"] == "73545"
best, _, _ = _pick_match(BSG, "Battlestar Galactica", 1978)
best, _, _ = pick_match(BSG, "Battlestar Galactica", 1978)
assert best["tvdb_id"] == "71173"
def test_pick_match_without_a_year_scores_on_title_alone() -> None:
best, _, _ = _pick_match(BSG, "Battlestar Galactica", None)
best, _, _ = pick_match(BSG, "Battlestar Galactica", None)
assert best["tvdb_id"] == "71173"
def test_pick_match_returns_nothing_when_no_year_fits() -> None:
assert _pick_match(BSG, "Battlestar Galactica", 1995)[0] is None
assert pick_match(BSG, "Battlestar Galactica", 1995)[0] is None
def test_tvdb2_tag_follows_the_matroska_spec() -> None:
# TVDB2 IDs are prefixed by entity type: matroska.org/technical/tagging.html
from unshackle.core.providers import ExternalIds
assert _build_tags_from_ids(ExternalIds(tvdb_id=73871), "tv")["TVDB2"] == "series/73871"
assert _build_tags_from_ids(ExternalIds(tvdb_id=113), "movie")["TVDB2"] == "movies/113"
assert build_tags_from_ids(ExternalIds(tvdb_id=73871), "tv")["TVDB2"] == "series/73871"
assert build_tags_from_ids(ExternalIds(tvdb_id=113), "movie")["TVDB2"] == "movies/113"
def test_provider_order_defaults(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -131,10 +131,10 @@ def test_provider_order_is_configurable(monkeypatch: pytest.MonkeyPatch) -> None
def test_enrichment_authority_is_fixed(monkeypatch: pytest.MonkeyPatch) -> None:
# search order must not demote TMDB below SIMKL for cross-validation tie-breaks
monkeypatch.setattr(config, "metadata_providers", [])
assert providers._enrichment_providers() == ["tmdb", "simkl", "tvdb"]
assert providers.enrichment_providers() == ["tmdb", "simkl", "tvdb"]
# `metadata_providers` filters the set but does not re-rank the trust order
monkeypatch.setattr(config, "metadata_providers", ["tvdb", "simkl"])
assert providers._enrichment_providers() == ["simkl", "tvdb"]
assert providers.enrichment_providers() == ["simkl", "tvdb"]
def test_cached_tvdb_result_keeps_enriched_ids() -> None:
@@ -144,7 +144,7 @@ def test_cached_tvdb_result_keeps_enriched_ids() -> None:
"year": "1999",
"_enriched_ids": {"imdb_id": "tt0149460", "tmdb_id": 615},
}
result = providers._cached_to_result(cached, "tvdb", "tv")
result = providers.cached_to_result(cached, "tvdb", "tv")
assert result is not None
assert result.external_ids.tvdb_id == 73871
assert result.external_ids.imdb_id == "tt0149460"
@@ -152,7 +152,7 @@ def test_cached_tvdb_result_keeps_enriched_ids() -> None:
# remote_ids stay authoritative over the enriched copies
cached["remote_ids"] = REMOTE_IDS
cached["_enriched_ids"] = {"imdb_id": "tt9999999", "tmdb_id": 1}
result = providers._cached_to_result(cached, "tvdb", "tv")
result = providers.cached_to_result(cached, "tvdb", "tv")
assert result.external_ids.imdb_id == "tt0149460"
assert result.external_ids.tmdb_id == 615
@@ -171,7 +171,7 @@ def test_get_by_id_supplies_what_enrich_needs(monkeypatch: pytest.MonkeyPatch, k
"remoteIds": [{"sourceName": "IMDB", "id": "tt0213338"}],
}
monkeypatch.setattr(p, "_get", fake_get)
monkeypatch.setattr(p, "api_get", fake_get)
result = p.get_by_id(73871, kind)
assert seen == [path]
assert (result.title, result.year, result.original_language) == ("Cowboy Bebop", 1998, "jpn")
@@ -181,7 +181,7 @@ def test_get_by_id_supplies_what_enrich_needs(monkeypatch: pytest.MonkeyPatch, k
def test_get_episodes_fails_closed_on_a_truncated_listing(monkeypatch: pytest.MonkeyPatch) -> None:
p = TVDBProvider()
pages: dict[int, object] = {0: {"episodes": [{"id": n} for n in range(500)]}, 1: None}
monkeypatch.setattr(p, "_get", lambda _path, params: pages[params["page"]])
monkeypatch.setattr(p, "api_get", lambda _path, params: pages[params["page"]])
# page 1 fails mid-listing: a partial list would renumber wrongly
assert p.get_episodes(73871, "official") == []
assert p._episodes == {}
@@ -189,7 +189,7 @@ def test_get_episodes_fails_closed_on_a_truncated_listing(monkeypatch: pytest.Mo
def test_get_episodes_does_not_cache_an_empty_listing(monkeypatch: pytest.MonkeyPatch) -> None:
p = TVDBProvider()
monkeypatch.setattr(p, "_get", lambda _path, params: None)
monkeypatch.setattr(p, "api_get", lambda _path, params: None)
assert p.get_episodes(73871, "official") == []
assert p._episodes == {}
@@ -212,7 +212,7 @@ class _FakeProvider:
return self.mapping
def _renumber(monkeypatch: pytest.MonkeyPatch, episodes: list, mapping: dict):
def renumber(monkeypatch: pytest.MonkeyPatch, episodes: list, mapping: dict):
from types import SimpleNamespace
from unshackle.commands.dl import dl
@@ -229,7 +229,7 @@ def _renumber(monkeypatch: pytest.MonkeyPatch, episodes: list, mapping: dict):
return dl.apply_tvdb_order(stub, Series(episodes)), errors
def _ep(season: int, number: int, part=None):
def ep(season: int, number: int, part=None):
from unshackle.core.titles.episode import Episode
return Episode(id_=f"{season}x{number}.{part}", service=_Svc, title="Show", season=season, number=number, part=part)
@@ -237,17 +237,17 @@ def _ep(season: int, number: int, part=None):
def test_parts_of_one_episode_renumber_together(monkeypatch: pytest.MonkeyPatch) -> None:
"""Three parts share one (season, number) slot, so they must not read as a collision."""
episodes = [_ep(1, 1, 1), _ep(1, 1, 2), _ep(1, 1, 3), _ep(1, 2)]
episodes = [ep(1, 1, 1), ep(1, 1, 2), ep(1, 1, 3), ep(1, 2)]
mapping = {(1, 1): (2, 1, "Part-ful"), (1, 2): (2, 2, "Whole")}
titles, errors = _renumber(monkeypatch, episodes, mapping)
titles, errors = renumber(monkeypatch, episodes, mapping)
assert errors == []
assert [(t.season, t.number, t.part) for t in titles] == [(2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, None)]
def test_a_real_collision_still_bails(monkeypatch: pytest.MonkeyPatch) -> None:
"""Dedupe must not disable the guard: two distinct episodes on one slot still refuses."""
episodes = [_ep(1, 1), _ep(1, 2)]
episodes = [ep(1, 1), ep(1, 2)]
mapping = {(1, 2): (1, 1, "Clash")} # (1, 1) is unmapped and keeps the slot (1, 2) moves onto
titles, errors = _renumber(monkeypatch, episodes, mapping)
titles, errors = renumber(monkeypatch, episodes, mapping)
assert errors # refused, with the "two episodes each" error
assert [(t.season, t.number) for t in titles] == [(1, 1), (1, 2)] # numbering untouched
+4 -4
View File
@@ -5,7 +5,7 @@ import threading
import pytest
import requests as rq
from unshackle.core.downloaders.requests import _is_content_encoded, download
from unshackle.core.downloaders.requests import download, is_content_encoded
@pytest.mark.parametrize(
@@ -34,7 +34,7 @@ from unshackle.core.downloaders.requests import _is_content_encoded, download
],
)
def test_is_content_encoded(value, expected):
assert _is_content_encoded(value) is expected
assert is_content_encoded(value) is expected
PLAIN = b"WEBVTT\n\n" + b"".join(f"{i:05d} cue text\n".encode() for i in range(2000))
@@ -50,9 +50,9 @@ class _EncodingServer:
self.sock.bind(("127.0.0.1", 0))
self.sock.listen(8)
self.url = f"http://127.0.0.1:{self.sock.getsockname()[1]}/sub.vtt"
threading.Thread(target=self._serve, daemon=True).start()
threading.Thread(target=self.serve, daemon=True).start()
def _serve(self):
def serve(self):
while True:
try:
conn, _ = self.sock.accept()
+5 -5
View File
@@ -6,7 +6,7 @@ import pytest
import requests as rq
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.downloaders.requests import _has_range_header, download
from unshackle.core.downloaders.requests import download, has_range_header
from unshackle.core.downloaders.requests import requests as requests_downloader
# the package re-exports the `requests` function, shadowing the module of the same name
@@ -26,9 +26,9 @@ class _Server:
self.sock.listen(8)
self.url = f"http://127.0.0.1:{self.sock.getsockname()[1]}/seg.mp4"
self.requests = []
threading.Thread(target=self._serve, daemon=True).start()
threading.Thread(target=self.serve, daemon=True).start()
def _serve(self):
def serve(self):
while True:
try:
conn, _ = self.sock.accept()
@@ -63,7 +63,7 @@ class _Server:
@pytest.fixture(autouse=True)
def _clear_cancel():
def clear_cancel():
# the batch failure path sets the process-global cancel; leaking it makes every later
# test that waits on the event (the speed limiter) return instantly
DOWNLOAD_CANCELLED.clear()
@@ -161,4 +161,4 @@ def test_failed_segment_fails_the_batch(tmp_path, server):
],
)
def test_has_range_header(item, expected):
assert _has_range_header(item) is expected
assert has_range_header(item) is expected
+3 -3
View File
@@ -99,11 +99,11 @@ def test_locked_limit_ignores_unlocked_calls():
set_speed_limit(5_000_000, lock=True)
set_speed_limit(None)
set_speed_limit(1_000_000)
limiter = requests_downloader._speed_limiter
limiter = requests_downloader.speed_limiter
assert limiter is not None and limiter.rate == 5_000_000
finally:
requests_downloader._speed_limit_locked = False
requests_downloader._speed_limiter = None
requests_downloader.speed_limit_locked = False
requests_downloader.speed_limiter = None
def test_bucket_wait_aborts_on_cancellation():
@@ -101,11 +101,11 @@ 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)]
@@ -124,56 +124,56 @@ def test_distinct_pairs_are_not_distance_zero(base, reg):
@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")]
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(["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)
+8 -8
View File
@@ -65,13 +65,13 @@ def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item
item.add_marker(skip_live)
def _free_port() -> int:
def free_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def _wait_for_health(url: str, timeout: float = 60.0) -> bool:
def wait_for_health(url: str, timeout: float = 60.0) -> bool:
import requests
deadline = time.monotonic() + timeout
@@ -87,11 +87,11 @@ def _wait_for_health(url: str, timeout: float = 60.0) -> bool:
@pytest.fixture(autouse=True)
def _isolated_job_history(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
def isolated_job_history(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Redirect job history writes to tmp_path so tests don't append to the server's api_history.jsonl."""
from unshackle.core.api import download_manager
monkeypatch.setattr(download_manager, "_history_path", lambda: tmp_path / "api_history.jsonl")
monkeypatch.setattr(download_manager, "history_path", lambda: tmp_path / "api_history.jsonl")
@pytest.fixture(scope="session")
@@ -120,19 +120,19 @@ def server_url(request: pytest.FixtureRequest):
if mode == "never":
if not explicit:
pytest.fail("--spawn-serve=never requires --server-url")
if not _wait_for_health(explicit, timeout=10):
if not wait_for_health(explicit, timeout=10):
pytest.fail(f"External serve not reachable at {explicit}")
yield explicit
return
if mode == "auto" and explicit:
if not _wait_for_health(explicit, timeout=10):
if not wait_for_health(explicit, timeout=10):
pytest.fail(f"External serve not reachable at {explicit}")
yield explicit
return
# Spawn our own serve.
port = _free_port()
port = free_port()
cmd = [
"uv",
"run",
@@ -153,7 +153,7 @@ def server_url(request: pytest.FixtureRequest):
)
url = f"http://127.0.0.1:{port}"
try:
if not _wait_for_health(url, timeout=60):
if not wait_for_health(url, timeout=60):
proc.terminate()
pytest.fail(f"Spawned serve at {url} did not become healthy within 60s")
yield url
+2 -2
View File
@@ -10,7 +10,7 @@ from pathlib import Path
import pytest
def _load_scenarios(config: pytest.Config) -> dict:
def load_scenarios(config: pytest.Config) -> dict:
cached = getattr(config, "_e2e_scenarios_cache", None)
if cached is not None:
return cached
@@ -31,7 +31,7 @@ def _load_scenarios(config: pytest.Config) -> dict:
def pytest_generate_tests(metafunc: pytest.Metafunc) -> None:
if "service_case" in metafunc.fixturenames:
scenarios = _load_scenarios(metafunc.config)
scenarios = load_scenarios(metafunc.config)
params = [pytest.param((tag, conf), id=tag) for tag, conf in (scenarios.get("services") or {}).items()]
if not params:
params = [
+6 -6
View File
@@ -20,7 +20,7 @@ import pytest
pytestmark = [pytest.mark.live, pytest.mark.slow]
def _wait_titles(http_session, server_url: str, sid: str, timeout: float = 120.0):
def wait_titles(http_session, server_url: str, sid: str, timeout: float = 120.0):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
r = http_session.get(f"{server_url}/api/session/{sid}/titles", timeout=30)
@@ -38,14 +38,14 @@ def _wait_titles(http_session, server_url: str, sid: str, timeout: float = 120.0
return None
def _pick_target_title(titles, season: int = 1, episode: int = 1):
def pick_target_title(titles, season: int = 1, episode: int = 1):
for t in titles:
if t.get("type") == "episode" and t.get("season") == season and t.get("number") == episode:
return t
return titles[0] if titles else None
def _pick_track_at_height(video_tracks, target_height: int):
def pick_track_at_height(video_tracks, target_height: int):
same_height = [v for v in video_tracks if v.get("height") == target_height and v.get("range") == "SDR"]
return sorted(same_height, key=lambda v: v.get("bitrate") or 0)[0] if same_height else None
@@ -77,10 +77,10 @@ def test_download_manifest_fetch(http_session, server_url: str, service_case) ->
sid = r.json()["session_id"]
try:
body = _wait_titles(http_session, server_url, sid)
body = wait_titles(http_session, server_url, sid)
if not body:
pytest.skip(f"{service}: titles timeout")
target = _pick_target_title(
target = pick_target_title(
body.get("titles") or [],
season=conf.get("target_season", 1),
episode=conf.get("target_episode", 1),
@@ -94,7 +94,7 @@ def test_download_manifest_fetch(http_session, server_url: str, service_case) ->
timeout=240,
)
assert tr.status_code == 200, tr.text
track = _pick_track_at_height(tr.json().get("video") or [], target_height)
track = pick_track_at_height(tr.json().get("video") or [], target_height)
if not track:
pytest.skip(f"{service}: no track at height={target_height}")
+6 -6
View File
@@ -20,7 +20,7 @@ import pytest
pytestmark = [pytest.mark.live, pytest.mark.slow]
def _wait_titles(http_session, server_url: str, sid: str, timeout: float = 120.0):
def wait_titles(http_session, server_url: str, sid: str, timeout: float = 120.0):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
r = http_session.get(f"{server_url}/api/session/{sid}/titles", timeout=30)
@@ -38,14 +38,14 @@ def _wait_titles(http_session, server_url: str, sid: str, timeout: float = 120.0
return None
def _pick_target_title(titles, season: int = 1, episode: int = 1):
def pick_target_title(titles, season: int = 1, episode: int = 1):
for t in titles:
if t.get("type") == "episode" and t.get("season") == season and t.get("number") == episode:
return t
return titles[0] if titles else None
def _pick_track_at_height(video_tracks, target_height: int):
def pick_track_at_height(video_tracks, target_height: int):
"""Prefer SDR + AVC at the requested height; smallest bitrate wins."""
same_height = [v for v in video_tracks if v.get("height") == target_height]
preferred = [v for v in same_height if v.get("codec") == "AVC" and v.get("range") == "SDR"]
@@ -80,10 +80,10 @@ def test_license_server_cdm(http_session, server_url: str, service_case) -> None
sid = r.json()["session_id"]
try:
body = _wait_titles(http_session, server_url, sid)
body = wait_titles(http_session, server_url, sid)
if not body:
pytest.skip(f"{service}: titles timeout")
target = _pick_target_title(
target = pick_target_title(
body.get("titles") or [],
season=conf.get("target_season", 1),
episode=conf.get("target_episode", 1),
@@ -97,7 +97,7 @@ def test_license_server_cdm(http_session, server_url: str, service_case) -> None
timeout=240,
)
assert tr.status_code == 200, tr.text
track = _pick_track_at_height(tr.json().get("video") or [], target_height)
track = pick_track_at_height(tr.json().get("video") or [], target_height)
if not track:
pytest.skip(f"{service}: no track at height={target_height}")
+10 -10
View File
@@ -18,7 +18,7 @@ import pytest
pytestmark = [pytest.mark.live, pytest.mark.slow]
def _create_session(http_session, server_url: str, service: str, title_id: str) -> str:
def create_session(http_session, server_url: str, service: str, title_id: str) -> str:
payload = {
"service": service,
"title_id": title_id,
@@ -33,7 +33,7 @@ def _create_session(http_session, server_url: str, service: str, title_id: str)
return r.json()["session_id"]
def _wait_for_titles(http_session, server_url: str, sid: str, timeout: float = 120.0):
def wait_for_titles(http_session, server_url: str, sid: str, timeout: float = 120.0):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
r = http_session.get(f"{server_url}/api/session/{sid}/titles", timeout=30)
@@ -51,7 +51,7 @@ def _wait_for_titles(http_session, server_url: str, sid: str, timeout: float = 1
return 408, {"message": "auth timeout"}
def _pick_target_title(titles: list[dict[str, Any]], season: int = 1, episode: int = 1) -> Optional[dict[str, Any]]:
def pick_target_title(titles: list[dict[str, Any]], season: int = 1, episode: int = 1) -> Optional[dict[str, Any]]:
"""Pick the configured target episode; fall back to the first title."""
for t in titles:
if t.get("type") == "episode" and t.get("season") == season and t.get("number") == episode:
@@ -59,7 +59,7 @@ def _pick_target_title(titles: list[dict[str, Any]], season: int = 1, episode: i
return titles[0] if titles else None
def _summarize(video_tracks: list[dict[str, Any]]) -> dict[str, Any]:
def summarize(video_tracks: list[dict[str, Any]]) -> dict[str, Any]:
max_height = max((v.get("height") or 0 for v in video_tracks), default=0)
max_width = max((v.get("width") or 0 for v in video_tracks), default=0)
codecs = sorted({v.get("codec") for v in video_tracks if v.get("codec")})
@@ -76,25 +76,25 @@ def _summarize(video_tracks: list[dict[str, Any]]) -> dict[str, Any]:
}
def _resolve_title_id(conf: dict) -> Optional[str]:
def resolve_title_id(conf: dict) -> Optional[str]:
"""Prefer series_url so S01E01 logic kicks in; fall back to movie title_url."""
return conf.get("series_url") or conf.get("title_url")
def test_track_quality_meets_expected(http_session, server_url: str, service_case, capsys) -> None:
service, conf = service_case
title_input = _resolve_title_id(conf)
title_input = resolve_title_id(conf)
if not title_input:
pytest.skip(f"{service}: no title_url/series_url in fixture")
sid = _create_session(http_session, server_url, service, title_input)
sid = create_session(http_session, server_url, service, title_input)
try:
code, body = _wait_for_titles(http_session, server_url, sid)
code, body = wait_for_titles(http_session, server_url, sid)
if code != 200:
pytest.skip(f"{service}: titles fetch failed {code}: {str(body)[:200]}")
titles = body.get("titles") or []
target = _pick_target_title(titles, season=conf.get("target_season", 1), episode=conf.get("target_episode", 1))
target = pick_target_title(titles, season=conf.get("target_season", 1), episode=conf.get("target_episode", 1))
if not target:
pytest.skip(f"{service}: no titles returned")
@@ -114,7 +114,7 @@ def test_track_quality_meets_expected(http_session, server_url: str, service_cas
tracks = r.json()
video = tracks.get("video") or []
summary = _summarize(video)
summary = summarize(video)
# Print summary even when test passes — discovery aid.
with capsys.disabled():
print(f"\n[{service}] target={kind} '{target.get('name')}' -> {summary}")
+13 -13
View File
@@ -9,7 +9,7 @@ import pytest
pytestmark = [pytest.mark.live, pytest.mark.slow]
def _create_session(http_session, server_url: str, service: str, conf: dict) -> str:
def create_session(http_session, server_url: str, service: str, conf: dict) -> str:
payload = {"service": service, "title_id": conf["title_url"]}
r = http_session.post(f"{server_url}/api/session/create", json=payload, timeout=120)
if r.status_code >= 400:
@@ -20,7 +20,7 @@ def _create_session(http_session, server_url: str, service: str, conf: dict) ->
return sid
def _wait_for_titles(http_session, server_url: str, sid: str, timeout: float = 120.0):
def wait_for_titles(http_session, server_url: str, sid: str, timeout: float = 120.0):
"""Poll /titles until auth completes. Returns (status_code, response_json).
Server returns 400 + auth_status=authenticating while auth is in-flight,
@@ -44,20 +44,20 @@ def _wait_for_titles(http_session, server_url: str, sid: str, timeout: float = 1
return 408, {"message": "timeout waiting for auth"}
def _delete_session(http_session, server_url: str, sid: str) -> None:
def delete_session(http_session, server_url: str, sid: str) -> None:
http_session.delete(f"{server_url}/api/session/{sid}", timeout=30)
def test_session_create_then_delete(http_session, server_url: str, service_case) -> None:
service, conf = service_case
sid = _create_session(http_session, server_url, service, conf)
sid = create_session(http_session, server_url, service, conf)
try:
r = http_session.get(f"{server_url}/api/session/{sid}", timeout=30)
assert r.status_code == 200
info = r.json()
assert info.get("session", {}).get("service_tag", service) == service or service in str(info)
finally:
_delete_session(http_session, server_url, sid)
delete_session(http_session, server_url, sid)
# After delete, info should 404
r2 = http_session.get(f"{server_url}/api/session/{sid}", timeout=30)
@@ -66,9 +66,9 @@ def test_session_create_then_delete(http_session, server_url: str, service_case)
def test_session_titles_returns_list(http_session, server_url: str, service_case) -> None:
service, conf = service_case
sid = _create_session(http_session, server_url, service, conf)
sid = create_session(http_session, server_url, service, conf)
try:
code, body = _wait_for_titles(http_session, server_url, sid)
code, body = wait_for_titles(http_session, server_url, sid)
if code != 200:
pytest.skip(f"{service}: titles fetch failed {code}: {str(body)[:200]}")
assert "titles" in body
@@ -78,14 +78,14 @@ def test_session_titles_returns_list(http_session, server_url: str, service_case
assert "id" in first
assert "type" in first
finally:
_delete_session(http_session, server_url, sid)
delete_session(http_session, server_url, sid)
def test_session_tracks_for_first_title(http_session, server_url: str, service_case) -> None:
service, conf = service_case
sid = _create_session(http_session, server_url, service, conf)
sid = create_session(http_session, server_url, service, conf)
try:
code, body = _wait_for_titles(http_session, server_url, sid)
code, body = wait_for_titles(http_session, server_url, sid)
if code != 200:
pytest.skip(f"{service}: titles fetch failed {code}: {str(body)[:200]}")
titles = body.get("titles") or []
@@ -104,13 +104,13 @@ def test_session_tracks_for_first_title(http_session, server_url: str, service_c
assert "video" in body or "audio" in body, body
assert body.get("video") or body.get("audio"), body
finally:
_delete_session(http_session, server_url, sid)
delete_session(http_session, server_url, sid)
def test_session_delete_idempotent_returns_404_after(http_session, server_url: str, service_case) -> None:
service, conf = service_case
sid = _create_session(http_session, server_url, service, conf)
_delete_session(http_session, server_url, sid)
sid = create_session(http_session, server_url, service, conf)
delete_session(http_session, server_url, sid)
r = http_session.delete(f"{server_url}/api/session/{sid}", timeout=30)
assert r.status_code in (404, 200) # tolerate both depending on server semantics
+42 -42
View File
@@ -26,7 +26,7 @@ class _FakeSvc:
pass
def _ep(season: int = 1, number: int = 1, part: Optional[int] = None, **overrides: Any) -> Episode:
def ep(season: int = 1, number: int = 1, part: Optional[int] = None, **overrides: Any) -> Episode:
base: Dict[str, Any] = dict(
id_=f"ep-{season}-{number}-{part or 0}",
service=_FakeSvc,
@@ -58,7 +58,7 @@ class _FakeService:
return _FakeTracks()
def _run_list_tracks(monkeypatch: pytest.MonkeyPatch, titles: List[Episode], **data: Any) -> Dict[str, Any]:
def run_list_tracks(monkeypatch: pytest.MonkeyPatch, titles: List[Episode], **data: Any) -> Dict[str, Any]:
"""Drive list_tracks_handler end to end with the service layer stubbed out."""
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "FAKE")
monkeypatch.setattr(handlers, "setup_list_service", lambda *a, **kw: _FakeService(titles))
@@ -71,7 +71,7 @@ def _run_list_tracks(monkeypatch: pytest.MonkeyPatch, titles: List[Episode], **d
return json.loads(response.body)
def _selected(result: Dict[str, Any]) -> List[str]:
def selected(result: Dict[str, Any]) -> List[str]:
"""Selection-syntax keys of whatever the handler returned, single or multi."""
entries = result["episodes"] if "episodes" in result else [{"title": result["title"]}]
keys = []
@@ -86,7 +86,7 @@ def _selected(result: Dict[str, Any]) -> List[str]:
def test_partless_episode_json_has_no_part_key() -> None:
d = serialize_title(_ep(part=None))
d = serialize_title(ep(part=None))
assert "part" not in d
assert list(d.keys()) == [
"type",
@@ -105,26 +105,26 @@ def test_partless_episode_json_has_no_part_key() -> None:
def test_partful_episode_json_carries_part_last() -> None:
d = serialize_title(_ep(part=2))
d = serialize_title(ep(part=2))
assert d["part"] == 2
# additive: `part` is appended, every pre-existing key keeps its position
assert list(d.keys())[:11] == list(serialize_title(_ep(part=None)).keys())
assert list(d.keys())[:11] == list(serialize_title(ep(part=None)).keys())
assert list(d.keys())[11] == "part"
def test_part_stays_out_of_the_name_field() -> None:
"""`name` is a reconstruction input for _build_title, not a display string."""
assert serialize_title(_ep(part=2))["name"] == "Pilot"
assert serialize_title(_ep(part=3, name=None))["name"] == "Episode 01"
"""`name` is a reconstruction input for build_title, not a display string."""
assert serialize_title(ep(part=2))["name"] == "Pilot"
assert serialize_title(ep(part=3, name=None))["name"] == "Episode 01"
def test_remote_build_title_round_trip() -> None:
from unshackle.core.remote_service import _build_title
from unshackle.core.remote_service import build_title
rebuilt = _build_title(serialize_title(_ep(1, 4, 2)), "FAKE", "fallback-id")
rebuilt = build_title(serialize_title(ep(1, 4, 2)), "FAKE", "fallback-id")
assert (rebuilt.season, rebuilt.number, rebuilt.part, rebuilt.name) == (1, 4, 2, "Pilot")
partless = _build_title(serialize_title(_ep(1, 4, None)), "FAKE", "fallback-id")
partless = build_title(serialize_title(ep(1, 4, None)), "FAKE", "fallback-id")
assert partless.part is None
@@ -143,32 +143,32 @@ def test_movie_json_unaffected() -> None:
@pytest.fixture
def split_titles() -> List[Episode]:
"""E1 split into three parts, E2 unsplit."""
return [_ep(1, 1, 1), _ep(1, 1, 2), _ep(1, 1, 3), _ep(1, 2, None)]
return [ep(1, 1, 1), ep(1, 1, 2), ep(1, 1, 3), ep(1, 2, None)]
def test_rest_bare_episode_key_selects_every_part(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, wanted="S01E01")
assert _selected(result) == ["1x1.1", "1x1.2", "1x1.3"]
result = run_list_tracks(monkeypatch, split_titles, wanted="S01E01")
assert selected(result) == ["1x1.1", "1x1.2", "1x1.3"]
def test_rest_part_key_selects_exactly_one(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, wanted="S01E01.2")
assert _selected(result) == ["1x1.2"]
result = run_list_tracks(monkeypatch, split_titles, wanted="S01E01.2")
assert selected(result) == ["1x1.2"]
def test_rest_negative_part_key_excludes_only_that_part(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, wanted=["S01", "-S01E01.2"])
assert _selected(result) == ["1x1.1", "1x1.3", "1x2"]
result = run_list_tracks(monkeypatch, split_titles, wanted=["S01", "-S01E01.2"])
assert selected(result) == ["1x1.1", "1x1.3", "1x2"]
def test_rest_partless_episode_unchanged(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, wanted="S01E02")
assert _selected(result) == ["1x2"]
result = run_list_tracks(monkeypatch, split_titles, wanted="S01E02")
assert selected(result) == ["1x2"]
assert "part" not in result["title"]
def test_rest_part_of_unsplit_episode_selects_nothing(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, wanted="S01E02.1")
result = run_list_tracks(monkeypatch, split_titles, wanted="S01E02.1")
assert result["status"] == 404
@@ -176,28 +176,28 @@ def test_rest_part_of_unsplit_episode_selects_nothing(monkeypatch, split_titles)
def test_discrete_fields_without_part_select_every_part(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, season=1, episode=1)
assert _selected(result) == ["1x1.1", "1x1.2", "1x1.3"]
result = run_list_tracks(monkeypatch, split_titles, season=1, episode=1)
assert selected(result) == ["1x1.1", "1x1.2", "1x1.3"]
def test_discrete_fields_with_part_select_one(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, season=1, episode=1, part=3)
assert _selected(result) == ["1x1.3"]
result = run_list_tracks(monkeypatch, split_titles, season=1, episode=1, part=3)
assert selected(result) == ["1x1.3"]
def test_discrete_part_accepts_string(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, season=1, episode=1, part="3")
assert _selected(result) == ["1x1.3"]
result = run_list_tracks(monkeypatch, split_titles, season=1, episode=1, part="3")
assert selected(result) == ["1x1.3"]
def test_discrete_no_match_error_reports_the_part_qualified_key(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, season=1, episode=1, part=9)
result = run_list_tracks(monkeypatch, split_titles, season=1, episode=1, part=9)
assert result["status"] == 404
assert result["details"]["wanted"] == "1x1.9"
def test_discrete_partless_error_key_unchanged(monkeypatch, split_titles) -> None:
result = _run_list_tracks(monkeypatch, split_titles, season=9, episode=9)
result = run_list_tracks(monkeypatch, split_titles, season=9, episode=9)
assert result["details"]["wanted"] == "9x9"
@@ -211,15 +211,15 @@ def test_part_is_a_transport_key_not_a_service_option() -> None:
def test_rest_multi_episode_order_is_stable_across_parts(monkeypatch) -> None:
titles = [_ep(1, 2, None), _ep(1, 1, 3), _ep(1, 1, 1), _ep(1, 1, 2)]
result = _run_list_tracks(monkeypatch, titles, wanted="S01")
assert _selected(result) == ["1x1.1", "1x1.2", "1x1.3", "1x2"]
titles = [ep(1, 2, None), ep(1, 1, 3), ep(1, 1, 1), ep(1, 1, 2)]
result = run_list_tracks(monkeypatch, titles, wanted="S01")
assert selected(result) == ["1x1.1", "1x1.2", "1x1.3", "1x2"]
# ---------- download_manager: already-internal wanted sniff ----------
_SNIFF = r"^!?\d+x\d+(\.\d+)?$"
SNIFF = r"^!?\d+x\d+(\.\d+)?$"
@pytest.mark.parametrize(
@@ -237,7 +237,7 @@ _SNIFF = r"^!?\d+x\d+(\.\d+)?$"
],
)
def test_download_manager_sniff_regex(wanted: List[str], internal: bool) -> None:
needs_conversion = any(not re.match(_SNIFF, w) for w in wanted)
needs_conversion = any(not re.match(SNIFF, w) for w in wanted)
assert needs_conversion is (not internal)
@@ -248,12 +248,12 @@ def test_sniff_regex_matches_the_one_in_download_manager() -> None:
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
assert f'needs_conversion = any(not re.match(r"{SNIFF}", w) for w in wanted_raw)' in source
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.api.download_manager import perform_download
from unshackle.core.utils.click_types import SeasonRange
calls = []
@@ -262,14 +262,14 @@ def test_perform_download_skips_reconversion_for_preparsed_part_keys(monkeypatch
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)
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.api.download_manager import perform_download
from unshackle.core.utils.click_types import SeasonRange
calls = []
@@ -277,7 +277,7 @@ def test_perform_download_still_converts_cli_style_tokens(monkeypatch) -> None:
params: Dict[str, Any] = {"wanted": "S01E01"}
with pytest.raises(BaseException):
_perform_download("job-2", "NoSuchServiceXYZ", "t1", params)
perform_download("job-2", "NoSuchServiceXYZ", "t1", params)
assert calls == [("S01E01",)]
assert params["wanted"] == ["1x1"]
@@ -325,7 +325,7 @@ def test_rest_filter_agrees_with_cli_filter(monkeypatch, split_titles, wanted_to
if t.matches_wanted(wanted)
]
result = _run_list_tracks(monkeypatch, split_titles, wanted=list(wanted_tokens))
rest_selected = [] if result.get("status") == 404 else _selected(result)
result = run_list_tracks(monkeypatch, split_titles, wanted=list(wanted_tokens))
rest_selected = [] if result.get("status") == 404 else selected(result)
assert sorted(rest_selected) == sorted(cli_selected)
+31 -31
View File
@@ -1,7 +1,7 @@
"""The title fields that cross the remote wire: air_date, absolute, anime and daily.
Covers serialize_title's conditional keys, the service-class ANIME/DAILY stamp, and the
serialize_title / title_to_meta round trips through remote_service._build_title.
serialize_title / title_to_meta round trips through remote_service.build_title.
"""
from __future__ import annotations
@@ -16,8 +16,8 @@ from langcodes import Language
from unshackle.commands.dl import dl
from unshackle.core.api import handlers
from unshackle.core.api.handlers import _stamp_service_flags, serialize_title
from unshackle.core.remote_service import _build_title
from unshackle.core.api.handlers import serialize_title, stamp_service_flags
from unshackle.core.remote_service import build_title
from unshackle.core.titles.episode import Episode
from unshackle.core.titles.movie import Movie
@@ -28,7 +28,7 @@ class _FakeSvc:
pass
def _ep(**overrides: Any) -> Episode:
def ep(**overrides: Any) -> Episode:
base: Dict[str, Any] = dict(
id_="ep-0001",
service=_FakeSvc,
@@ -56,7 +56,7 @@ NEW_KEYS = ("air_date", "absolute", "daily", "anime")
def test_a_plain_episode_gains_no_new_keys() -> None:
d = serialize_title(_ep())
d = serialize_title(ep())
assert not [k for k in NEW_KEYS if k in d]
@@ -66,20 +66,20 @@ def test_a_plain_movie_gains_no_new_keys() -> None:
def test_air_date_is_serialized_as_an_iso_string() -> None:
assert serialize_title(_ep(air_date=date(2026, 8, 11)))["air_date"] == "2026-08-11"
assert serialize_title(ep(air_date=date(2026, 8, 11)))["air_date"] == "2026-08-11"
def test_an_unparseable_air_date_is_serialized_as_text() -> None:
assert serialize_title(_ep(air_date="soon"))["air_date"] == "soon"
assert serialize_title(ep(air_date="soon"))["air_date"] == "soon"
def test_absolute_is_serialized() -> None:
assert serialize_title(_ep(absolute=57))["absolute"] == 57
assert serialize_title(ep(absolute=57))["absolute"] == 57
@pytest.mark.parametrize("value", [True, False])
def test_per_title_daily_and_anime_are_serialized_both_ways(value: bool) -> None:
episode = _ep()
episode = ep()
episode.daily = value
episode.anime = value
d = serialize_title(episode)
@@ -107,25 +107,25 @@ class _PlainSvc:
def test_the_stamp_fills_both_flags_from_the_service_class() -> None:
d = _stamp_service_flags(serialize_title(_ep()), _AnimeDailySvc())
d = stamp_service_flags(serialize_title(ep()), _AnimeDailySvc())
assert (d["anime"], d["daily"]) == (True, True)
def test_the_stamp_never_overrides_a_per_title_false() -> None:
episode = _ep()
episode = ep()
episode.anime = False
episode.daily = False
d = _stamp_service_flags(serialize_title(episode), _AnimeDailySvc())
d = stamp_service_flags(serialize_title(episode), _AnimeDailySvc())
assert (d["anime"], d["daily"]) == (False, False)
def test_a_plain_service_stamps_nothing() -> None:
d = _stamp_service_flags(serialize_title(_ep()), _PlainSvc())
d = stamp_service_flags(serialize_title(ep()), _PlainSvc())
assert not [k for k in NEW_KEYS if k in d]
def test_a_movie_is_never_stamped_daily() -> None:
d = _stamp_service_flags(serialize_title(_movie()), _AnimeDailySvc())
d = stamp_service_flags(serialize_title(_movie()), _AnimeDailySvc())
assert d["anime"] is True
assert "daily" not in d
@@ -143,55 +143,55 @@ class _FakeService:
def test_list_titles_stamps_the_service_flags(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "FAKE")
monkeypatch.setattr(handlers, "setup_list_service", lambda *a, **kw: _FakeService([_ep()]))
monkeypatch.setattr(handlers, "setup_list_service", lambda *a, **kw: _FakeService([ep()]))
response = asyncio.run(handlers.list_titles_handler({"service": "FAKE", "title_id": "t1"}))
title = json.loads(response.body)["titles"][0]
assert (title["anime"], title["daily"]) == (True, True)
# ---------- round trips through _build_title ----------
# ---------- round trips through build_title ----------
def _round_trip(episode: Episode, stamp: Optional[Any] = None) -> Episode:
def round_trip(episode: Episode, stamp: Optional[Any] = None) -> Episode:
info = serialize_title(episode)
if stamp is not None:
info = _stamp_service_flags(info, stamp)
return _build_title(info, "FAKE", "fallback-id")
info = stamp_service_flags(info, stamp)
return build_title(info, "FAKE", "fallback-id")
def test_serialize_round_trip_keeps_the_new_fields() -> None:
episode = _ep(air_date=date(2026, 8, 11), absolute=57)
episode = ep(air_date=date(2026, 8, 11), absolute=57)
episode.daily = True
episode.anime = True
rebuilt = _round_trip(episode)
rebuilt = round_trip(episode)
assert rebuilt.air_date == date(2026, 8, 11)
assert rebuilt.absolute == 57
assert (rebuilt.daily, rebuilt.anime) == (True, True)
def test_serialize_round_trip_leaves_unset_flags_inheriting() -> None:
rebuilt = _round_trip(_ep())
rebuilt = round_trip(ep())
assert rebuilt.air_date is None
assert rebuilt.absolute is None
assert (rebuilt.daily, rebuilt.anime) == (None, None)
def test_the_stamped_service_flags_survive_the_round_trip() -> None:
rebuilt = _round_trip(_ep(), stamp=_AnimeDailySvc())
rebuilt = round_trip(ep(), stamp=_AnimeDailySvc())
assert (rebuilt.daily, rebuilt.anime) == (True, True)
def test_a_per_title_false_survives_the_round_trip() -> None:
episode = _ep()
episode = ep()
episode.daily = False
rebuilt = _round_trip(episode)
rebuilt = round_trip(episode)
assert rebuilt.daily is False
def test_a_movie_round_trip_keeps_the_anime_flag() -> None:
movie = _movie()
movie.anime = True
rebuilt = _build_title(serialize_title(movie), "FAKE", "fallback-id")
rebuilt = build_title(serialize_title(movie), "FAKE", "fallback-id")
assert isinstance(rebuilt, Movie)
assert rebuilt.anime is True
@@ -200,22 +200,22 @@ def test_a_movie_round_trip_keeps_the_anime_flag() -> None:
def test_title_to_meta_omits_the_new_keys_for_a_plain_episode() -> None:
meta = dl.title_to_meta(_ep())
meta = dl.title_to_meta(ep())
assert not [k for k in ("absolute", "daily", "anime") if k in meta]
def test_title_to_meta_round_trip_keeps_the_new_fields() -> None:
episode = _ep(air_date=date(2026, 8, 11), absolute=57)
episode = ep(air_date=date(2026, 8, 11), absolute=57)
episode.daily = True
episode.anime = True
rebuilt = _build_title(dl.title_to_meta(episode), "FAKE", "fallback-id")
rebuilt = build_title(dl.title_to_meta(episode), "FAKE", "fallback-id")
assert rebuilt.air_date == date(2026, 8, 11)
assert rebuilt.absolute == 57
assert (rebuilt.daily, rebuilt.anime) == (True, True)
def test_title_to_meta_round_trip_leaves_unset_flags_inheriting() -> None:
rebuilt = _build_title(dl.title_to_meta(_ep()), "FAKE", "fallback-id")
rebuilt = build_title(dl.title_to_meta(ep()), "FAKE", "fallback-id")
assert rebuilt.absolute is None
assert (rebuilt.daily, rebuilt.anime) == (None, None)
@@ -223,5 +223,5 @@ def test_title_to_meta_round_trip_leaves_unset_flags_inheriting() -> None:
def test_title_to_meta_round_trip_keeps_the_movie_anime_flag() -> None:
movie = _movie()
movie.anime = True
rebuilt = _build_title(dl.title_to_meta(movie), "FAKE", "fallback-id")
rebuilt = build_title(dl.title_to_meta(movie), "FAKE", "fallback-id")
assert rebuilt.anime is True
+5 -5
View File
@@ -19,7 +19,7 @@ class _FakeReq:
self.headers = {"Accept-Encoding": accept_encoding}
def _run(coro):
def run(coro):
return asyncio.run(coro)
@@ -30,7 +30,7 @@ def test_skips_when_client_does_not_accept_gzip() -> None:
return web.json_response({"data": "x" * 4096})
req = _FakeReq(accept_encoding="identity")
resp = _run(compression_middleware(req, handler))
resp = run(compression_middleware(req, handler))
assert resp.headers.get("Content-Encoding") != "gzip"
assert resp.body == body_json or len(resp.body) >= len(body_json) - 8
@@ -39,7 +39,7 @@ def test_skips_when_body_below_threshold() -> None:
async def handler(req): # noqa: ARG001
return web.json_response({"hi": "x"})
resp = _run(compression_middleware(_FakeReq(), handler))
resp = run(compression_middleware(_FakeReq(), handler))
assert resp.headers.get("Content-Encoding") != "gzip"
@@ -47,7 +47,7 @@ def test_skips_non_json_response() -> None:
async def handler(req): # noqa: ARG001
return web.Response(body=b"x" * 4096, content_type="text/plain")
resp = _run(compression_middleware(_FakeReq(), handler))
resp = run(compression_middleware(_FakeReq(), handler))
assert resp.headers.get("Content-Encoding") != "gzip"
@@ -57,7 +57,7 @@ def test_compresses_large_json_when_accepted() -> None:
async def handler(req): # noqa: ARG001
return web.json_response(big)
resp = _run(compression_middleware(_FakeReq(), handler))
resp = run(compression_middleware(_FakeReq(), handler))
assert resp.headers.get("Content-Encoding") == "gzip"
decompressed = gzip.decompress(resp.body)
assert json.loads(decompressed) == big
@@ -12,9 +12,9 @@ from unshackle.core.api import handlers
from unshackle.core.api.download_manager import (
DownloadJob,
JobStatus,
_redact_parameters,
_redact_text,
_secret_values,
redact_parameters,
secret_values,
)
from unshackle.core.api.errors import APIError, APIErrorCode
@@ -34,7 +34,7 @@ def test_redact_parameters_masks_secrets_and_proxy_userinfo():
"proxy": "http://bob:secret@proxy.example:8080",
"quality": "1080p",
}
red = _redact_parameters(params)
red = redact_parameters(params)
assert red["credential"] == "***"
assert red["password"] == "***"
assert red["token"] == "***"
@@ -45,11 +45,11 @@ def test_redact_parameters_masks_secrets_and_proxy_userinfo():
def test_redact_parameters_masks_credentials_dict():
assert _redact_parameters({"credentials": {"default": "u:p"}})["credentials"] == "***"
assert redact_parameters({"credentials": {"default": "u:p"}})["credentials"] == "***"
def test_secret_values_includes_password_half_and_dict_values():
secrets = _secret_values({"credential": "user:hunter2", "credentials": {"d": "alice:wonder"}})
secrets = secret_values({"credential": "user:hunter2", "credentials": {"d": "alice:wonder"}})
assert "user:hunter2" in secrets # full credential
assert "hunter2" in secrets # password half of user:pass
assert "alice:wonder" in secrets # value from the credentials map
@@ -98,10 +98,10 @@ def stub_handler(monkeypatch):
forbidden request raises APIError *before* the try block and an allowed one is caught inside it."""
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: tag)
def _boom(*_args, **_kwargs):
def boom(*_args, **_kwargs):
raise _PastGate()
monkeypatch.setattr(handlers.Services, "load", _boom)
monkeypatch.setattr(handlers.Services, "load", boom)
return monkeypatch
+26 -7
View File
@@ -5,8 +5,10 @@ from __future__ import annotations
import pytest
from langcodes import Language
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.api.handlers import (
sanitize_log,
search_handler,
serialize_audio_track,
serialize_drm,
serialize_subtitle_track,
@@ -27,7 +29,7 @@ class _FakeSvc:
pass
def _video(**overrides) -> Video:
def video(**overrides) -> Video:
base = dict(
url="https://example.com/v.mpd",
language=Language.get("en"),
@@ -44,7 +46,7 @@ def _video(**overrides) -> Video:
return Video(**base)
def _audio(**overrides) -> Audio:
def audio(**overrides) -> Audio:
base = dict(
url="https://example.com/a.mpd",
language=Language.get("en"),
@@ -60,7 +62,7 @@ def _audio(**overrides) -> Audio:
return Audio(**base)
def _subtitle(**overrides) -> Subtitle:
def subtitle(**overrides) -> Subtitle:
base = dict(
url="https://example.com/s.vtt",
language=Language.get("en"),
@@ -142,7 +144,7 @@ def test_serialize_title_episode_unnamed_falls_back_to_number() -> None:
def test_serialize_video_track_basic() -> None:
d = serialize_video_track(_video())
d = serialize_video_track(video())
assert d["id"] == "video-001"
assert d["codec"] == "AVC"
assert d["bitrate"] == 5000 # kbps
@@ -155,12 +157,12 @@ def test_serialize_video_track_basic() -> None:
def test_serialize_video_track_include_url() -> None:
d = serialize_video_track(_video(), include_url=True)
d = serialize_video_track(video(), include_url=True)
assert d["url"] == "https://example.com/v.mpd"
def test_serialize_audio_track_basic() -> None:
d = serialize_audio_track(_audio())
d = serialize_audio_track(audio())
assert d["id"] == "audio-001"
assert d["codec"] == "AAC"
assert d["bitrate"] == 128
@@ -169,7 +171,7 @@ def test_serialize_audio_track_basic() -> None:
def test_serialize_subtitle_track_basic() -> None:
d = serialize_subtitle_track(_subtitle(forced=True))
d = serialize_subtitle_track(subtitle(forced=True))
assert d["id"] == "sub-001"
assert d["codec"] == "WebVTT"
assert d["forced"] is True
@@ -287,3 +289,20 @@ def test_validate_download_params_accepts_valid_values() -> None:
)
is None
)
async def test_search_missing_service_raises_invalid_input() -> None:
# MISSING_SERVICE was never an APIErrorCode member, so this raised AttributeError
# and routes.py surfaced a 500 instead of the intended 400.
with pytest.raises(APIError) as exc:
await search_handler({"query": "dune"}, None)
assert exc.value.error_code == APIErrorCode.INVALID_INPUT
assert APIError.default_http_status(exc.value.error_code) == 400
async def test_search_unknown_service_raises_invalid_service() -> None:
# get_tag echoes unknown tags back, so the old `not normalized_service` guard
# never fired and Services.get_path leaked a KeyError as a 500.
with pytest.raises(APIError) as exc:
await search_handler({"service": "NOPE_THIS_IS_NOT_REAL_", "query": "x"}, None)
assert exc.value.error_code == APIErrorCode.INVALID_SERVICE
+6 -6
View File
@@ -45,7 +45,7 @@ class Subtitle:
self.bitrate = None
def _noop(**kwargs):
def noop(**kwargs):
pass
@@ -66,7 +66,7 @@ def test_weight_video_over_audio_over_subtitle():
def test_weighting_makes_video_dominate_progress():
updates: list[dict] = []
video, sub = Video(bitrate=4_000_000), Subtitle()
cbs = build_job_progress_callables([video, sub], [_noop, _noop], updates.append)
cbs = build_job_progress_callables([video, sub], [noop, noop], updates.append)
# subtitle fully done, video untouched -> progress is tiny (subtitle barely weighted)
cbs[1](downloaded="Downloaded")
@@ -80,7 +80,7 @@ def test_weighting_makes_video_dominate_progress():
def test_active_tracks_labels_reported_and_cleared_on_done():
updates: list[dict] = []
cbs = build_job_progress_callables([Video(2160, "DV"), Audio("en-US", "2.0")], [_noop, _noop], updates.append)
cbs = build_job_progress_callables([Video(2160, "DV"), Audio("en-US", "2.0")], [noop, noop], updates.append)
cbs[0](total=100, completed=10) # video downloading
assert updates[-1]["active_tracks"] == ["video 2160p DV"]
@@ -121,7 +121,7 @@ def test_aggregate_progress_is_monotonic_with_counts():
def test_all_tracks_done_reaches_download_ceiling():
# Downloads fill up to the ceiling; dl.result drives muxing the rest of the way to 100.
updates: list[dict] = []
cbs = build_job_progress_callables([Audio(bitrate=1000), Audio(bitrate=1000)], [_noop, _noop], updates.append)
cbs = build_job_progress_callables([Audio(bitrate=1000), Audio(bitrate=1000)], [noop, noop], updates.append)
cbs[0](total=10, completed=10, downloaded="Downloaded")
assert updates[-1]["progress"] < DOWNLOAD_PROGRESS_CEILING
@@ -136,7 +136,7 @@ def test_finished_track_does_not_dip_when_callable_reused_for_decrypt():
"""A track hits 100% (then decrypt reuses the callable with completed=0); the aggregate must
hold, never dip - even before the terminal 'Downloaded'/'Decrypted' string arrives."""
updates: list[dict] = []
cbs = build_job_progress_callables([Video(bitrate=1000), Video(bitrate=1000)], [_noop, _noop], updates.append)
cbs = build_job_progress_callables([Video(bitrate=1000), Video(bitrate=1000)], [noop, noop], updates.append)
cbs[0](total=100, completed=100) # download hits 100% BEFORE any terminal string -> 50%
cbs[0](total=200, completed=0) # decrypt phase resets counts, still no terminal string
@@ -151,7 +151,7 @@ def test_finished_track_does_not_dip_when_callable_reused_for_decrypt():
def test_skipped_subtitle_counts_as_done():
updates: list[dict] = []
cbs = build_job_progress_callables([Subtitle()], [_noop], updates.append)
cbs = build_job_progress_callables([Subtitle()], [noop], updates.append)
cbs[0](downloaded="[yellow]SKIPPED")
assert updates[-1]["completed_tracks"] == 1
assert updates[-1]["progress"] == pytest.approx(DOWNLOAD_PROGRESS_CEILING)
+6 -6
View File
@@ -1,11 +1,11 @@
"""Unit tests for resolve_server / _resolve_proxy in unshackle.core.remote_service."""
"""Unit tests for resolve_server / resolve_proxy_arg in unshackle.core.remote_service."""
from __future__ import annotations
import click
import pytest
from unshackle.core.remote_service import _resolve_proxy, resolve_server
from unshackle.core.remote_service import resolve_proxy_arg, resolve_server
pytestmark = pytest.mark.unit
@@ -126,8 +126,8 @@ def test_resolve_server_multi_with_name(multi_remote_services) -> None:
def test_resolve_proxy_none_returns_none() -> None:
assert _resolve_proxy(None) is None
assert _resolve_proxy("") is None
assert resolve_proxy_arg(None) is None
assert resolve_proxy_arg("") is None
def test_resolve_proxy_passes_through_value(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -136,7 +136,7 @@ def test_resolve_proxy_passes_through_value(monkeypatch: pytest.MonkeyPatch) ->
monkeypatch.setattr(resolve_mod, "initialize_proxy_providers", lambda: [])
monkeypatch.setattr(resolve_mod, "resolve_proxy", lambda arg, providers: f"http://proxy/{arg}")
assert _resolve_proxy("us") == "http://proxy/us"
assert resolve_proxy_arg("us") == "http://proxy/us"
def test_resolve_proxy_value_error_becomes_click(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -150,5 +150,5 @@ def test_resolve_proxy_value_error_becomes_click(monkeypatch: pytest.MonkeyPatch
monkeypatch.setattr(resolve_mod, "resolve_proxy", boom)
with pytest.raises(click.ClickException) as exc:
_resolve_proxy("xx")
resolve_proxy_arg("xx")
assert "no such country" in str(exc.value.message)
@@ -7,14 +7,14 @@ from enum import Enum
import pytest
from unshackle.core.remote_service import (
_build_title,
_build_tracks,
_deserialize_audio,
_deserialize_subtitle,
_deserialize_video,
_enum_get,
_match_track,
_reconstruct_drm,
build_title,
build_tracks,
deserialize_audio,
deserialize_subtitle,
deserialize_video,
enum_get,
match_track,
reconstruct_drm,
)
from unshackle.core.titles.episode import Episode
from unshackle.core.titles.movie import Movie
@@ -29,19 +29,19 @@ class _Color(Enum):
def test_enum_get_known() -> None:
assert _enum_get(_Color, "RED") is _Color.RED
assert enum_get(_Color, "RED") is _Color.RED
def test_enum_get_unknown_returns_default() -> None:
assert _enum_get(_Color, "PURPLE", default=_Color.BLUE) is _Color.BLUE
assert enum_get(_Color, "PURPLE", default=_Color.BLUE) is _Color.BLUE
def test_enum_get_none_returns_default() -> None:
assert _enum_get(_Color, None, default=_Color.RED) is _Color.RED
assert enum_get(_Color, None, default=_Color.RED) is _Color.RED
def test_deserialize_video_minimal() -> None:
v = _deserialize_video({"id": "video-1", "codec": "AVC", "width": 1920, "height": 1080, "bitrate": 5000})
v = deserialize_video({"id": "video-1", "codec": "AVC", "width": 1920, "height": 1080, "bitrate": 5000})
assert isinstance(v, Video)
assert v.id == "video-1"
assert v.codec is Video.Codec.AVC
@@ -52,12 +52,12 @@ def test_deserialize_video_minimal() -> None:
def test_deserialize_video_unknown_codec_falls_back_to_none() -> None:
v = _deserialize_video({"id": "v2", "codec": "MADE_UP", "width": 0, "height": 0})
v = deserialize_video({"id": "v2", "codec": "MADE_UP", "width": 0, "height": 0})
assert v.codec is None
def test_deserialize_audio_atmos_flag_sets_joc() -> None:
a = _deserialize_audio({"id": "a1", "codec": "AAC", "atmos": True, "channels": 6, "bitrate": 256})
a = deserialize_audio({"id": "a1", "codec": "AAC", "atmos": True, "channels": 6, "bitrate": 256})
assert isinstance(a, Audio)
assert a.joc == 1
assert a.channels == 6
@@ -65,34 +65,34 @@ def test_deserialize_audio_atmos_flag_sets_joc() -> None:
def test_deserialize_audio_no_atmos() -> None:
a = _deserialize_audio({"id": "a2", "codec": "AAC", "channels": 2})
a = deserialize_audio({"id": "a2", "codec": "AAC", "channels": 2})
assert a.joc == 0
def test_deserialize_subtitle_forced_flag() -> None:
s = _deserialize_subtitle({"id": "s1", "codec": "WebVTT", "language": "en", "forced": True})
s = deserialize_subtitle({"id": "s1", "codec": "WebVTT", "language": "en", "forced": True})
assert isinstance(s, Subtitle)
assert s.forced is True
assert s.sdh is False
def test_deserialize_subtitle_sdh_flag() -> None:
s = _deserialize_subtitle({"id": "s2", "codec": "WebVTT", "language": "en", "sdh": True})
s = deserialize_subtitle({"id": "s2", "codec": "WebVTT", "language": "en", "sdh": True})
assert s.sdh is True
assert s.forced is False
def test_reconstruct_drm_empty() -> None:
assert _reconstruct_drm(None) == []
assert _reconstruct_drm([]) == []
assert reconstruct_drm(None) == []
assert reconstruct_drm([]) == []
def test_reconstruct_drm_skips_entries_without_pssh() -> None:
assert _reconstruct_drm([{"type": "widevine"}]) == []
assert reconstruct_drm([{"type": "widevine"}]) == []
def test_reconstruct_drm_invalid_pssh_silently_dropped() -> None:
assert _reconstruct_drm([{"type": "widevine", "pssh": "not-real-pssh"}]) == []
assert reconstruct_drm([{"type": "widevine", "pssh": "not-real-pssh"}]) == []
def test_build_tracks_aggregates() -> None:
@@ -102,33 +102,33 @@ def test_build_tracks_aggregates() -> None:
"subtitles": [{"id": "s", "codec": "WebVTT", "language": "en"}],
"attachments": [],
}
t = _build_tracks(data)
t = build_tracks(data)
assert len(t.videos) == 1
assert len(t.audio) == 1
assert len(t.subtitles) == 1
def test_match_track_by_id() -> None:
a = _deserialize_video({"id": "v1", "codec": "AVC", "width": 1920, "height": 1080})
b = _deserialize_video({"id": "v2", "codec": "AVC", "width": 1280, "height": 720})
remote = _deserialize_video({"id": "v2", "codec": "AVC", "width": 1280, "height": 720})
assert _match_track(remote, [a, b]) is b
a = deserialize_video({"id": "v1", "codec": "AVC", "width": 1920, "height": 1080})
b = deserialize_video({"id": "v2", "codec": "AVC", "width": 1280, "height": 720})
remote = deserialize_video({"id": "v2", "codec": "AVC", "width": 1280, "height": 720})
assert match_track(remote, [a, b]) is b
def test_match_track_by_attributes_when_id_missing() -> None:
local = _deserialize_video({"id": "X", "codec": "AVC", "width": 1920, "height": 1080, "language": "en"})
remote = _deserialize_video({"id": "Y", "codec": "AVC", "width": 1920, "height": 1080, "language": "en"})
assert _match_track(remote, [local]) is local
local = deserialize_video({"id": "X", "codec": "AVC", "width": 1920, "height": 1080, "language": "en"})
remote = deserialize_video({"id": "Y", "codec": "AVC", "width": 1920, "height": 1080, "language": "en"})
assert match_track(remote, [local]) is local
def test_match_track_no_candidates_returns_none() -> None:
remote = _deserialize_video({"id": "X", "codec": "AVC", "width": 1, "height": 1})
assert _match_track(remote, []) is None
remote = deserialize_video({"id": "X", "codec": "AVC", "width": 1, "height": 1})
assert match_track(remote, []) is None
def test_build_title_movie() -> None:
info = {"type": "movie", "id": "movie-0001", "name": "Foo", "year": 2024, "language": "en"}
title = _build_title(info, "ATV", "fallback")
title = build_title(info, "ATV", "fallback")
assert isinstance(title, Movie)
assert title.id == "movie-0001"
assert title.name == "Foo"
@@ -145,7 +145,7 @@ def test_build_title_episode() -> None:
"year": 2024,
"language": "en",
}
title = _build_title(info, "ATV", "fallback")
title = build_title(info, "ATV", "fallback")
assert isinstance(title, Episode)
assert title.season == 1
assert title.number == 2
@@ -153,5 +153,5 @@ def test_build_title_episode() -> None:
def test_build_title_falls_back_to_id_when_missing() -> None:
title = _build_title({"type": "movie", "name": "x"}, "ATV", "fallback-id")
title = build_title({"type": "movie", "name": "x"}, "ATV", "fallback-id")
assert title.id == "fallback-id"
+12 -12
View File
@@ -21,20 +21,20 @@ pytestmark = pytest.mark.unit
def make_app():
"""Factory that builds an aiohttp app for tests."""
def _factory(remote_only: bool = False, with_auth_middleware: bool = False):
def factory(remote_only: bool = False, with_auth_middleware: bool = False):
middlewares = [cors_middleware, compression_middleware]
if with_auth_middleware:
middlewares.insert(1, _no_key_required_auth())
middlewares.insert(1, no_key_required_auth())
app = web.Application(middlewares=middlewares)
app["config"] = {"users": {}}
app["debug_api"] = False
setup_routes(app, remote_only=remote_only)
return app
return _factory
return factory
def _no_key_required_auth():
def no_key_required_auth():
"""Mirror serve.py's api_key_authentication middleware: required X-Secret-Key
on every endpoint except /api/health."""
@@ -52,13 +52,13 @@ def _no_key_required_auth():
return mw
def _collect_paths(app: web.Application) -> list[tuple[str, str]]:
def collect_paths(app: web.Application) -> list[tuple[str, str]]:
return sorted({(r.method, r.resource.canonical) for r in app.router.routes()})
def test_setup_routes_full_mode_wires_all_endpoints(make_app) -> None:
app = make_app(remote_only=False)
paths = _collect_paths(app)
paths = collect_paths(app)
expected = {
("GET", "/api/health"),
("GET", "/api/services"),
@@ -84,7 +84,7 @@ def test_setup_routes_full_mode_wires_all_endpoints(make_app) -> None:
def test_setup_routes_remote_only_excludes_list_and_download(make_app) -> None:
app = make_app(remote_only=True)
paths = set(_collect_paths(app))
paths = set(collect_paths(app))
assert ("POST", "/api/list-titles") not in paths
assert ("POST", "/api/list-tracks") not in paths
assert ("POST", "/api/download") not in paths
@@ -121,7 +121,7 @@ async def test_api_handler_maps_apierror(aiohttp_client) -> None:
client = await aiohttp_client(app)
resp = await client.get("/boom")
assert resp.status == 404 # NOT_FOUND -> 404 per errors.APIError._default_http_status
assert resp.status == 404 # NOT_FOUND -> 404 per errors.APIError.default_http_status
body = await resp.json()
assert body["status"] == "error"
assert body["error_code"] == "NOT_FOUND"
@@ -142,10 +142,10 @@ async def test_cors_preflight_returns_headers(make_app, aiohttp_client) -> None:
async def test_health_endpoint_responds_ok(make_app, aiohttp_client, monkeypatch: pytest.MonkeyPatch) -> None:
from unshackle.core.api import routes as routes_mod
async def _no_update(_):
async def no_update(_):
return None
monkeypatch.setattr(routes_mod.UpdateChecker, "check_for_updates", _no_update)
monkeypatch.setattr(routes_mod.UpdateChecker, "check_for_updates", no_update)
app = make_app(remote_only=True)
client = await aiohttp_client(app)
resp = await client.get("/api/health")
@@ -158,10 +158,10 @@ async def test_health_endpoint_responds_ok(make_app, aiohttp_client, monkeypatch
async def test_health_bypasses_api_key_auth_middleware(make_app, aiohttp_client, monkeypatch) -> None:
from unshackle.core.api import routes as routes_mod
async def _no_update(_):
async def no_update(_):
return None
monkeypatch.setattr(routes_mod.UpdateChecker, "check_for_updates", _no_update)
monkeypatch.setattr(routes_mod.UpdateChecker, "check_for_updates", no_update)
app = make_app(remote_only=True, with_auth_middleware=True)
client = await aiohttp_client(app)
+4 -4
View File
@@ -28,13 +28,13 @@ def serve_users(monkeypatch):
monkeypatch.setattr(handlers, "request_secret_key", lambda request: request.headers.get("X-Secret-Key"))
def _request(key):
def request(key):
return SimpleNamespace(headers={"X-Secret-Key": key} if key else {})
@pytest.mark.parametrize(("key", "allowed"), ENTITLEMENTS)
def test_server_cdm_allowed(serve_users, key, allowed):
assert handlers.server_cdm_allowed(_request(key)) is allowed
assert handlers.server_cdm_allowed(request(key)) is allowed
def test_no_request_allows(serve_users):
@@ -45,10 +45,10 @@ def test_no_request_allows(serve_users):
def test_download_gate_follows_entitlement(serve_users, key, allowed):
# A download job licenses with the server CDM, so submission obeys the same gate.
if allowed:
handlers.enforce_download_gates({}, _request(key))
handlers.enforce_download_gates({}, request(key))
else:
with pytest.raises(APIError) as ei:
handlers.enforce_download_gates({}, _request(key))
handlers.enforce_download_gates({}, request(key))
assert ei.value.error_code == APIErrorCode.FORBIDDEN
+2 -2
View File
@@ -69,7 +69,7 @@ async def test_cleanup_expired_drops_old_authenticated(store: SessionStore, monk
from datetime import datetime, timedelta, timezone
entry = await store.create("ATV", _FakeService())
entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store._ttl + 100)
entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 100)
removed = await store.cleanup_expired()
assert removed == 1
assert store.session_count == 0
@@ -118,7 +118,7 @@ async def test_get_session_store_returns_singleton() -> None:
async def test_max_sessions_evicts_oldest(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(type(store), "_max_sessions", property(lambda _: 2))
monkeypatch.setattr(type(store), "max_sessions", property(lambda _: 2))
await store.create("A", _FakeService(), session_id="a")
await asyncio.sleep(0.01)
+23 -23
View File
@@ -14,73 +14,73 @@ from pathlib import Path
from unshackle.core.tracks.track import has_encrypted_sample_entry
def _box(fmt: bytes, payload: bytes = b"") -> bytes:
def box(fmt: bytes, payload: bytes = b"") -> bytes:
return struct.pack(">I", 8 + len(payload)) + fmt + payload
def _sample_entry(fmt: bytes, payload: bytes = b"") -> bytes:
def sample_entry(fmt: bytes, payload: bytes = b"") -> bytes:
body = b"\x00" * 6 + struct.pack(">H", 1) + payload # reserved + data_reference_index
return struct.pack(">I", 8 + len(body)) + fmt + body
def _stsd(entries: list[bytes]) -> bytes:
def stsd(entries: list[bytes]) -> bytes:
body = b"\x00" * 4 + struct.pack(">I", len(entries)) + b"".join(entries) # version/flags + count
return _box(b"stsd", body)
return box(b"stsd", body)
def _moov(*children: bytes) -> bytes:
stbl = _box(b"stbl", b"".join(children))
return _box(b"moov", _box(b"trak", _box(b"mdia", _box(b"minf", stbl))))
def moov(*children: bytes) -> bytes:
stbl = box(b"stbl", b"".join(children))
return box(b"moov", box(b"trak", box(b"mdia", box(b"minf", stbl))))
FTYP = _box(b"ftyp", b"isom\x00\x00\x02\x00isomiso2")
FTYP = box(b"ftyp", b"isom\x00\x00\x02\x00isomiso2")
# stray [size][encv] byte run as compressed A/V payload could randomly contain
STRAY_ENCV = b"\xde\xad" * 4 + struct.pack(">I", 100) + b"encv" + b"\xbe\xef" * 8
def _write(tmp_path: Path, name: str, *boxes: bytes) -> Path:
def write(tmp_path: Path, name: str, *boxes: bytes) -> Path:
f = tmp_path / name
f.write_bytes(b"".join(boxes))
return f
def test_dual_stsd_encv_and_avc1_detected(tmp_path: Path) -> None:
sinf = _box(b"sinf", _box(b"frma", b"avc1"))
avc1 = _sample_entry(b"avc1", b"\x00" * 70)
encv = _sample_entry(b"encv", b"\x00" * 70 + sinf)
f = _write(tmp_path, "dual.mp4", FTYP, _moov(_stsd([avc1, encv])), _box(b"mdat", b"\x00" * 32))
sinf = box(b"sinf", box(b"frma", b"avc1"))
avc1 = sample_entry(b"avc1", b"\x00" * 70)
encv = sample_entry(b"encv", b"\x00" * 70 + sinf)
f = write(tmp_path, "dual.mp4", FTYP, moov(stsd([avc1, encv])), box(b"mdat", b"\x00" * 32))
assert has_encrypted_sample_entry(f) is True
def test_single_avc1_not_detected(tmp_path: Path) -> None:
avc1 = _sample_entry(b"avc1", b"\x00" * 70)
f = _write(tmp_path, "clear.mp4", FTYP, _moov(_stsd([avc1])), _box(b"mdat", b"\x00" * 32))
avc1 = sample_entry(b"avc1", b"\x00" * 70)
f = write(tmp_path, "clear.mp4", FTYP, moov(stsd([avc1])), box(b"mdat", b"\x00" * 32))
assert has_encrypted_sample_entry(f) is False
def test_stray_encv_in_mdat_not_detected(tmp_path: Path) -> None:
# clean moov, mdat happens to contain a plausible [size][encv] run -> must NOT flag
avc1 = _sample_entry(b"avc1", b"\x00" * 70)
f = _write(tmp_path, "stray.mp4", FTYP, _moov(_stsd([avc1])), _box(b"mdat", STRAY_ENCV))
avc1 = sample_entry(b"avc1", b"\x00" * 70)
f = write(tmp_path, "stray.mp4", FTYP, moov(stsd([avc1])), box(b"mdat", STRAY_ENCV))
assert has_encrypted_sample_entry(f) is False
def test_leading_mdat_does_not_mask_real_encv(tmp_path: Path) -> None:
# progressive layout (mdat before moov) with a stray run must not hide a genuine encv
enca = _sample_entry(b"enca", b"\x00" * 20 + _box(b"sinf", _box(b"frma", b"mp4a")))
f = _write(tmp_path, "masked.mp4", FTYP, _box(b"mdat", STRAY_ENCV), _moov(_stsd([enca])))
enca = sample_entry(b"enca", b"\x00" * 20 + box(b"sinf", box(b"frma", b"mp4a")))
f = write(tmp_path, "masked.mp4", FTYP, box(b"mdat", STRAY_ENCV), moov(stsd([enca])))
assert has_encrypted_sample_entry(f) is True
def test_text_containing_enca_in_moov_not_detected(tmp_path: Path) -> None:
# "enca" inside a metadata string has no plausible box size before it -> must NOT flag
avc1 = _sample_entry(b"avc1", b"\x00" * 70)
udta = _box(b"udta", b"data is encapsulated here")
f = _write(tmp_path, "text.mp4", FTYP, _box(b"moov", _stsd([avc1]) + udta))
avc1 = sample_entry(b"avc1", b"\x00" * 70)
udta = box(b"udta", b"data is encapsulated here")
f = write(tmp_path, "text.mp4", FTYP, box(b"moov", stsd([avc1]) + udta))
assert has_encrypted_sample_entry(f) is False
def test_missing_or_bogus_file(tmp_path: Path) -> None:
assert has_encrypted_sample_entry(tmp_path / "nope.mp4") is False
bogus = _write(tmp_path, "bogus.bin", b"\x00\x01\x02\x03not-an-mp4")
bogus = write(tmp_path, "bogus.bin", b"\x00\x01\x02\x03not-an-mp4")
assert has_encrypted_sample_entry(bogus) is False
+38 -38
View File
@@ -19,54 +19,54 @@ from unshackle.core.manifests.ism_init import PIFF_SENC_UUID
from unshackle.core.tracks.track import assert_fragments_decrypted
def _box(fmt: bytes, payload: bytes = b"") -> bytes:
def box(fmt: bytes, payload: bytes = b"") -> bytes:
return struct.pack(">I", 8 + len(payload)) + fmt + payload
def _senc(sample_count: int = 4) -> bytes:
return _box(b"senc", b"\x00" * 4 + struct.pack(">I", sample_count) + b"\x00" * (8 * sample_count))
def senc(sample_count: int = 4) -> bytes:
return box(b"senc", b"\x00" * 4 + struct.pack(">I", sample_count) + b"\x00" * (8 * sample_count))
def _piff_senc(sample_count: int = 4) -> bytes:
def piff_senc(sample_count: int = 4) -> bytes:
body = PIFF_SENC_UUID + b"\x00" * 4 + struct.pack(">I", sample_count) + b"\x00" * (8 * sample_count)
return _box(b"uuid", body)
return box(b"uuid", body)
def _moof(*children: bytes, sdi: int = 1) -> bytes:
tfhd = _box(b"tfhd", b"\x00\x00\x00\x02" + struct.pack(">II", 1, sdi)) # sample-description-index-present
return _box(b"moof", _box(b"mfhd", b"\x00" * 8) + _box(b"traf", tfhd + b"".join(children)))
def moof(*children: bytes, sdi: int = 1) -> bytes:
tfhd = box(b"tfhd", b"\x00\x00\x00\x02" + struct.pack(">II", 1, sdi)) # sample-description-index-present
return box(b"moof", box(b"mfhd", b"\x00" * 8) + box(b"traf", tfhd + b"".join(children)))
FTYP = _box(b"ftyp", b"isom\x00\x00\x02\x00isomiso2")
MOOV = _box(b"moov", _box(b"mvex", _box(b"trex", b"\x00" * 24)))
MDAT = _box(b"mdat", b"\x00" * 64)
FTYP = box(b"ftyp", b"isom\x00\x00\x02\x00isomiso2")
MOOV = box(b"moov", box(b"mvex", box(b"trex", b"\x00" * 24)))
MDAT = box(b"mdat", b"\x00" * 64)
# a compressed payload can contain anything, including plausible-looking box runs
STRAY = _box(b"mdat", struct.pack(">I", 64) + b"senc" + b"\xbe\xef" * 8 + PIFF_SENC_UUID)
STRAY = box(b"mdat", struct.pack(">I", 64) + b"senc" + b"\xbe\xef" * 8 + PIFF_SENC_UUID)
def _write(tmp_path: Path, name: str, *boxes: bytes) -> Path:
def write(tmp_path: Path, name: str, *boxes: bytes) -> Path:
f = tmp_path / name
f.write_bytes(b"".join(boxes))
return f
def test_all_fragments_decrypted_passes(tmp_path: Path) -> None:
f = _write(tmp_path, "clean.mp4", FTYP, MOOV, _moof(), MDAT, _moof(sdi=2), MDAT)
f = write(tmp_path, "clean.mp4", FTYP, MOOV, moof(), MDAT, moof(sdi=2), MDAT)
assert_fragments_decrypted(f)
def test_surviving_senc_raises(tmp_path: Path) -> None:
# the real bug: fragment 1 (index 1) decrypted, the rest (index 2) silently skipped
boxes = [FTYP, MOOV, _moof(), MDAT]
boxes = [FTYP, MOOV, moof(), MDAT]
for _ in range(3):
boxes += [_moof(_senc(), sdi=2), MDAT]
f = _write(tmp_path, "skipped.mp4", *boxes)
boxes += [moof(senc(), sdi=2), MDAT]
f = write(tmp_path, "skipped.mp4", *boxes)
with pytest.raises(ValueError, match=r"3/4 fragment"):
assert_fragments_decrypted(f)
def test_surviving_cenc_senc_raises(tmp_path: Path) -> None:
f = _write(tmp_path, "cenc.mp4", FTYP, MOOV, _moof(_senc()), MDAT)
f = write(tmp_path, "cenc.mp4", FTYP, MOOV, moof(senc()), MDAT)
with pytest.raises(ValueError, match=r"1/1 fragment"):
assert_fragments_decrypted(f)
@@ -76,59 +76,59 @@ def test_leftover_piff_uuid_after_senc_removed_does_not_raise(tmp_path: Path) ->
# consumed senc, detached senc/saiz/saio, and left the uuid on a fully decrypted fragment.
boxes = [FTYP, MOOV]
for _ in range(3):
boxes += [_moof(_piff_senc()), MDAT]
f = _write(tmp_path, "piff_leftover.mp4", *boxes)
boxes += [moof(piff_senc()), MDAT]
f = write(tmp_path, "piff_leftover.mp4", *boxes)
assert_fragments_decrypted(f)
def test_stray_senc_bytes_in_mdat_ignored(tmp_path: Path) -> None:
f = _write(tmp_path, "stray.mp4", FTYP, MOOV, _moof(), STRAY, _moof(sdi=2), STRAY)
f = write(tmp_path, "stray.mp4", FTYP, MOOV, moof(), STRAY, moof(sdi=2), STRAY)
assert_fragments_decrypted(f)
def test_senc_text_without_plausible_size_ignored(tmp_path: Path) -> None:
# "senc" inside a free-box string has no valid box size before it
f = _write(tmp_path, "text.mp4", FTYP, MOOV, _moof(_box(b"free", b"presence sencoded here")), MDAT)
f = write(tmp_path, "text.mp4", FTYP, MOOV, moof(box(b"free", b"presence sencoded here")), MDAT)
assert_fragments_decrypted(f)
def test_senc_bytes_inside_trun_payload_ignored(tmp_path: Path) -> None:
# a trun sample entry spelling "senc" after a size-looking duration; only a byte scan bites
trun = _box(b"trun", b"\x00\x00\x03\x01" + struct.pack(">I", 2) + struct.pack(">I", 512) + b"senc")
f = _write(tmp_path, "trun.mp4", FTYP, MOOV, _moof(trun), MDAT)
trun = box(b"trun", b"\x00\x00\x03\x01" + struct.pack(">I", 2) + struct.pack(">I", 512) + b"senc")
f = write(tmp_path, "trun.mp4", FTYP, MOOV, moof(trun), MDAT)
assert_fragments_decrypted(f)
def test_empty_senc_on_clear_fragment_ignored(tmp_path: Path) -> None:
# sample_count 0 marks a fragment with no protected samples, so the guard ignores it
f = _write(tmp_path, "empty.mp4", FTYP, MOOV, _moof(_senc(sample_count=0)), MDAT)
f = write(tmp_path, "empty.mp4", FTYP, MOOV, moof(senc(sample_count=0)), MDAT)
assert_fragments_decrypted(f)
def _senc_override(sample_count: int) -> bytes:
def senc_override(sample_count: int) -> bytes:
# flags&1 => AlgorithmID(3) + IV_size(1) + KID(16) precede sample_count
head = b"\x00\x00\x00\x01" + b"\x00\x00\x08" + b"\x08" + b"\xaa" * 16
return _box(b"senc", head + struct.pack(">I", sample_count) + b"\x00" * (8 * sample_count))
return box(b"senc", head + struct.pack(">I", sample_count) + b"\x00" * (8 * sample_count))
def test_override_flag_shifts_sample_count_offset(tmp_path: Path) -> None:
clear = _write(tmp_path, "ovr_clear.mp4", FTYP, MOOV, _moof(_senc_override(0)), MDAT)
clear = write(tmp_path, "ovr_clear.mp4", FTYP, MOOV, moof(senc_override(0)), MDAT)
assert_fragments_decrypted(clear)
f = _write(tmp_path, "ovr.mp4", FTYP, MOOV, _moof(_senc_override(5)), MDAT)
f = write(tmp_path, "ovr.mp4", FTYP, MOOV, moof(senc_override(5)), MDAT)
with pytest.raises(ValueError, match=r"1/1 fragment"):
assert_fragments_decrypted(f)
def test_senc_outside_traf_ignored(tmp_path: Path) -> None:
# a decrypted moof whose only "senc" sits in a sibling box outside any traf
f = _write(tmp_path, "sibling.mp4", FTYP, MOOV, _box(b"moof", _box(b"mfhd", b"\x00" * 8) + _senc()), MDAT)
f = write(tmp_path, "sibling.mp4", FTYP, MOOV, box(b"moof", box(b"mfhd", b"\x00" * 8) + senc()), MDAT)
assert_fragments_decrypted(f)
def test_senc_nested_under_non_traf_ignored(tmp_path: Path) -> None:
# senc two levels down under a non-traf container: only traf children count
meta = _box(b"meta", _senc())
f = _write(tmp_path, "nested.mp4", FTYP, MOOV, _box(b"moof", _box(b"mfhd", b"\x00" * 8) + meta), MDAT)
meta = box(b"meta", senc())
f = write(tmp_path, "nested.mp4", FTYP, MOOV, box(b"moof", box(b"mfhd", b"\x00" * 8) + meta), MDAT)
assert_fragments_decrypted(f)
@@ -136,17 +136,17 @@ def test_undersized_largesize_box_does_not_desync_walk(tmp_path: Path, caplog: p
# size==1 reads a 16-byte header, so a largesize of 12 clears the 8-byte floor but
# still stalls the cursor onto payload; only a header-aware floor catches it
runt = struct.pack(">I", 1) + b"free" + struct.pack(">Q", 12)
f = _write(tmp_path, "runt.mp4", FTYP, MOOV, runt, _moof(_senc()), MDAT, _moof(_senc()), MDAT)
f = write(tmp_path, "runt.mp4", FTYP, MOOV, runt, moof(senc()), MDAT, moof(senc()), MDAT)
with caplog.at_level("WARNING"):
assert_fragments_decrypted(f)
assert "malformed box size" in caplog.text
def test_largesize_and_zero_size_boxes_walked(tmp_path: Path) -> None:
frag = _moof(_senc())
frag = moof(senc())
large = struct.pack(">I", 1) + b"mdat" + struct.pack(">Q", 16 + 64) + b"\x00" * 64
trailing = struct.pack(">I", 0) + b"mdat" + b"\x00" * 64 # size 0 => runs to EOF
f = _write(tmp_path, "large.mp4", FTYP, MOOV, frag, large, trailing)
f = write(tmp_path, "large.mp4", FTYP, MOOV, frag, large, trailing)
with pytest.raises(ValueError, match=r"1/1 fragment"):
assert_fragments_decrypted(f)
@@ -154,7 +154,7 @@ def test_largesize_and_zero_size_boxes_walked(tmp_path: Path) -> None:
def test_malformed_box_size_warns_and_does_not_raise(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
# failing open is deliberate, but the abort must be logged so it cannot pass as clean
overrun = struct.pack(">I", 1 << 30) + b"free" + b"\x00" * 8
f = _write(tmp_path, "overrun.mp4", FTYP, MOOV, overrun, _moof(_senc()), MDAT)
f = write(tmp_path, "overrun.mp4", FTYP, MOOV, overrun, moof(senc()), MDAT)
with caplog.at_level("WARNING"):
assert_fragments_decrypted(f)
assert "malformed box size" in caplog.text
@@ -162,6 +162,6 @@ def test_malformed_box_size_warns_and_does_not_raise(tmp_path: Path, caplog: pyt
def test_missing_or_bogus_file_is_noop(tmp_path: Path) -> None:
assert_fragments_decrypted(tmp_path / "nope.mp4")
assert_fragments_decrypted(_write(tmp_path, "bogus.bin", b"\x00\x01\x02\x03not-an-mp4"))
truncated = _write(tmp_path, "cut.mp4", FTYP, MOOV, _moof(_senc())[:20])
assert_fragments_decrypted(write(tmp_path, "bogus.bin", b"\x00\x01\x02\x03not-an-mp4"))
truncated = write(tmp_path, "cut.mp4", FTYP, MOOV, moof(senc())[:20])
assert_fragments_decrypted(truncated)
+1 -1
View File
@@ -50,7 +50,7 @@ Dialogue: 0,0:00:03.00,0:00:04.00,Default,,0,0,0,,World
@pytest.fixture(autouse=True)
def _no_subtitleedit(monkeypatch):
def no_subtitleedit(monkeypatch):
"""Default every test to a SubtitleEdit-less environment; tests opt in when needed."""
monkeypatch.setattr(binaries, "SubtitleEdit", None)
+70
View File
@@ -0,0 +1,70 @@
"""``strip_hearing_impaired`` fallback path (``tracks/subtitle.py``).
Pins the filter-subs fallback's warn-and-continue branch: an invalid subtitle file must
log a warning and return, not crash (it previously raised AttributeError via a
nonexistent ``self.log``).
"""
from __future__ import annotations
import pytest
from unshackle.core import binaries
from unshackle.core.config import config
from unshackle.core.tracks.subtitle import Subtitle
SRT_SAMPLE = """1
00:00:01,000 --> 00:00:02,000
Hello
"""
@pytest.fixture()
def srt_track(tmp_path):
path = tmp_path / "sub.srt"
path.write_text(SRT_SAMPLE, encoding="utf-8")
sub = Subtitle(url="https://example.test/x", language="en", codec=Subtitle.Codec.SubRip)
sub.path = path
return sub
def test_invalid_subtitle_warns_and_continues(srt_track, monkeypatch, caplog):
import unshackle.core.tracks.subtitle as subtitle_mod
monkeypatch.setattr(binaries, "SubtitleEdit", None)
monkeypatch.setattr(config, "subtitle", {"sdh_method": "auto"}, raising=False)
def broken(*args, **kwargs):
raise RuntimeError("subby unavailable")
monkeypatch.setattr(subtitle_mod, "CommonIssuesFixer", broken)
def invalid(path):
raise OSError(f"{path} is not valid subtitle file")
monkeypatch.setattr(subtitle_mod, "Subtitles", invalid)
with caplog.at_level("WARNING", logger="Subtitle"):
srt_track.strip_hearing_impaired()
assert any("Failed to strip SDH" in r.message for r in caplog.records)
def test_other_oserror_still_raises(srt_track, monkeypatch):
import unshackle.core.tracks.subtitle as subtitle_mod
monkeypatch.setattr(binaries, "SubtitleEdit", None)
monkeypatch.setattr(config, "subtitle", {"sdh_method": "auto"}, raising=False)
def broken(*args, **kwargs):
raise RuntimeError("subby unavailable")
monkeypatch.setattr(subtitle_mod, "CommonIssuesFixer", broken)
def denied(path):
raise PermissionError("permission denied")
monkeypatch.setattr(subtitle_mod, "Subtitles", denied)
with pytest.raises(PermissionError):
srt_track.strip_hearing_impaired()
+1 -1
View File
@@ -77,7 +77,7 @@ class Harness:
@pytest.fixture(autouse=True)
def _clear_event():
def clear_event():
DOWNLOAD_CANCELLED.clear()
yield
DOWNLOAD_CANCELLED.clear()