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