mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-29 20:45:11 +00:00
style: turn on ruff UP and B rules and fix every finding
This commit is contained in:
+6
-1
@@ -142,12 +142,17 @@ force-exclude = true
|
||||
line-length = 120
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E4", "E7", "E9", "F", "W"]
|
||||
select = ["E4", "E7", "E9", "F", "W", "UP", "B"]
|
||||
# StrEnum makes str() and format() of a member give its value, not "Codec.AVC"; callers and services read that text.
|
||||
ignore = ["UP042"]
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
# binaries are resolved lazily via module-level __getattr__ (PEP 562), so the
|
||||
# names in __all__ are intentionally not defined statically.
|
||||
"unshackle/core/binaries.py" = ["F822"]
|
||||
# Optional hooks with a no-op default: a service or vault overrides only the ones it needs.
|
||||
"unshackle/core/service.py" = ["B027"]
|
||||
"unshackle/core/vault.py" = ["B027"]
|
||||
|
||||
[tool.isort]
|
||||
profile = "black"
|
||||
|
||||
+18
-18
@@ -40,7 +40,7 @@ import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from shutil import rmtree
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
import click
|
||||
import fault_server # local sibling (scripts/): fault-injection server + payload verifier
|
||||
@@ -105,7 +105,7 @@ class SegmentHandler(http.server.BaseHTTPRequestHandler):
|
||||
server.connections += 1
|
||||
self.slow_conn = server.connections <= server.faults["slow_conn"]
|
||||
|
||||
def _parse_range(self, total: int) -> Optional[tuple[int, int]]:
|
||||
def _parse_range(self, total: int) -> tuple[int, int] | None:
|
||||
header = self.headers.get("Range")
|
||||
if not header or not header.startswith("bytes="):
|
||||
return None
|
||||
@@ -214,8 +214,8 @@ class SegmentHandler(http.server.BaseHTTPRequestHandler):
|
||||
|
||||
|
||||
def run_batch(
|
||||
urls: list[str], out_dir: Path, workers: int, session: Optional[Any], adaptive: bool = False, procs: int = 1
|
||||
) -> tuple[float, list[float], Optional[BaseException]]:
|
||||
urls: list[str], out_dir: Path, workers: int, session: Any | None, adaptive: bool = False, procs: int = 1
|
||||
) -> tuple[float, list[float], BaseException | None]:
|
||||
"""Download one batch through the real code path.
|
||||
|
||||
Returns (wall seconds, completion timestamps relative to start, error-or-None).
|
||||
@@ -223,7 +223,7 @@ def run_batch(
|
||||
"""
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
completions: list[float] = []
|
||||
err: Optional[BaseException] = None
|
||||
err: BaseException | None = None
|
||||
start = time.perf_counter()
|
||||
try:
|
||||
for event in download_batch(
|
||||
@@ -258,7 +258,7 @@ def run_batch(
|
||||
return wall, completions, err, strays, locked, pool_threads
|
||||
|
||||
|
||||
def incomplete_segments(out_dir: Path, expected: int, expected_bytes: Optional[bytes]) -> list[int]:
|
||||
def incomplete_segments(out_dir: Path, expected: int, expected_bytes: bytes | None) -> list[int]:
|
||||
"""Segment indexes that are missing, empty, or (synthetic mode) not byte-identical.
|
||||
|
||||
Content compare (not just size) is required: on a mid-body interruption the downloader
|
||||
@@ -331,9 +331,9 @@ def sweep(
|
||||
urls: list[str],
|
||||
workers: list[int],
|
||||
runs: int,
|
||||
session: Optional[Any],
|
||||
server: Optional[SegmentServer],
|
||||
expected_bytes: Optional[bytes],
|
||||
session: Any | None,
|
||||
server: SegmentServer | None,
|
||||
expected_bytes: bytes | None,
|
||||
adaptive: bool = False,
|
||||
procs: int = 1,
|
||||
) -> list[Row]:
|
||||
@@ -468,7 +468,7 @@ def print_fault_report(rows: list[FaultRow], runs: int, segments: int, profile:
|
||||
)
|
||||
|
||||
|
||||
def _procs_notice(procs: int, n_urls: int, session: Optional[Any]) -> None:
|
||||
def _procs_notice(procs: int, n_urls: int, session: Any | None) -> None:
|
||||
"""Warn loudly when --procs cannot engage, so a run is never mistaken for a multiprocess test."""
|
||||
if procs <= 1:
|
||||
return
|
||||
@@ -490,7 +490,7 @@ def run_fault_mode(
|
||||
seg_size: int,
|
||||
worker_counts: list[int],
|
||||
runs: int,
|
||||
session: Optional[Any],
|
||||
session: Any | None,
|
||||
adaptive: bool,
|
||||
procs: int,
|
||||
seed: int,
|
||||
@@ -650,12 +650,12 @@ def main(
|
||||
fault_slow_conn: int,
|
||||
part_size_mib: int,
|
||||
fast_timeouts: bool,
|
||||
urls_file: Optional[str],
|
||||
impersonate: Optional[str],
|
||||
urls_file: str | None,
|
||||
impersonate: str | None,
|
||||
adaptive: bool,
|
||||
procs: int,
|
||||
no_read1: bool,
|
||||
fault_profile: Optional[str],
|
||||
fault_profile: str | None,
|
||||
seed: int,
|
||||
) -> None:
|
||||
"""Benchmark downloader throughput vs worker count, with optional fault injection."""
|
||||
@@ -668,12 +668,12 @@ def main(
|
||||
"tail_slow_once": fault_tail_slow_once,
|
||||
"slow_conn": fault_slow_conn,
|
||||
}
|
||||
server: Optional[SegmentServer] = None
|
||||
session: Optional[Any] = None
|
||||
server: SegmentServer | None = None
|
||||
session: Any | None = None
|
||||
saved: dict[str, Any] = {}
|
||||
saved_network: Optional[dict] = None
|
||||
saved_network: dict | None = None
|
||||
total = segments
|
||||
expected_bytes: Optional[bytes] = None # synthetic reference buffer; None in real-URL mode
|
||||
expected_bytes: bytes | None = None # synthetic reference buffer; None in real-URL mode
|
||||
|
||||
if fast_timeouts: # bench-only: patched globals are read at call time inside download()
|
||||
fast = {"READ_TIMEOUT": 2, "RETRY_WAIT": 1, "HEDGE_MIN_WAIT": 1.0}
|
||||
|
||||
@@ -45,7 +45,7 @@ import threading
|
||||
import time
|
||||
from dataclasses import asdict, dataclass
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
MIB = 1024 * 1024
|
||||
DEFAULT_SEED = 1729
|
||||
@@ -186,7 +186,7 @@ class FaultServer(ThreadingHTTPServer):
|
||||
"""Deterministic per-(path, attempt) fault gate: fires for ``pct`` percent of them."""
|
||||
if pct <= 0:
|
||||
return False
|
||||
digest = hashlib.sha256(f"{self.seed}:{kind}:{path}:{attempt}".encode("utf-8")).digest()
|
||||
digest = hashlib.sha256(f"{self.seed}:{kind}:{path}:{attempt}".encode()).digest()
|
||||
return (int.from_bytes(digest[:4], "big") / 0xFFFFFFFF) * 100.0 < pct
|
||||
|
||||
def reset_counters(self) -> None:
|
||||
@@ -212,7 +212,7 @@ class FaultHandler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_: Any) -> None: # silence per-request logging
|
||||
pass
|
||||
|
||||
def _parse_range(self, total: int) -> Optional[tuple[int, int]]:
|
||||
def _parse_range(self, total: int) -> tuple[int, int] | None:
|
||||
header = self.headers.get("Range")
|
||||
if not header or not header.startswith("bytes="):
|
||||
return None
|
||||
@@ -372,7 +372,7 @@ class FaultHandler(BaseHTTPRequestHandler):
|
||||
time.sleep(per_chunk)
|
||||
|
||||
|
||||
def resolve_profile(name: str, overrides: Optional[dict[str, Any]] = None) -> FaultProfile:
|
||||
def resolve_profile(name: str, overrides: dict[str, Any] | None = None) -> FaultProfile:
|
||||
"""Return a copy of the named preset with any non-None ``overrides`` applied."""
|
||||
if name not in PROFILES:
|
||||
raise KeyError(f"unknown profile {name!r}; choices: {', '.join(sorted(PROFILES))}")
|
||||
|
||||
@@ -18,7 +18,7 @@ import re
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import requests
|
||||
@@ -56,7 +56,7 @@ EXCLUDED: dict[str, str] = {
|
||||
"https://storage.googleapis.com/shaka-demo-assets/heliocentrism-xlink/heliocentrism.mpd": "xlink:href remote Periods are not resolved",
|
||||
}
|
||||
|
||||
Stream = tuple[str, str, str, Optional[dict[str, Any]]]
|
||||
Stream = tuple[str, str, str, dict[str, Any] | None]
|
||||
|
||||
|
||||
def dashif_streams() -> list[Stream]:
|
||||
@@ -128,7 +128,7 @@ def shaka_packager_streams() -> list[Stream]:
|
||||
]
|
||||
|
||||
|
||||
def kind_of(head: bytes) -> Optional[str]:
|
||||
def kind_of(head: bytes) -> str | None:
|
||||
"""Tell the manifest type from the first bytes, since many manifest URLs have no telling extension."""
|
||||
text = head.lstrip(b"\xef\xbb\xbf").lstrip()
|
||||
if text.startswith(b"#EXTM3U"):
|
||||
@@ -145,7 +145,7 @@ def file_name(source: str, name: str, url: str, kind: str) -> str:
|
||||
return f"{kind}/{source}-{slug}-{hashlib.sha1(url.encode()).hexdigest()[:8]}.{EXTENSIONS[kind]}"
|
||||
|
||||
|
||||
def fetch(stream: Stream) -> Optional[dict[str, Any]]:
|
||||
def fetch(stream: Stream) -> dict[str, Any] | None:
|
||||
"""Download one manifest into OUT and return its index entry, or None when it is not a manifest."""
|
||||
source, name, url, expect = stream
|
||||
try:
|
||||
|
||||
@@ -22,7 +22,7 @@ import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from tempfile import mkdtemp
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
import click
|
||||
from requests import Session
|
||||
@@ -94,7 +94,7 @@ class Counter:
|
||||
self.files += 1
|
||||
|
||||
|
||||
def pick_track(tracks: object, which: str) -> Optional[Any]:
|
||||
def pick_track(tracks: object, which: str) -> Any | None:
|
||||
vids = list(getattr(tracks, "videos", []))
|
||||
if not vids:
|
||||
auds = list(getattr(tracks, "audio", []))
|
||||
|
||||
@@ -19,7 +19,7 @@ import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
from tempfile import mkdtemp
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
import click
|
||||
from requests import Session
|
||||
@@ -34,7 +34,7 @@ STREAMS: list[tuple[str, str]] = [
|
||||
("sony-1a", "https://dash.akamaized.net/dash264/TestCases/1a/sony/SNE_DASH_SD_CASE1A_REVISED.mpd"),
|
||||
]
|
||||
|
||||
guard_results: list[Optional[tuple[int, int]]] = []
|
||||
guard_results: list[tuple[int, int] | None] = []
|
||||
|
||||
|
||||
def install_guard_spy() -> bool:
|
||||
@@ -43,7 +43,7 @@ def install_guard_spy() -> bool:
|
||||
if orig is None:
|
||||
return False
|
||||
|
||||
def spy(is_subtitle: bool, segments: Any, init_len: int) -> Optional[tuple[int, int]]:
|
||||
def spy(is_subtitle: bool, segments: Any, init_len: int) -> tuple[int, int] | None:
|
||||
result = orig(is_subtitle, segments, init_len)
|
||||
guard_results.append(result)
|
||||
return result
|
||||
|
||||
@@ -9,7 +9,7 @@ key pair and a blocking request to its host.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -32,7 +32,7 @@ def builds(monkeypatch) -> list[tuple[str, str]]:
|
||||
"""Record every ``load_cdm`` call and hand back a fresh stub for each one."""
|
||||
calls: list[tuple[str, str]] = []
|
||||
|
||||
def fake_load_cdm(cdm_name: str, *, service_name: str = "", vaults: Optional[Any] = None) -> StubCdm:
|
||||
def fake_load_cdm(cdm_name: str, *, service_name: str = "", vaults: Any | None = None) -> StubCdm:
|
||||
calls.append((cdm_name, service_name))
|
||||
return StubCdm(cdm_name, service_name)
|
||||
|
||||
|
||||
+3
-2
@@ -5,8 +5,9 @@ from __future__ import annotations
|
||||
import importlib
|
||||
import socket
|
||||
import socketserver
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Optional
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -87,7 +88,7 @@ def mux_args(monkeypatch: pytest.MonkeyPatch) -> Callable[..., list[str]]:
|
||||
class Stop(Exception):
|
||||
pass
|
||||
|
||||
def run(tracks: Any, ids: Optional[dict[str, int]] = None, **kwargs: Any) -> list[str]:
|
||||
def run(tracks: Any, ids: dict[str, int] | None = None, **kwargs: Any) -> list[str]:
|
||||
captured: list[list[str]] = []
|
||||
|
||||
def fake_popen(args: list[str], **_: object) -> None:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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,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)
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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), "")
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,6 +1,6 @@
|
||||
import warnings
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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] = []
|
||||
|
||||
|
||||
@@ -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,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
@@ -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)
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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] = []
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,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)
|
||||
|
||||
@@ -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,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,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
|
||||
|
||||
@@ -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})
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,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
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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")))
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -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,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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})
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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,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]:
|
||||
|
||||
@@ -9,12 +9,13 @@ media requests must ask for identity encoding.
|
||||
|
||||
import importlib
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from email.utils import format_datetime
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
dl = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
|
||||
@@ -109,7 +110,7 @@ def test_range_item_ignored_by_server_fails_not_corrupts(server, tmp_path, monke
|
||||
server.honor_range = False
|
||||
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
|
||||
urls = [{"url": url(server), "headers": {"Range": f"bytes={SLICE_START}-{SLICE_END}"}}]
|
||||
with pytest.raises(Exception):
|
||||
with pytest.raises(OSError):
|
||||
run(server, tmp_path, urls, max_workers=1)
|
||||
# nothing finalized: a 200 full-parent body must never become the segment
|
||||
assert not list(tmp_path.glob("seg_*.bin"))
|
||||
@@ -154,7 +155,7 @@ def test_retry_sleep_honors_numeric_retry_after():
|
||||
|
||||
|
||||
def test_retry_sleep_honors_http_date_retry_after():
|
||||
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 <= dl.retry_sleep(exc_with_headers({"Retry-After": when}), 1) <= 10
|
||||
|
||||
|
||||
@@ -172,7 +173,7 @@ def test_retry_sleep_invalid_retry_after_falls_back():
|
||||
|
||||
def test_retry_sleep_naive_http_date_treated_as_utc():
|
||||
# "-0000" makes parsedate_to_datetime return a naive datetime; must clamp, not raise
|
||||
when = format_datetime(datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(seconds=10))
|
||||
when = format_datetime(datetime.now(UTC).replace(tzinfo=None) + timedelta(seconds=10))
|
||||
assert when.endswith("-0000")
|
||||
v = dl.retry_sleep(exc_with_headers({"Retry-After": when}), 1)
|
||||
assert 5 <= v <= 10
|
||||
@@ -219,7 +220,7 @@ def test_session_retry_does_not_nest_inside_an_attempt(server, tmp_path, monkeyp
|
||||
session.mount("http://", adapter)
|
||||
session.mount("https://", adapter)
|
||||
|
||||
with pytest.raises(Exception):
|
||||
with pytest.raises(requests.HTTPError):
|
||||
run(server, tmp_path, [{"url": url(server)}], max_workers=1, session=session)
|
||||
|
||||
assert len(server.requests) == dl.MAX_ATTEMPTS
|
||||
|
||||
@@ -121,7 +121,7 @@ def test_disk_full_is_not_retried(tmp_path, monkeypatch, serve):
|
||||
|
||||
def test_status_failure_keeps_the_normal_budget(tmp_path, serve):
|
||||
server = serve(503)
|
||||
with pytest.raises(Exception):
|
||||
with pytest.raises(rq.HTTPError):
|
||||
list(dl.download(url=server.url, save_path=tmp_path / "a.bin", session=rq.Session()))
|
||||
|
||||
assert server.requests == dl.MAX_ATTEMPTS
|
||||
|
||||
@@ -211,7 +211,7 @@ def test_permanent_status_unwraps_causes():
|
||||
assert dl.permanent_status(HTTPError(response=_Resp(403))) == 403
|
||||
assert dl.permanent_status(HTTPError(response=_Resp(429))) is None
|
||||
assert dl.permanent_status(HTTPError(response=_Resp(503))) is None
|
||||
assert dl.permanent_status(IOError("short read")) is None
|
||||
assert dl.permanent_status(OSError("short read")) is None
|
||||
# RnetSession wraps the HTTPError one level down as __cause__
|
||||
wrapped = RuntimeError("max retries")
|
||||
wrapped.__cause__ = HTTPError(response=_Resp(404))
|
||||
|
||||
@@ -210,7 +210,7 @@ def test_tail_boost_permanent_part_failure_still_fails_the_batch(server, tmp_pat
|
||||
server.deny_offset_ranges = True # every part window past the first is a 403
|
||||
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
|
||||
|
||||
with pytest.raises(Exception):
|
||||
with pytest.raises(dl.TailPartFailed):
|
||||
run(server, tmp_path, seg_urls(server))
|
||||
|
||||
assert boost_engaged(server), "tail boost never engaged; the permanent-failure rule is untested"
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.utilities import as_requested
|
||||
@@ -20,5 +18,5 @@ from unshackle.core.utilities import as_requested
|
||||
([], "en", ""),
|
||||
],
|
||||
)
|
||||
def test_as_requested(tokens: list[str], orig_token: Optional[str], expected: str) -> None:
|
||||
def test_as_requested(tokens: list[str], orig_token: str | None, expected: str) -> None:
|
||||
assert as_requested(tokens, orig_token) == expected
|
||||
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
import inspect
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional, cast
|
||||
from typing import Any, cast
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
@@ -97,7 +97,7 @@ def run(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
episodes: dict,
|
||||
service: Optional[FakeService] = None,
|
||||
service: FakeService | None = None,
|
||||
to_end: bool = False,
|
||||
**flags: Any,
|
||||
) -> Any:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Sequence
|
||||
from collections.abc import Sequence
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.wire import original_audio_ids
|
||||
@@ -14,7 +12,7 @@ class FakeTrack:
|
||||
|
||||
|
||||
class FakeTitle:
|
||||
def __init__(self, language: Optional[str]) -> None:
|
||||
def __init__(self, language: str | None) -> None:
|
||||
self.language = language
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional, Sequence
|
||||
from collections.abc import Sequence
|
||||
|
||||
import pytest
|
||||
from langcodes import Language
|
||||
@@ -22,7 +22,7 @@ from unshackle.core.utilities import ServiceTag, resolve_sort_langs
|
||||
([], "ja", []),
|
||||
],
|
||||
)
|
||||
def test_resolve_sort_langs(tokens: Sequence[str], original: Optional[str], expected: list[str]) -> None:
|
||||
def test_resolve_sort_langs(tokens: Sequence[str], original: str | None, expected: list[str]) -> None:
|
||||
assert resolve_sort_langs(tokens, original) == expected
|
||||
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ def selection(**flags: Any) -> TrackSelection:
|
||||
"""A TrackSelection with every filter off but the given flags."""
|
||||
off: dict[str, Any] = {}
|
||||
for flag in fields(TrackSelection):
|
||||
off[flag.name] = [] if str(flag.type).startswith("list") else None if "Optional" in str(flag.type) else False
|
||||
off[flag.name] = None if "None" in str(flag.type) else [] if str(flag.type).startswith("list") else False
|
||||
return TrackSelection(**{**off, **flags})
|
||||
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ discovered and skips so you can copy values back into the fixture.
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -51,7 +51,7 @@ def wait_for_titles(http_session, server_url: str, sid: str, timeout: float = 12
|
||||
return 408, {"message": "auth timeout"}
|
||||
|
||||
|
||||
def pick_target_title(titles: list[dict[str, Any]], season: int = 1, episode: int = 1) -> Optional[dict[str, Any]]:
|
||||
def pick_target_title(titles: list[dict[str, Any]], season: int = 1, episode: int = 1) -> dict[str, Any] | None:
|
||||
"""Pick the configured target episode; fall back to the first title."""
|
||||
for t in titles:
|
||||
if t.get("type") == "episode" and t.get("season") == season and t.get("number") == episode:
|
||||
@@ -76,7 +76,7 @@ def summarize(video_tracks: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def resolve_title_id(conf: dict) -> Optional[str]:
|
||||
def resolve_title_id(conf: dict) -> str | None:
|
||||
"""Prefer series_url so S01E01 logic kicks in; fall back to movie title_url."""
|
||||
return conf.get("series_url") or conf.get("title_url")
|
||||
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import logging
|
||||
from collections.abc import Iterable
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Iterable, Optional
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from unshackle.core.remote_service import RemoteService, ServerVault
|
||||
|
||||
|
||||
def remote_keys(
|
||||
server_cdm: Optional[bool] = True,
|
||||
server_cdm: bool | None = True,
|
||||
server_cdm_type: str = "widevine",
|
||||
local_cdm: Any = None,
|
||||
) -> RemoteService:
|
||||
@@ -39,7 +40,7 @@ class MemoryKeySource:
|
||||
self.local_cdm = local_cdm
|
||||
self.client_licensed = set(client_licensed)
|
||||
self.server_vault_keys: dict[UUID, str] = {}
|
||||
self.asked: list[tuple[Any, Optional[UUID]]] = []
|
||||
self.asked: list[tuple[Any, UUID | None]] = []
|
||||
|
||||
def resolve_server_keys(self, title: Any) -> None:
|
||||
pass
|
||||
@@ -47,7 +48,7 @@ class MemoryKeySource:
|
||||
def licenses_locally(self, track: Any) -> bool:
|
||||
return str(track.id) in self.client_licensed
|
||||
|
||||
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.asked.append((track.id, kid))
|
||||
if self.licence is None:
|
||||
self.client_licensed.add(str(track.id))
|
||||
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -27,8 +27,8 @@ class _FakeSvc:
|
||||
pass
|
||||
|
||||
|
||||
def ep(season: int = 1, number: int = 1, part: Optional[int] = None, **overrides: Any) -> Episode:
|
||||
base: Dict[str, Any] = dict(
|
||||
def ep(season: int = 1, number: int = 1, part: int | None = None, **overrides: Any) -> Episode:
|
||||
base: dict[str, Any] = dict(
|
||||
id_=f"ep-{season}-{number}-{part or 0}",
|
||||
service=_FakeSvc,
|
||||
title="My Show",
|
||||
@@ -43,23 +43,23 @@ def ep(season: int = 1, number: int = 1, part: Optional[int] = None, **overrides
|
||||
|
||||
|
||||
class _FakeTracks:
|
||||
videos: List[Any] = []
|
||||
audio: List[Any] = []
|
||||
subtitles: List[Any] = []
|
||||
videos: list[Any] = []
|
||||
audio: list[Any] = []
|
||||
subtitles: list[Any] = []
|
||||
|
||||
|
||||
class _FakeService:
|
||||
def __init__(self, titles: List[Episode]) -> None:
|
||||
def __init__(self, titles: list[Episode]) -> None:
|
||||
self._titles = titles
|
||||
|
||||
def get_titles(self) -> List[Episode]:
|
||||
def get_titles(self) -> list[Episode]:
|
||||
return self._titles
|
||||
|
||||
def get_tracks(self, title: Episode) -> _FakeTracks:
|
||||
return _FakeTracks()
|
||||
|
||||
|
||||
def run_list_tracks(monkeypatch: pytest.MonkeyPatch, titles: List[Episode], **data: Any) -> Dict[str, Any]:
|
||||
def run_list_tracks(monkeypatch: pytest.MonkeyPatch, titles: list[Episode], **data: Any) -> dict[str, Any]:
|
||||
"""Drive list_tracks_handler end to end with the service layer stubbed out."""
|
||||
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "FAKE")
|
||||
monkeypatch.setattr(handlers, "setup_list_service", lambda *a, **kw: _FakeService(titles))
|
||||
@@ -72,7 +72,7 @@ def run_list_tracks(monkeypatch: pytest.MonkeyPatch, titles: List[Episode], **da
|
||||
return json.loads(response.body)
|
||||
|
||||
|
||||
def selected(result: Dict[str, Any]) -> List[str]:
|
||||
def selected(result: dict[str, Any]) -> list[str]:
|
||||
"""Selection-syntax keys of whatever the handler returned, single or multi."""
|
||||
entries = result["episodes"] if "episodes" in result else [{"title": result["title"]}]
|
||||
keys = []
|
||||
@@ -134,7 +134,7 @@ def test_movie_json_unaffected() -> None:
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def split_titles() -> List[Episode]:
|
||||
def split_titles() -> list[Episode]:
|
||||
"""E1 split into three parts, E2 unsplit."""
|
||||
return [ep(1, 1, 1), ep(1, 1, 2), ep(1, 1, 3), ep(1, 2, None)]
|
||||
|
||||
@@ -214,7 +214,7 @@ def test_rest_multi_episode_order_is_stable_across_parts(monkeypatch) -> None:
|
||||
(["1x01"], ["1x1"]),
|
||||
],
|
||||
)
|
||||
def test_parsed_keys_pass_unchanged(wanted: Any, parsed: List[str]) -> None:
|
||||
def test_parsed_keys_pass_unchanged(wanted: Any, parsed: list[str]) -> None:
|
||||
"""A pre-parsed part or negative key never reaches parse_tokens, which cannot read it."""
|
||||
assert SEASON_RANGE.convert(wanted) == parsed
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import date
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from langcodes import Language
|
||||
@@ -30,7 +30,7 @@ class _FakeSvc:
|
||||
|
||||
|
||||
def ep(**overrides: Any) -> Episode:
|
||||
base: Dict[str, Any] = dict(
|
||||
base: dict[str, Any] = dict(
|
||||
id_="ep-0001",
|
||||
service=_FakeSvc,
|
||||
title="My Show",
|
||||
@@ -45,7 +45,7 @@ def ep(**overrides: Any) -> Episode:
|
||||
|
||||
|
||||
def _movie(**overrides: Any) -> Movie:
|
||||
base: Dict[str, Any] = dict(id_="movie-0001", service=_FakeSvc, name="Film", year=2024, language=Language.get("en"))
|
||||
base: dict[str, Any] = dict(id_="movie-0001", service=_FakeSvc, name="Film", year=2024, language=Language.get("en"))
|
||||
base.update(overrides)
|
||||
return Movie(**base)
|
||||
|
||||
@@ -129,10 +129,10 @@ class _FakeService:
|
||||
ANIME = True
|
||||
DAILY = True
|
||||
|
||||
def __init__(self, titles: List[Episode]) -> None:
|
||||
def __init__(self, titles: list[Episode]) -> None:
|
||||
self._titles = titles
|
||||
|
||||
def get_titles(self) -> List[Episode]:
|
||||
def get_titles(self) -> list[Episode]:
|
||||
return self._titles
|
||||
|
||||
|
||||
@@ -144,7 +144,7 @@ def test_list_titles_stamps_the_service_flags(monkeypatch: pytest.MonkeyPatch) -
|
||||
assert (title["anime"], title["daily"]) == (True, True)
|
||||
|
||||
|
||||
def round_trip(episode: Episode, stamp: Optional[Any] = None) -> Episode:
|
||||
def round_trip(episode: Episode, stamp: Any | None = None) -> Episode:
|
||||
info = serialize_title(episode)
|
||||
if stamp is not None:
|
||||
info = stamp_service_flags(info, stamp)
|
||||
|
||||
@@ -61,7 +61,7 @@ def test_writer_skips_unsafe_entry(tmp_path, monkeypatch, write) -> None:
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"expiration",
|
||||
[None, dt.datetime(2030, 1, 1, 12, 0, 0), dt.datetime(2030, 1, 1, 12, 0, 0, tzinfo=dt.timezone.utc)],
|
||||
[None, dt.datetime(2030, 1, 1, 12, 0, 0), dt.datetime(2030, 1, 1, 12, 0, 0, tzinfo=dt.UTC)],
|
||||
ids=["none", "naive", "aware"],
|
||||
)
|
||||
def test_real_cacher_file_round_trips(tmp_path, monkeypatch, expiration) -> None:
|
||||
|
||||
@@ -16,7 +16,6 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -29,7 +28,7 @@ PACKAGE_SETATTR = re.compile(r"""setattr\(\s*(?!loader\b)[\w.]+\s*,\s*["']load_c
|
||||
|
||||
|
||||
def test_no_test_patches_load_cdm_on_the_package() -> None:
|
||||
offenders: List[str] = []
|
||||
offenders: list[str] = []
|
||||
for path in sorted(TESTS_ROOT.rglob("test_*.py")):
|
||||
if path == Path(__file__).resolve():
|
||||
continue
|
||||
|
||||
@@ -7,7 +7,7 @@ import logging
|
||||
import sys
|
||||
import threading
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
@@ -326,7 +326,7 @@ async def test_dashboard_log_read_does_not_touch_the_session() -> None:
|
||||
store = SessionStore()
|
||||
entry = await store.create("EXAMPLE", object())
|
||||
|
||||
stale = datetime.now(timezone.utc) - timedelta(seconds=1)
|
||||
stale = datetime.now(UTC) - timedelta(seconds=1)
|
||||
entry.last_accessed = stale
|
||||
assert store.peek(entry.session_id) is entry
|
||||
assert entry.last_accessed == stale
|
||||
|
||||
@@ -12,8 +12,9 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
from collections.abc import Awaitable, Callable
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Awaitable, Callable, List
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
@@ -56,7 +57,7 @@ class BlockingTitles:
|
||||
def __init__(self, handshake: Handshake) -> None:
|
||||
self.handshake = handshake
|
||||
|
||||
def get_titles(self) -> List[Movie]:
|
||||
def get_titles(self) -> list[Movie]:
|
||||
self.handshake.block()
|
||||
return [a_movie()]
|
||||
|
||||
@@ -65,7 +66,7 @@ class BlockingTracks:
|
||||
def __init__(self, handshake: Handshake) -> None:
|
||||
self.handshake = handshake
|
||||
|
||||
def get_titles(self) -> List[Movie]:
|
||||
def get_titles(self) -> list[Movie]:
|
||||
return [a_movie()]
|
||||
|
||||
def get_tracks(self, title: Any) -> Any:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""The server spends its own proxy subscriptions only for a key that opts in."""
|
||||
|
||||
from datetime import UTC
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
@@ -266,7 +267,7 @@ class TestDownloadEnforcement:
|
||||
def created_params(self, monkeypatch):
|
||||
"""Drive download_handler with the job machinery faked out; capture create_job params."""
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime
|
||||
|
||||
from unshackle.core.api import download_manager as dm
|
||||
|
||||
@@ -279,7 +280,7 @@ class TestDownloadEnforcement:
|
||||
def create_job(self, service, title_id, owner_key=None, **params):
|
||||
created.update(params)
|
||||
return SimpleNamespace(
|
||||
job_id="job1", status=SimpleNamespace(value="queued"), created_time=datetime.now(timezone.utc)
|
||||
job_id="job1", status=SimpleNamespace(value="queued"), created_time=datetime.now(UTC)
|
||||
)
|
||||
|
||||
monkeypatch.setattr(dm, "get_download_manager", lambda: FakeManager())
|
||||
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
import pyplayready.system.pssh as pr_pssh_mod
|
||||
@@ -59,13 +59,13 @@ class SessionService(_Recorder):
|
||||
"""DEMO: a session-aware service, the shape that needs the open CDM session id."""
|
||||
|
||||
def get_widevine_license(
|
||||
self, *, challenge: bytes, title: Any, track: Any, session_id: Optional[bytes] = None
|
||||
self, *, challenge: bytes, title: Any, track: Any, session_id: bytes | None = None
|
||||
) -> bytes:
|
||||
self.calls.append({"challenge": challenge, "title": title, "track": track, "session_id": session_id})
|
||||
return b"LIC"
|
||||
|
||||
def get_playready_license(
|
||||
self, *, challenge: bytes, title: Any, track: Any, session_id: Optional[bytes] = None
|
||||
self, *, challenge: bytes, title: Any, track: Any, session_id: bytes | None = None
|
||||
) -> str:
|
||||
self.calls.append({"challenge": challenge, "title": title, "track": track, "session_id": session_id})
|
||||
return "<License>ok</License>"
|
||||
@@ -104,7 +104,7 @@ class StubPlayReady(PlayReady):
|
||||
pssh_b64: Any = None
|
||||
kids: Any = None
|
||||
|
||||
def __init__(self, pssh: Any = None, pssh_b64: Optional[str] = None, **kwargs: Any) -> None:
|
||||
def __init__(self, pssh: Any = None, pssh_b64: str | None = None, **kwargs: Any) -> None:
|
||||
self.pssh = SimpleNamespace(wrm_headers=[SimpleNamespace(dumps=lambda: "<WRMHEADER/>")])
|
||||
self.pssh_b64 = pssh_b64
|
||||
self.kids = [KID]
|
||||
|
||||
@@ -6,10 +6,11 @@ import asyncio
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from collections.abc import Callable, Iterator
|
||||
from datetime import UTC, datetime
|
||||
from threading import Event, Semaphore, Thread
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Callable, Iterator, Optional
|
||||
from typing import Any
|
||||
|
||||
import aiohttp
|
||||
import click
|
||||
@@ -46,7 +47,7 @@ class StubService:
|
||||
"""
|
||||
|
||||
logins = 0
|
||||
hooks: dict[str, Callable[["StubService"], None]] = {}
|
||||
hooks: dict[str, Callable[[StubService], None]] = {}
|
||||
|
||||
def __init__(self, beats: Semaphore) -> None:
|
||||
self.beats = beats
|
||||
@@ -187,7 +188,7 @@ def on_loop(server: SimpleNamespace, coroutine: Any) -> Any:
|
||||
return asyncio.run_coroutine_threadsafe(coroutine, server.loop).result(10)
|
||||
|
||||
|
||||
def count(server: SimpleNamespace, method: str, route: str, session_id: Optional[str] = None) -> int:
|
||||
def count(server: SimpleNamespace, method: str, route: str, session_id: str | None = None) -> int:
|
||||
"""The requests the server saw for one route; without a session id, for any session."""
|
||||
if session_id is None:
|
||||
prefix, _, suffix = route.partition("{session_id}")
|
||||
@@ -210,7 +211,7 @@ def example_messages(caplog: pytest.LogCaptureFixture) -> list[str]:
|
||||
|
||||
|
||||
def idle_seconds(entry: Any) -> float:
|
||||
return (datetime.now(timezone.utc) - entry.last_accessed).total_seconds()
|
||||
return (datetime.now(UTC) - entry.last_accessed).total_seconds()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
|
||||
@@ -4,9 +4,10 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from collections.abc import Callable
|
||||
from threading import Event, Thread
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Callable
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import responses
|
||||
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
import ast
|
||||
import functools
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
@@ -193,7 +193,7 @@ def keys(shape: Any) -> set[str]:
|
||||
return set(shape.__required_keys__ | shape.__optional_keys__)
|
||||
|
||||
|
||||
def properties(schema: Optional[dict]) -> set[str]:
|
||||
def properties(schema: dict | None) -> set[str]:
|
||||
return set(
|
||||
((schema or {}).get("content", {}).get("application/json", {}).get("schema", {}) or {}).get("properties", {})
|
||||
)
|
||||
|
||||
@@ -14,7 +14,7 @@ from collections import Counter, defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, NoReturn, Optional
|
||||
from typing import Any, NoReturn
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
@@ -58,7 +58,7 @@ RELEASE = threading.Event()
|
||||
SEEN: list[dict[str, Any]] = []
|
||||
|
||||
|
||||
def raise_fault(kind: Optional[str]) -> NoReturn:
|
||||
def raise_fault(kind: str | None) -> NoReturn:
|
||||
if kind == "api":
|
||||
raise APIError(APIErrorCode.SERVICE_ERROR, "pinned refusal", details={"pinned": True})
|
||||
if kind == "exit":
|
||||
@@ -69,7 +69,7 @@ def raise_fault(kind: Optional[str]) -> NoReturn:
|
||||
class Faulty:
|
||||
"""A stand-in whose methods all raise the fault *kind*; a *late* one first waits for RELEASE."""
|
||||
|
||||
def __init__(self, kind: Optional[str] = None, late: bool = False, **attrs: Any) -> None:
|
||||
def __init__(self, kind: str | None = None, late: bool = False, **attrs: Any) -> None:
|
||||
self.kind = kind
|
||||
self.late = late
|
||||
self.session = SimpleNamespace(headers={}, cookies=[], get=self.fail)
|
||||
@@ -139,11 +139,11 @@ class Case:
|
||||
method: str
|
||||
path: str
|
||||
body: Any = None
|
||||
session: Optional[Faulty] = None
|
||||
session: Faulty | None = None
|
||||
owner: str = KEY
|
||||
status: AuthStatus = AuthStatus.AUTHENTICATED
|
||||
patch: dict[str, Any] = field(default_factory=dict)
|
||||
key: Optional[str] = KEY
|
||||
key: str | None = KEY
|
||||
|
||||
|
||||
def generic_cases() -> dict[str, Case]:
|
||||
@@ -291,7 +291,7 @@ async def open_session(stand_in: Faulty, owner: str, status: AuthStatus) -> None
|
||||
session.served_keys["00" * 16] = ("11" * 16, "pinned-vault")
|
||||
|
||||
|
||||
def masked(value: Any, ref: Optional[str]) -> Any:
|
||||
def masked(value: Any, ref: str | None) -> Any:
|
||||
"""*value* with the error ref and the timestamp replaced, at any depth.
|
||||
|
||||
The longer Python 3.14 text of an unhashable key error reads as the 3.11 text.
|
||||
|
||||
@@ -653,9 +653,10 @@ class _SentCreate(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def sent_create(
|
||||
server_cdm, cdm_name=None, local_cdm=SimpleNamespace(is_playready=False), cdm_entry=False, cdm_map=None
|
||||
):
|
||||
WIDEVINE_CDM = SimpleNamespace(is_playready=False)
|
||||
|
||||
|
||||
def sent_create(server_cdm, cdm_name=None, local_cdm=WIDEVINE_CDM, cdm_entry=False, cdm_map=None):
|
||||
def post(path, data):
|
||||
raise _SentCreate(data)
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import logging
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
import click
|
||||
@@ -121,7 +121,7 @@ def decrypt(
|
||||
ffmpeg: Any,
|
||||
decodes: bool = True,
|
||||
track: Any = "track",
|
||||
flagged: Optional[dict] = None,
|
||||
flagged: dict | None = None,
|
||||
licence: Any = None,
|
||||
) -> list:
|
||||
"""Decrypt a track that holds a licence key, a vault key and a null key; return what reached the server vault."""
|
||||
|
||||
@@ -18,8 +18,9 @@ import asyncio
|
||||
import contextlib
|
||||
import json
|
||||
import threading
|
||||
from collections.abc import Iterator
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Iterator, List
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -42,7 +43,7 @@ class Overlap:
|
||||
def __init__(self, window: float = OVERLAP_WINDOW) -> None:
|
||||
self.window = window
|
||||
self.max_active = 0
|
||||
self.trace: List[str] = []
|
||||
self.trace: list[str] = []
|
||||
self._lock = threading.Lock()
|
||||
self._active = 0
|
||||
self._joined = threading.Event()
|
||||
@@ -86,7 +87,7 @@ class ServiceProbe:
|
||||
self.name = name
|
||||
self.session = SimpleNamespace(headers={}, cookies=[])
|
||||
|
||||
def get_titles(self) -> List[Movie]:
|
||||
def get_titles(self) -> list[Movie]:
|
||||
with self.overlap.call(f"{self.name}:titles"):
|
||||
return [a_movie("movie-0001"), a_movie("movie-0002")]
|
||||
|
||||
@@ -94,7 +95,7 @@ class ServiceProbe:
|
||||
with self.overlap.call(f"{self.name}:tracks:{title.id}"):
|
||||
return empty_tracks()
|
||||
|
||||
def get_chapters(self, title: Any) -> List[Any]:
|
||||
def get_chapters(self, title: Any) -> list[Any]:
|
||||
with self.overlap.call(f"{self.name}:chapters:{title.id}"):
|
||||
return []
|
||||
|
||||
@@ -105,14 +106,14 @@ def seed_titles(session: SessionEntry) -> None:
|
||||
session.title_map[title_id] = a_movie(title_id)
|
||||
|
||||
|
||||
def bodies(responses: List[Any]) -> List[dict]:
|
||||
def bodies(responses: list[Any]) -> list[dict]:
|
||||
parsed = [json.loads(response.body) for response in responses]
|
||||
for body in parsed:
|
||||
assert "error" not in body, body
|
||||
return parsed
|
||||
|
||||
|
||||
async def two_track_calls(session_id: str) -> List[Any]:
|
||||
async def two_track_calls(session_id: str) -> list[Any]:
|
||||
return list(
|
||||
await asyncio.gather(
|
||||
handlers.session_tracks_handler({"title_id": "movie-0001"}, session_id),
|
||||
@@ -151,7 +152,7 @@ async def test_the_track_lock_covers_the_chapters_call() -> None:
|
||||
# Every call closes before the next one opens, so one title's chapters are read before the
|
||||
# other title's tracks are fetched.
|
||||
assert len(overlap.trace) == 8, overlap.trace
|
||||
for opened, closed in zip(overlap.trace[0::2], overlap.trace[1::2]):
|
||||
for opened, closed in zip(overlap.trace[0::2], overlap.trace[1::2], strict=True):
|
||||
assert closed == f"-{opened[1:]}", overlap.trace
|
||||
|
||||
|
||||
@@ -211,7 +212,7 @@ class BlockingTracks:
|
||||
self.loop_was_blocked = not self.resume.wait(timeout=HANDSHAKE_TIMEOUT)
|
||||
return empty_tracks()
|
||||
|
||||
def get_chapters(self, title: Any) -> List[Any]:
|
||||
def get_chapters(self, title: Any) -> list[Any]:
|
||||
return []
|
||||
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import threading
|
||||
import time
|
||||
from datetime import UTC
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
@@ -71,10 +72,10 @@ async def test_delete_returns_false_when_missing(store: SessionStore) -> None:
|
||||
|
||||
|
||||
async def test_cleanup_expired_drops_old_authenticated(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
entry = await store.create("EXAMPLE", _FakeService())
|
||||
entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 100)
|
||||
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
|
||||
removed = await store.cleanup_expired()
|
||||
assert removed == 1
|
||||
assert store.session_count == 0
|
||||
@@ -82,10 +83,10 @@ async def test_cleanup_expired_drops_old_authenticated(store: SessionStore, monk
|
||||
|
||||
async def test_session_with_work_in_progress_does_not_expire(store: SessionStore) -> None:
|
||||
"""A request that holds the lock for longer than the TTL keeps its session and cache directory."""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
entry = await store.create("EXAMPLE", _FakeService(), session_id="busy")
|
||||
entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 100)
|
||||
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
|
||||
async with entry.lock:
|
||||
assert await store.cleanup_expired() == 0
|
||||
assert await store.get("busy") is entry
|
||||
@@ -93,31 +94,31 @@ async def test_session_with_work_in_progress_does_not_expire(store: SessionStore
|
||||
|
||||
async def test_cleanup_expired_keeps_a_login_under_grace(store: SessionStore) -> None:
|
||||
"""A session that still logs in, a prompt included, gets a longer grace period (10 min) than authenticated TTL."""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
entry = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge())
|
||||
entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 1)
|
||||
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 1)
|
||||
removed = await store.cleanup_expired()
|
||||
assert removed == 0
|
||||
assert store.session_count == 1
|
||||
|
||||
|
||||
async def test_get_keeps_a_login_past_the_ttl(store: SessionStore) -> None:
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
entry = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge())
|
||||
entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 1)
|
||||
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 1)
|
||||
assert await store.get(entry.session_id) is entry
|
||||
|
||||
|
||||
async def test_cleanup_expired_drops_a_login_past_grace(store: SessionStore) -> None:
|
||||
"""The auth-state grace is the single AUTH_INPUT_TIMEOUT rule, not a separate magic number."""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT
|
||||
|
||||
entry = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge())
|
||||
entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=AUTH_INPUT_TIMEOUT + 1)
|
||||
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=AUTH_INPUT_TIMEOUT + 1)
|
||||
removed = await store.cleanup_expired()
|
||||
assert removed == 1
|
||||
assert store.session_count == 0
|
||||
@@ -167,13 +168,13 @@ async def test_max_sessions_evicts_the_oldest_session_of_the_key_that_holds_the_
|
||||
|
||||
|
||||
async def test_get_expiry_removes_cache_dir(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
removed: list = []
|
||||
monkeypatch.setattr(SessionStore, "cleanup_cache_dir", staticmethod(removed.append))
|
||||
entry = await store.create("EXAMPLE", _FakeService())
|
||||
entry.cache_tag = "_sessions/k/s/EXAMPLE"
|
||||
entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 100)
|
||||
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
|
||||
assert await store.get(entry.session_id) is None
|
||||
assert removed == ["_sessions/k/s/EXAMPLE"]
|
||||
|
||||
@@ -251,12 +252,12 @@ async def test_eviction_applies_staged_service_reload(store: SessionStore, monke
|
||||
async def test_inline_expiry_applies_staged_service_reload(
|
||||
store: SessionStore, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
applied = _stage_reload(monkeypatch, {"EXAMPLE"})
|
||||
|
||||
entry = await store.create("EXAMPLE", _FakeService())
|
||||
entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 100)
|
||||
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
|
||||
assert await store.get(entry.session_id) is None
|
||||
await asyncio.sleep(0.05)
|
||||
assert applied == [set()]
|
||||
@@ -266,10 +267,10 @@ async def test_cleanup_expired_applies_staged_service_reload_once(
|
||||
store: SessionStore, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A cleanup sweep that drops several sessions on one tag schedules one reload for that tag."""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
applied = _stage_reload(monkeypatch, {"EXAMPLE"})
|
||||
stale = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 100)
|
||||
stale = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
|
||||
for sid in ("a", "b"):
|
||||
(await store.create("EXAMPLE", _FakeService(), session_id=sid)).last_accessed = stale
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user