style: turn on ruff UP and B rules and fix every finding

This commit is contained in:
imSp4rky
2026-11-25 16:34:09 -07:00
parent 1a63076df2
commit d8058a3610
264 changed files with 2950 additions and 2966 deletions
+3 -2
View File
@@ -2,8 +2,9 @@
from __future__ import annotations
from collections.abc import Callable
from types import SimpleNamespace
from typing import Any, Callable, Optional
from typing import Any
from uuid import UUID
from rich.table import Table
@@ -45,7 +46,7 @@ WIDEVINE = cdm_type_stub("widevine")
def resolver(
vaults: Any = None,
cdm: Any = WIDEVINE,
cdm_for: Optional[Callable[..., Any]] = None,
cdm_for: Callable[..., Any] | None = None,
tag: str = "TEST",
**flags: Any,
) -> ContentKeyResolver:
+3 -2
View File
@@ -6,6 +6,7 @@ from __future__ import annotations
import inspect
from functools import partial
from itertools import pairwise
from pathlib import Path
import pytest
@@ -252,7 +253,7 @@ def test_plan_tail_parts_full_coverage_no_gaps() -> None:
assert parts, "expected a split for a large segment with spare capacity"
assert parts[0][0] == 0
assert parts[-1][1] == size - 1
for (_, prev_end), (start, _) in zip(parts, parts[1:]):
for (_, prev_end), (start, _) in pairwise(parts):
assert start == prev_end + 1 # each part begins exactly where the previous one ended
covered = sum(end - start + 1 for start, end in parts)
assert covered == size
@@ -282,7 +283,7 @@ def test_split_ranges_covers_exactly_no_gaps_no_overlaps() -> None:
for size in (1, 100, 4 * 1024 * 1024, 16 * 1024 * 1024 + 7, 64 * 1024 * 1024):
parts = split_ranges(size, max_parts=8, part_target=4 * 1024 * 1024)
assert parts[0][0] == 0 and parts[-1][1] == size - 1
for (_, prev_end), (start, _) in zip(parts, parts[1:]):
for (_, prev_end), (start, _) in pairwise(parts):
assert start == prev_end + 1
assert all(start <= end for start, end in parts)
assert sum(end - start + 1 for start, end in parts) == size
+5 -5
View File
@@ -5,7 +5,7 @@ from __future__ import annotations
import base64
import logging
from types import SimpleNamespace
from typing import Any, Optional
from typing import Any
from uuid import UUID
import m3u8
@@ -53,20 +53,20 @@ def playready(kid: UUID = KID) -> PlayReady:
class Run:
"""A ContentKeyResolver whose DRM objects license with fixed content keys, for one track in an --all-drm run."""
def __init__(self, vault: Optional[dict[UUID, str]] = None, **flags: Any) -> None:
def __init__(self, vault: dict[UUID, str] | None = None, **flags: Any) -> None:
self.requests: list[str] = []
self.held: list[dict[UUID, str]] = []
self.vault_queries: list[UUID] = []
self.keys = resolver(Vault(self.get_key(vault or {})), tag="EXAMPLE", **flags)
def get_key(self, vault: dict[UUID, str]) -> Any:
def get_key(kid: UUID) -> tuple[Optional[str], Optional[str]]:
def get_key(kid: UUID) -> tuple[str | None, str | None]:
self.vault_queries.append(kid)
return vault.get(kid), "vault" if kid in vault else None
return get_key
def drm(self, drm: Any, keys: Optional[dict[UUID, str]] = None, fail: bool = False) -> Any:
def drm(self, drm: Any, keys: dict[UUID, str] | None = None, fail: bool = False) -> Any:
"""Give ``drm`` a licence that returns ``keys`` (KID:KEY by default), or that is refused."""
def get_content_keys(cdm: Any, certificate: Any = None, licence: Any = None) -> None:
@@ -79,7 +79,7 @@ class Run:
drm.get_content_keys = get_content_keys
return drm
def run(self, drm: Any, *others: Any, track_kid: Optional[UUID] = KID) -> None:
def run(self, drm: Any, *others: Any, track_kid: UUID | None = KID) -> None:
track = SimpleNamespace(drm=[drm, *others], id="track", height=None)
self.keys.licence_for(track, None, key_table(), all_drm=True)(drm, track_kid=track_kid)
+5 -5
View File
@@ -2,7 +2,7 @@
from __future__ import annotations
from typing import Any, Optional
from typing import Any
import pytest
@@ -41,7 +41,7 @@ def _provider(monkeypatch: pytest.MonkeyPatch, body: dict) -> tuple[AniListProvi
provider = AniListProvider()
sent: list[dict] = []
def fake_post(url: str, json: Optional[dict] = None, **kwargs: Any) -> FakeResponse:
def fake_post(url: str, json: dict | None = None, **kwargs: Any) -> FakeResponse:
sent.append(json or {})
return FakeResponse(body)
@@ -75,7 +75,7 @@ def default_title_language(monkeypatch: pytest.MonkeyPatch) -> None:
("²", None), # superscript two passes isdigit() but crashes int()
],
)
def test_parse_anilist_ref(value: Any, expected: Optional[tuple[str, int]]) -> None:
def test_parse_anilist_ref(value: Any, expected: tuple[str, int] | None) -> None:
assert parse_anilist_ref(value) == expected
@@ -215,7 +215,7 @@ def test_a_title_with_no_variant_at_all_is_a_miss(monkeypatch: pytest.MonkeyPatc
[("JP", "ja"), ("KR", "ko"), ("CN", "zh"), ("TW", "zh"), ("US", None), (None, None)],
)
def test_country_of_origin_maps_to_a_language(
monkeypatch: pytest.MonkeyPatch, country: Optional[str], language: Optional[str]
monkeypatch: pytest.MonkeyPatch, country: str | None, language: str | None
) -> None:
provider, _ = _provider(monkeypatch, {"data": {"Media": {**ONE_PIECE, "countryOfOrigin": country}}})
@@ -228,7 +228,7 @@ def test_country_of_origin_maps_to_a_language(
@pytest.mark.parametrize(
("format_", "kind"), [("MOVIE", "movie"), ("TV", "tv"), ("ONA", "tv"), ("SPECIAL", "tv"), (None, "tv")]
)
def test_format_maps_to_kind(monkeypatch: pytest.MonkeyPatch, format_: Optional[str], kind: str) -> None:
def test_format_maps_to_kind(monkeypatch: pytest.MonkeyPatch, format_: str | None, kind: str) -> None:
provider, _ = _provider(monkeypatch, {"data": {"Media": {**ONE_PIECE, "format": format_}}})
result = provider.get_by_id(21, "tv")
+3 -3
View File
@@ -1,7 +1,7 @@
import sys
import time
from collections.abc import Callable
from pathlib import Path
from typing import Callable, Optional
import pytest
@@ -35,8 +35,8 @@ def test_parse_version(text: str, expected: str | None) -> None:
assert parse_version(text) == expected
def fake_probe(outputs: dict[str, Optional[str]], calls: list[list[str]]) -> Callable[[Path, list[str]], Optional[str]]:
def probe(path: Path, args: list[str]) -> Optional[str]:
def fake_probe(outputs: dict[str, str | None], calls: list[list[str]]) -> Callable[[Path, list[str]], str | None]:
def probe(path: Path, args: list[str]) -> str | None:
calls.append(args)
return outputs.get(" ".join(args), "")
+2 -2
View File
@@ -1,5 +1,5 @@
import time
from datetime import datetime, timedelta, timezone
from datetime import UTC, datetime, timedelta
from pathlib import Path
import jsonpickle
@@ -53,7 +53,7 @@ def test_unix_timestamp_is_absolute_also_when_it_is_in_the_past(offset: int) ->
def test_iso_string_with_utc_offset_becomes_naive_local_time() -> None:
moment = datetime.now(timezone.utc).replace(microsecond=0) + timedelta(hours=1)
moment = datetime.now(UTC).replace(microsecond=0) + timedelta(hours=1)
expected = datetime.fromtimestamp(moment.timestamp())
assert Cacher.resolve_datetime(moment.isoformat()) == expected
assert Cacher.resolve_datetime(moment.strftime("%Y-%m-%dT%H:%M:%SZ")) == expected
+8 -6
View File
@@ -4,8 +4,10 @@ Device names start with the system they are for: ``wv_`` is Widevine, ``pr_`` is
``stub:pr``. Each answer tuple runs over the named systems of its column.
"""
from collections.abc import Callable
from functools import partial
from types import SimpleNamespace
from typing import Any, Callable, Optional
from typing import Any
import pytest
@@ -22,7 +24,7 @@ SERVER = ("widevine", "playready", "wv")
TIER = {"devices": ["wv_tier"], "playready_devices": ["pr_tier"]}
DUAL = {"widevine": "wv_dev", "playready": "pr_dev"}
ROWS: dict[str, tuple[dict, Optional[str], Optional[dict]]] = {
ROWS: dict[str, tuple[dict, str | None, dict | None]] = {
"string widevine": ({"EXAMPLE": "wv_dev"}, None, None),
"string playready": ({"EXAMPLE": "pr_dev"}, None, None),
"profile mapping, no profile": ({"EXAMPLE": {"alice": "pr_alice", "default": "wv_dev"}}, None, None),
@@ -89,10 +91,10 @@ def attempt(answer: Callable[[], Any]) -> Any:
def each(systems: tuple, answer: Callable[[Any], Any]) -> tuple:
"""``answer`` for each named system."""
return tuple(attempt(lambda: answer(system)) for system in systems)
return tuple(attempt(partial(answer, system)) for system in systems)
def answers(monkeypatch: pytest.MonkeyPatch, cdm: dict, profile: Optional[str], key_cdm: Optional[dict]) -> dict:
def answers(monkeypatch: pytest.MonkeyPatch, cdm: dict, profile: str | None, key_cdm: dict | None) -> dict:
"""What every ladder answers for one config row."""
monkeypatch.setattr(handlers.config, "cdm", cdm, raising=False)
user = {**TIER, **({"cdm": key_cdm} if key_cdm else {})}
@@ -336,7 +338,7 @@ def test_each_ladder_gives_the_pinned_choice(monkeypatch: pytest.MonkeyPatch, de
("name", "system"),
[("wv", "widevine"), ("PlayReady", "playready"), ("PR", "playready"), ("clearkey", None), (5, None), (None, None)],
)
def test_drm_system_reads_each_name_of_a_system(name: Any, system: Optional[str]) -> None:
def test_drm_system_reads_each_name_of_a_system(name: Any, system: str | None) -> None:
assert drm_system(name) == system
@@ -344,5 +346,5 @@ def test_drm_system_reads_each_name_of_a_system(name: Any, system: Optional[str]
("entry", "system"),
[({"widevine": "wv_dev"}, "widevine"), (DUAL, None), ({"default": "pr_dev"}, None), ("pr_dev", None)],
)
def test_the_entry_settles_a_system_only_when_it_names_one(entry: Any, system: Optional[str]) -> None:
def test_the_entry_settles_a_system_only_when_it_names_one(entry: Any, system: str | None) -> None:
assert choose_cdm({"EXAMPLE": entry}, "EXAMPLE").system == system
+4 -4
View File
@@ -12,7 +12,7 @@ from __future__ import annotations
import base64
import json
from typing import Any, Optional
from typing import Any
from uuid import UUID
import pytest
@@ -52,7 +52,7 @@ class StubLicence:
def __init__(self, response: Any) -> None:
self.response = response
self.challenge: Optional[bytes] = None
self.challenge: bytes | None = None
def __call__(self, *, challenge: bytes) -> Any:
self.challenge = challenge
@@ -72,8 +72,8 @@ class StubSession:
def __init__(self, content: bytes) -> None:
self.content = content
self.url: Optional[str] = None
self.data: Optional[bytes] = None
self.url: str | None = None
self.data: bytes | None = None
def post(self, url: str, data: Any = None, **_: Any) -> StubResponse:
self.url = url
+1 -1
View File
@@ -12,8 +12,8 @@ import socket
import socketserver
import threading
import time
from collections.abc import Iterator
from types import SimpleNamespace
from typing import Iterator
from unittest.mock import Mock
import click
+1 -2
View File
@@ -1,5 +1,4 @@
import xml.etree.ElementTree as ET
from typing import Optional
import pytest
@@ -66,5 +65,5 @@ def test_the_first_decodable_descriptor_wins() -> None:
@pytest.mark.parametrize(
("representation", "expected"), [(config((COUNT, "6"), tag="Representation"), 5.1), (None, 2.0)]
)
def test_the_representation_overrides_the_adaptation_set(representation: Optional[ET.Element], expected: float) -> None:
def test_the_representation_overrides_the_adaptation_set(representation: ET.Element | None, expected: float) -> None:
assert DASH.get_audio_channels(config((COUNT, "2")), representation) == expected
+2 -1
View File
@@ -1,12 +1,13 @@
import re
import struct
import threading
from collections.abc import Iterator
from functools import partial
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from io import BytesIO
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Iterator
from typing import Any
import pytest
import requests
+5 -7
View File
@@ -2,8 +2,6 @@
from __future__ import annotations
from typing import Optional, Union
import pytest
from unshackle.core import providers
@@ -14,23 +12,23 @@ from unshackle.core.providers._base import ExternalIds, MetadataProvider, Metada
class FakeProvider(MetadataProvider):
"""Stands in for a real provider; fails the test if it is searched."""
def __init__(self, name: str, result: Optional[MetadataResult] = None) -> None:
def __init__(self, name: str, result: MetadataResult | None = None) -> None:
self.NAME = name
self._result = result
self.asked: list[Union[int, str]] = []
self.asked: list[int | str] = []
super().__init__()
def is_available(self) -> bool:
return True
def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
raise AssertionError("no provider may be searched while disable_metadata is set")
def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
def get_by_id(self, provider_id: int | str, kind: str) -> MetadataResult | None:
self.asked.append(provider_id)
return self._result
def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
def get_external_ids(self, provider_id: int | str, kind: str) -> ExternalIds:
return ExternalIds()
+4 -4
View File
@@ -20,9 +20,9 @@ import importlib
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Optional
import pytest
import urllib3
from requests import Session
# the downloaders package re-exports a `requests` function that shadows this submodule
@@ -40,7 +40,7 @@ class _FaultServer:
def __init__(self, body: bytes) -> None:
self.body = body
self.attempts = 0 # GETs seen for the single resource
self.ranges: list[Optional[str]] = [] # Range header per GET, in order
self.ranges: list[str | None] = [] # Range header per GET, in order
self.truncate_first = 0 # send only half the body + close, for the first N attempts
self._lock = threading.Lock()
server = self
@@ -85,7 +85,7 @@ class _FaultServer:
self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self._thread = threading.Thread(target=self._httpd.serve_forever, daemon=True)
def __enter__(self) -> "_FaultServer":
def __enter__(self) -> _FaultServer:
self._thread.start()
return self
@@ -111,7 +111,7 @@ def test_truncated_segment_is_not_finalized(tmp_path: Path, monkeypatch: pytest.
save = tmp_path / "seg.bin"
with _FaultServer(body) as srv:
srv.truncate_first = 99 # every attempt under-delivers
with pytest.raises(Exception):
with pytest.raises((OSError, urllib3.exceptions.HTTPError)):
consume(dl.download(url=srv.url, save_path=save, session=Session(), segmented=True))
assert not save.exists(), "truncated segment must not be finalized as complete"
+2 -2
View File
@@ -4,7 +4,7 @@ take turns so the second one reads the content keys out of the cache."""
from __future__ import annotations
from threading import Lock
from typing import Any, Optional
from typing import Any
from uuid import UUID
import pytest
@@ -18,7 +18,7 @@ KID_B = UUID("22222222222222222222222222222222")
class FakeDRM:
def __init__(self, kids: Optional[list[Any]] = None, content_id: Optional[str] = None) -> None:
def __init__(self, kids: list[Any] | None = None, content_id: str | None = None) -> None:
self.kids = kids or []
self.content_id = content_id
+5 -4
View File
@@ -2,9 +2,10 @@
from __future__ import annotations
from collections.abc import Callable
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Callable, Optional
from typing import Any
import click
import pytest
@@ -25,7 +26,7 @@ from unshackle.core.service import Service
from unshackle.core.utils import ip_info, run_proxy
def code_of(call: Callable[[], Any]) -> Optional[APIErrorCode]:
def code_of(call: Callable[[], Any]) -> APIErrorCode | None:
"""The code the raised exception names itself, not the one its message would give."""
with pytest.raises(BaseException) as caught:
call()
@@ -77,7 +78,7 @@ class Blocked(Service):
@pytest.mark.parametrize("proxy", [None, "https://u:p@chosen.example:89"], ids=["own-region", "proxy-region"])
def test_a_blocked_region_is_a_geofence_error(monkeypatch: pytest.MonkeyPatch, proxy: Optional[str]) -> None:
def test_a_blocked_region_is_a_geofence_error(monkeypatch: pytest.MonkeyPatch, proxy: str | None) -> None:
monkeypatch.setattr(service_mod, "get_ip_info", lambda *args, **kwargs: {"country": "gb"})
monkeypatch.setattr(service_mod, "verify_proxy_exit", lambda session: {"country": "gb"})
monkeypatch.setattr(run_proxy, "watched", {})
@@ -140,7 +141,7 @@ def http_failure(status: Any) -> requests.ConnectionError:
ids=["404", "410", "429", "503", "403", "not-a-status", "no-answer"],
)
def test_a_manifest_fetch_failure_is_coded_from_an_unambiguous_status(
failure: Exception, code: Optional[APIErrorCode]
failure: Exception, code: APIErrorCode | None
) -> None:
error = manifest_fetch_error("DASH", "Example Movie", failure)
assert isinstance(error, click.ClickException) and "may have expired" in error.message
+3 -3
View File
@@ -12,7 +12,7 @@ import json
import logging
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Optional, cast
from typing import Any, cast
from uuid import UUID
import click
@@ -396,7 +396,7 @@ def ad_mpd(ad_id: str) -> str:
{period(ad_id, "PRE_ROLL")}{period("main", "")}</MPD>"""
def export_service_filtered_title(tmp_path: Path, manifest_url: Optional[str]) -> Path:
def export_service_filtered_title(tmp_path: Path, manifest_url: str | None) -> Path:
"""Export a DASH title as a service would, its own period_filter dropping the pre-roll, with no manifest snapshot.
Without a snapshot the import re-fetches the manifest, the path ``content_periods`` serves.
@@ -423,7 +423,7 @@ def export_service_filtered_title(tmp_path: Path, manifest_url: Optional[str]) -
@pytest.mark.parametrize("manifest_url", [AD_MPD_URL, None])
@pytest.mark.parametrize("ad_id_on_refetch", ["ad-1", "ad-9"])
def test_import_keeps_out_the_periods_the_service_filtered(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, manifest_url: Optional[str], ad_id_on_refetch: str
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, manifest_url: str | None, ad_id_on_refetch: str
) -> None:
"""The import re-fetches the MPD without the service, so its filter must travel in the export.
+1 -1
View File
@@ -1,6 +1,6 @@
import warnings
from collections.abc import Callable
from pathlib import Path
from typing import Callable
import pytest
+3 -1
View File
@@ -67,7 +67,9 @@ def ladder(
) -> tuple[list[Any], list[str]]:
"""HEVC HDR10 tracks, highest bitrate first; '+' marks the ones whose fragment carries HDR10+."""
heights = heights or [2160 - 100 * i for i in range(len(pattern))]
videos = [hevc(f"v{i}{mark}", height, 100 - i) for i, (mark, height) in enumerate(zip(pattern, heights))]
videos = [
hevc(f"v{i}{mark}", height, 100 - i) for i, (mark, height) in enumerate(zip(pattern, heights, strict=False))
]
return videos, probe(monkeypatch, videos)
+1 -1
View File
@@ -43,7 +43,7 @@ def test_concat_list_is_written_as_utf8(tmp_path: Path, monkeypatch: pytest.Monk
def spy_write_text(self, data, encoding=None, *args, **kwargs):
encodings.append(encoding)
return real_write_text(self, data, encoding=encoding, *args, **kwargs)
return real_write_text(self, data, *args, encoding=encoding, **kwargs)
seen: list[bytes] = []
+3 -4
View File
@@ -4,7 +4,6 @@ from __future__ import annotations
import base64
import json
from typing import Optional
import m3u8
import pytest
@@ -34,14 +33,14 @@ def _b64(items: list[dict]) -> str:
return base64.b64encode(json.dumps(items).encode()).decode()
def _item(method: str, keyformat: Optional[str] = None) -> dict:
def _item(method: str, keyformat: str | None = None) -> dict:
item = {"method": method, "uri": KEY_URI}
if keyformat:
item["keyformat"] = keyformat
return item
def _key(method: str, keyformat: Optional[str] = None) -> m3u8.model.Key:
def _key(method: str, keyformat: str | None = None) -> m3u8.model.Key:
return m3u8.model.Key(method=method, base_uri="", uri=KEY_URI, keyformat=keyformat)
@@ -60,7 +59,7 @@ def test_session_data_playready_urn_key_is_kept() -> None:
("ISO-23001-7", None),
],
)
def test_session_data_supported_keys_are_kept(method: str, keyformat: Optional[str]) -> None:
def test_session_data_supported_keys_are_kept(method: str, keyformat: str | None) -> None:
keys = HLS.parse_session_data_keys(_master(_b64([_item(method, keyformat)])))
assert [k.keyformat for k in keys] == [keyformat]
+2 -3
View File
@@ -2,7 +2,6 @@ from functools import partial
from http.server import ThreadingHTTPServer
from pathlib import Path
from types import SimpleNamespace
from typing import Optional
from tests.core.test_dash_period_rebase import fragment, init_segment, server, tfdts
from unshackle.core.manifests import HLS
@@ -23,7 +22,7 @@ def starts(text: str) -> list[str]:
def rebase(texts: list[str], bounds_ms: list[int]) -> list[str]:
return [shift_webvtt(t, o) for t, o in zip(texts, webvtt_block_offsets(texts, bounds_ms))]
return [shift_webvtt(t, o) for t, o in zip(texts, webvtt_block_offsets(texts, bounds_ms), strict=False)]
def test_restarting_blocks_move_to_their_playlist_start() -> None:
@@ -84,7 +83,7 @@ def playlist(names: list[str], init: str = "") -> bytes:
return f"#EXTM3U\n#EXT-X-VERSION:6\n#EXT-X-TARGETDURATION:4\n{blocks}#EXT-X-ENDLIST\n".encode()
def download(server: ThreadingHTTPServer, tmp_path: Path, codec: Optional[Subtitle.Codec] = None) -> Path:
def download(server: ThreadingHTTPServer, tmp_path: Path, codec: Subtitle.Codec | None = None) -> Path:
url = f"http://127.0.0.1:{server.server_address[1]}/master.m3u8"
track = HLS.from_text(MASTER, url=url).to_tracks(language="en").subtitles[0]
if codec:
+16 -16
View File
@@ -3,7 +3,7 @@
from __future__ import annotations
import base64
from typing import Any, Dict, List, Optional
from typing import Any
from uuid import UUID
import pytest
@@ -23,17 +23,17 @@ KEY_A, KEY_B, KEY_X = "01" * 16, "02" * 16, "0f" * 16
class FakeVaults:
def __init__(self, keys: Dict[UUID, str]) -> None:
def __init__(self, keys: dict[UUID, str]) -> None:
self.keys = dict(keys)
self.added: Dict[Any, str] = {}
self.added: dict[Any, str] = {}
def __len__(self) -> int:
return 1
def get_key(self, kid: UUID) -> tuple[Optional[str], None]:
def get_key(self, kid: UUID) -> tuple[str | None, None]:
return self.keys.get(kid), None
def add_keys(self, keys: Dict[Any, str]) -> None:
def add_keys(self, keys: dict[Any, str]) -> None:
self.added.update(keys)
@@ -42,21 +42,21 @@ class StubCdm(HttpCdm):
def __init__(
self,
cached: Optional[List[Dict[str, Any]]] = None,
licence: Optional[List[Dict[str, Any]]] = None,
cached: list[dict[str, Any]] | None = None,
licence: list[dict[str, Any]] | None = None,
vaults: Any = None,
) -> None:
super().__init__("https://cdm.test/", "L3", None, "EXAMPLE", vaults, {})
self.cached = cached
self.licence = licence or []
self.challenges = 0
self.required: List[Optional[List[str]]] = []
self.bodies: List[Dict[str, Any]] = []
self.required: list[list[str] | None] = []
self.bodies: list[dict[str, Any]] = []
def _request_challenge(
self,
session: Dict[str, Any],
body: Dict[str, Any],
session: dict[str, Any],
body: dict[str, Any],
license_type: str,
privacy_mode: bool,
) -> bytes:
@@ -66,16 +66,16 @@ class StubCdm(HttpCdm):
return b""
return self._keep_challenge(session, b"challenge", "remote-1")
def _request_keys(self, session: Dict[str, Any], body: Dict[str, Any]) -> List[Dict[str, Any]]:
def _request_keys(self, session: dict[str, Any], body: dict[str, Any]) -> list[dict[str, Any]]:
self.bodies.append(body)
return self.licence
def key(kid: UUID, value: str) -> Dict[str, str]:
def key(kid: UUID, value: str) -> dict[str, str]:
return {"kid": kid.hex, "key": value, "type": "CONTENT"}
def licensed(cdm: StubCdm, *kids: UUID) -> Dict[UUID, str]:
def licensed(cdm: StubCdm, *kids: UUID) -> dict[UUID, str]:
"""Run one challenge and licence round and return the content keys of the session."""
session_id = cdm.open()
cdm.set_required_kids(list(kids), session_id=session_id)
@@ -149,9 +149,9 @@ class L1StubCdm(StubCdm):
def __init__(self) -> None:
super().__init__(licence=[key(KID_A, KEY_A)])
self.sent: List[Dict[str, Any]] = []
self.sent: list[dict[str, Any]] = []
def _request_challenge(self, session: Dict[str, Any], body: Dict[str, Any], *rest: Any) -> bytes:
def _request_challenge(self, session: dict[str, Any], body: dict[str, Any], *rest: Any) -> bytes:
self.sent.append(body)
return super()._request_challenge(session, body, *rest)
+7 -6
View File
@@ -9,8 +9,9 @@ from __future__ import annotations
import base64
import json
import threading
from collections.abc import Callable, Iterator
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Callable, Dict, Iterator, List
from typing import Any
from uuid import UUID
import pytest
@@ -29,15 +30,15 @@ CHALLENGE = b"loopback challenge"
LICENCE = b"loopback licence"
PR_LICENCE = "<License>loopback</License>"
Answer = Callable[[Dict[str, Any]], Dict[str, Any]]
Answer = Callable[[dict[str, Any]], dict[str, Any]]
class Api:
"""A loopback HTTP API: one answer per path, every request recorded."""
def __init__(self) -> None:
self.answers: Dict[str, Answer] = {}
self.requests: List[tuple[str, Dict[str, str], Dict[str, Any]]] = []
self.answers: dict[str, Answer] = {}
self.requests: list[tuple[str, dict[str, str], dict[str, Any]]] = []
api = self
class Handler(BaseHTTPRequestHandler):
@@ -192,7 +193,7 @@ def test_decrypt_labs_partial_cache_asks_for_a_licence(api: Api, second_answer:
assert keys == {KID: KEY}
CUSTOM_CONFIG: Dict[str, Any] = {
CUSTOM_CONFIG: dict[str, Any] = {
"auth": {"type": "header", "header_name": "x-api-key", "key": "s3cret"},
"endpoints": {"get_request": "/challenge", "decrypt_response": {"path": "/keys"}},
"request_mapping": {"get_request": {"param_names": {"init_data": "pssh"}}},
@@ -221,7 +222,7 @@ def custom_answers(api: Api) -> None:
({"name": "SL3000", "type": "PLAYREADY"}, playready_drm, PR_LICENCE),
],
)
def test_custom_api(api: Api, device: Dict[str, Any], drm_of: Callable[[], Any], licence: Any) -> None:
def test_custom_api(api: Api, device: dict[str, Any], drm_of: Callable[[], Any], licence: Any) -> None:
custom_answers(api)
drm = drm_of()
cdm = CustomRemoteCDM(host=api.url, device=device, **CUSTOM_CONFIG)
+7 -6
View File
@@ -10,9 +10,10 @@ import json
import logging
import re
import weakref
from collections.abc import Iterator
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Iterator, Optional
from typing import Any
import pytest
@@ -219,7 +220,7 @@ def make_hybrid() -> Hybrid:
return obj
def stub_hybrid_steps(monkeypatch: pytest.MonkeyPatch, *steps: str, tool: Optional[str] = "hdr10plus_tool") -> None:
def stub_hybrid_steps(monkeypatch: pytest.MonkeyPatch, *steps: str, tool: str | None = "hdr10plus_tool") -> None:
"""Make the stream, Level 5 and inject steps (and those named) do nothing, with a fixed active area."""
for name in ("extract_stream", "level_5", "injecting", *steps):
monkeypatch.setattr(Hybrid, name, lambda self, *a, **k: None)
@@ -240,7 +241,7 @@ def capture_generate(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
@pytest.mark.parametrize("top, expected", [(277, (2160 - 554) / 2160), (1000, None)])
def test_active_area_share(top: int, expected: Optional[float], quiet: None, monkeypatch: pytest.MonkeyPatch) -> None:
def test_active_area_share(top: int, expected: float | None, quiet: None, monkeypatch: pytest.MonkeyPatch) -> None:
"""A letterboxed picture gives its crop and share of the frame; an implausibly small one gives None.
cropdetect settles over its frames, so the last crop line counts.
@@ -451,7 +452,7 @@ def test_a_conversion_run_removes_its_rpus_so_the_next_base_makes_its_own(
@pytest.mark.parametrize("range_, tool", [(Video.Range.HDR10, "hdr10plus_tool"), (Video.Range.HDR10P, None)])
def test_a_base_without_usable_hdr10plus_is_measured_inside_its_crop(
range_: Video.Range, tool: Optional[str], quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
range_: Video.Range, tool: str | None, quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
base = tmp_path / "base.mkv"
base.write_bytes(b"")
@@ -594,7 +595,7 @@ def test_an_hdr10plus_conversion_fills_light_levels_the_stream_does_not_state(
],
)
def test_a_sample_rpu_is_shifted_to_the_first_frame_of_the_base(
dv_start: float, expected: Optional[dict[str, Any]], quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
dv_start: float, expected: dict[str, Any] | None, quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""--sample cuts each track on its own segment grid, so the RPU can start before or after the base."""
seen: dict[str, Any] = {}
@@ -850,7 +851,7 @@ def video(
id_: str,
range_: Video.Range,
height: int = 2160,
codec: Optional[Video.Codec] = Video.Codec.HEVC,
codec: Video.Codec | None = Video.Codec.HEVC,
native_hybrid: bool = False,
) -> Any:
return SimpleNamespace(id=id_, height=height, range=range_, codec=codec, native_hybrid=native_hybrid, stereo=False)
+3 -2
View File
@@ -9,8 +9,9 @@ import contextlib
import json
import logging
import subprocess
from collections.abc import Iterator
from pathlib import Path
from typing import Any, Iterator, Optional
from typing import Any
import pytest
@@ -128,7 +129,7 @@ def rpu_info(max_cll: int, max_fall: int, max_mdl: int, min_mdl: int) -> dict:
def patch_level6(
monkeypatch: pytest.MonkeyPatch,
info: dict,
probe: Optional[tuple[int, int, int, int]],
probe: tuple[int, int, int, int] | None,
) -> list[Path]:
"""Mock the RPU read, the HDR10 probe, and the editor. Returns the editor call log."""
edits: list[Path] = []
+2 -2
View File
@@ -3,7 +3,7 @@
from __future__ import annotations
import json
from typing import Any, Optional
from typing import Any
import pytest
@@ -21,7 +21,7 @@ class _Response:
def node(
imdb_id: str = "tt3581920",
text: str = "The Last of Us",
year: Optional[int] = 2023,
year: int | None = 2023,
title_type: str = "tvSeries",
languages: Any = ({"id": "en", "text": "English"}, {"id": "id", "text": "Indonesian"}),
) -> dict:
+4 -4
View File
@@ -12,7 +12,7 @@ import json
import struct
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Optional, cast
from typing import Any, cast
from unittest.mock import patch
from uuid import UUID
@@ -42,7 +42,7 @@ def playready_object(kid: UUID) -> str:
return base64.b64encode(struct.pack("<IH", len(record) + 6, 1) + record).decode()
def media_playlist(kid: Optional[UUID]) -> str:
def media_playlist(kid: UUID | None) -> str:
key = ""
if kid:
key = (
@@ -91,7 +91,7 @@ def write_export(tmp_path: Path, language: str = "", manifest_url: str = MASTER_
return path
def import_title(export: Path, master_text: str, playlists: dict[str, Optional[UUID]]) -> tuple[ImportService, Any]:
def import_title(export: Path, master_text: str, playlists: dict[str, UUID | None]) -> tuple[ImportService, Any]:
ctx = cast(click.Context, SimpleNamespace(parent=None, params={}))
svc = ImportService(ctx, "EXAMPLE", "ep-1", str(export))
@@ -99,7 +99,7 @@ def import_title(export: Path, master_text: str, playlists: dict[str, Optional[U
name = url.split("?")[0].rsplit("/", 1)[-1]
return SimpleNamespace(text=media_playlist(playlists.get(name)), raise_for_status=lambda: None)
setattr(svc.session, "get", get)
svc.session.get = get
episode = next(iter(svc.get_titles()))
with patch.object(HLS, "from_url", side_effect=lambda url, session=None, **kw: HLS.from_text(master_text, url)):
episode.tracks = svc.get_tracks(episode)
+2 -2
View File
@@ -12,7 +12,7 @@ from __future__ import annotations
import json
from functools import partial
from pathlib import Path
from typing import Any, Optional
from typing import Any
import click
import pytest
@@ -57,7 +57,7 @@ def exported_video(track_id: str, url: str, codec: str, width: int, height: int)
}
def make_service(tmp_path: Path, manifest_url: Optional[str], tracks: dict[str, Any]) -> ImportService:
def make_service(tmp_path: Path, manifest_url: str | None, tracks: dict[str, Any]) -> ImportService:
entry: dict[str, Any] = {
"meta": {"type": "movie", "id": "movie-1", "name": "Example Movie", "year": 2024, "language": "en"},
"manifest_type": "DASH",
+2 -2
View File
@@ -9,7 +9,7 @@ from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Optional
from typing import Any
from uuid import UUID
import click
@@ -66,7 +66,7 @@ class CountedImport(ImportService):
self.calls = calls
self.server_cdm_type = "widevine"
def license_track(self, track: Any, drm: Any, kid: Optional[UUID] = None) -> Optional[dict[UUID, str]]:
def license_track(self, track: Any, drm: Any, kid: UUID | None = None) -> dict[UUID, str] | None:
self.calls.append("licence")
return super().license_track(track, drm, kid)
+6 -8
View File
@@ -11,7 +11,7 @@ from __future__ import annotations
import json
from pathlib import Path
from typing import Any, Optional
from typing import Any
from unittest.mock import patch
from uuid import UUID
@@ -56,9 +56,9 @@ URL_SUBTITLE = {
def make_service(
tmp_path: Path,
language: Optional[str],
tracks: Optional[dict[str, Any]] = None,
manifest_url: Optional[str] = "https://example.invalid/m.mpd",
language: str | None,
tracks: dict[str, Any] | None = None,
manifest_url: str | None = "https://example.invalid/m.mpd",
) -> ImportService:
entry: dict[str, Any] = {
"meta": {"type": "movie", "id": "movie-1", "name": "Example Movie", "year": 2024, "language": language},
@@ -86,9 +86,7 @@ def test_manifest_supplies_language_without_title_language(tmp_path: Path, mpd:
@pytest.mark.parametrize("language", [None, "und"], ids=["missing", "und"])
def test_unlabelled_manifest_without_usable_language_blames_the_service(
tmp_path: Path, language: Optional[str]
) -> None:
def test_unlabelled_manifest_without_usable_language_blames_the_service(tmp_path: Path, language: str | None) -> None:
"""`und` is truthy and a valid tag, so it must be rejected as firmly as no language at all."""
with pytest.raises(click.ClickException) as error:
get_tracks(make_service(tmp_path, language=language), MPD_NO_LANG)
@@ -111,7 +109,7 @@ def exported_video(language: str = "ja") -> dict[str, Any]:
@pytest.mark.parametrize("manifest_url", ["https://example.invalid/m.mpd", None], ids=["manifest-url", "per-track-url"])
def test_unlabelled_manifest_takes_the_exported_track_language(tmp_path: Path, manifest_url: Optional[str]) -> None:
def test_unlabelled_manifest_takes_the_exported_track_language(tmp_path: Path, manifest_url: str | None) -> None:
"""A title with no language takes it from its exported tracks, for either import branch."""
service = make_service(tmp_path, language=None, tracks={"v1": exported_video()}, manifest_url=manifest_url)
tracks = get_tracks(service, MPD_NO_LANG)
+1 -1
View File
@@ -470,7 +470,7 @@ def test_avcc_requires_sps_and_pps():
def test_read_track_id_from_fragment():
# Minimal moof/traf/tfhd carrying track_ID = 7.
tfhd = full_box("tfhd".encode(), 0, 0, struct.pack(">I", 7) + b"\x00" * 4)
tfhd = full_box(b"tfhd", 0, 0, struct.pack(">I", 7) + b"\x00" * 4)
traf = box(b"traf", tfhd)
moof = box(b"moof", traf)
mdat = box(b"mdat", b"\x00\x00")
+1 -2
View File
@@ -1,6 +1,5 @@
import struct
from pathlib import Path
from typing import Optional
from uuid import UUID
import pytest
@@ -79,7 +78,7 @@ def moof(
time: int,
*groups: bytes,
samples: int = 48,
duration: Optional[int] = None,
duration: int | None = None,
tfxd: bool = False,
) -> bytes:
flags = 0x02 | (0x08 if duration is not None else 0)
+5 -5
View File
@@ -3,8 +3,8 @@
from __future__ import annotations
import logging
from collections.abc import Iterator
from pathlib import Path
from typing import Iterator, Optional, Union
from uuid import UUID
import pytest
@@ -27,16 +27,16 @@ class RecordingVault(Vault):
super().__init__("net")
self.batches: list[int] = []
def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
def get_key(self, kid: UUID | str, service: str) -> str | None:
return None
def get_keys(self, service: str) -> Iterator[tuple[str, str]]:
return iter(())
def add_key(self, service: str, kid: Union[UUID, str], key: str) -> bool:
def add_key(self, service: str, kid: UUID | str, key: str) -> bool:
return False
def add_keys(self, service: str, kid_keys: dict[Union[UUID, str], str]) -> int:
def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
self.batches.append(len(kid_keys))
return len(kid_keys)
@@ -49,7 +49,7 @@ def test_sql_vault_gets_one_call(tmp_path: Path, monkeypatch: pytest.MonkeyPatch
calls: list[int] = []
real = vault.add_keys
def spy(service: str, kid_keys: dict[Union[UUID, str], str]) -> int:
def spy(service: str, kid_keys: dict[UUID | str, str]) -> int:
calls.append(len(kid_keys))
return real(service, kid_keys)
+2 -4
View File
@@ -2,8 +2,6 @@
from __future__ import annotations
from typing import Optional
import pytest
from unshackle.commands.dl import latest_episode_keys
@@ -16,7 +14,7 @@ class Svc:
pass
def episode(season: int, number: int, part: Optional[int] = None) -> Episode:
def episode(season: int, number: int, part: int | None = None) -> Episode:
return Episode(id_=f"ep-{season}x{number}.{part}", service=Svc, title="T", season=season, number=number, part=part)
@@ -36,7 +34,7 @@ def series() -> Series:
],
)
def test_the_newest_episodes_are_picked_across_seasons(
latest_episode: bool, latest_episodes: Optional[int], expected: list[tuple[int, int]]
latest_episode: bool, latest_episodes: int | None, expected: list[tuple[int, int]]
) -> None:
assert latest_episode_keys(series(), latest_episode, latest_episodes) == expected
+2 -1
View File
@@ -2,9 +2,10 @@
from __future__ import annotations
from collections.abc import Callable
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Callable
from typing import Any
import click
import pytest
+4 -3
View File
@@ -3,8 +3,9 @@
from __future__ import annotations
import threading
from collections.abc import Callable
from types import SimpleNamespace
from typing import Any, Callable, Optional
from typing import Any
from uuid import UUID
import click
@@ -68,7 +69,7 @@ def widevine(*kids: UUID) -> Widevine:
return Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=list(kids)))
def prepare(keys: ContentKeyResolver, drm: Any, track_kid: Optional[UUID], table: Table, all_drm: bool = False) -> None:
def prepare(keys: ContentKeyResolver, drm: Any, track_kid: UUID | None, table: Table, all_drm: bool = False) -> None:
keys.licence_for(SimpleNamespace(drm=[drm]), None, table, all_drm)(drm, track_kid=track_kid)
@@ -150,7 +151,7 @@ def test_a_key_label_is_added_once_with_its_marker_and_source(licences: Licences
ids=["widevine", "playready", "clearkey"],
)
def test_an_all_zero_licence_key_is_dropped(
monkeypatch: pytest.MonkeyPatch, drm_class: type, build: Callable[[], Any], cdm: Optional[str]
monkeypatch: pytest.MonkeyPatch, drm_class: type, build: Callable[[], Any], cdm: str | None
) -> None:
def get_content_keys(self: Any, **_: Any) -> None:
self.content_keys.update({KID_A: KEYS[KID_A], KID_C: "0" * 32})
+2 -2
View File
@@ -5,7 +5,7 @@ from __future__ import annotations
import json
from collections import Counter
from pathlib import Path
from typing import Any, Union
from typing import Any
from unittest.mock import MagicMock
import pytest
@@ -33,7 +33,7 @@ def cases(entries: list[dict[str, Any]]) -> list[Any]:
def parse(entry: dict[str, Any]) -> Tracks:
"""Parse a fixture the way from_url does: XML from bytes, M3U8 decoded as UTF-8."""
data = (CORPUS / entry["file"]).read_bytes()
parser: Union[DASH, HLS, ISM]
parser: DASH | HLS | ISM
if entry["kind"] == "hls":
parser = HLS.from_text(data.decode("utf-8"), entry["url"])
else:
+3 -3
View File
@@ -7,7 +7,7 @@ import json
import logging
import zlib
from copy import deepcopy
from typing import Any, Optional
from typing import Any
import pytest
@@ -21,7 +21,7 @@ from unshackle.core.wire import track_from_dict, track_to_dict
URL = "https://cdn.example/title/manifest.mpd"
def period(pid: Optional[str], kind: str) -> str:
def period(pid: str | None, kind: str) -> str:
attr = f' id="{pid}"' if pid else ""
name = pid or "noid"
return f"""
@@ -67,7 +67,7 @@ def service_tracks(text: str = MPD) -> Tracks:
return DASH.from_text(text, URL).to_tracks(language="en", period_filter=is_ad)
def detach_video(tracks: Tracks, track_id: Optional[str] = None) -> Track:
def detach_video(tracks: Tracks, track_id: str | None = None) -> Track:
"""Give the video an AdaptationSet outside the tree, the way a service that builds its own does."""
video = tracks.videos[0]
data = video.data["dash"]
+2 -1
View File
@@ -3,8 +3,9 @@ from __future__ import annotations
import io
import subprocess
import sys
from collections.abc import Callable
from pathlib import Path
from typing import Any, Callable
from typing import Any
from uuid import UUID
import pytest
+2 -3
View File
@@ -13,7 +13,6 @@ from __future__ import annotations
import shutil
import subprocess
from pathlib import Path
from typing import Optional
import mutagen
import pytest
@@ -148,7 +147,7 @@ def test_a_failed_remux_keeps_the_source_and_removes_its_partial_file(tmp_path:
assert not list(tmp_path.glob("track_music*")), "a failed remux must not leave a partial file"
def make_track(path: Path, codec: Optional[Audio.Codec]) -> Audio:
def make_track(path: Path, codec: Audio.Codec | None) -> Audio:
track = Audio(id_="a1", url="https://example.test/a1.mp4", language="en", codec=codec)
track.path = path
return track
@@ -167,7 +166,7 @@ def make_track(path: Path, codec: Optional[Audio.Codec]) -> Audio:
],
)
def test_the_file_codec_decides_the_container(
tmp_path: Path, encoder: str, fmt: str, declared: Optional[Audio.Codec], extension: str, probed: Audio.Codec
tmp_path: Path, encoder: str, fmt: str, declared: Audio.Codec | None, extension: str, probed: Audio.Codec
) -> None:
"""Every track downloads under a .mp4 name, and a service can declare no codec or the wrong one."""
track = make_track(encode(tmp_path / "track.mp4", encoder, "-f", fmt), declared)
+9 -9
View File
@@ -2,7 +2,7 @@
from __future__ import annotations
from typing import Any, Optional
from typing import Any
import pytest
@@ -31,11 +31,11 @@ def make_song(
album: str = "Album",
artist: str = "Artist",
name: str = "Song",
album_artist: Optional[str] = None,
total_tracks: Optional[int] = None,
total_discs: Optional[int] = None,
artwork_url: Optional[str] = None,
data: Optional[Any] = None,
album_artist: str | None = None,
total_tracks: int | None = None,
total_discs: int | None = None,
artwork_url: str | None = None,
data: Any | None = None,
) -> Song:
return Song(
id_=f"{album}-{disc}-{track}",
@@ -81,7 +81,7 @@ def test_first_text(values: tuple[Any, ...], default: str, expected: str) -> Non
((), None),
],
)
def test_first_number(values: tuple[Any, ...], expected: Optional[float]) -> None:
def test_first_number(values: tuple[Any, ...], expected: float | None) -> None:
assert first_number(*values) == expected
@@ -110,7 +110,7 @@ def test_year_from_value(value: Any, expected: int) -> None:
("nope", None),
],
)
def test_duration_seconds(value: Any, expected: Optional[float]) -> None:
def test_duration_seconds(value: Any, expected: float | None) -> None:
assert duration_seconds(value) == expected
@@ -165,7 +165,7 @@ def test_format_names(value: Any, sep: str, expected: str) -> None:
("", None, "album"),
],
)
def test_classify_release_kind(raw_kind: str, count: Optional[float], expected: str) -> None:
def test_classify_release_kind(raw_kind: str, count: float | None, expected: str) -> None:
assert classify_release_kind(raw_kind, count) == expected
+1 -1
View File
@@ -40,7 +40,7 @@ class FakeResponse:
def raise_for_status(self) -> None:
pass
def __enter__(self) -> "FakeResponse":
def __enter__(self) -> FakeResponse:
return self
def __exit__(self, *exc_info: Any) -> None:
+2 -1
View File
@@ -2,8 +2,9 @@
from __future__ import annotations
from collections.abc import Iterator
from pathlib import Path
from typing import Any, Iterator
from typing import Any
import pytest
from pymediainfo import MediaInfo
+2 -2
View File
@@ -5,7 +5,7 @@ XML declaration gives the encoding."""
from __future__ import annotations
from typing import Any, Optional
from typing import Any
import pytest
import requests
@@ -21,7 +21,7 @@ MASTER = b'#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1000000,RESOLUTION=1280x720,CODE
MEDIA = b"#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXTINF:6.0,\nseg1.ts\n#EXT-X-ENDLIST\n"
def make_response(body: bytes, url: str, encoding: Optional[str]) -> requests.Response:
def make_response(body: bytes, url: str, encoding: str | None) -> requests.Response:
res = requests.Response()
res.status_code = 200
res._content = body
+1 -1
View File
@@ -85,7 +85,7 @@ def test_dash_skips_an_unparseable_playready_entry_and_keeps_widevine(caplog: py
@pytest.mark.parametrize(
"data",
[b"\x00\x00not a header", "<WRMHEADER/>".encode("utf-8")],
[b"\x00\x00not a header", b"<WRMHEADER/>"],
ids=["garbage", "utf-8-header"],
)
def test_other_bad_data_keeps_the_original_error(data: bytes) -> None:
+5 -5
View File
@@ -5,7 +5,7 @@ from __future__ import annotations
import json
import logging
from typing import Iterator, Optional
from collections.abc import Iterator
import pytest
@@ -31,22 +31,22 @@ class Alpha(Proxy):
def __repr__(self) -> str:
return "Alpha"
def get_proxy(self, query: str) -> Optional[str]:
def get_proxy(self, query: str) -> str | None:
return self.answers.get(query)
class Beta(Alpha):
def last_connection_display(self) -> Optional[str]:
def last_connection_display(self) -> str | None:
return "via Dallas (server 12)"
class Tunnel(Alpha):
def __init__(self, info: Optional[dict] = None, **answers: str) -> None:
def __init__(self, info: dict | None = None, **answers: str) -> None:
super().__init__(**answers)
self.info = info
self.asked: list[str] = []
def get_connection_info(self, query: str) -> Optional[dict]:
def get_connection_info(self, query: str) -> dict | None:
self.asked.append(query)
return self.info
+2 -2
View File
@@ -7,8 +7,8 @@ import re
import socket
import ssl
import threading
from collections.abc import Iterator
from pathlib import Path
from typing import Iterator
from unittest.mock import MagicMock
import pytest
@@ -306,7 +306,7 @@ def tls_echo(tmp_path: Path) -> Iterator[tuple[int, ssl.SSLContext]]:
"""A TLS echo server for *.prod.surfshark.com on loopback, and a client context that trusts it."""
key = ec.generate_private_key(ec.SECP256R1())
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "*.prod.surfshark.com")])
now = datetime.datetime.now(datetime.timezone.utc)
now = datetime.datetime.now(datetime.UTC)
cert = (
x509.CertificateBuilder()
.subject_name(name)
+2 -1
View File
@@ -1,7 +1,8 @@
import json
import threading
from collections.abc import Iterator
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Iterator
from typing import Any
import pytest
import requests
+4 -3
View File
@@ -7,7 +7,8 @@ decrypt in parallel on it. Each CDM session keeps its own PSSH and required KIDs
from __future__ import annotations
import base64
from typing import Any, Callable, List
from collections.abc import Callable
from typing import Any
import pytest
from pyplayready.system.wrmheader import WRMHeader
@@ -36,9 +37,9 @@ class FakePssh:
self.raw = raw
def recording(cdm: Any) -> List[tuple[str, Any]]:
def recording(cdm: Any) -> list[tuple[str, Any]]:
"""Make the adapter record the init data and required KIDs of each challenge instead of sending it."""
sent: List[tuple[str, Any]] = []
sent: list[tuple[str, Any]] = []
def request_challenge(session: Any, body: Any, *_: Any) -> bytes:
sent.append((body["init_data"], session.get("required_kids")))
+1 -2
View File
@@ -3,7 +3,6 @@
from __future__ import annotations
import types
from typing import Optional
import pytest
@@ -26,7 +25,7 @@ def clean_config(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "codec_names", {})
def quality(width: Optional[int], height: Optional[int], scan_type: str = "Progressive") -> str:
def quality(width: int | None, height: int | None, scan_type: str = "Progressive") -> str:
movie = Movie(id_="movie-0001", service=DummyService, name="The Film", year=2024, language="en")
video = types.SimpleNamespace(
width=width,
+5 -7
View File
@@ -2,8 +2,6 @@
from __future__ import annotations
from typing import Optional, Union
import pytest
from unshackle.core import providers
@@ -14,26 +12,26 @@ from unshackle.core.providers._base import ExternalIds, MetadataProvider, Metada
class FakeProvider(MetadataProvider):
"""Stands in for a real provider; records the ID it was asked for."""
def __init__(self, name: str, result: Optional[MetadataResult] = None, raises: bool = False) -> None:
def __init__(self, name: str, result: MetadataResult | None = None, raises: bool = False) -> None:
self.NAME = name
self._result = result
self._raises = raises
self.asked: list[Union[int, str]] = []
self.asked: list[int | str] = []
super().__init__()
def is_available(self) -> bool:
return True
def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
raise AssertionError("resolve_by_ids must not search when an ID was supplied")
def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
def get_by_id(self, provider_id: int | str, kind: str) -> MetadataResult | None:
self.asked.append(provider_id)
if self._raises:
raise ValueError("provider is down")
return self._result
def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
def get_external_ids(self, provider_id: int | str, kind: str) -> ExternalIds:
return ExternalIds()
+3 -2
View File
@@ -14,6 +14,7 @@ from functools import partial
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
import requests
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED
@@ -109,7 +110,7 @@ def test_hls_second_run_reuses_completed_segments(server, tmp_path):
# part1.bin missing -> run 1 completes part0 then dies during the download phase
ctx = make_ctx(tmp_path)
with pytest.raises(Exception):
with pytest.raises(requests.HTTPError):
HLS.download_track(make_track(server), ctx)
assert (ctx.save_dir / "segments" / "0.bin").read_bytes() == PART0
@@ -133,7 +134,7 @@ def test_hls_aes128_content_never_writes_sidecar(server, tmp_path):
# part1.bin missing -> crash mid-download, the state resume would normally preserve
ctx = make_ctx(tmp_path)
with pytest.raises(Exception):
with pytest.raises(requests.HTTPError):
HLS.download_track(make_track(server), ctx)
assert not resume.sidecar_path(ctx.save_dir).exists()
+3 -2
View File
@@ -16,6 +16,7 @@ from functools import partial
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
import requests
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED
@@ -116,7 +117,7 @@ def test_second_run_reuses_completed_segments(server, tmp_path):
# part1.bin is missing -> the first run completes part0 then dies on part1
ctx = make_ctx(tmp_path)
with pytest.raises(Exception):
with pytest.raises(requests.HTTPError):
DASH.download_track(make_track(mpd(server), server), ctx)
assert (ctx.save_dir / "0.mp4").read_bytes() == PART0
@@ -138,7 +139,7 @@ def test_changed_segmentation_wipes_stale_segments(server, tmp_path):
server.routes["/part0.bin"] = PART0
ctx = make_ctx(tmp_path)
with pytest.raises(Exception):
with pytest.raises(requests.HTTPError):
DASH.download_track(make_track(mpd(server), server), ctx)
assert (ctx.save_dir / "0.mp4").exists()
+4 -4
View File
@@ -1,6 +1,6 @@
"""RnetSession.get_sleep_time must survive hostile or malformed Retry-After headers."""
from datetime import datetime, timedelta, timezone
from datetime import UTC, datetime, timedelta
from email.utils import format_datetime
from types import SimpleNamespace
@@ -35,18 +35,18 @@ def test_huge_numeric_retry_after_respects_session_cap():
def test_http_date_retry_after_honoured(session):
when = format_datetime(datetime.now(timezone.utc) + timedelta(seconds=10), usegmt=True)
when = format_datetime(datetime.now(UTC) + timedelta(seconds=10), usegmt=True)
assert 5 <= session.get_sleep_time(response(when), 1) <= 10
def test_naive_http_date_does_not_raise(session):
# "-0000" makes parsedate_to_datetime return a naive datetime
when = format_datetime(datetime.now(timezone.utc) + timedelta(seconds=10)).replace("+0000", "-0000")
when = format_datetime(datetime.now(UTC) + timedelta(seconds=10)).replace("+0000", "-0000")
assert 5 <= session.get_sleep_time(response(when), 1) <= 10
def test_past_http_date_yields_no_sleep(session):
when = format_datetime(datetime.now(timezone.utc) - timedelta(seconds=30), usegmt=True)
when = format_datetime(datetime.now(UTC) - timedelta(seconds=30), usegmt=True)
assert session.get_sleep_time(response(when), 1) <= 0
+2 -1
View File
@@ -2,11 +2,12 @@
from __future__ import annotations
from collections.abc import Iterator
from concurrent.futures import Future
from functools import partial
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Iterator
from typing import Any
from uuid import UUID
import pytest
+1 -1
View File
@@ -2,8 +2,8 @@
from __future__ import annotations
from collections.abc import Callable
from pathlib import Path
from typing import Callable
import click
import pytest
+2 -2
View File
@@ -3,7 +3,7 @@
from __future__ import annotations
import logging
from typing import Any, Optional
from typing import Any
import click
import pytest
@@ -16,7 +16,7 @@ from unshackle.core.utils.click_types import LANGUAGE_RANGE, MultipleChoice
log = logging.getLogger("test_service_dl_overrides")
def make_ctx(args: Optional[list[str]] = None, default_map: Optional[dict[str, Any]] = None) -> click.Context:
def make_ctx(args: list[str] | None = None, default_map: dict[str, Any] | None = None) -> click.Context:
"""Build a parsed context for a mirror of the dl group's option shapes."""
@click.group("dl", invoke_without_command=True)
+8 -8
View File
@@ -2,7 +2,7 @@
from __future__ import annotations
from typing import Any, Optional, cast
from typing import Any, cast
import click
import pytest
@@ -14,7 +14,7 @@ from unshackle.core.services import Services
def make_ctx(
command: click.Command, args: Optional[list[str]] = None, default_map: Optional[dict[str, Any]] = None
command: click.Command, args: list[str] | None = None, default_map: dict[str, Any] | None = None
) -> click.Context:
"""Parse the group options of a real ``Services`` command, without running its callback."""
return command.make_context(
@@ -27,11 +27,11 @@ def group(ctx: click.Context) -> Services:
@pytest.fixture
def routed(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, Optional[str]]]:
def routed(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, str | None]]:
"""Record the path get_command takes and the server it passes, without loading a service or calling a server."""
calls: list[tuple[str, Optional[str]]] = []
calls: list[tuple[str, str | None]] = []
def remote(name: str, server_name: Optional[str]) -> click.Command:
def remote(name: str, server_name: str | None) -> click.Command:
calls.append(("remote", server_name))
return click.Command(name)
@@ -46,7 +46,7 @@ def routed(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, Optional[str]]]:
@pytest.mark.parametrize("command", [dl.cli, search])
def test_service_remote_routes_to_remote_command(
monkeypatch: pytest.MonkeyPatch, routed: list[tuple[str, Optional[str]]], command: click.Command
monkeypatch: pytest.MonkeyPatch, routed: list[tuple[str, str | None]], command: click.Command
) -> None:
"""The typed name matches the config key in any case, as a service only the server has keeps the typed case."""
monkeypatch.setattr(config, "services", {"EXAMPLE": {"dl": {"remote": True, "server": "box"}}})
@@ -73,8 +73,8 @@ def test_routing_precedence(
routed: list,
services: dict,
args: list[str],
default_map: Optional[dict[str, Any]],
expected: tuple[str, Optional[str]],
default_map: dict[str, Any] | None,
expected: tuple[str, str | None],
) -> None:
monkeypatch.setattr(config, "services", services)
ctx = make_ctx(dl.cli, args, default_map)
+1 -1
View File
@@ -8,9 +8,9 @@ server received, because the session dicts pass even with the leak in place.
from __future__ import annotations
import threading
from collections.abc import Iterator
from http.cookiejar import Cookie, CookieJar
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Iterator
import pytest
import rnet
+2 -1
View File
@@ -4,7 +4,8 @@ from __future__ import annotations
import inspect
import types
from typing import Any, Iterator
from collections.abc import Iterator
from typing import Any
import pytest
from langcodes import Language
+4 -5
View File
@@ -3,7 +3,6 @@ import threading
import time
from pathlib import Path
from types import SimpleNamespace
from typing import Optional, Union
from uuid import UUID
import pytest
@@ -103,7 +102,7 @@ SERVER = SimpleNamespace(
)
def batch_title(*batches: dict[UUID, str], kids: Optional[list[UUID]] = None) -> SimpleNamespace:
def batch_title(*batches: dict[UUID, str], kids: list[UUID] | None = None) -> SimpleNamespace:
"""A title with one track per batch, whose DRM names ``kids`` (every KID of its batch by default)."""
return SimpleNamespace(
tracks=[
@@ -259,13 +258,13 @@ def test_retry_takes_the_next_parallel_answer_without_a_new_request(tmp_path: Pa
started, release = threading.Event(), threading.Event()
class Fast(FakeVault):
def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
def get_key(self, kid: UUID | str, service: str) -> str | None:
# answer only once the slow query runs, or the pool shutdown cancels it before it starts
started.wait(5)
return super().get_key(kid, service)
class Slow(FakeVault):
def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
def get_key(self, kid: UUID | str, service: str) -> str | None:
started.set()
release.wait(5)
return super().get_key(kid, service)
@@ -409,7 +408,7 @@ def test_stale_backup_from_a_killed_run_is_not_restored(tmp_path: Path, monkeypa
ids=["file-uses-it", "file-does-not", "unmapped"],
)
def test_an_unkeyed_kid_the_file_uses_is_licensed_before_the_decrypt(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, windows: Optional[dict], licensed: list[UUID]
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, windows: dict | None, licensed: list[UUID]
) -> None:
keys = make_resolver(monkeypatch, Vaults("SVC"))
drm = FakeDRM({KID: GOOD})
+6 -6
View File
@@ -11,8 +11,8 @@ from __future__ import annotations
import logging
import sqlite3
import threading
from collections.abc import Iterator
from pathlib import Path
from typing import Iterator, Optional, Union
from uuid import UUID
import pytest
@@ -40,16 +40,16 @@ def tables(path: Path) -> list[str]:
class UnlistableVault(Vault):
"""Stands in for the API vault, which supports neither listing nor bulk dumps."""
def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
def get_key(self, kid: UUID | str, service: str) -> str | None:
return None
def get_keys(self, service: str) -> Iterator[tuple[str, str]]:
raise ValueError("Bulk dump is not supported.")
def add_key(self, service: str, kid: Union[UUID, str], key: str) -> bool:
def add_key(self, service: str, kid: UUID | str, key: str) -> bool:
return False
def add_keys(self, service: str, kid_keys: dict[Union[UUID, str], str]) -> int:
def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
return 0
def get_services(self) -> Iterator[str]:
@@ -131,7 +131,7 @@ def test_synced_lowercase_table_survives_the_service_being_added_later(tmp_path:
("00112233445566778899AABBCCDDEEFF", False),
],
)
def test_is_null_key(key: Optional[str], expected: bool) -> None:
def test_is_null_key(key: str | None, expected: bool) -> None:
assert is_null_key(key) is expected
@@ -201,7 +201,7 @@ def test_copy_skips_a_vault_that_cannot_list_services() -> None:
def test_lookups_work_from_another_thread(vault: SQLite) -> None:
"""`kv search` probes services in a ThreadPoolExecutor; connections are thread-local."""
found: list[Optional[str]] = []
found: list[str | None] = []
thread = threading.Thread(target=lambda: found.append(vault.get_key(KID, "SVCA")))
thread.start()
thread.join()
+4 -4
View File
@@ -1,6 +1,6 @@
import threading
import time
from typing import Iterator, Optional, Union
from collections.abc import Iterator
from uuid import UUID
from unshackle.core.vault import Vault
@@ -8,13 +8,13 @@ from unshackle.core.vaults import Vaults
class FakeVault(Vault):
def __init__(self, name: str, key: Optional[str], delay: float = 0.0, local: bool = False):
def __init__(self, name: str, key: str | None, delay: float = 0.0, local: bool = False):
super().__init__(name)
self.key, self.delay, self.local = key, delay, local
self.calls = 0
self.threads: set[int] = set()
def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
def get_key(self, kid: UUID | str, service: str) -> str | None:
self.calls += 1
self.threads.add(threading.get_ident())
time.sleep(self.delay)
@@ -23,7 +23,7 @@ class FakeVault(Vault):
def get_keys(self, service: str) -> Iterator[tuple[str, str]]:
return iter(())
def add_key(self, service: str, kid: Union[UUID, str], key: str) -> bool:
def add_key(self, service: str, kid: UUID | str, key: str) -> bool:
return False
def add_keys(self, service: str, kid_keys: dict) -> int:
+1 -2
View File
@@ -1,7 +1,6 @@
from __future__ import annotations
import base64
from typing import Union
from uuid import UUID
import pytest
@@ -17,7 +16,7 @@ AUDIO_KID = UUID("ffeeddcc-bbaa-9988-7766-554433221100")
VIDEO_KEY = "0000000000000000000000000000000a"
AUDIO_KEY = "0000000000000000000000000000000b"
DRM = Union[Widevine, PlayReady]
DRM = Widevine | PlayReady
def _playready_pssh(*kids: UUID) -> tuple[PlayReadyPSSH, str]: