mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-25 18:35:07 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
645d5756ba | ||
|
|
16c3e42508 | ||
|
|
2284f6a478 | ||
|
|
d6264740fc | ||
|
|
d109fe63eb |
-204
@@ -6,210 +6,6 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
|
||||
|
||||
This changelog is automatically generated using [git-cliff](https://git-cliff.org).
|
||||
|
||||
## [7.0.0] - 2026-11-23
|
||||
|
||||
### Features
|
||||
|
||||
- *drm*: Add in-process cbcs decrypter with an external sample decrypter hook
|
||||
- *remote*: Decrypt service-owned cbcs samples on the server
|
||||
- *music*: Save lyrics beside the audio and keep song fields over remote
|
||||
- *music*: Embed plain lyrics and save timed lyrics from Song.synced_lyrics
|
||||
- *ip-info*: Return timezone and add a required-field filter
|
||||
- *tracks*: [**breaking**] Match a language tag to the variant it means
|
||||
- *api*: Relay services from remote servers with pooled sessions and login prompts
|
||||
- *hybrid*: Generate dolby vision from hdr10+ with --generate-dv
|
||||
- *tracks*: Probe HDR10 tracks for HDR10+ SEI before selection
|
||||
- *tracks*: Probe dv tracks for hdr10+ and list them as DV+HDR10P
|
||||
- *hybrid*: Use a dv track that carries hdr10+ as the hybrid of its resolution
|
||||
- *search*: Add --remote to search through a remote server
|
||||
- *dash*: Flag dv profile 8 tracks from supplementalCodecs and use hdr10+dv as the hybrid
|
||||
- *dl*: Add --local to override a remote: true service config
|
||||
- *dl*: Keep failed track segments across runs in a resume stash
|
||||
- *api*: Apply services.<TAG>.dl as defaults for API download jobs
|
||||
- *api*: Tag each error with a ref and count errors by service
|
||||
- *remote*: Add --local-proxy to send server requests through the client
|
||||
- *api*: [**breaking**] Add a server drain and never answer with a 5xx
|
||||
- *proxy*: Select a vpn server by network or ip with @
|
||||
- *proxy*: Accept an @ selector as a server_map value
|
||||
- *config*: Warn with the lines of a duplicate key in any config load
|
||||
- *proxy*: Try bare --proxy providers in proxy_providers key order
|
||||
- *tracks*: Name unnamed tracks by language and tag subtitle scripts
|
||||
- *tracks*: Add native track names with muxing.track_names
|
||||
- *tracks*: Add muxing.track_names none to leave unnamed tracks unnamed
|
||||
- *tracks*: Add muxing.original_label to mark original-language tracks
|
||||
- *manifests*: Add dts-hd, mpeg-h and lcevc codecs and a manifest corpus
|
||||
- *drm*: Add blowfish stripe cipher and mp3 audio codec
|
||||
- *tracks*: Add Tracks.dedupe and match variant tracks by signature
|
||||
- *tracks*: Add Video.hdr10_base and forward s_lang over remote and REST
|
||||
- *remote*: Reopen a lost remote session and resume at the current title
|
||||
- *kv*: Accept an sqlite vault file path and read plain-tag tables on copy
|
||||
- *naming*: Add codec_names to rename codec and HDR labels in filenames
|
||||
- *remote*: [**breaking**] Let server_cdm outrank a service's cdm entry and set it per service
|
||||
- *naming*: Add audio_contain_all language tag condition
|
||||
- *tracks*: Add a display-only note shown in --list and over --remote
|
||||
- *tracks*: Add subtitle.dedupe_codecs to keep one codec per subtitle variant
|
||||
- *PR*: Add session ID return
|
||||
- *env*: Show tool versions in env check, paths with --verbose
|
||||
- *titles*: Add a sports output and folder template kind
|
||||
- *remote*: Match the server CDM to the client's DRM and read vaults first
|
||||
- *api*: Carry the service catalogue on /api/dashboard/services
|
||||
- *dl*: [**breaking**] Treat a missing -sl language as a warning
|
||||
- *tunnel*: Free finished tunnels at once and wait out 429s on --remote
|
||||
- *tunnel*: Route --local-proxy through a typed --proxy
|
||||
- *hybrid*: Generate Dolby Vision from the decoded video
|
||||
- *mux*: Add muxing.default_subtitle_type for the default subtitle
|
||||
- *dl*: Add -ce/--continuous-episodes to number seasons on
|
||||
- *subtitles*: Add --sub-font and subtitle.ass_style for converted ASS
|
||||
- *tracks*: Download and mux stereoscopic 3D (MV-HEVC) video to MP4
|
||||
- *drm*: License a track only when its own KID has no key
|
||||
- *subtitle*: Read scc closed captions and convert them before muxing
|
||||
- *dl*: Add --skip-missing to skip titles that miss a required language or track
|
||||
- *music*: Pick the song container from the codec in the downloaded file
|
||||
- *tracks*: Support HDR Vivid and Audio Vivid
|
||||
- *mux*: Keep Audio Vivid beside the output and add wide_output listings
|
||||
- *dl*: Let --worst run without -q and pick the lowest bitrate
|
||||
- *serve*: Per-api-key cdm and service config with server-side identity cache
|
||||
- *api*: Expose optional account-scoped title availability
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- *vaults*: Lengthen the whole-file key check and steady its HEVC test
|
||||
- *providers*: Stop metadata lookups sleeping on Retry-After
|
||||
- *cacher*: Resolve cache expiry by unix time
|
||||
- *session*: Cap Retry-After on the requests retry policies
|
||||
- *session*: Log "Retrying" only when a retry follows
|
||||
- *vaults*: Size the HTTP vault connection pool for parallel lookups
|
||||
- *subtitles*: Sort cues by start time when converting from SSA/ASS
|
||||
- *console*: Count spacing combining marks as one cell
|
||||
- *import*: Add decrypts_samples to ImportService
|
||||
- *vaults*: Stop querying sibling KIDs and skip unavailable vaults
|
||||
- *vaults*: Back off longer on 429 and shorten the skip messages
|
||||
- *proxy*: Keep service traffic on --proxy and warn about requests that bypass it
|
||||
- *proxy*: Do not warn about requests to a configured remote CDM
|
||||
- *remote*: Retry once on a proxy 502/503/504 page and keep server errors from ending a relicense
|
||||
- *tracks*: Annotate the hdr10+ probe plans list for strict mypy
|
||||
- *tracks*: Match probed hdr10p tracks on remote and hint dv+hdr10p on -r HDR10P
|
||||
- *proton*: Update query parsing and server selection logic for improved accuracy
|
||||
- *services*: Route a service remote from services.<TAG>.dl.remote
|
||||
- *api*: Parse client cookies with the dl cookie parser
|
||||
- *api*: Refuse peer cache files that name types other than datetime
|
||||
- *api*: Validate quality and bitrate params like dl and pass cdm_only to services
|
||||
- *api*: Split global speed limit across job workers
|
||||
- *hls*: Keep PlayReady session-data keys by matching the URN string
|
||||
- *import*: Take a missing title language from the exported tracks
|
||||
- *remote*: Send the typed --proxy to the server when it resolved to loopback
|
||||
- *api*: [**breaking**] Send service and DRM errors as 422, not 502
|
||||
- *tracks*: Keep a locked segment file from hiding the download error
|
||||
- *proxy*: Name the reason when the Control D forwarder answers 502
|
||||
- *cfg*: Give the lines of each duplicate config key instead of crashing
|
||||
- *cfg*: Show only the duplicate-key warning, once
|
||||
- *remote*: Keep each session cookie's domain, path and secure flag
|
||||
- *vaults*: Stop false bad-key flags from a failed decode check
|
||||
- *drm*: Load a bare PlayReady WRMHEADER from DASH, HLS and ISM manifests
|
||||
- *vaults*: Copy no vault key from a clear track
|
||||
- *tracks*: Flag every encrypted sample entry type after decrypt
|
||||
- *downloader*: Report spent segment retries in one line without the URL
|
||||
- *core*: Cut user-facing errors and warnings to one line
|
||||
- *mux*: Address embedded audio by the file's real mkvmerge track IDs
|
||||
- *sample*: Stop a malformed sidx from hanging the download
|
||||
- *console*: Count a virama conjunct as one cell
|
||||
- *dash*: Treat a caption subtitle also marked SDH as SDH
|
||||
- *services*: Ignore tracked bytecode in the service-repo dirty check
|
||||
- *services*: Clear service-repo bytecode with git pathspecs before a pull
|
||||
- *proxy*: Match a reloaded service class by name and dedup warnings per run
|
||||
- *cacher*: Treat an expiry within 1 µs of now as expired
|
||||
- *tunnel*: Accept fake-ip dns answers for --local-proxy host names
|
||||
- *subtitle*: Rebase live-clock dash webvtt cues by presentationTimeOffset
|
||||
- *tracks*: Read sidx boxes with struct so concurrent tracks parse correctly
|
||||
- *mp4*: Serialize pymp4 parses of bit-field boxes across threads
|
||||
- *dash*: End segmentbase media range at the last byte of the file
|
||||
- *tunnel*: Block local networks instead of allowing public ones for --local-proxy
|
||||
- *manifests*: Keep service drm, rebase carried vtt cues, ship single-track mpds
|
||||
- *api*: Cache the health update check and fix a remote-session test fixture
|
||||
- *tunnel*: Refuse 192.0.0.0/24 and 6to4 literals on python before 3.11.10
|
||||
- *api*: Show filename codec and range labels in codec_display and range_display
|
||||
- *api*: Stop a service's sys.exit from killing the serve process
|
||||
- *titles*: Compare dub languages under their macrolanguage
|
||||
- *subtitles*: Accept TTML2 rw/rh and vw/vh sizes in fTTML conversion
|
||||
- *tracks*: Keep HDR colour metadata when muxing VP9
|
||||
- *naming*: Tag HDR10+ from the track range when MediaInfo misses it
|
||||
- *manifests*: Decode audio channels by scheme in dash, hls and ism
|
||||
- *subtitle*: Remove the DASH presentationTimeOffset from stpp and wvtt cues
|
||||
- *subtitle*: Place fragment-relative ISM TTML cues on the track timeline
|
||||
- *tracks*: Retry ccextractor on the repackaged file
|
||||
- *dl*: Take turns on licence requests so one licence serves every track
|
||||
- *subtitle*: Join cues that a segment boundary splits in stpp and wvtt
|
||||
- *titles*: Name a PQ video track without HDR10 metadata HDR
|
||||
- *titles*: Name a dv profile 7 or 8 track with an unnamed pq base DV.HDR
|
||||
- *session*: Keep cookie paths so same-name cookies stay on their own path
|
||||
- *remote*: Send a service's filtered dash periods so the client skips them too
|
||||
- *music*: Stop reading a kb/s bitrate as a hi-res sample rate
|
||||
- *api*: Keep a pooled remote session to the api key that opened it
|
||||
- *api*: Refuse a non-public proxy host for a key without server_proxy
|
||||
- *api*: Skip the local geoblock for a relayed tag not installed here
|
||||
- *api*: Check and cast download job service options like a session does
|
||||
- *dl*: Read the drm's content keys again after a relicence replaces them
|
||||
- *subtitle*: Convert wvtt cue times by the media timescale
|
||||
- *drm*: Keep the monalisa ciphertext when the decrypt tool fails
|
||||
- *drm*: Retry a licence call only for an argument the service rejects
|
||||
- *binaries*: Kill the whole process tree when a version probe times out
|
||||
- *manifests*: Match dash representations across periods by shape, not id
|
||||
- *api*: Cast download job options with the dl click types
|
||||
- *manifests*: Skip filtered dash periods after the main content and keep them over export
|
||||
- *import*: Keep only exported dash content periods on a re-fetch
|
||||
- Drop null vault keys, cap snapshot restore size, isolate test globals
|
||||
- *api*: [**breaking**] Key the health route and keep server internals from user keys
|
||||
- *attachment*: Download through the track downloader with its retries
|
||||
- *binaries*: Report a version for git ffmpeg builds
|
||||
- *drm*: Key PIFF-first tracks by track ID and trust shaka's exit code
|
||||
- *install*: Check out batch files with CRLF line endings
|
||||
- *drm*: Read PlayReady KIDs through the PlayReady class when converting to Widevine
|
||||
- *fonts*: Find per-user Windows fonts by their family name
|
||||
- *mux*: Strip encoding dates from MP4Box and shaka-packager output
|
||||
- *remote*: Keep vault keys when a relayed licence is refused
|
||||
- *remote*: Report each handled remote error once, from the code that catches it
|
||||
- *mux*: Pass the exact frame rate to mkvmerge default duration
|
||||
- *mux*: Repoint sample entries with a missing data reference for MP4Box
|
||||
- *tracks*: Rank video picks by quality across regional tags and in hybrid
|
||||
- *mux*: Mux H.266 as VVC and leave Audio Vivid decoding to services
|
||||
- *api*: Convert quality to heights for remote sessions
|
||||
- *manifests*: Rebase restarting timelines across dash periods and hls discontinuities
|
||||
- *downloader*: Outlast network outages and harden segment merges
|
||||
- *chapters*: Drop duplicate timestamps in the EXAMPLE template and docs
|
||||
- *api*: Refuse deeply nested cache payloads by depth, not RecursionError
|
||||
|
||||
### Documentation
|
||||
|
||||
- *dev*: Align self.config description with the merge in dl
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
- *proxy*: Test the remote CDM hosts only after the walk finds service code
|
||||
- *dash*: Collapse single-file tracks that have a sidx gap
|
||||
- *api*: Stop rebuilding proxy catalogues, vaults and cdms per request
|
||||
- *api*: [**breaking**] Cut per-request and per-tick event bus traffic
|
||||
- *api*: Move blocking file and hash work off the event loop
|
||||
- *proxies*: Cache expressvpn and proton catalogues across requests
|
||||
- Lazy-load services and proxy catalogues, faster namespace strip
|
||||
|
||||
### Changes
|
||||
|
||||
- *config*: Log the duplicate-key warning without the python warning prefix
|
||||
- *remote*: [**breaking**] Send service options only in service_params
|
||||
- *types*: Bring mypy to zero errors across unshackle
|
||||
- *dl*: Share the cache, vault and key-label steps in prepare_drm
|
||||
- *tracks*: Name and match resolutions by one standard-height rule
|
||||
- *api*: Register each route once and merge duplicated handler code
|
||||
- *api*: Tidy leftovers from the api perf pass
|
||||
- *api*: Simplify leftovers from the perf pass
|
||||
- *drm*: Resolve content keys in one licence path behind ServerKeySource
|
||||
- *drm*: Share one CENC decrypt path across Widevine, PlayReady and ClearKey
|
||||
- *tracks*: Simplify the dynamic HDR probe and read less for TS audio
|
||||
|
||||
### Builds
|
||||
|
||||
- Keep dot-folders out of the sdist
|
||||
|
||||
## [6.0.0] - 2026-10-13
|
||||
|
||||
### Features
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "unshackle"
|
||||
version = "7.0.0"
|
||||
version = "6.0.0"
|
||||
description = "Modular Movie, TV, and Music Archival Software."
|
||||
authors = [{ name = "unshackle team" }]
|
||||
requires-python = ">=3.11,<3.15"
|
||||
|
||||
+22
-43
@@ -43,7 +43,7 @@ from shutil import rmtree
|
||||
from typing import Any, Optional
|
||||
|
||||
import click
|
||||
import fault_server # local sibling (scripts/): fault-injection server + payload verifier
|
||||
import fault_server
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
|
||||
@@ -51,13 +51,11 @@ from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED
|
||||
from unshackle.core.downloaders.requests import requests as download_batch
|
||||
|
||||
# the downloaders package re-exports the requests() function, shadowing the submodule
|
||||
# attribute. import_module returns the real module so --fast-timeouts can patch its globals
|
||||
dl_mod = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
|
||||
MIB = 1024 * 1024
|
||||
TAIL_FRACTION = 0.25 # last quarter of segments (by completion order)
|
||||
TAIL_SLOW_KIB = 256 # crawl rate forced onto --fault-tail-slow segments
|
||||
TAIL_FRACTION = 0.25
|
||||
TAIL_SLOW_KIB = 256
|
||||
SLOW_CONN_KIB = 2048
|
||||
console = Console()
|
||||
|
||||
@@ -67,7 +65,7 @@ class SegmentServer(socketserver.ThreadingTCPServer):
|
||||
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
request_queue_size = 128 # default 5 drops SYNs at >5 concurrent connects -> phantom 1s retransmit tail
|
||||
request_queue_size = 128
|
||||
|
||||
def __init__(
|
||||
self, buffer: bytes, latency_ms: int, rate_kib: int, faults: dict[str, int], total_segments: int
|
||||
@@ -77,10 +75,10 @@ class SegmentServer(socketserver.ThreadingTCPServer):
|
||||
self.rate_kib = rate_kib
|
||||
self.faults = faults
|
||||
self.total_segments = total_segments
|
||||
self.attempts: dict[int, int] = {} # per-segment GET count, drives first-attempt faults
|
||||
self.attempts: dict[int, int] = {}
|
||||
self.connections = 0
|
||||
self.lock = threading.Lock()
|
||||
self.stall_event = threading.Event() # set at teardown to release stalled handlers
|
||||
self.stall_event = threading.Event()
|
||||
super().__init__(("127.0.0.1", 0), SegmentHandler)
|
||||
|
||||
def reset(self) -> None:
|
||||
@@ -88,14 +86,14 @@ class SegmentServer(socketserver.ThreadingTCPServer):
|
||||
self.attempts.clear()
|
||||
self.connections = 0
|
||||
|
||||
def handle_error(self, request: Any, client_address: Any) -> None: # silence expected fault noise
|
||||
def handle_error(self, request: Any, client_address: Any) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class SegmentHandler(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, *_: Any) -> None: # silence per-request logging
|
||||
def log_message(self, *_: Any) -> None:
|
||||
pass
|
||||
|
||||
def setup(self) -> None:
|
||||
@@ -130,13 +128,13 @@ class SegmentHandler(http.server.BaseHTTPRequestHandler):
|
||||
attempt = server.attempts[idx]
|
||||
|
||||
f = server.faults
|
||||
if idx < f["stall"]: # permanent: stalls on every attempt, never completes
|
||||
if idx < f["stall"]:
|
||||
self._serve(stall=True)
|
||||
return
|
||||
if attempt == 1 and idx < f["reset"]: # first attempt only: RST mid-body, retry succeeds
|
||||
if attempt == 1 and idx < f["reset"]:
|
||||
self._serve(reset=True)
|
||||
return
|
||||
if attempt == 1 and idx < f["http503"]: # first attempt only: 503, retry succeeds
|
||||
if attempt == 1 and idx < f["http503"]:
|
||||
self.send_response(503)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
@@ -145,7 +143,6 @@ class SegmentHandler(http.server.BaseHTTPRequestHandler):
|
||||
rate = server.rate_kib
|
||||
if f["tail_slow"] and idx >= server.total_segments - f["tail_slow"]:
|
||||
rate = TAIL_SLOW_KIB
|
||||
# first attempt only: models a bad CDN connection, so a hedge racer gets full speed
|
||||
if f["tail_slow_once"] and attempt == 1 and idx >= server.total_segments - f["tail_slow_once"]:
|
||||
rate = TAIL_SLOW_KIB
|
||||
if self.slow_conn:
|
||||
@@ -156,7 +153,7 @@ class SegmentHandler(http.server.BaseHTTPRequestHandler):
|
||||
server: SegmentServer = self.server # type: ignore[assignment]
|
||||
full = server.buffer
|
||||
rng = self._parse_range(len(full))
|
||||
if rng is not None and rng[0] >= len(full): # unsatisfiable resume: a real CDN answers 416
|
||||
if rng is not None and rng[0] >= len(full):
|
||||
self.send_response(416)
|
||||
self.send_header("Content-Range", f"bytes */{len(full)}")
|
||||
self.send_header("Content-Length", "0")
|
||||
@@ -176,19 +173,17 @@ class SegmentHandler(http.server.BaseHTTPRequestHandler):
|
||||
self.send_header("Content-Type", "application/octet-stream")
|
||||
self.end_headers()
|
||||
|
||||
if server.latency_ms: # delay before first byte
|
||||
if server.latency_ms:
|
||||
time.sleep(server.latency_ms / 1000)
|
||||
try:
|
||||
if stall: # serve only up to a fixed midpoint, then hold forever
|
||||
# capped at an absolute byte so Range-resume never advances past it, a true
|
||||
# unrecoverable hang (unlike "half of remaining", which resume would converge)
|
||||
if stall:
|
||||
stall_point = len(full) // 2
|
||||
chunk = full[start:stall_point]
|
||||
if chunk:
|
||||
self.wfile.write(chunk)
|
||||
self.wfile.flush()
|
||||
server.stall_event.wait(120)
|
||||
elif reset: # send half, then abort the TCP connection (RST via SO_LINGER=0)
|
||||
elif reset:
|
||||
half = max(1, len(body) // 2)
|
||||
self.wfile.write(body[:half])
|
||||
self.wfile.flush()
|
||||
@@ -205,7 +200,6 @@ class SegmentHandler(http.server.BaseHTTPRequestHandler):
|
||||
if rate_kib <= 0:
|
||||
self.wfile.write(body)
|
||||
return
|
||||
# throttle: fixed-size chunks paced to rate_kib KiB/s
|
||||
chunk = 64 * 1024
|
||||
per_chunk = chunk / (rate_kib * 1024)
|
||||
for off in range(0, len(body), chunk):
|
||||
@@ -232,7 +226,6 @@ def run_batch(
|
||||
filename="seg_{i}.bin",
|
||||
max_workers=workers,
|
||||
session=session,
|
||||
# only pass when set so the script also runs against checkouts without the flag
|
||||
**({"adaptive": True} if adaptive else {}),
|
||||
**({"processes": procs} if procs > 1 else {}),
|
||||
):
|
||||
@@ -242,17 +235,12 @@ def run_batch(
|
||||
err = exc
|
||||
wall = time.perf_counter() - start
|
||||
if err is not None:
|
||||
# a failed batch shuts down without waiting, so a leaked racer may sit in one last
|
||||
# blocked read (<= READ_TIMEOUT) holding its .!dev handle. merge never sweeps after
|
||||
# a failure; what races the leak is the cleanup that runs once the error propagates,
|
||||
# so drain before measuring. a handle still held past the deadline is a real leak.
|
||||
deadline = time.monotonic() + dl_mod.READ_TIMEOUT + dl_mod.RETRY_WAIT + 2
|
||||
while time.monotonic() < deadline and (
|
||||
any(t.name.startswith("ThreadPoolExecutor") for t in threading.enumerate())
|
||||
or multiprocessing.active_children()
|
||||
):
|
||||
time.sleep(0.1)
|
||||
# on success this is the exact moment merge would sweep
|
||||
strays, locked = sweep_strays(out_dir)
|
||||
pool_threads = sum(1 for t in threading.enumerate() if t.name.startswith("ThreadPoolExecutor"))
|
||||
return wall, completions, err, strays, locked, pool_threads
|
||||
@@ -305,7 +293,7 @@ def sweep_strays(out_dir: Path) -> tuple[int, int]:
|
||||
for s in strays:
|
||||
try:
|
||||
s.unlink()
|
||||
except OSError: # PermissionError on Windows: the real-world crash
|
||||
except OSError:
|
||||
locked += 1
|
||||
return len(strays), locked
|
||||
|
||||
@@ -322,8 +310,6 @@ def tail_droop(completions: list[float], wall: float) -> tuple[int, float, float
|
||||
return bucket, tail_time, tail_time / wall * 100
|
||||
|
||||
|
||||
# per worker-count: workers, median_s, MB/s, tail_bucket, tail_seconds, tail_pct, missing_idxs, raised,
|
||||
# then worst-across-runs sweep safety: strays, locked handles, live pool threads at completion
|
||||
Row = tuple[int, float, float, int, float, float, list[int], bool, int, int, int]
|
||||
|
||||
|
||||
@@ -353,10 +339,9 @@ def sweep(
|
||||
)
|
||||
rmtree(out_dir, ignore_errors=True)
|
||||
median_s = statistics.median(s[0] for s in samples)
|
||||
best = min(samples, key=lambda s: abs(s[0] - median_s)) # representative run near the median
|
||||
best = min(samples, key=lambda s: abs(s[0] - median_s))
|
||||
bucket, tail_s, tail_pct = tail_droop(best[1], best[0])
|
||||
mbps = best[2] / best[0] if best[0] else 0.0
|
||||
# sweep safety reports the WORST run: one locked handle in any run is the bug
|
||||
rows.append(
|
||||
(
|
||||
w,
|
||||
@@ -425,9 +410,6 @@ def fault_integrity(out_dir: Path, segments: int, seg_size: int) -> tuple[list[i
|
||||
return missing, corrupt
|
||||
|
||||
|
||||
# per worker-count under a fault profile: workers, median_s, MB/s, missing, corrupt, raised,
|
||||
# requests seen, amplification (requests/segments), retries (requests-segments), status_counts,
|
||||
# then worst-across-runs sweep safety: strays, locked handles, live pool threads
|
||||
FaultRow = tuple[int, float, float, list[int], list[int], bool, int, float, int, dict[int, int], int, int, int]
|
||||
|
||||
|
||||
@@ -541,7 +523,7 @@ def run_fault_mode(
|
||||
)
|
||||
rmtree(out_dir, ignore_errors=True)
|
||||
median_s = statistics.median(s[0] for s in samples)
|
||||
best = min(samples, key=lambda s: abs(s[0] - median_s)) # representative run near the median
|
||||
best = min(samples, key=lambda s: abs(s[0] - median_s))
|
||||
mbps = best[1] / best[0] if best[0] else 0.0
|
||||
requests_seen = best[5]
|
||||
amp = requests_seen / segments if segments else 0.0
|
||||
@@ -564,7 +546,7 @@ def run_fault_mode(
|
||||
)
|
||||
)
|
||||
finally:
|
||||
server.stall_event.set() # release any stalled handler threads before shutdown
|
||||
server.stall_event.set()
|
||||
server.shutdown()
|
||||
|
||||
print_fault_report(rows, runs, segments, profile_name)
|
||||
@@ -673,16 +655,15 @@ def main(
|
||||
saved: dict[str, Any] = {}
|
||||
saved_network: Optional[dict] = None
|
||||
total = segments
|
||||
expected_bytes: Optional[bytes] = None # synthetic reference buffer; None in real-URL mode
|
||||
expected_bytes: Optional[bytes] = None
|
||||
|
||||
if fast_timeouts: # bench-only: patched globals are read at call time inside download()
|
||||
if fast_timeouts:
|
||||
fast = {"READ_TIMEOUT": 2, "RETRY_WAIT": 1, "HEDGE_MIN_WAIT": 1.0}
|
||||
saved = {k: getattr(dl_mod, k) for k in fast}
|
||||
for k, v in fast.items():
|
||||
setattr(dl_mod, k, v)
|
||||
saved_network = config.network
|
||||
config.network = {**config.network, "read_timeout": fast["READ_TIMEOUT"]}
|
||||
# --procs children are spawned fresh and would otherwise keep the real timeouts
|
||||
os.environ["UNSHACKLE_DL_TIMING_OVERRIDES"] = ",".join(f"{k}={v}" for k, v in fast.items())
|
||||
|
||||
if part_size_mib and hasattr(dl_mod, "RANGE_PARALLEL_PART_SIZE"):
|
||||
@@ -720,8 +701,6 @@ def main(
|
||||
_procs_notice(procs, len(urls), session)
|
||||
console.print(f"[cyan]URL-file mode:[/] {len(urls)} URLs, impersonate={impersonate or 'none'}")
|
||||
else:
|
||||
# deterministic shared buffer; generated once, served for every segment, and
|
||||
# reused as the reference for byte-exact completeness verification
|
||||
buffer = (b"unshackle-bench-" * (seg_size // 16 + 1))[:seg_size]
|
||||
expected_bytes = buffer
|
||||
server = SegmentServer(buffer, latency_ms, rate_kib, faults, segments)
|
||||
@@ -748,7 +727,7 @@ def main(
|
||||
raise SystemExit(130) from None
|
||||
finally:
|
||||
if server is not None:
|
||||
server.stall_event.set() # release any stalled handler threads
|
||||
server.stall_event.set()
|
||||
server.shutdown()
|
||||
for k, v in saved.items():
|
||||
setattr(dl_mod, k, v)
|
||||
|
||||
+31
-43
@@ -66,44 +66,35 @@ class FaultProfile:
|
||||
"""A named set of deterministic response faults. Presets live in ``PROFILES``."""
|
||||
|
||||
name: str
|
||||
stall_pct: float = 0.0 # % of (path, attempt)s that stall mid-body
|
||||
stall_secs: float = 3.0 # seconds to hold when a stall fires
|
||||
reset_pct: float = 0.0 # % of (path, attempt)s that RST mid-body
|
||||
rate_limit: bool = False # 429 + Retry-After during closed windows
|
||||
retry_after: int = 1 # Retry-After seconds advertised on a 429
|
||||
window_open: float = 5.0 # seconds serving normally before a throttle window
|
||||
window_closed: float = 5.0 # seconds replying 429 during a throttle window
|
||||
body_rate_kib: int = 0 # throttle every segment body to this KiB/s (0 = unthrottled)
|
||||
tail_slow: int = 0 # throttle the last K segments' bodies
|
||||
tail_rate_kib: int = 256 # throttle rate for tail-slow segments (KiB/s)
|
||||
flaky_first: bool = False # fail attempt 1 per path, succeed after
|
||||
flaky_status: int = 503 # status returned by a flaky-first failure
|
||||
cut_secs: float = 0.0 # close the body cleanly (FIN) after this long (0 = never)
|
||||
cut_bytes: int = 0 # close the body cleanly (FIN) after this many bytes (0 = never)
|
||||
deny: bool = False # reply deny_status to every request past deny_after
|
||||
deny_status: int = 403 # status returned by a deny
|
||||
deny_after: int = 0 # serve this many attempts per path before denying (0 = deny all)
|
||||
stall_pct: float = 0.0
|
||||
stall_secs: float = 3.0
|
||||
reset_pct: float = 0.0
|
||||
rate_limit: bool = False
|
||||
retry_after: int = 1
|
||||
window_open: float = 5.0
|
||||
window_closed: float = 5.0
|
||||
body_rate_kib: int = 0
|
||||
tail_slow: int = 0
|
||||
tail_rate_kib: int = 256
|
||||
flaky_first: bool = False
|
||||
flaky_status: int = 503
|
||||
cut_secs: float = 0.0
|
||||
cut_bytes: int = 0
|
||||
deny: bool = False
|
||||
deny_status: int = 403
|
||||
deny_after: int = 0
|
||||
|
||||
|
||||
PROFILES: dict[str, FaultProfile] = {
|
||||
"loopback": FaultProfile("loopback"),
|
||||
"stall": FaultProfile("stall", stall_pct=25.0, stall_secs=3.0),
|
||||
"reset": FaultProfile("reset", reset_pct=25.0),
|
||||
# short windows + a body throttle so a fast loopback batch actually spans several throttle
|
||||
# windows and trips the 429 + Retry-After retry path (a real 900 MB/s batch would otherwise
|
||||
# finish inside the first open window). Standalone use can widen the windows via overrides.
|
||||
"rate-limit": FaultProfile(
|
||||
"rate-limit", rate_limit=True, retry_after=1, window_open=1.0, window_closed=1.0, body_rate_kib=2048
|
||||
),
|
||||
"tail-slow": FaultProfile("tail-slow", tail_slow=4, tail_rate_kib=256),
|
||||
"flaky-first": FaultProfile("flaky-first", flaky_first=True, flaky_status=503),
|
||||
# a CDN that throttles one flow and drops it on a timer: every connection delivers bytes
|
||||
# and then ends short, so each retry makes progress but no single attempt finishes. Not
|
||||
# seed-gated like stall and reset, because the real host cuts every attempt, not a share.
|
||||
"throttle-cut": FaultProfile("throttle-cut", body_rate_kib=480, cut_secs=6.5, cut_bytes=5 * MIB // 2),
|
||||
# a permanently refused resource (expired token, geo block): no retry and no fallback
|
||||
# recovers, so a client that keeps trying is burning attempts for nothing. --deny-after
|
||||
# serves the first N attempts per path, which lets a range probe through first.
|
||||
"deny": FaultProfile("deny", deny=True),
|
||||
}
|
||||
|
||||
@@ -118,7 +109,7 @@ class FaultServer(ThreadingHTTPServer):
|
||||
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
request_queue_size = 128 # default 5 drops SYNs past 5 concurrent connects -> phantom 1s retransmit tail
|
||||
request_queue_size = 128
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -133,27 +124,25 @@ class FaultServer(ThreadingHTTPServer):
|
||||
self.seg_size = seg_size
|
||||
self.total_segments = total_segments
|
||||
self.seed = seed
|
||||
self.stall_event = threading.Event() # set at teardown to release stalled handlers
|
||||
self.stall_event = threading.Event()
|
||||
self._lock = threading.Lock()
|
||||
self._request_count = 0
|
||||
self._status_counts: dict[int, int] = {}
|
||||
self._attempts: dict[str, int] = {}
|
||||
self._window_origin = time.monotonic()
|
||||
# precompute the known segment bodies so serving is a dict lookup (no per-request
|
||||
# generation), making the loopback profile a true python-overhead ceiling
|
||||
self._payloads: dict[str, bytes] = {
|
||||
f"/seg/{i}": segment_payload(f"/seg/{i}", seg_size) for i in range(total_segments)
|
||||
}
|
||||
super().__init__((host, port), FaultHandler)
|
||||
|
||||
def handle_error(self, request: Any, client_address: Any) -> None: # silence expected fault noise
|
||||
def handle_error(self, request: Any, client_address: Any) -> None:
|
||||
pass
|
||||
|
||||
def payload(self, path: str) -> bytes:
|
||||
cached = self._payloads.get(path)
|
||||
if cached is not None:
|
||||
return cached
|
||||
with self._lock: # unknown path (standalone use): generate + cache once
|
||||
with self._lock:
|
||||
body = self._payloads.get(path)
|
||||
if body is None:
|
||||
body = segment_payload(path, self.seg_size)
|
||||
@@ -194,7 +183,7 @@ class FaultServer(ThreadingHTTPServer):
|
||||
self._request_count = 0
|
||||
self._status_counts.clear()
|
||||
self._attempts.clear()
|
||||
self._window_origin = time.monotonic() # realign throttle windows to this run's start
|
||||
self._window_origin = time.monotonic()
|
||||
|
||||
def stats(self) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
@@ -209,7 +198,7 @@ class FaultServer(ThreadingHTTPServer):
|
||||
class FaultHandler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, *_: Any) -> None: # silence per-request logging
|
||||
def log_message(self, *_: Any) -> None:
|
||||
pass
|
||||
|
||||
def _parse_range(self, total: int) -> Optional[tuple[int, int]]:
|
||||
@@ -217,11 +206,11 @@ class FaultHandler(BaseHTTPRequestHandler):
|
||||
if not header or not header.startswith("bytes="):
|
||||
return None
|
||||
start_s, _, end_s = header[len("bytes=") :].partition("-")
|
||||
if not start_s: # RFC 7233 suffix range: bytes=-N means the last N bytes
|
||||
if not start_s:
|
||||
return max(0, total - int(end_s)), total - 1
|
||||
start = int(start_s)
|
||||
end = int(end_s) if end_s else total - 1
|
||||
if start > end: # inverted range: report unsatisfiable so _serve answers 416
|
||||
if start > end:
|
||||
return total, total - 1
|
||||
return start, min(end, total - 1)
|
||||
|
||||
@@ -243,10 +232,10 @@ class FaultHandler(BaseHTTPRequestHandler):
|
||||
if prof.deny and attempt > prof.deny_after:
|
||||
self._send_status(prof.deny_status)
|
||||
return
|
||||
if prof.flaky_first and attempt == 1: # first attempt per path always fails, retry recovers
|
||||
if prof.flaky_first and attempt == 1:
|
||||
self._send_status(prof.flaky_status)
|
||||
return
|
||||
if prof.rate_limit and server.in_throttle_window(): # recurring throttle window
|
||||
if prof.rate_limit and server.in_throttle_window():
|
||||
self._send_429(prof.retry_after)
|
||||
return
|
||||
|
||||
@@ -290,7 +279,7 @@ class FaultHandler(BaseHTTPRequestHandler):
|
||||
) -> None:
|
||||
server: FaultServer = self.server # type: ignore[assignment]
|
||||
rng = self._parse_range(len(full))
|
||||
if rng is not None and rng[0] >= len(full): # unsatisfiable resume: a real CDN answers 416
|
||||
if rng is not None and rng[0] >= len(full):
|
||||
server.note_status(416)
|
||||
self.send_response(416)
|
||||
self.send_header("Content-Range", f"bytes */{len(full)}")
|
||||
@@ -313,7 +302,7 @@ class FaultHandler(BaseHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
|
||||
try:
|
||||
if reset: # send half, then abort the TCP connection (RST via SO_LINGER=0)
|
||||
if reset:
|
||||
half = max(1, len(body) // 2)
|
||||
self.wfile.write(body[:half])
|
||||
self.wfile.flush()
|
||||
@@ -321,7 +310,7 @@ class FaultHandler(BaseHTTPRequestHandler):
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
|
||||
sock.close()
|
||||
self.close_connection = True
|
||||
elif stall: # send half, hold (a client READ_TIMEOUT shorter than stall_secs will retry), then finish
|
||||
elif stall:
|
||||
half = max(1, len(body) // 2)
|
||||
self.wfile.write(body[:half])
|
||||
self.wfile.flush()
|
||||
@@ -351,7 +340,7 @@ class FaultHandler(BaseHTTPRequestHandler):
|
||||
if rate_kib <= 0 and cut_secs <= 0 and cut_bytes <= 0:
|
||||
self.wfile.write(body)
|
||||
return
|
||||
chunk = 64 * 1024 # throttle: fixed-size chunks paced to rate_kib KiB/s
|
||||
chunk = 64 * 1024
|
||||
per_chunk = chunk / (rate_kib * 1024) if rate_kib > 0 else 0.0
|
||||
deadline = time.monotonic() + cut_secs if cut_secs > 0 else None
|
||||
sent = 0
|
||||
@@ -390,7 +379,6 @@ def _build_arg_parser() -> argparse.ArgumentParser:
|
||||
p.add_argument("--segments", type=int, default=32, help="Number of /seg/i payloads to precompute.")
|
||||
p.add_argument("--seg-size", type=int, default=2 * MIB, help="Bytes per segment payload.")
|
||||
p.add_argument("--seed", type=int, default=DEFAULT_SEED, help="Fault RNG seed (printed for reproducibility).")
|
||||
# profile knobs (override the chosen preset when given)
|
||||
p.add_argument("--stall-pct", type=float, help="Override: %% of (path, attempt)s that stall.")
|
||||
p.add_argument("--stall-secs", type=float, help="Override: seconds a stall holds.")
|
||||
p.add_argument("--reset-pct", type=float, help="Override: %% of (path, attempt)s that RST.")
|
||||
|
||||
@@ -45,7 +45,6 @@ MAX_BYTES = 500_000
|
||||
DEADLINE = 60
|
||||
EXTENSIONS = {"dash": "mpd", "hls": "m3u8", "ism": "ism.xml"}
|
||||
|
||||
# url -> reason; manifests the parsers do not support yet, left out until a live service needs them
|
||||
EXCLUDED: dict[str, str] = {
|
||||
"https://playertest.longtailvideo.com/adaptive/vod-with-mp3/manifest.m3u8": "the same variant listed twice gives a duplicate track ID",
|
||||
"https://raw.githubusercontent.com/MPEGGroup/DASHSchema/6th-Ed/example_G29-2.mpd": "spec example fragment with no playable Representation",
|
||||
@@ -71,7 +70,6 @@ def dashif_streams() -> list[Stream]:
|
||||
expect = None
|
||||
if vector.get("mpd_type") == "static" and vector.get("num_periods") == 1:
|
||||
expect = {k: vector.get(k) for k in ("max_num_video", "max_num_audio", "video_codec", "audio_codec")}
|
||||
# the vector names are only "Test Vector N", the URL path says what the vector covers
|
||||
name = "/".join(urlparse(vector["url"]).path.split("/")[-3:]).removesuffix(".mpd")
|
||||
streams.append(("dashif", name, vector["url"], expect))
|
||||
return streams
|
||||
@@ -169,7 +167,6 @@ def fetch(stream: Stream) -> Optional[dict[str, Any]]:
|
||||
return None
|
||||
file = file_name(source, name, url, kind)
|
||||
(OUT / file).write_bytes(body)
|
||||
# a redirect moves the base that relative segment URLs resolve against
|
||||
entry: dict[str, Any] = {"file": file, "kind": kind, "source": source, "name": name, "url": final_url}
|
||||
if expect and kind == "dash":
|
||||
entry["expect"] = expect
|
||||
|
||||
@@ -31,8 +31,6 @@ from unshackle.core.manifests import DASH, HLS, ISM
|
||||
from unshackle.core.tracks.track import DownloadContext
|
||||
from unshackle.core.utilities import close_debug_logger, init_debug_logger
|
||||
|
||||
# (format label, parser, CDN label, manifest URL); tears-of-steel is the same asset in
|
||||
# all three formats on Unified Streaming, so the formats are comparable on one CDN.
|
||||
STREAMS: list[tuple[str, Any, str, str]] = [
|
||||
("HLS", HLS, "mux", "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8"),
|
||||
(
|
||||
@@ -70,7 +68,6 @@ STREAMS: list[tuple[str, Any, str, str]] = [
|
||||
"dtaps",
|
||||
"https://playready.directtaps.net/smoothstreaming/SSWSS720H264/SuperSpeedway_720.ism/Manifest",
|
||||
),
|
||||
# public 4K / HDR / Dolby-Vision tier: large high-bitrate tracks, no auth
|
||||
("DASH", DASH, "uhd-hevc", "https://dash.akamaized.net/dash264/TestCasesUHD/2b/11/MultiRate.mpd"),
|
||||
("HLS", HLS, "dv-atmos", "https://devstreaming-cdn.apple.com/videos/streaming/examples/adv_dv_atmos/main.m3u8"),
|
||||
(
|
||||
@@ -133,7 +130,6 @@ def run_one(label: str, parser: Any, cdn: str, url: str, workers: int, which: st
|
||||
work = Path(mkdtemp(prefix="live_"))
|
||||
save_path = work / "out.mp4"
|
||||
counter = Counter()
|
||||
# adaptive_workers only exists on the downloader-speed branch; skip on older checkouts
|
||||
extra = (
|
||||
{"adaptive_workers": True} if "adaptive_workers" in getattr(DownloadContext, "__dataclass_fields__", {}) else {}
|
||||
)
|
||||
@@ -147,7 +143,7 @@ def run_one(label: str, parser: Any, cdn: str, url: str, workers: int, which: st
|
||||
**extra,
|
||||
)
|
||||
|
||||
track.drm = None # download-speed only: time raw segment download, no license/decrypt
|
||||
track.drm = None
|
||||
t0 = time.time()
|
||||
err = ""
|
||||
try:
|
||||
@@ -170,7 +166,6 @@ def run_one(label: str, parser: Any, cdn: str, url: str, workers: int, which: st
|
||||
@click.option("--track", "which", type=click.Choice(["smallest", "largest"]), default="largest")
|
||||
@click.option("--only", default="", help="substring filter on CDN/format labels (e.g. 'apple' or 'ISM')")
|
||||
def main(workers: int, which: str, only: str) -> None:
|
||||
# download-speed only: skip HLS key handling so segments just download, no license server
|
||||
HLS.get_drm = staticmethod(lambda *a, **k: None) # type: ignore[assignment]
|
||||
|
||||
log_path = Path(mkdtemp(prefix="live_dbg_")) / "debug.jsonl"
|
||||
@@ -181,7 +176,7 @@ def main(workers: int, which: str, only: str) -> None:
|
||||
try:
|
||||
streams = [s for s in STREAMS if only.lower() in s[0].lower() or only.lower() in s[2].lower()]
|
||||
for label, parser, cdn, url in streams:
|
||||
_, line0 = read_new_transitions(log_path, line0) # advance past prior run's lines
|
||||
_, line0 = read_new_transitions(log_path, line0)
|
||||
row = run_one(label, parser, cdn, url, workers, which, log_path, line0)
|
||||
print(row)
|
||||
rows.append(row)
|
||||
|
||||
@@ -27,8 +27,6 @@ from requests import Session
|
||||
from unshackle.core.manifests import DASH
|
||||
from unshackle.core.tracks.track import DownloadContext
|
||||
|
||||
# (label, SegmentBase MPD). netflix-1a is collapse-eligible (Initialization range from
|
||||
# byte 0); sony-1a has no Initialization range so every checkout takes the classic path.
|
||||
STREAMS: list[tuple[str, str]] = [
|
||||
("netflix-1a", "https://dash.akamaized.net/dash264/TestCases/1a/netflix/exMPD_BIP_TC1.mpd"),
|
||||
("sony-1a", "https://dash.akamaized.net/dash264/TestCases/1a/sony/SNE_DASH_SD_CASE1A_REVISED.mpd"),
|
||||
@@ -53,7 +51,6 @@ def install_guard_spy() -> bool:
|
||||
|
||||
|
||||
def _major_brand(path: Path) -> str:
|
||||
# ftyp box: [4-byte size][b"ftyp"][4-byte major brand]; empty if not an ftyp file
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(12)
|
||||
return head[8:12].decode("latin-1") if head[4:8] == b"ftyp" else ""
|
||||
@@ -69,8 +66,6 @@ def ffprobe(path: Path) -> str:
|
||||
)
|
||||
if r.stdout.strip():
|
||||
return f"{float(r.stdout.strip()):.0f}s"
|
||||
# Sony's senvu-profile MP4s use major brand "senv", which ffmpeg can't parse
|
||||
# ("Not yet implemented in FFmpeg"). The download is intact, so verify by size.
|
||||
if _major_brand(path) == "senv":
|
||||
return f"senv ok ({path.stat().st_size} B)"
|
||||
return "INVALID"
|
||||
@@ -91,7 +86,6 @@ def run_one(label: str, url: str, which: str, workers: int, has_guard: bool) ->
|
||||
|
||||
work = Path(mkdtemp(prefix="segbase_ab_"))
|
||||
save_path = work / "out.mp4"
|
||||
# adaptive_workers only exists on the downloader-speed branch; skip elsewhere
|
||||
extra = {"adaptive_workers": True} if "adaptive_workers" in DownloadContext.__dataclass_fields__ else {}
|
||||
ctx = DownloadContext(
|
||||
save_path=save_path,
|
||||
|
||||
@@ -36,14 +36,11 @@ def builds(monkeypatch) -> list[tuple[str, str]]:
|
||||
calls.append((cdm_name, service_name))
|
||||
return StubCdm(cdm_name, service_name)
|
||||
|
||||
# The package resolves ``load_cdm`` lazily, so a ``setattr`` here would write the real
|
||||
# function into the package dict on undo and shadow that lookup for the whole process.
|
||||
monkeypatch.setitem(cdm_mod.__dict__, "load_cdm", fake_load_cdm)
|
||||
return calls
|
||||
|
||||
|
||||
def make_dl() -> dl:
|
||||
# __new__ skips the CLI-driven __init__; get_cdm only needs these three.
|
||||
instance = dl.__new__(dl)
|
||||
instance.log = logging.getLogger("test_cdm_cache")
|
||||
instance.cdm_override = None
|
||||
|
||||
@@ -17,8 +17,6 @@ from unshackle.core.update_checker import UpdateChecker
|
||||
|
||||
requests_downloader = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
|
||||
# shutdown() blocks until the serve loop polls again, and the 0.5s default is paid by every
|
||||
# test server at teardown. The default changes for the whole process, servers in core included.
|
||||
socketserver.BaseServer.serve_forever.__defaults__ = (0.01,)
|
||||
|
||||
|
||||
|
||||
@@ -58,34 +58,32 @@ def run_tick(c: AdaptiveWorkerController, rate: float, now: float, errors: int =
|
||||
def test_starts_at_cap() -> None:
|
||||
assert AdaptiveWorkerController(cap=16).target == 16
|
||||
assert AdaptiveWorkerController(cap=4).target == 4
|
||||
assert AdaptiveWorkerController(cap=1).target == 2 # clamped up to ADAPTIVE_MIN
|
||||
assert AdaptiveWorkerController(cap=16, start=6).target == 6 # explicit start wins
|
||||
assert AdaptiveWorkerController(cap=1).target == 2
|
||||
assert AdaptiveWorkerController(cap=16, start=6).target == 6
|
||||
|
||||
|
||||
def test_no_op_before_warmup() -> None:
|
||||
c = AdaptiveWorkerController(cap=16, start=6, tick=TICK, window=WINDOW)
|
||||
assert c.update(0.0) == 6 # arms last_tick before any samples are recorded
|
||||
assert c.update(0.0) == 6
|
||||
c.record_bytes(500_000, 3.0)
|
||||
# a full tick has elapsed since arming, but under half a tick of samples exists -> hold
|
||||
assert c.update(4.5) == 6
|
||||
c.record_bytes(500_000, 6.5)
|
||||
# warmed up (first sample 3.0, now 8.5) -> the probe fires
|
||||
assert c.update(8.5) == 8
|
||||
|
||||
|
||||
def test_climbs_while_speed_improves() -> None:
|
||||
c = AdaptiveWorkerController(cap=16, start=6, tick=TICK, window=WINDOW)
|
||||
now = 0.0
|
||||
c.update(now) # arm
|
||||
c.update(now)
|
||||
rate = 1_000_000.0
|
||||
now = fill_window(c, rate, now)
|
||||
targets = [c.update(now)] # first evaluation: 6 -> 8
|
||||
targets = [c.update(now)]
|
||||
for _ in range(6):
|
||||
rate *= 2 # sustained >10% windowed gain each tick
|
||||
rate *= 2
|
||||
target, now = run_tick(c, rate, now)
|
||||
targets.append(target)
|
||||
assert targets == sorted(targets) # monotonic non-decreasing
|
||||
assert targets[-1] == 16 # climbed to the cap
|
||||
assert targets == sorted(targets)
|
||||
assert targets[-1] == 16
|
||||
assert max(targets) <= 16
|
||||
|
||||
|
||||
@@ -95,11 +93,9 @@ def test_reverts_on_plateau() -> None:
|
||||
c.update(now)
|
||||
rate = 1_000_000.0
|
||||
now = fill_window(c, rate, now)
|
||||
assert c.update(now) == 8 # first increase 6 -> 8
|
||||
# hold the rate flat: <10% gain -> the tick reverts the increase to its restore point
|
||||
assert c.update(now) == 8
|
||||
target, now = run_tick(c, rate, now)
|
||||
assert target == 6
|
||||
# a paying probe climbs again from the restore point
|
||||
target, now = run_tick(c, rate * 4, now)
|
||||
assert target == 8
|
||||
|
||||
@@ -111,20 +107,18 @@ def test_halves_and_cooldown_on_error_burst() -> None:
|
||||
now = fill_window(c, 1_000_000.0, now)
|
||||
for _ in range(3):
|
||||
c.record_error(now)
|
||||
assert c.update(now) == 3 # 3 errors -> multiplicative decrease 6 // 2
|
||||
assert c.update(now) == 3
|
||||
|
||||
# cooldown tick holds even with improving throughput
|
||||
target, now = run_tick(c, 2_000_000.0, now)
|
||||
assert target == 3
|
||||
|
||||
# cooldown consumed -> climbing resumes
|
||||
target, now = run_tick(c, 4_000_000.0, now)
|
||||
assert target == 5
|
||||
|
||||
|
||||
def test_clamps_to_bounds_and_never_exceeds_cap() -> None:
|
||||
c = AdaptiveWorkerController(cap=4, tick=TICK, window=WINDOW)
|
||||
assert c.target == 4 # already at cap (min(6, 4))
|
||||
assert c.target == 4
|
||||
now = 0.0
|
||||
c.update(now)
|
||||
rate = 1_000_000.0
|
||||
@@ -135,7 +129,7 @@ def test_clamps_to_bounds_and_never_exceeds_cap() -> None:
|
||||
target, now = run_tick(c, rate, now)
|
||||
seen.append(target)
|
||||
assert all(2 <= s <= 4 for s in seen)
|
||||
assert max(seen) == 4 # never exceeds the cap
|
||||
assert max(seen) == 4
|
||||
|
||||
|
||||
def test_error_burst_floors_at_min() -> None:
|
||||
@@ -145,39 +139,36 @@ def test_error_burst_floors_at_min() -> None:
|
||||
now = fill_window(c, 1_000_000.0, now)
|
||||
for _ in range(5):
|
||||
c.record_error(now)
|
||||
assert c.update(now) == 2 # max(ADAPTIVE_MIN, 2 // 2)
|
||||
assert c.update(now) == 2
|
||||
|
||||
|
||||
def test_tail_guard_suppresses_increase() -> None:
|
||||
# with fewer units of work than the target, the tick must hold instead of probing up
|
||||
c = AdaptiveWorkerController(cap=16, start=6, tick=TICK, window=WINDOW)
|
||||
now = 0.0
|
||||
c.update(now) # arm at target 6
|
||||
now = fill_window(c, 1_000_000.0, now)
|
||||
assert c.update(now, 3) == 6 # 3 < target 6 -> holds at 6 rather than climbing to 8
|
||||
|
||||
|
||||
def test_tail_guard_none_path_unchanged() -> None:
|
||||
# without a tail count, the update still probes upward on the first evaluation
|
||||
c = AdaptiveWorkerController(cap=16, start=6, tick=TICK, window=WINDOW)
|
||||
now = 0.0
|
||||
c.update(now)
|
||||
now = fill_window(c, 1_000_000.0, now)
|
||||
assert c.update(now) == 8 # first evaluation 6 -> 8
|
||||
assert c.update(now, 3) == 6
|
||||
|
||||
|
||||
def test_tail_guard_none_path_unchanged() -> None:
|
||||
c = AdaptiveWorkerController(cap=16, start=6, tick=TICK, window=WINDOW)
|
||||
now = 0.0
|
||||
c.update(now)
|
||||
now = fill_window(c, 1_000_000.0, now)
|
||||
assert c.update(now) == 8
|
||||
|
||||
|
||||
def test_tail_guard_still_halves_on_error_burst() -> None:
|
||||
# the guard suppresses growth but never blocks an error-burst decrease
|
||||
c = AdaptiveWorkerController(cap=16, start=6, tick=TICK, window=WINDOW)
|
||||
now = 0.0
|
||||
c.update(now)
|
||||
now = fill_window(c, 1_000_000.0, now)
|
||||
for _ in range(3):
|
||||
c.record_error(now)
|
||||
assert c.update(now, 2) == 3 # guard active (2 < 6) but 3 errors -> 6 // 2
|
||||
assert c.update(now, 2) == 3
|
||||
|
||||
|
||||
PER_WORKER = 1_000_000.0 # bytes/sec each worker adds, so throughput scales with the target
|
||||
PER_WORKER = 1_000_000.0
|
||||
|
||||
|
||||
def run_scaling(c: AdaptiveWorkerController, now: float, seconds: float, work: int = 10_000) -> float:
|
||||
@@ -201,9 +192,9 @@ def test_probe_kept_when_the_true_gain_clears_the_bar() -> None:
|
||||
c.update(now)
|
||||
rate = 1_000_000.0
|
||||
now = fill_window(c, rate, now)
|
||||
assert c.update(now) == 12 # first evaluation probes 10 -> 12
|
||||
assert c.update(now) == 12
|
||||
target, now = run_tick(c, rate * 1.2, now)
|
||||
assert target == 14 # probe held, and the controller climbs again
|
||||
assert target == 14
|
||||
|
||||
|
||||
def test_recovers_to_the_cap_after_an_error_burst() -> None:
|
||||
@@ -236,7 +227,7 @@ def test_reverts_when_the_probe_stops_paying_on_a_saturated_link() -> None:
|
||||
now += DT
|
||||
c.record_bytes(int(rate * DT), now)
|
||||
seen.append(c.update(now, 10_000))
|
||||
assert max(seen) <= 12 # one probe past the knee is the most it may hold
|
||||
assert max(seen) <= 12
|
||||
assert seen[-1] <= 12
|
||||
|
||||
|
||||
@@ -253,13 +244,13 @@ def test_plan_tail_parts_full_coverage_no_gaps() -> None:
|
||||
assert parts[0][0] == 0
|
||||
assert parts[-1][1] == size - 1
|
||||
for (_, prev_end), (start, _) in zip(parts, parts[1:]):
|
||||
assert start == prev_end + 1 # each part begins exactly where the previous one ended
|
||||
assert start == prev_end + 1
|
||||
covered = sum(end - start + 1 for start, end in parts)
|
||||
assert covered == size
|
||||
|
||||
|
||||
def test_plan_tail_parts_respects_spare_cap() -> None:
|
||||
size = 100 * 1024 * 1024 # would want ~25 parts at 4MB, but spare caps it
|
||||
size = 100 * 1024 * 1024
|
||||
parts = plan_tail_parts(size, spare=3)
|
||||
assert len(parts) <= 3
|
||||
assert parts[0][0] == 0 and parts[-1][1] == size - 1
|
||||
@@ -268,13 +259,12 @@ def test_plan_tail_parts_respects_spare_cap() -> None:
|
||||
def test_plan_tail_parts_part_size_bounded() -> None:
|
||||
size = 40 * 1024 * 1024
|
||||
parts = plan_tail_parts(size, spare=16)
|
||||
# never more parts than ~ceil(size / TAIL_BOOST_PART_SIZE)
|
||||
assert len(parts) <= -(-size // TAIL_BOOST_PART_SIZE)
|
||||
|
||||
|
||||
def test_plan_tail_parts_skips_small_or_no_spare() -> None:
|
||||
assert plan_tail_parts(TAIL_BOOST_MIN_SEGMENT_SIZE - 1, spare=8) == [] # too small
|
||||
assert plan_tail_parts(20 * 1024 * 1024, spare=1) == [] # not enough spare workers
|
||||
assert plan_tail_parts(TAIL_BOOST_MIN_SEGMENT_SIZE - 1, spare=8) == []
|
||||
assert plan_tail_parts(20 * 1024 * 1024, spare=1) == []
|
||||
assert plan_tail_parts(20 * 1024 * 1024, spare=0) == []
|
||||
|
||||
|
||||
@@ -289,34 +279,30 @@ def test_split_ranges_covers_exactly_no_gaps_no_overlaps() -> None:
|
||||
|
||||
|
||||
def test_split_ranges_respects_max_parts_and_target() -> None:
|
||||
assert len(split_ranges(100 * 1024 * 1024, max_parts=4, part_target=16 * 1024 * 1024)) == 4 # capped
|
||||
assert len(split_ranges(10 * 1024 * 1024, max_parts=8, part_target=16 * 1024 * 1024)) == 1 # below one target
|
||||
assert len(split_ranges(100 * 1024 * 1024, max_parts=4, part_target=16 * 1024 * 1024)) == 4
|
||||
assert len(split_ranges(10 * 1024 * 1024, max_parts=8, part_target=16 * 1024 * 1024)) == 1
|
||||
assert split_ranges(1, max_parts=8, part_target=16 * 1024 * 1024) == [(0, 0)]
|
||||
|
||||
|
||||
def test_tail_boost_engages_on_idle_capacity() -> None:
|
||||
# engages at the tail: idle workers outnumber the remaining whole segments
|
||||
assert tail_boost_engages(remaining=4, pending=2, target=8) # spare 6 >= 4
|
||||
assert tail_boost_engages(remaining=6, pending=6, target=16) # spare 10 >= 6
|
||||
assert tail_boost_engages(remaining=4, pending=2, target=8)
|
||||
assert tail_boost_engages(remaining=6, pending=6, target=16)
|
||||
|
||||
|
||||
def test_tail_boost_engages_when_remaining_is_a_full_stride() -> None:
|
||||
# remaining sits at 6 (one worker stride) while the target has climbed to 16, so 14 workers
|
||||
# are idle. idle capacity far exceeds the remaining segments, so the boost must engage.
|
||||
assert tail_boost_engages(remaining=6, pending=2, target=16)
|
||||
|
||||
|
||||
def test_tail_boost_does_not_engage_early_or_saturated() -> None:
|
||||
assert not tail_boost_engages(remaining=54, pending=2, target=6) # early: 54 > spare 4
|
||||
assert not tail_boost_engages(remaining=1, pending=8, target=8) # saturated: spare 0
|
||||
assert not tail_boost_engages(remaining=0, pending=2, target=8) # nothing left
|
||||
assert not tail_boost_engages(remaining=5, pending=10, target=8) # over-subscribed: spare < 0
|
||||
assert not tail_boost_engages(remaining=54, pending=2, target=6)
|
||||
assert not tail_boost_engages(remaining=1, pending=8, target=8)
|
||||
assert not tail_boost_engages(remaining=0, pending=2, target=8)
|
||||
assert not tail_boost_engages(remaining=5, pending=10, target=8)
|
||||
|
||||
|
||||
def test_has_range_header_detects_byte_range_slices() -> None:
|
||||
# items carrying a Range header are byte-range slices; ranged-parallel must skip them
|
||||
assert has_range_header({"url": "u", "headers": {"Range": "bytes=0-99"}})
|
||||
assert has_range_header({"url": "u", "headers": {"range": "bytes=0-99"}}) # case-insensitive
|
||||
assert has_range_header({"url": "u", "headers": {"range": "bytes=0-99"}})
|
||||
assert not has_range_header({"url": "u", "headers": {"Authorization": "Bearer x"}})
|
||||
assert not has_range_header({"url": "u", "headers": {}})
|
||||
assert not has_range_header({"url": "u"})
|
||||
|
||||
@@ -72,7 +72,7 @@ def default_title_language(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
("mal:0", None),
|
||||
(-3, None),
|
||||
("21.5", None),
|
||||
("²", None), # superscript two passes isdigit() but crashes int()
|
||||
("²", None),
|
||||
],
|
||||
)
|
||||
def test_parse_anilist_ref(value: Any, expected: Optional[tuple[str, int]]) -> None:
|
||||
|
||||
@@ -47,7 +47,6 @@ def test_decrypt_round_trip(tmp_path: Path) -> None:
|
||||
|
||||
|
||||
def test_short_trailing_chunk_untouched(tmp_path: Path) -> None:
|
||||
# the last stripe starts at CHUNK * 3 and holds only 100 bytes, so it stays clear
|
||||
plain = os.urandom(CHUNK * 3 + 100)
|
||||
encrypted = stripe_encrypt(plain)
|
||||
assert encrypted[CHUNK * 3 :] == plain[CHUNK * 3 :]
|
||||
|
||||
@@ -52,7 +52,6 @@ def test_stamped_remote_widevine():
|
||||
|
||||
|
||||
def test_drm_stamp_beats_conflicting_is_playready_attr():
|
||||
# The stamped drm takes priority over the wrapper's own is_playready guess.
|
||||
cdm = SimpleNamespace(drm="playready", is_playready=False, is_remote_cdm=True)
|
||||
assert is_playready_cdm(cdm)
|
||||
assert not is_widevine_cdm(cdm)
|
||||
@@ -136,7 +135,7 @@ def test_stamp_remote_is_best_effort_on_unsettable_object():
|
||||
__slots__ = ()
|
||||
|
||||
obj = Slotted()
|
||||
out = stamp_remote(obj, "widevine") # must not raise
|
||||
out = stamp_remote(obj, "widevine")
|
||||
assert out is obj
|
||||
assert not hasattr(obj, "drm")
|
||||
|
||||
|
||||
@@ -29,9 +29,6 @@ def encrypt(plaintext: bytes, key: bytes = KEY, iv: bytes = IV) -> bytes:
|
||||
|
||||
|
||||
def clear_ts(packets: int = 4) -> bytes:
|
||||
# Plaintext MPEG-TS: sync byte 0x47 at every 188-byte packet boundary. Default 4 packets so
|
||||
# the fixture satisfies the hardened 4-boundary sniff (and 752 B is 16-aligned, so it must be
|
||||
# caught by the clear-TS guard, not the len%16 guard).
|
||||
return b"".join(bytes([SYNC_BYTE]) + b"\x00" * (TS_PACKET_SIZE - 1) for _ in range(packets))
|
||||
|
||||
|
||||
@@ -56,7 +53,7 @@ def test_clear_ts_passes_through(tmp_path) -> None:
|
||||
|
||||
|
||||
def test_non_block_aligned_passes_through(tmp_path) -> None:
|
||||
data = b"\x01" * 17 # not TS, and not a 16-byte multiple -> not valid CBC ciphertext
|
||||
data = b"\x01" * 17
|
||||
assert len(data) % AES.block_size != 0
|
||||
seg = tmp_path / "0.ts"
|
||||
seg.write_bytes(data)
|
||||
@@ -107,7 +104,6 @@ def test_data_uri_key_wrong_length_rejected() -> None:
|
||||
|
||||
|
||||
def test_raw_data_uri_key_materialises_and_validates() -> None:
|
||||
# A raw (non-base64) data: payload must be taken as literal key bytes, not hex-parsed.
|
||||
drm = ClearKey.from_m3u_key(data_key(KEY, base64_encoded=False))
|
||||
assert drm.key == KEY
|
||||
|
||||
@@ -118,9 +114,6 @@ def test_raw_data_uri_key_wrong_length_rejected() -> None:
|
||||
|
||||
|
||||
def test_data_uri_split_tolerates_commas_in_payload() -> None:
|
||||
# base64 with padding contains no comma, but the split must only break on the first comma
|
||||
# so a payload that itself contains a comma is not truncated. Encode a 16-byte key whose
|
||||
# base64 happens to be split-safe, and assert the mediatype comma is the only split point.
|
||||
raw = bytes(range(16))
|
||||
b64 = base64.b64encode(raw).decode("ascii")
|
||||
key = Key(
|
||||
@@ -160,19 +153,15 @@ def test_sequence_number_iv_uses_absolute_media_sequence() -> None:
|
||||
wanted segment's ``media_sequence`` (EXT-X-MEDIA-SEQUENCE + absolute position).
|
||||
"""
|
||||
master = m3u8.loads(SEQ_PLAYLIST)
|
||||
# media sequence numbers are the offset (100) plus absolute playlist position.
|
||||
assert [s.media_sequence for s in master.segments] == [100, 101, 102, 103]
|
||||
|
||||
# Drop an early segment (index 1), as an OnSegmentFilter would.
|
||||
unwanted = {master.segments[1]}
|
||||
wanted_segments = [s for s in master.segments if s not in unwanted]
|
||||
|
||||
# download index 1 is the SECOND surviving segment (absolute seq 102), not 101.
|
||||
download_i = 1
|
||||
seq = wanted_segments[download_i].media_sequence
|
||||
assert seq == 102
|
||||
|
||||
iv = int(seq).to_bytes(16, "big")
|
||||
assert iv == (102).to_bytes(16, "big")
|
||||
# the old download-index derivation would have produced the wrong IV (100 + 1 = 101)
|
||||
assert iv != (100 + download_i).to_bytes(16, "big")
|
||||
|
||||
@@ -16,8 +16,6 @@ from typing import Any, Optional
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
|
||||
# lxml.etree: XML parser used to build ContentProtection fixtures for DASH.get_drm
|
||||
from lxml import etree
|
||||
|
||||
from unshackle.core.drm import drm_from_dict
|
||||
@@ -120,7 +118,6 @@ def test_get_drm_clearkey_laurl_variants(laurl_xml: str) -> None:
|
||||
|
||||
|
||||
def test_get_drm_clearkey_kid_from_sibling_mp4protection() -> None:
|
||||
# Canonical DASH-IF shape: default_KID on the mp4protection element only.
|
||||
clearkey = protection(f'<ContentProtection schemeIdUri="{CLEARKEY_URN}" value="ClearKey1.0"/>')
|
||||
mp4protection = protection(
|
||||
f'<ContentProtection xmlns:cenc="{CENC_NS}" '
|
||||
@@ -165,7 +162,6 @@ def test_get_content_keys_challenge_shape() -> None:
|
||||
assert licence.challenge is not None
|
||||
request = json.loads(licence.challenge.decode("utf8"))
|
||||
assert request == {"kids": [b64url_nopad(KID.bytes)], "type": "temporary"}
|
||||
# W3C EME mandates unpadded base64url key IDs
|
||||
assert all("=" not in kid for kid in request["kids"])
|
||||
|
||||
|
||||
@@ -199,7 +195,7 @@ def test_get_content_keys_skips_when_already_keyed() -> None:
|
||||
drm = ClearKeyCENC(kids=[KID], content_keys={KID: KEY.hex()})
|
||||
drm.get_content_keys(licence=licence)
|
||||
|
||||
assert licence.challenge is None # no license round-trip needed
|
||||
assert licence.challenge is None
|
||||
|
||||
|
||||
def test_to_dict_roundtrip() -> None:
|
||||
|
||||
@@ -109,7 +109,7 @@ def test_exclusions_are_unchanged():
|
||||
assert not any(k.startswith("3x") for k in keys)
|
||||
assert "2x1" not in keys
|
||||
assert "2x0" in keys and "2x2" in keys
|
||||
assert len(keys) == 3999 # 5 seasons less all of S03 less 2x1
|
||||
assert len(keys) == 3999
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tokens", [("S01E01",), ("S01",), ("S01-S05", "-S03", "-S02E01"), ("S02E03-S02E05",)])
|
||||
@@ -128,7 +128,7 @@ def test_part_range_within_one_episode():
|
||||
def test_part_exclusion_becomes_a_negative_key():
|
||||
keys = parse("S01", "-S01E01.2")
|
||||
assert "!1x1.2" in keys
|
||||
assert "1x1" in keys # base key stays so the other parts still match
|
||||
assert "1x1" in keys
|
||||
|
||||
|
||||
def test_base_exclusion_covers_part_keys():
|
||||
@@ -136,18 +136,17 @@ def test_base_exclusion_covers_part_keys():
|
||||
|
||||
|
||||
def test_exclusion_removes_duplicate_keys():
|
||||
# "S01" and "S01E01" both emit 1x1; the exclusion must remove every copy
|
||||
assert "1x1" not in parse("S01", "S01E01", "-S01E01")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"token",
|
||||
[
|
||||
"S01E01.0", # parts count from 1
|
||||
"S01E01.1-S01E02.2", # a part range cannot cross episodes
|
||||
"S01-S01E01.2", # a part on only one side
|
||||
"S01E01.3-S01E01.1", # reversed part range
|
||||
"S01E01.200", # above MAX_PART
|
||||
"S01E01.0",
|
||||
"S01E01.1-S01E02.2",
|
||||
"S01-S01E01.2",
|
||||
"S01E01.3-S01E01.1",
|
||||
"S01E01.200",
|
||||
],
|
||||
)
|
||||
def test_bad_part_tokens_fail(token):
|
||||
@@ -182,10 +181,10 @@ def test_comma_separated_dates_convert():
|
||||
@pytest.mark.parametrize(
|
||||
"token",
|
||||
[
|
||||
"2026-13-01", # not a real month
|
||||
"2026-02-30", # not a real day
|
||||
"2026-08-03:2026-08-01", # reversed range
|
||||
"2020-01-01:2026-01-01", # over MAX_DATE_SPAN
|
||||
"2026-13-01",
|
||||
"2026-02-30",
|
||||
"2026-08-03:2026-08-01",
|
||||
"2020-01-01:2026-01-01",
|
||||
],
|
||||
)
|
||||
def test_bad_date_tokens_fail(token):
|
||||
|
||||
@@ -32,7 +32,7 @@ def test_covers_the_framework_dirs_only() -> None:
|
||||
assert not any(rel.startswith("services/") for rel in rels)
|
||||
assert not any("__pycache__" in rel for rel in rels)
|
||||
assert all(rel.endswith(".py") for rel in rels)
|
||||
assert rels == sorted(rels) # order must not depend on the filesystem
|
||||
assert rels == sorted(rels)
|
||||
|
||||
|
||||
def test_content_changes_the_hash() -> None:
|
||||
|
||||
@@ -34,9 +34,7 @@ def test_decryption_map_keys_upper_cased_on_build():
|
||||
def test_resolve_decryption_per_service_and_default():
|
||||
c = Config(decryption={"EXAMPLE": "mp4decrypt", "default": "shaka"})
|
||||
assert resolve_decryption(c.decryption_map, c.decryption, "EXAMPLE") == "mp4decrypt"
|
||||
# service not mapped -> default
|
||||
assert resolve_decryption(c.decryption_map, c.decryption, "DEMO") == "shaka"
|
||||
# case-insensitive both ways (lowercase yaml key, mixed-case lookup)
|
||||
c2 = Config(decryption={"example": "mp4decrypt", "default": "shaka"})
|
||||
assert resolve_decryption(c2.decryption_map, c2.decryption, "Example") == "mp4decrypt"
|
||||
|
||||
@@ -53,12 +51,9 @@ def test_cdm_keys_preserved_on_build():
|
||||
|
||||
|
||||
def test_resolve_cdm_name_case_insensitive():
|
||||
# lowercase yaml key must resolve for an uppercase service tag (the bug being fixed)
|
||||
c = Config(cdm={"demo": "dev_a", "default": "dev_b"})
|
||||
assert resolve_cdm_name(c.cdm, "DEMO") == "dev_a"
|
||||
# unmapped service -> default
|
||||
assert resolve_cdm_name(c.cdm, "EXAMPLE") == "dev_b"
|
||||
# uppercase yaml key, lowercase lookup
|
||||
c2 = Config(cdm={"DEMO": "dev_a", "default": "dev_b"})
|
||||
assert resolve_cdm_name(c2.cdm, "demo") == "dev_a"
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import unshackle.core.console # noqa: F401 # installs the cell width override
|
||||
|
||||
|
||||
def test_spacing_marks_take_one_cell() -> None:
|
||||
assert cell_len("हिंदी") == 4 # two Mc marks count, the Mn anusvara does not
|
||||
assert cell_len("हिंदी") == 4
|
||||
assert cell_len("தமிழ்") == 4
|
||||
assert cell_len("ไทย") == 3
|
||||
|
||||
@@ -25,5 +25,5 @@ def test_panel_pads_an_indic_label_to_the_border() -> None:
|
||||
|
||||
|
||||
def test_a_virama_conjunct_shares_one_cell() -> None:
|
||||
assert cell_len("हिन्दी") == 4 # न्द is one conjunct
|
||||
assert cell_len("ಕನ್ನಡ") == 4 # a Kannada virama does not join, so ನ್ನ keeps two cells
|
||||
assert cell_len("हिन्दी") == 4
|
||||
assert cell_len("ಕನ್ನಡ") == 4
|
||||
|
||||
@@ -174,7 +174,7 @@ def failing_resolver(error: Exception) -> Resolver:
|
||||
def test_a_failed_lookup_hides_the_resolver(error: Exception, reason: str) -> None:
|
||||
with pytest.raises(ConnectionError) as e:
|
||||
failing_resolver(error).resolve("a.test")
|
||||
assert str(e.value) == reason and e.value.__suppress_context__ # a traceback must not print the URL
|
||||
assert str(e.value) == reason and e.value.__suppress_context__
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -188,7 +188,6 @@ def test_a_failed_lookup_hides_the_resolver(error: Exception, reason: str) -> No
|
||||
failing_resolver(requests.ConnectionError("dns.controld.com: /SECRETID")),
|
||||
"Control D DNS could not be reached",
|
||||
),
|
||||
# a CR/LF left in the reason would end the status line early and cut the reason off
|
||||
(
|
||||
SimpleNamespace(resolve=Mock(side_effect=ConnectionError("no A record\r\nX-Injected: 1"))),
|
||||
"no A record X-Injected: 1",
|
||||
@@ -205,7 +204,6 @@ def test_a_failed_tunnel_names_the_reason(forwarder: LocalProxy, reason: str, ca
|
||||
assert "SECRETID" not in str(e.value)
|
||||
response = requests.get(f"http://a.test:{get_free_port()}/", proxies={"http": forwarder.uri}, timeout=10)
|
||||
assert response.status_code == 502
|
||||
# clients that drop the reason phrase still get it once in the log
|
||||
warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
|
||||
assert len(warnings) == 1 and reason in warnings[0]
|
||||
|
||||
@@ -238,11 +236,11 @@ def test_resolve_asks_control_d_in_wireformat_and_caches_it() -> None:
|
||||
assert url == "https://dns.controld.com/efgh456"
|
||||
assert headers == {"accept": "application/dns-message"}
|
||||
assert params["dns"] == base64.urlsafe_b64encode(build_query("a.test")).rstrip(b"=").decode()
|
||||
assert "=" not in params["dns"] # RFC 8484 wants the padding stripped
|
||||
assert "=" not in params["dns"]
|
||||
|
||||
assert resolver.resolve("a.test") == "9.8.7.6"
|
||||
assert len(seen) == 1
|
||||
assert resolver.cache["a.test"][1] > time.monotonic() + MIN_TTL - 1 # a 1s TTL is floored
|
||||
assert resolver.cache["a.test"][1] > time.monotonic() + MIN_TTL - 1
|
||||
|
||||
|
||||
def test_resolve_raises_when_control_d_has_no_address() -> None:
|
||||
@@ -330,8 +328,8 @@ def account(catalogue: None, monkeypatch: pytest.MonkeyPatch) -> Iterator[Accoun
|
||||
|
||||
def test_locations_come_from_control_d(account: Account) -> None:
|
||||
provider = ControlD(token="secret")
|
||||
assert provider.location("ca") in ("YUL", "YYZ") # never the hidden residential one
|
||||
assert provider.location("res_yyz") == "RES_YYZ" # unless asked for by name
|
||||
assert provider.location("ca") in ("YUL", "YYZ")
|
||||
assert provider.location("res_yyz") == "RES_YYZ"
|
||||
assert provider.location("jp") is None
|
||||
assert repr(provider) == "2 Countries (4 Servers)"
|
||||
|
||||
@@ -349,7 +347,6 @@ def test_a_query_steers_the_profile_default_rule(account: Account) -> None:
|
||||
assert provider.get_proxy("JFK") == uri
|
||||
assert len(account.moves()) == 1
|
||||
|
||||
# one profile only: a second country moves it and must clear its cache
|
||||
cache = controld.FORWARDERS["https://dns.controld.com/efgh456"].resolver.cache
|
||||
cache["cached.test"] = ("1.2.3.4", float("inf"))
|
||||
assert provider.get_proxy("yul") == uri
|
||||
@@ -367,7 +364,6 @@ def test_each_region_gets_its_own_profile_and_forwarder(account: Account) -> Non
|
||||
assert us != ca
|
||||
assert account.moves() == [("one", "JFK"), ("two", "YUL")]
|
||||
|
||||
# out of profiles: the oldest claim moves
|
||||
assert provider.get_proxy("yyz") == us
|
||||
assert account.moves()[-1] == ("one", "YYZ")
|
||||
assert provider.get_proxy("yul") == ca
|
||||
@@ -377,7 +373,7 @@ def test_each_region_gets_its_own_profile_and_forwarder(account: Account) -> Non
|
||||
def test_a_region_uses_the_endpoint_named_after_it_or_creates_one(account: Account) -> None:
|
||||
account.device("unshackle-us", "kept")
|
||||
account.device("Phone", "theirs")
|
||||
account.device("unshackle-gb", "theirs") # shares the user's own profile, so never touched
|
||||
account.device("unshackle-gb", "theirs")
|
||||
provider = ControlD(token="secret")
|
||||
|
||||
us = provider.get_proxy("us")
|
||||
@@ -387,7 +383,6 @@ def test_a_region_uses_the_endpoint_named_after_it_or_creates_one(account: Accou
|
||||
assert [x[0] for x in account.moves()] == ["kept", "punshackleca"]
|
||||
assert "theirs" not in provider.resolvers
|
||||
|
||||
# the REST API makes a provider per request; it must find the endpoint by name
|
||||
assert ControlD(token="secret").get_proxy("ca") == ca
|
||||
assert len(account.moves()) == 2
|
||||
|
||||
@@ -426,7 +421,7 @@ def test_a_server_runs_a_forwarder_for_a_resolver_a_client_sends(account: Accoun
|
||||
|
||||
uri = resolve_proxy(sent, [])
|
||||
assert uri and uri.startswith("http://127.0.0.1:")
|
||||
assert local_proxy(sent) == uri # one forwarder per resolver
|
||||
assert local_proxy(sent) == uri
|
||||
with pytest.raises(ValueError):
|
||||
local_proxy("controld://evil.example/x@dns.controld.com")
|
||||
|
||||
@@ -434,7 +429,7 @@ def test_a_server_runs_a_forwarder_for_a_resolver_a_client_sends(account: Accoun
|
||||
def test_the_log_names_the_location_and_masks_the_resolver(account: Account) -> None:
|
||||
provider = ControlD(token="secret", profile="abcd123", resolver="efgh456")
|
||||
provider.get_proxy("yul")
|
||||
provider.get_proxy("yul") # a profile already on the region keeps its location
|
||||
provider.get_proxy("yul")
|
||||
assert provider.last_connection_display() == "(YUL - Montreal): efgh***@dns.controld.com"
|
||||
|
||||
|
||||
@@ -448,7 +443,7 @@ def test_remote_sends_the_resolver_and_a_bare_region_skips_control_d(
|
||||
|
||||
assert remote_service.resolve_remote_proxy_arg("controld:us") == "controld://efgh456@dns.controld.com"
|
||||
with pytest.raises(click.ClickException):
|
||||
remote_service.resolve_remote_proxy_arg("us") # a loopback forwarder is useless to a server
|
||||
remote_service.resolve_remote_proxy_arg("us")
|
||||
|
||||
|
||||
def test_a_server_gets_the_typed_proxy_only_when_this_machine_resolved_it_to_loopback() -> None:
|
||||
|
||||
@@ -36,7 +36,6 @@ def config(*descriptors: tuple[str, str], tag: str = "AdaptationSet") -> ET.Elem
|
||||
(CICP, "20", "9.1.4"),
|
||||
(DOLBY, "F801", 5.1),
|
||||
(DOLBY_LEGACY, "FA01", 7.1),
|
||||
# an all-digit mask is still a mask under a Dolby scheme
|
||||
(DOLBY, "4000", 1.0),
|
||||
],
|
||||
)
|
||||
|
||||
@@ -13,7 +13,6 @@ def test_caption_role_is_closed_caption() -> None:
|
||||
|
||||
|
||||
def test_caption_role_with_sdh_value_is_sdh_only() -> None:
|
||||
# a Subtitle cannot be both CC and SDH, so a set marked both used to fail the whole title
|
||||
element = ET.fromstring(f"<AdaptationSet>{CAPTION}{SDH}</AdaptationSet>")
|
||||
assert DASH.is_closed_caption(element) is False
|
||||
assert DASH.is_sdh(element) is True
|
||||
|
||||
@@ -76,7 +76,6 @@ def licence_only(track: Any, tmp_path: Any) -> RecordingLicence:
|
||||
|
||||
def test_download_track_licenses_clearkey_cenc(tmp_path, monkeypatch) -> None:
|
||||
track = DASH.from_text(MPD, MANIFEST_URL).to_tracks().videos[0]
|
||||
# KID normally comes from the init segment; short-circuit the probe (offline).
|
||||
monkeypatch.setattr(track, "get_key_id", lambda *args, **kwargs: KID)
|
||||
|
||||
licence = licence_only(track, tmp_path)
|
||||
@@ -85,7 +84,6 @@ def test_download_track_licenses_clearkey_cenc(tmp_path, monkeypatch) -> None:
|
||||
drm, track_kid = licence.calls[0]
|
||||
assert isinstance(drm, ClearKeyCENC)
|
||||
assert track_kid == KID
|
||||
# with content keys populated, decrypt has what it needs
|
||||
assert drm.content_keys == {KID: KEY.hex()}
|
||||
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ def collapsible(segments, init_len: int, is_subtitle: bool = False) -> bool:
|
||||
|
||||
|
||||
def test_segmentbase_single_range_eligible():
|
||||
# init occupies [0, 863); one media segment covers the rest of the same URL
|
||||
assert collapsible([(URL, "863-999999")], init_len=863) is True
|
||||
|
||||
|
||||
@@ -38,7 +37,6 @@ def test_mixed_urls_ineligible():
|
||||
|
||||
|
||||
def test_first_segment_gap_after_init_left_to_prefix_check():
|
||||
# the gap may be the sidx; single_url_prefix_matches decides from the bytes
|
||||
segments = [(URL, "900-1999"), (URL, "2000-2999")]
|
||||
assert DASH.collapsible_single_url(False, segments, 863) == (900, 2999)
|
||||
|
||||
@@ -48,7 +46,6 @@ def test_first_segment_inside_init_ineligible():
|
||||
|
||||
|
||||
def test_gap_between_segments_ineligible():
|
||||
# the merge path would skip 2000-2999; collapsing the parent would include it
|
||||
segments = [(URL, "863-1999"), (URL, "3000-3999")]
|
||||
assert collapsible(segments, init_len=863) is False
|
||||
|
||||
|
||||
@@ -34,13 +34,10 @@ from unshackle.core.tracks.track import DownloadContext
|
||||
|
||||
pytestmark = pytest.mark.skipif(shutil.which("ffprobe") is None, reason="requires ffprobe")
|
||||
|
||||
# distinctive parent resource for the collapse case; init is its [0, INIT_LEN) prefix
|
||||
PARENT = bytes(i % 256 for i in range(10240))
|
||||
INIT_LEN = 512
|
||||
# last indexed byte for the clipped case; the parent carries 1024 bytes past it
|
||||
CLIP_END = len(PARENT) - 1025
|
||||
|
||||
# separate resources for the non-collapse (mixed-URL) case
|
||||
INIT2 = bytes(range(100))
|
||||
PART0 = bytes([0xA0]) * 300
|
||||
PART1 = bytes([0xB1]) * 200
|
||||
@@ -106,7 +103,6 @@ def base(srv) -> str:
|
||||
|
||||
|
||||
def mixed_mpd(srv) -> str:
|
||||
# Two SegmentURLs on distinct paths -> mixed URLs -> predicate False -> segmented path.
|
||||
return f"""<?xml version="1.0"?>
|
||||
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" profiles="urn:mpeg:dash:profile:isoff-on-demand:2011">
|
||||
<BaseURL>{base(srv)}</BaseURL>
|
||||
@@ -125,14 +121,12 @@ def mixed_mpd(srv) -> str:
|
||||
|
||||
|
||||
def sidx_box(sizes: list[int]) -> bytes:
|
||||
# version 0 sidx: one MEDIA reference per size, each starting with a SAP
|
||||
refs = b"".join(struct.pack(">III", size, 1, 0x90000000) for size in sizes)
|
||||
body = struct.pack(">IIIIIHH", 0, 1, 1, 0, 0, 0, len(sizes)) + refs
|
||||
return struct.pack(">I", 8 + len(body)) + b"sidx" + body
|
||||
|
||||
|
||||
def media_mpd(srv, segments: str) -> str:
|
||||
# one Representation on media.mp4, described by the given segment element
|
||||
return f"""<?xml version="1.0"?>
|
||||
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" profiles="urn:mpeg:dash:profile:isoff-on-demand:2011">
|
||||
<BaseURL>{base(srv)}</BaseURL>
|
||||
@@ -148,7 +142,6 @@ def media_mpd(srv, segments: str) -> str:
|
||||
|
||||
|
||||
def ranged_mpd(srv, ranges: list[tuple[int, int]], init: str = f'range="0-{INIT_LEN - 1}"') -> str:
|
||||
# SegmentList of byte ranges on one media.mp4, with the given Initialization attributes
|
||||
segment_urls = "\n".join(f' <SegmentURL mediaRange="{s}-{e}"/>' for s, e in ranges)
|
||||
return media_mpd(
|
||||
srv,
|
||||
@@ -160,7 +153,6 @@ def ranged_mpd(srv, ranges: list[tuple[int, int]], init: str = f'range="0-{INIT_
|
||||
|
||||
|
||||
def segment_base_mpd(srv) -> str:
|
||||
# the media range comes from the init response, not the manifest
|
||||
return media_mpd(
|
||||
srv,
|
||||
f""" <SegmentBase>
|
||||
@@ -188,14 +180,10 @@ def test_collapse_downloads_parent_whole_in_one_direct_request(server, tmp_path)
|
||||
|
||||
DASH.download_track(track, ctx)
|
||||
|
||||
# the whole parent lands at save_path, byte-for-byte
|
||||
assert ctx.save_path.read_bytes() == PARENT
|
||||
assert track.path == ctx.save_path
|
||||
# exactly one Range-less GET (the direct whole-resource download); the only other hit is
|
||||
# the ranged init probe done while parsing SegmentList, never a per-segment slice fetch.
|
||||
no_range = [path for path, rng in server.requests if rng is None]
|
||||
assert no_range == ["/media.mp4"]
|
||||
# collapse skips the segment dir + merge entirely: no dir, no leftover control files
|
||||
assert not ctx.save_dir.exists()
|
||||
assert not list(tmp_path.glob("*.!dev"))
|
||||
assert not list(tmp_path.glob("**/*.!dev"))
|
||||
@@ -203,13 +191,11 @@ def test_collapse_downloads_parent_whole_in_one_direct_request(server, tmp_path)
|
||||
|
||||
def test_collapse_trims_parent_bytes_past_the_last_segment(server, tmp_path):
|
||||
server.routes["/media.mp4"] = PARENT
|
||||
# the ranges stop short of the parent's end, so the collapsed file must be trimmed
|
||||
track = make_track(ranged_mpd(server, [(INIT_LEN, 5119), (5120, CLIP_END)]), server)
|
||||
ctx = make_ctx(tmp_path, "clipped.mp4")
|
||||
|
||||
DASH.download_track(track, ctx)
|
||||
|
||||
# the parent's trailing 1024 bytes are not part of any segment, so they must not survive
|
||||
assert ctx.save_path.read_bytes() == PARENT[: CLIP_END + 1]
|
||||
|
||||
|
||||
@@ -233,7 +219,6 @@ def test_segment_base_collapse_ends_at_the_last_byte(server, tmp_path):
|
||||
|
||||
DASH.download_track(make_track(segment_base_mpd(server), server), ctx)
|
||||
|
||||
# the media range ends at total - 1, so the truncate after the collapse adds no byte
|
||||
assert ctx.save_path.read_bytes() == PARENT
|
||||
|
||||
|
||||
@@ -249,7 +234,6 @@ def test_segment_base_unknown_total_fetches_the_rest_open_ended(server, tmp_path
|
||||
|
||||
|
||||
def test_leading_gap_that_is_not_a_sidx_takes_segmented_path(server, tmp_path):
|
||||
# a filtered period cut from the same file leaves a gap of media, not an index
|
||||
gap = struct.pack(">I", 1000) + b"moof" + bytes(992)
|
||||
media = bytes([0xC0]) * 3000
|
||||
server.routes["/media.mp4"] = PARENT[:INIT_LEN] + gap + media
|
||||
@@ -263,7 +247,6 @@ def test_leading_gap_that_is_not_a_sidx_takes_segmented_path(server, tmp_path):
|
||||
|
||||
|
||||
def test_sidx_indexing_more_than_the_listed_segments_takes_segmented_path(server, tmp_path):
|
||||
# the file carries a post-roll after the listed segments, and the sidx indexes it too
|
||||
media, post_roll = bytes([0xC0]) * 3000, bytes([0xEE]) * 500
|
||||
head = PARENT[:INIT_LEN] + sidx_box([len(media), len(post_roll)])
|
||||
server.routes["/media.mp4"] = head + media + post_roll
|
||||
@@ -275,7 +258,6 @@ def test_sidx_indexing_more_than_the_listed_segments_takes_segmented_path(server
|
||||
|
||||
|
||||
def test_init_from_another_file_takes_segmented_path(server, tmp_path):
|
||||
# the media ranges start where an init of the same length would end, but the init is elsewhere
|
||||
init = bytes([0x11]) * INIT_LEN
|
||||
server.routes["/init.bin"] = init
|
||||
server.routes["/media.mp4"] = PARENT
|
||||
@@ -297,12 +279,9 @@ def test_non_collapse_takes_segmented_merge_path(server, tmp_path):
|
||||
|
||||
DASH.download_track(track, ctx)
|
||||
|
||||
# merged output is init followed by both segments, in order
|
||||
assert ctx.save_path.read_bytes() == INIT2 + PART0 + PART1
|
||||
# both distinct segments were fetched -> genuinely the per-segment path, not a collapse
|
||||
fetched = {path for path, _ in server.requests}
|
||||
assert {"/part0.bin", "/part1.bin"} <= fetched
|
||||
# segment files are consumed and the segment dir is cleaned up after merge
|
||||
assert not list(ctx.save_dir.glob("*")) if ctx.save_dir.exists() else True
|
||||
|
||||
|
||||
@@ -317,8 +296,6 @@ def test_cancelled_sibling_does_not_report_missing_segments(server, tmp_path):
|
||||
with pytest.raises(DownloadCancelled):
|
||||
DASH.download_track(track, ctx)
|
||||
|
||||
# the workers returned early, so there is nothing to merge; a FileNotFoundError about the
|
||||
# missing segments here would mask the sibling failure that set the flag
|
||||
assert track.path is None
|
||||
assert not ctx.save_path.exists()
|
||||
|
||||
|
||||
@@ -12,8 +12,6 @@ def adaptation_set(scheme: str, value: str) -> ET.Element:
|
||||
@pytest.mark.parametrize(
|
||||
"scheme,value",
|
||||
[
|
||||
# "description" is the value the DASH role scheme defines. A service writes it, and reading only
|
||||
# "descriptive" left every audio-description track unflagged.
|
||||
("urn:mpeg:dash:role:2011", "description"),
|
||||
("urn:mpeg:dash:role:2011", "descriptive"),
|
||||
("urn:tva:metadata:cs:AudioPurposeCS:2007", "1"),
|
||||
@@ -40,7 +38,6 @@ def test_no_accessibility_element() -> None:
|
||||
|
||||
|
||||
def test_descriptive_role_element() -> None:
|
||||
# some manifests mark audio description with a Role and no Accessibility element
|
||||
element = ET.fromstring(
|
||||
'<AdaptationSet><Role schemeIdUri="urn:mpeg:dash:role:2011" value="description"/></AdaptationSet>'
|
||||
)
|
||||
|
||||
@@ -152,7 +152,6 @@ def test_segment_template_init_is_fetched_once_for_two_periods(server, probes, l
|
||||
|
||||
DASH.download_track(track, make_ctx(tmp_path))
|
||||
|
||||
# both periods contributed a segment, so period 1 was parsed, not skipped
|
||||
assert len(track.data["dash"]["segment_durations"]) == 2
|
||||
assert [path for path, _ in server.requests] == ["/p0/init.bin"]
|
||||
assert len(probes) == 1
|
||||
@@ -163,7 +162,6 @@ def test_segment_base_keeps_each_request_but_probes_once(server, probes, licence
|
||||
|
||||
DASH.download_track(track, make_ctx(tmp_path))
|
||||
|
||||
# media_range needs the init bytes of every period, so every period keeps its request
|
||||
assert [path for path, _ in server.requests] == ["/p0.mp4", "/p1.mp4"]
|
||||
assert len(probes) == 1
|
||||
|
||||
|
||||
@@ -51,20 +51,17 @@ def merge(
|
||||
|
||||
|
||||
def test_restarting_periods_follow_each_other(tmp_path: Path) -> None:
|
||||
# three periods of 10 s, 20 s and 5 s, each packaged with its own timeline from 0
|
||||
segments = [fragment(0), fragment(5000), fragment(0), fragment(10000), fragment(0, version=0)]
|
||||
merged = merge(tmp_path, segments, {0: (0, 10, 0), 2: (10, 20, 0), 4: (30, 5, 0)})
|
||||
assert tfdts(merged) == [0, 5000, 10000, 20000, 30000]
|
||||
|
||||
|
||||
def test_a_period_the_track_lacks_keeps_its_time(tmp_path: Path) -> None:
|
||||
# the track has no segments in the 20 s period between the two it holds
|
||||
merged = merge(tmp_path, [fragment(0), fragment(0)], {0: (0, 10, 0), 1: (30, 5, 0)})
|
||||
assert tfdts(merged) == [0, 30000]
|
||||
|
||||
|
||||
def test_presentation_time_offset_marks_the_period_start(tmp_path: Path) -> None:
|
||||
# the second period's first segment starts 500 ms before its presentationTimeOffset
|
||||
merged = merge(tmp_path, [fragment(0), fragment(1500)], {0: (0, 10, 0), 1: (10, 10, 2)})
|
||||
assert tfdts(merged) == [0, 9500]
|
||||
|
||||
@@ -75,7 +72,6 @@ def test_restart_below_the_previous_end_is_caught(tmp_path: Path) -> None:
|
||||
|
||||
|
||||
def test_continuous_timeline_is_unchanged(tmp_path: Path) -> None:
|
||||
# absolute timestamps with a filtered ad between the periods keep their gap
|
||||
segments = [fragment(0), fragment(5000), fragment(40000), fragment(45000)]
|
||||
assert merge(tmp_path, segments, {0: (0, 10, 0), 2: (10, 10, 0)}) == b"".join(segments)
|
||||
|
||||
@@ -149,7 +145,6 @@ def test_remote_fragment_writes_each_period_duration() -> None:
|
||||
tracks = mpd.to_tracks(language="en", period_filter=lambda period: period.get("id") == "ad")
|
||||
own = Tracks()
|
||||
own.add(tracks.videos[0])
|
||||
# a fragment is built for a track whose AdaptationSet is not in its manifest tree
|
||||
own.videos[0].data["dash"]["adaptation_set"] = etree.fromstring(
|
||||
etree.tostring(own.videos[0].data["dash"]["adaptation_set"])
|
||||
)
|
||||
@@ -231,7 +226,6 @@ def test_a_restart_after_a_continuous_gap_follows_the_previous_period(tmp_path:
|
||||
|
||||
|
||||
def test_a_period_back_on_the_first_timeline_leaves_the_restart_shift(tmp_path: Path) -> None:
|
||||
# an unfiltered 30 s ad restarts at 0 between two parts of one continuous timeline
|
||||
merged = merge(
|
||||
tmp_path, [fragment(0), fragment(0), fragment(600000)], {0: (0, 600, 0), 1: (600, 30, 0), 2: (630, 600, 600)}
|
||||
)
|
||||
|
||||
@@ -19,7 +19,6 @@ def test_no_placeholder_returns_unchanged() -> None:
|
||||
|
||||
|
||||
def test_printf_padding_applied() -> None:
|
||||
# the '%05d' padding path must still fire when a '%' spec is present
|
||||
url = "seg-$Number%05d$.mp4"
|
||||
assert DASH.replace_fields(url, Number=7) == "seg-00007.mp4"
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ TIMELINE_MPD = """
|
||||
</MPD>
|
||||
"""
|
||||
|
||||
# github.com/unshackle-dl/unshackle/issues/37: 96.72s at 6s per segment is 17 segments, 0 to 16, never a segment 17.
|
||||
DURATION_MPD = """
|
||||
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" mediaPresentationDuration="PT{seconds}S">
|
||||
<Period id="0" start="PT0S" duration="PT{seconds}S">
|
||||
@@ -48,10 +47,10 @@ def _numbers(mpd: str) -> list[int]:
|
||||
@pytest.mark.parametrize(
|
||||
("start", "count"),
|
||||
[
|
||||
(0, 5), # zero-based numbering
|
||||
(1, 5), # plain VOD
|
||||
(2642, 4667), # DVR catch-up: startNumber below segment count
|
||||
(5000, 10), # DVR catch-up: startNumber above segment count
|
||||
(0, 5),
|
||||
(1, 5),
|
||||
(2642, 4667),
|
||||
(5000, 10),
|
||||
],
|
||||
)
|
||||
def test_timeline_numbers_follow_start_number(start: int, count: int) -> None:
|
||||
@@ -80,10 +79,8 @@ TIME_MPD = """
|
||||
@pytest.mark.parametrize(
|
||||
("timeline", "starts"),
|
||||
[
|
||||
# a negative @r repeats to the end of the Period, or to the next S@t
|
||||
('<S t="0" d="20" r="-1"/>', [0, 20, 40, 60, 80]),
|
||||
('<S t="0" d="20" r="-1"/><S t="60" d="40"/>', [0, 20, 40, 60]),
|
||||
# an S with @p cycles the Pattern durations from index @pE
|
||||
('<Pattern id="1"><P d="10" r="1"/><P d="30"/></Pattern><S t="0" r="4" p="1" pE="1"/>', [0, 10, 40, 50, 60]),
|
||||
],
|
||||
)
|
||||
|
||||
@@ -60,7 +60,7 @@ def debug_log_with_keys(tmp_path: Path):
|
||||
|
||||
def test_every_line_is_valid_json_with_required_fields(debug_log: Path):
|
||||
log_event("sample_event", message="hi", context={"a": 1})
|
||||
close_debug_logger() # flush session_end
|
||||
close_debug_logger()
|
||||
entries = read_entries(debug_log)
|
||||
assert entries, "expected at least one JSONL entry"
|
||||
for e in entries:
|
||||
@@ -87,7 +87,7 @@ def test_log_event_emits_with_level_message_and_context(debug_log: Path):
|
||||
def test_log_event_noop_when_disabled():
|
||||
close_debug_logger()
|
||||
assert get_debug_logger() is None
|
||||
log_event("should_not_explode", message="no logger") # must not raise
|
||||
log_event("should_not_explode", message="no logger")
|
||||
|
||||
|
||||
def test_timed_operation_logs_success_and_duration(debug_log: Path):
|
||||
@@ -113,7 +113,7 @@ def test_timed_operation_logs_error_and_reraises(debug_log: Path):
|
||||
|
||||
def test_timed_operation_noop_when_disabled():
|
||||
close_debug_logger()
|
||||
with timed_operation("disabled_block"): # must not raise, must still run body
|
||||
with timed_operation("disabled_block"):
|
||||
value = 1 + 1
|
||||
assert value == 2
|
||||
|
||||
@@ -127,8 +127,8 @@ def test_sanitize_redacts_sensitive_key_names(debug_log: Path):
|
||||
"auth": "bearer x",
|
||||
"cookie": "sess=1",
|
||||
"secret": "s",
|
||||
"has_password": True, # has_ prefix stays
|
||||
"quality": "1080p", # non-secret stays
|
||||
"has_password": True,
|
||||
"quality": "1080p",
|
||||
}
|
||||
)
|
||||
assert cleaned["password"] == "[REDACTED]"
|
||||
@@ -141,16 +141,16 @@ def test_sanitize_redacts_sensitive_key_names(debug_log: Path):
|
||||
|
||||
|
||||
def test_sanitize_gates_key_fields_unless_log_keys(debug_log: Path):
|
||||
dl = get_debug_logger() # log_keys=False
|
||||
dl = get_debug_logger()
|
||||
cleaned = dl.sanitize_data({"content_key": "deadbeef", "kid": "00112233", "key_found": True, "key_count": 2})
|
||||
assert cleaned["content_key"] == "[REDACTED]" # redacted when log_keys False
|
||||
assert cleaned["kid"] == "00112233" # kid whitelisted
|
||||
assert cleaned["key_found"] is True # key_found whitelisted
|
||||
assert cleaned["key_count"] == 2 # _count whitelisted
|
||||
assert cleaned["content_key"] == "[REDACTED]"
|
||||
assert cleaned["kid"] == "00112233"
|
||||
assert cleaned["key_found"] is True
|
||||
assert cleaned["key_count"] == 2
|
||||
|
||||
|
||||
def test_sanitize_keeps_keys_when_log_keys_enabled(debug_log_with_keys: Path):
|
||||
dl = get_debug_logger() # log_keys=True
|
||||
dl = get_debug_logger()
|
||||
cleaned = dl.sanitize_data({"content_key": "deadbeef"})
|
||||
assert cleaned["content_key"] == "deadbeef"
|
||||
|
||||
@@ -172,9 +172,9 @@ def test_sanitize_collapses_urls(debug_log: Path):
|
||||
"proxy": "http://bob:secret@proxy.example:8080/x",
|
||||
}
|
||||
)
|
||||
assert cleaned["segment"] == "redacted.mp4" # extension kept, host/path/query gone
|
||||
assert cleaned["segment"] == "redacted.mp4"
|
||||
assert cleaned["manifest"] == "redacted.mpd"
|
||||
assert cleaned["proxy"] == "redacted" # userinfo + host never reaches disk
|
||||
assert cleaned["proxy"] == "redacted"
|
||||
|
||||
|
||||
def test_logged_content_url_is_collapsed_on_disk(debug_log: Path):
|
||||
@@ -220,7 +220,7 @@ def test_safe_display_url_strips_userinfo_and_query():
|
||||
("https://cdn.x/v/manifest.mpd", "redacted.mpd"),
|
||||
("https://cdn.x/v/playlist.m3u8", "redacted.m3u8"),
|
||||
("http://u:p@cdn.x/seg.m4s", "redacted.m4s"),
|
||||
("https://api.example/auth/token", "redacted"), # no extension
|
||||
("https://api.example/auth/token", "redacted"),
|
||||
],
|
||||
)
|
||||
def test_redact_url_collapses_to_redacted_ext(url: str, expected: str):
|
||||
@@ -236,7 +236,6 @@ def test_redact_url_handles_url_embedded_in_text():
|
||||
|
||||
|
||||
def test_redact_path_strips_install_root():
|
||||
# redact.py resolves the project/install root as the <unshackle> anchor.
|
||||
from unshackle.core.utils import redact as redact_mod
|
||||
|
||||
root = str(Path(redact_mod.__file__).resolve().parents[3])
|
||||
@@ -253,7 +252,6 @@ def test_redact_path_leaves_relative_paths_untouched():
|
||||
|
||||
|
||||
def test_redact_path_disabled_by_config(monkeypatch):
|
||||
# config.redact_paths: false shows full paths verbatim
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.utils import redact as redact_mod
|
||||
|
||||
@@ -287,12 +285,11 @@ def test_logged_output_dir_is_path_redacted(debug_log: Path):
|
||||
log_event("downloader_start", context={"output_dir": f"{root}/temp", "filename": "Audio_3eeab4ed.mp4"})
|
||||
e = find(read_entries(debug_log), "downloader_start")
|
||||
assert e["context"]["output_dir"] == "<unshackle>/temp"
|
||||
assert e["context"]["filename"] == "Audio_3eeab4ed.mp4" # bare filename untouched
|
||||
assert e["context"]["filename"] == "Audio_3eeab4ed.mp4"
|
||||
|
||||
|
||||
def test_log_drm_operation_accepts_message_and_level_override(debug_log: Path):
|
||||
dl = get_debug_logger()
|
||||
# Previously raised: TypeError: log() got multiple values for keyword argument 'message'
|
||||
dl.log_drm_operation("Widevine", "license_request", level="INFO", message="custom msg", kid="abc")
|
||||
e = find(read_entries(debug_log), "drm_license_request")
|
||||
assert e["message"] == "custom msg"
|
||||
@@ -339,4 +336,4 @@ def test_log_tool_run_failure_is_error(debug_log: Path):
|
||||
|
||||
def test_log_tool_run_noop_when_disabled():
|
||||
close_debug_logger()
|
||||
log_tool_run("ffmpeg", "ffmpeg", 0) # must not raise
|
||||
log_tool_run("ffmpeg", "ffmpeg", 0)
|
||||
|
||||
@@ -24,7 +24,6 @@ def test_a_var_keyword_function_gets_everything() -> None:
|
||||
|
||||
|
||||
def test_an_unreadable_signature_gets_everything() -> None:
|
||||
# min() has no readable signature, and a compiled service may not either
|
||||
assert declared_kwargs(min, SENT) == SENT
|
||||
|
||||
|
||||
|
||||
@@ -25,8 +25,6 @@ from typing import Optional
|
||||
import pytest
|
||||
from requests import Session
|
||||
|
||||
# the downloaders package re-exports a `requests` function that shadows this submodule
|
||||
# attribute, so fetch the real module object from sys.modules via importlib
|
||||
dl = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
|
||||
|
||||
@@ -39,14 +37,14 @@ 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.truncate_first = 0 # send only half the body + close, for the first N attempts
|
||||
self.attempts = 0
|
||||
self.ranges: list[Optional[str]] = []
|
||||
self.truncate_first = 0
|
||||
self._lock = threading.Lock()
|
||||
server = self
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_a: object) -> None: # silence
|
||||
def log_message(self, *_a: object) -> None:
|
||||
pass
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802 (stdlib name)
|
||||
@@ -61,7 +59,7 @@ class _FaultServer:
|
||||
if rng and rng.startswith("bytes="):
|
||||
start = int(rng.removeprefix("bytes=").split("-", 1)[0])
|
||||
|
||||
if start >= total: # unsatisfiable: real CDNs answer 416
|
||||
if start >= total:
|
||||
self.send_response(416)
|
||||
self.send_header("Content-Range", f"bytes */{total}")
|
||||
self.end_headers()
|
||||
@@ -69,8 +67,8 @@ class _FaultServer:
|
||||
|
||||
chunk = server.body[start:]
|
||||
partial = attempt <= server.truncate_first
|
||||
declared = len(chunk) # honest Content-Length...
|
||||
sent = chunk[: declared // 2] if partial else chunk # ...but under-deliver the body
|
||||
declared = len(chunk)
|
||||
sent = chunk[: declared // 2] if partial else chunk
|
||||
|
||||
if rng:
|
||||
self.send_response(206)
|
||||
@@ -80,7 +78,7 @@ class _FaultServer:
|
||||
self.send_header("Accept-Ranges", "bytes")
|
||||
self.send_header("Content-Length", str(declared))
|
||||
self.end_headers()
|
||||
self.wfile.write(sent) # short write + return => connection closes (clean FIN)
|
||||
self.wfile.write(sent)
|
||||
|
||||
self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
self._thread = threading.Thread(target=self._httpd.serve_forever, daemon=True)
|
||||
@@ -110,7 +108,7 @@ def test_truncated_segment_is_not_finalized(tmp_path: Path, monkeypatch: pytest.
|
||||
body = b"A" * 2000
|
||||
save = tmp_path / "seg.bin"
|
||||
with _FaultServer(body) as srv:
|
||||
srv.truncate_first = 99 # every attempt under-delivers
|
||||
srv.truncate_first = 99
|
||||
with pytest.raises(Exception):
|
||||
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"
|
||||
@@ -122,10 +120,9 @@ def test_interrupted_download_resumes_from_bytes_written(tmp_path: Path) -> None
|
||||
body = b"".join(bytes([i % 256]) for i in range(4000))
|
||||
save = tmp_path / "file.bin"
|
||||
with _FaultServer(body) as srv:
|
||||
srv.truncate_first = 1 # first attempt delivers half then closes; retry completes
|
||||
srv.truncate_first = 1
|
||||
consume(dl.download(url=srv.url, save_path=save, session=Session()))
|
||||
assert save.read_bytes() == body
|
||||
# attempt 1 had no Range; attempt 2 must resume partway in, not from 0 or past the end
|
||||
assert srv.ranges[0] is None
|
||||
resume_start = int(srv.ranges[1].removeprefix("bytes=").split("-", 1)[0])
|
||||
assert 0 < resume_start < len(body), f"resume offset {resume_start} not derived from bytes written"
|
||||
@@ -137,7 +134,7 @@ def test_resumes_from_preexisting_dev_partial(tmp_path: Path) -> None:
|
||||
body = b"".join(bytes([i % 256]) for i in range(4000))
|
||||
save = tmp_path / "file.bin"
|
||||
tmp = save.with_name("file.bin.!dev")
|
||||
tmp.write_bytes(body[:1500]) # correct prefix the interrupted run flushed to disk
|
||||
tmp.write_bytes(body[:1500])
|
||||
with _FaultServer(body) as srv:
|
||||
consume(dl.download(url=srv.url, save_path=save, session=Session()))
|
||||
assert save.read_bytes() == body
|
||||
@@ -156,7 +153,7 @@ def test_byte_range_slice_segments_never_probed_or_boosted(tmp_path: Path, monke
|
||||
"""
|
||||
seg = 2 * 1024 * 1024
|
||||
nseg = 8
|
||||
body = b"".join(bytes([i]) * seg for i in range(nseg)) # 16 MiB, distinct byte per slice
|
||||
body = b"".join(bytes([i]) * seg for i in range(nseg))
|
||||
|
||||
barrier_count = [0]
|
||||
barrier_lock = threading.Lock()
|
||||
@@ -172,7 +169,7 @@ def test_byte_range_slice_segments_never_probed_or_boosted(tmp_path: Path, monke
|
||||
barrier_count[0] += 1
|
||||
if barrier_count[0] >= 6:
|
||||
barrier.set()
|
||||
barrier.wait(5) # cluster the first six completions; auto-release as a safety net
|
||||
barrier.wait(5)
|
||||
start, _, end_s = rng.removeprefix("bytes=").partition("-")
|
||||
start = int(start or 0)
|
||||
end = int(end_s) if end_s else len(body) - 1
|
||||
@@ -224,8 +221,8 @@ def test_oversized_resume_416_restarts_clean(tmp_path: Path) -> None:
|
||||
body = b"Z" * 1500
|
||||
save = tmp_path / "file.bin"
|
||||
tmp = save.with_name(f"{save.name}.!dev")
|
||||
tmp.write_bytes(b"X" * 4096) # poisoned partial, bigger than the server's body
|
||||
tmp.write_bytes(b"X" * 4096)
|
||||
with _FaultServer(body) as srv:
|
||||
consume(dl.download(url=srv.url, save_path=save, session=Session()))
|
||||
assert save.read_bytes() == body
|
||||
assert srv.ranges[0] is not None and "4096" in srv.ranges[0] # first request over-ranged → 416
|
||||
assert srv.ranges[0] is not None and "4096" in srv.ranges[0]
|
||||
|
||||
@@ -13,8 +13,8 @@ from unshackle.core.providers.tvdb import primary_language as tvdb_language
|
||||
@pytest.mark.parametrize(
|
||||
("tag", "expected"),
|
||||
[
|
||||
("ja", "ja"), # TMDB alpha-2
|
||||
("jpn", "ja"), # IMDb alpha-3
|
||||
("ja", "ja"),
|
||||
("jpn", "ja"),
|
||||
("pt-BR", "pt-BR"),
|
||||
(None, None),
|
||||
("", None),
|
||||
@@ -43,7 +43,7 @@ def test_imdb_language_is_alpha_2() -> None:
|
||||
"data",
|
||||
[
|
||||
{},
|
||||
{"spokenLanguages": None}, # search hits can come back with the whole block null
|
||||
{"spokenLanguages": None},
|
||||
{"spokenLanguages": {}},
|
||||
{"spokenLanguages": {"spokenLanguages": []}},
|
||||
{"spokenLanguages": {"spokenLanguages": None}},
|
||||
@@ -57,9 +57,9 @@ def test_imdb_language_missing(data: dict) -> None:
|
||||
("names", "expected"),
|
||||
[
|
||||
("Korean", "ko"),
|
||||
("Korean, English", "ko"), # OMDb lists the main language first
|
||||
("Korean, English", "ko"),
|
||||
("", None),
|
||||
("None", None), # OMDb's literal placeholder for unknown
|
||||
("None", None),
|
||||
("Not A Language", None),
|
||||
],
|
||||
)
|
||||
@@ -70,8 +70,8 @@ def test_omdb_language_from_english_name(names: str, expected: str | None) -> No
|
||||
@pytest.mark.parametrize(
|
||||
("data", "expected"),
|
||||
[
|
||||
({"primary_language": "kor"}, "kor"), # /search
|
||||
({"originalLanguage": "kor"}, "kor"), # /series/{id}/extended
|
||||
({"primary_language": "kor"}, "kor"),
|
||||
({"originalLanguage": "kor"}, "kor"),
|
||||
({"primary_language": ""}, None),
|
||||
({}, None),
|
||||
],
|
||||
|
||||
@@ -51,8 +51,8 @@ def test_air_date_replaces_season_episode_dotted(reset_template):
|
||||
assert ctx["season_episode"] == "2024.06.30"
|
||||
assert ctx["season"] == "2024.06.30"
|
||||
assert ctx["episode"] == ""
|
||||
assert ctx["year"] == "" # date carries the year
|
||||
assert ctx["date"] == "2024-06-30" # ISO regardless of separator
|
||||
assert ctx["year"] == ""
|
||||
assert ctx["date"] == "2024-06-30"
|
||||
|
||||
|
||||
def test_air_date_uses_space_separator(reset_template):
|
||||
@@ -106,7 +106,7 @@ def test_dated_folder_groups_by_year(reset_template):
|
||||
reset_template.folder_template = ""
|
||||
folder = make_episode(air_date=date(2024, 6, 30)).get_filename(StubMediaInfo(), folder=True)
|
||||
assert "2024" in folder
|
||||
assert "S2024" not in folder # season folder is the year, not the faked season
|
||||
assert "S2024" not in folder
|
||||
|
||||
|
||||
def test_dated_folder_drops_year_matching_air_year(reset_template):
|
||||
|
||||
@@ -86,8 +86,6 @@ def test_str_shows_the_selection_syntax():
|
||||
|
||||
|
||||
def test_str_tells_dated_parts_apart():
|
||||
# dated content renders the air date instead of SxxExx, so without the suffix both
|
||||
# parts print the same string while their filenames differ
|
||||
assert str(make_episode(part=2, air_date="2024-05-06")) == "The Show 2024.05.06.2 The Reckoning"
|
||||
assert str(make_episode(air_date="2024-05-06")) == "The Show 2024.05.06 The Reckoning"
|
||||
|
||||
@@ -126,7 +124,7 @@ def test_filename_is_unchanged_without_a_part(reset_template):
|
||||
def test_dotted_template_folds_the_part_after_the_episode(reset_template):
|
||||
name = make_episode(part=2).get_filename(StubMediaInfo())
|
||||
assert name == "The.Show.S01E01.Part.2.DummyService-GROUP"
|
||||
assert name.endswith("-GROUP") # group tag stays last
|
||||
assert name.endswith("-GROUP")
|
||||
|
||||
|
||||
def test_spaced_template_uses_spaces(reset_template):
|
||||
@@ -147,7 +145,6 @@ def test_part_token_is_empty_without_a_part(reset_template):
|
||||
|
||||
|
||||
def test_parts_share_one_season_folder(reset_template):
|
||||
# {season_episode} in a folder template would otherwise carry the part into the path
|
||||
reset_template.folder_template = "{title}/{season_episode}"
|
||||
folders = {make_episode(part=p).get_filename(StubMediaInfo(), folder=True) for p in (1, 2)}
|
||||
assert folders == {"The.Show/S01E01"}
|
||||
@@ -159,7 +156,6 @@ def test_parts_share_one_derived_season_folder(reset_template):
|
||||
assert folders == {make_episode().get_filename(StubMediaInfo(), folder=True)}
|
||||
|
||||
|
||||
# the worked key scheme from the design: (token, part-less E1 selected, E1 part 2 selected)
|
||||
MATCH_TABLE = [
|
||||
(("S01",), True, True),
|
||||
(("S01E01",), True, True),
|
||||
|
||||
@@ -44,7 +44,6 @@ class StubDRM:
|
||||
|
||||
|
||||
def make_dl() -> dl:
|
||||
# __new__ skips the CLI-driven __init__; write_export only needs `service` and `log`.
|
||||
instance = dl.__new__(dl)
|
||||
instance.service = "EXAMPLE"
|
||||
instance.log = logging.getLogger("download")
|
||||
@@ -86,7 +85,6 @@ def make_title() -> Movie:
|
||||
|
||||
|
||||
def import_ctx() -> click.Context:
|
||||
# ImportService only touches ctx.parent.params (proxy flags) when building its session.
|
||||
return cast(click.Context, SimpleNamespace(parent=None, params={}))
|
||||
|
||||
|
||||
@@ -137,8 +135,8 @@ def test_post_download_write_keeps_licensed_keys(tmp_path: Path) -> None:
|
||||
video = title.tracks.videos[0]
|
||||
runner = make_dl()
|
||||
|
||||
runner.write_export(export, title, video, StubDRM()) # prepare_drm
|
||||
runner.write_export(export, title, video) # post-download hook
|
||||
runner.write_export(export, title, video, StubDRM())
|
||||
runner.write_export(export, title, video)
|
||||
|
||||
tinfo = entry(export)
|
||||
assert tinfo["drm"] == [{"system": "widevine", "pssh": "AAAA"}]
|
||||
@@ -174,7 +172,6 @@ def test_drm_free_export_roundtrips_through_import_service(tmp_path: Path) -> No
|
||||
svc.resolve_server_keys(movie)
|
||||
assert all(not t.drm for t in movie.tracks)
|
||||
|
||||
# Chapters.add auto-inserts a nameless 00:00:00 baseline chapter; it round-trips too.
|
||||
assert [c.name for c in svc.get_chapters(movie)] == [None, "Intro"]
|
||||
|
||||
|
||||
|
||||
@@ -182,7 +182,6 @@ def test_collision_gets_a_suffix(tmp_path: Path) -> None:
|
||||
assert other.read_text() == "{}"
|
||||
assert moved.read_text() == "mine"
|
||||
assert not current.exists()
|
||||
# the run's own file keeps its suffix instead of moving on to -3
|
||||
assert move_export(moved, "Example.Movie.2024-EXAMPLE") == moved
|
||||
|
||||
|
||||
|
||||
@@ -22,8 +22,7 @@ pytestmark = pytest.mark.skipif(binaries.FFMPEG is None, reason="requires ffmpeg
|
||||
KID = "00000000098ac6820000000000000000"
|
||||
KEY = "13c795e9383efc0387c0bad6a10df73f"
|
||||
WRONG_KEY = "00000000000000000000000000000000"
|
||||
IV = "0123456789abcdef" # the packager's random IV would change the wrong-key noise on each run
|
||||
# 24 fps with a keyframe every 48 frames: one 2 s GOP for each 2 s fragment.
|
||||
IV = "0123456789abcdef"
|
||||
GOP_PARAMS = "keyint=48:min-keyint=48:scenecut=0"
|
||||
GOP = ["-x264-params", GOP_PARAMS]
|
||||
|
||||
@@ -51,7 +50,6 @@ def video(out: Path, *x264: str, codec: str = "libx264", size: str = "320x180")
|
||||
|
||||
|
||||
def test_audio_only_passes_fallback(tmp_path: Path) -> None:
|
||||
# -skip_frame on a file with no video decoder makes FFmpeg refuse to open it.
|
||||
audio = ffmpeg(tmp_path / "a.m4a", "sine=f=440:duration=12", "-c:a", "aac")
|
||||
assert ffmpeg_decodes(audio)
|
||||
assert ffmpeg_decodes(audio, video=False)
|
||||
@@ -64,7 +62,6 @@ def test_mpegts_video_passes_fallback(tmp_path: Path) -> None:
|
||||
|
||||
|
||||
def test_open_gop_passes_windows(tmp_path: Path) -> None:
|
||||
# The B-frames before each open-GOP keyframe refer to the GOP before the window.
|
||||
og = video(tmp_path / "og.mp4", "-x264-params", f"open-gop=1:{GOP_PARAMS}:bframes=3")
|
||||
assert all(ffmpeg_decodes(og, start=start, seconds=2, video=True) for start in (2.0, 4.0, 6.0, 8.0))
|
||||
|
||||
@@ -79,10 +76,6 @@ def test_open_gop_hevc_passes_windows(tmp_path: Path) -> None:
|
||||
assert all(ffmpeg_decodes(og, start=start, seconds=2, video=True) for start in (2.0, 4.0, 6.0, 8.0))
|
||||
|
||||
|
||||
# An HEVC keyframe decrypted with a wrong key can decode without an error, so the HEVC cases
|
||||
# prove that the check decodes the frames after it too. HEVC noise trips fewer decoder checks
|
||||
# in a small frame, and a 320x180 window often decodes clean, so the HEVC clips are 640x360.
|
||||
# Each param is the x265 params to add, or None for H.264.
|
||||
@pytest.fixture(
|
||||
scope="module",
|
||||
params=[None, "", ":open-gop=1"],
|
||||
@@ -136,14 +129,11 @@ def test_right_key_passes_every_window(encrypted: tuple[KidMap, Path, Path]) ->
|
||||
|
||||
|
||||
def test_wrong_key_fails_the_kid(encrypted: tuple[KidMap, Path, Path]) -> None:
|
||||
# One failed window flags the KID, so one clean window of noise does not hide a wrong key.
|
||||
kid_map, _, wrong = encrypted
|
||||
assert not all(windows_pass(kid_map, wrong))
|
||||
|
||||
|
||||
def test_wrong_key_passes_the_clear_lead(encrypted: tuple[KidMap, Path, Path]) -> None:
|
||||
# The window ends where the encrypted fragment starts, and B-frames put that fragment's
|
||||
# keyframe first in decode order: the decoder must not get it.
|
||||
kid_map, _, wrong = encrypted
|
||||
lead = kid_map.windows[UUID(KID)][0][0]
|
||||
assert ffmpeg_decodes(wrong, start=0.0, seconds=lead, video=True)
|
||||
|
||||
@@ -80,7 +80,6 @@ def licence_only(text: str, tmp_path: Path) -> list[tuple[list[UUID], Any]]:
|
||||
|
||||
|
||||
def test_download_track_licenses_with_the_init_segment_kid(tmp_path: Path, monkeypatch: Any) -> None:
|
||||
# the probe itself needs the network and FFprobe; the order of the calls is under test
|
||||
monkeypatch.setattr(HLS, "get_track_kid_from_init", staticmethod(lambda *args, **kwargs: INIT_KID))
|
||||
assert licence_only(playlist(keyed_segment(NO_KID_PSSH)), tmp_path) == [([INIT_KID], INIT_KID)]
|
||||
|
||||
|
||||
@@ -54,7 +54,6 @@ def test_licence_only_licenses_a_key_that_starts_part_way(tmp_path: Path, monkey
|
||||
codec=Video.Codec.HEVC,
|
||||
)
|
||||
track.from_file = playlist
|
||||
# the KID normally comes from the init segment; this test is offline
|
||||
monkeypatch.setattr(HLS, "get_track_kid_from_init", staticmethod(lambda *args, **kwargs: None))
|
||||
|
||||
licensed: list[UUID] = []
|
||||
|
||||
@@ -50,7 +50,6 @@ def test_failed_ffmpeg_concat_writes_nothing_to_the_terminal(
|
||||
tmp_path: Path, segments: list[Path], monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
def fake_run(args, **kwargs):
|
||||
# emulate the child: with no capture it writes straight to the inherited terminal
|
||||
if not kwargs.get("capture_output") and kwargs.get("stderr") is None:
|
||||
os.write(2, (FFMPEG_ERROR + "\n").encode())
|
||||
raise subprocess.CalledProcessError(1, args)
|
||||
@@ -94,7 +93,6 @@ def test_binary_concat_advances_progress_per_segment(tmp_path: Path, monkeypatch
|
||||
segments.append(seg)
|
||||
|
||||
calls: list[dict] = []
|
||||
# no ffmpeg binary means merge_segments takes the binary fallback
|
||||
monkeypatch.setattr("unshackle.core.manifests.hls.binaries.FFMPEG", None)
|
||||
HLS.merge_segments(
|
||||
segments=segments,
|
||||
|
||||
@@ -71,7 +71,6 @@ def test_session_data_unknown_keyformat_is_dropped() -> None:
|
||||
|
||||
def test_session_data_plain_json_value_is_parsed() -> None:
|
||||
manifest = _master("placeholder")
|
||||
# a quoted attribute cannot hold raw JSON quotes, so set the value after parsing
|
||||
manifest.session_data[0].value = json.dumps([_item("SAMPLE-AES-CTR", WV_URN)])
|
||||
keys = HLS.parse_session_data_keys(manifest)
|
||||
assert len(keys) == 1
|
||||
|
||||
@@ -33,7 +33,6 @@ def test_restarting_blocks_move_to_their_playlist_start() -> None:
|
||||
|
||||
|
||||
def test_absolute_cue_times_are_not_changed() -> None:
|
||||
# a cue carried over the block boundary starts just before the block, not before its middle
|
||||
texts = [block("00:00:01.000"), block("00:09:58.000", "00:10:05.000")]
|
||||
assert rebase(texts, [0, 600000, 1200000]) == texts
|
||||
|
||||
|
||||
@@ -161,7 +161,6 @@ def test_zero_light_levels_are_filled_from_the_probe(monkeypatch: pytest.MonkeyP
|
||||
assert written["max_content_light_level"] == 588
|
||||
assert written["max_frame_average_light_level"] == 148
|
||||
assert written["max_display_mastering_luminance"] == 1000
|
||||
# The RPU mastering display wins over the probed 50; only unset values come from the probe.
|
||||
assert written["min_display_mastering_luminance"] == 1
|
||||
assert obj.rpu_file == "RPU_L6.bin"
|
||||
|
||||
|
||||
@@ -78,7 +78,6 @@ def test_persisted_query_miss_falls_back_to_one_post(monkeypatch: pytest.MonkeyP
|
||||
result = p.get_by_id("tt3581920", "tv")
|
||||
assert result is not None and result.external_ids.imdb_id == "tt3581920"
|
||||
assert len(session.gets) == 1 and len(session.posts) == 1
|
||||
# the POST registers the query by sending its text, keyed by the same hash the GET sent
|
||||
assert "query UnshackleTitle" in session.posts[0]["query"]
|
||||
sent_hash = json.loads(session.gets[0]["extensions"])["persistedQuery"]["sha256Hash"]
|
||||
assert session.posts[0]["extensions"]["persistedQuery"]["sha256Hash"] == sent_hash
|
||||
|
||||
@@ -87,7 +87,6 @@ def test_import_rejects_a_file_that_is_not_an_export(tmp_path: Path, forwarded:
|
||||
export = tmp_path / "export.json"
|
||||
export.write_text(json.dumps({"hello": "world"}), encoding="utf-8")
|
||||
|
||||
# rich-click wraps the error panel to the terminal width, so a long tmp path can split the phrase in the output
|
||||
result = CliRunner().invoke(import_cli, [str(export)], standalone_mode=False)
|
||||
|
||||
assert result.exit_code != 0
|
||||
|
||||
@@ -179,7 +179,7 @@ def test_hls_tracks_tolerate_the_empty_manifest_data(tmp_path: Path) -> None:
|
||||
|
||||
track = tracks.videos[0]
|
||||
assert not track.data.get("hls"), "to_dict cannot carry the m3u8 objects, and does not need to"
|
||||
track.data["hls"]["segment_durations"] = [1, 2, 3] # hls.py, in download_track
|
||||
track.data["hls"]["segment_durations"] = [1, 2, 3]
|
||||
assert track.data["hls"]["segment_durations"] == [1, 2, 3]
|
||||
|
||||
|
||||
@@ -188,7 +188,7 @@ def test_hls_round_trip_keeps_the_dropped_segments(tmp_path: Path) -> None:
|
||||
original = HLS.from_text(HLS_MANIFEST, HLS_URL).to_tracks(language="en")
|
||||
video = original.videos[0]
|
||||
dropped = "https://cdn.example/bumper_1.m4s?token=a"
|
||||
video.data["hls"]["unwanted_segments"] = [dropped] # hls.py, in download_track
|
||||
video.data["hls"]["unwanted_segments"] = [dropped]
|
||||
|
||||
export = export_tracks(tmp_path, original, HLS_URL)
|
||||
_, tracks = import_tracks(export)
|
||||
|
||||
@@ -83,7 +83,6 @@ def test_export_without_manifest_url_still_rebuilds_dash_manifest_data(tmp_path:
|
||||
tracks = service.get_tracks(next(iter(service.get_titles())))
|
||||
|
||||
assert [t.id for t in tracks.videos] == ["v-avc"]
|
||||
# DASH.download_track reads all three of these; a missing one is a KeyError mid-download.
|
||||
assert set(tracks.videos[0].data.get("dash", {})) >= {"manifest", "adaptation_set", "representation"}
|
||||
|
||||
|
||||
@@ -106,7 +105,6 @@ def test_exported_hevc_on_its_own_mpd_survives_the_reparse(tmp_path: Path) -> No
|
||||
assert "HEVC" in codecs, "the exported HEVC track was dropped, so -v h.265 has nothing to select"
|
||||
hevc = next(t for t in tracks.videos if t.codec and t.codec.name == "HEVC")
|
||||
assert set(hevc.data.get("dash", {})) >= {"manifest", "adaptation_set", "representation"}
|
||||
# bound to its own manifest's representation, not just to any populated mapping
|
||||
assert hevc.data["dash"]["representation"].get("id") == "v-hevc"
|
||||
|
||||
|
||||
|
||||
@@ -38,8 +38,6 @@ MPD_TEMPLATE = """<?xml version="1.0"?>
|
||||
</MPD>
|
||||
"""
|
||||
|
||||
# labelled by @lang; unlabelled but with Unified Streaming ids DASH derives a language from;
|
||||
# and labelled by neither, which is the only shape that needs the title's language
|
||||
MPD_WITH_LANG = MPD_TEMPLATE.format(lang=' lang="ja"', video_id="v1", sub_id="s1")
|
||||
MPD_ID_LANG = MPD_TEMPLATE.format(lang="", video_id="video_eng=5000000", sub_id="text_eng=1000")
|
||||
MPD_NO_LANG = MPD_TEMPLATE.format(lang="", video_id="v1", sub_id="s1")
|
||||
|
||||
+33
-123
@@ -33,21 +33,15 @@ from unshackle.core.manifests.ism_init import (
|
||||
synthesize_aac_codec_private_data,
|
||||
)
|
||||
|
||||
# Real CodecPrivateData taken from a Smooth Streaming manifest.
|
||||
VIDEO_HEVC_CPD = (
|
||||
"0000000140010C01FFFF01600000030090000003000003009695980900000001420101016000000300900000"
|
||||
"030000030096A001E020064165959A4930BC05A80808082000007D20000BB801000000014401C172B66240"
|
||||
)
|
||||
# H.264 SPS+PPS (start-code delimited) for the AVC path.
|
||||
VIDEO_AVC_CPD = "00000001674d401e9a6602800b76020000003e90000bb800f18311200000000168ebccb22c"
|
||||
# 10-bit (Main 10) HEVC VPS+SPS+PPS minted with x265; ffprobe reads the
|
||||
# synthesized init as "Main 10 / yuv420p10le".
|
||||
VIDEO_HEVC10_CPD = (
|
||||
"0000000140010c01ffff02200000030090000003000003003c959809000000000142010102200000030090"
|
||||
"000003000003003ca00a080b9f6d96566924caf0168080000003008000000c8400000000014401c172b4624000"
|
||||
)
|
||||
# HEVC VPS+SPS+PPS minted with x265, explicit SPS VUI colour signalling:
|
||||
# PQ (bt2020/smpte2084/bt2020nc), HLG (arib-std-b67) and BT.709 SDR.
|
||||
VIDEO_HEVC_PQ_CPD = (
|
||||
"0000000140010c01ffff02200000030090000003000003001e9598090000000142010102200000030090000003000003001ea020"
|
||||
"8104d96566924caf016a12201208000003000800000300c840000000014401c172b42240"
|
||||
@@ -60,17 +54,12 @@ VIDEO_HEVC_SDR_CPD = (
|
||||
"0000000140010c01ffff02200000030090000003000003001e9598090000000142010102200000030090000003000003001ea020"
|
||||
"8104d96566924caf016a02020208000003000800000300c840000000014401c172b42240"
|
||||
)
|
||||
# Real Dolby Vision (dvhe, DoViProfile "stn") CodecPrivateData from a Smooth
|
||||
# manifest: NALs arrive SPS,PPS,VPS (VPS last) and the VUI colour triple is
|
||||
# Unspecified (2,2,2): DV is signalled by FourCC only, never by CICP.
|
||||
VIDEO_HEVC_DV_CPD = (
|
||||
"00000001420101022000000300B00000030000030096A001E020021C4D9457B91CAF016E0404042800001F480002EE0401F4E1"
|
||||
"15EE7E0001312D00002FAF0C80000000014401C1ACBE0EC90000000140010C01FFFF022000000300B00000030000030096"
|
||||
"15C0C00000FA40001770200FA680"
|
||||
)
|
||||
AAC_LC_CPD = "1190"
|
||||
# Real Smooth EC-3 CodecPrivateData: WAVEFORMATEXTENSIBLE extension (samples
|
||||
# per block + channel mask + DD+ GUID) followed by the 5-byte dec3 payload.
|
||||
EC3_CPD = "00063F000000AF87FBA7022DFB42A4D405CD93843BDD0600200F00"
|
||||
KID = bytes.fromhex("09fd2bd778bb544785ed2322dc6a7d87")
|
||||
|
||||
@@ -91,7 +80,6 @@ def top_level_boxes(data: bytes) -> list[tuple[str, int]]:
|
||||
|
||||
def test_split_nal_units_drops_start_codes():
|
||||
nals = split_nal_units(bytes.fromhex(VIDEO_HEVC_CPD))
|
||||
# VPS (32), SPS (33), PPS (34) by HEVC NAL type = (first_byte >> 1) & 0x3F.
|
||||
assert [(n[0] >> 1) & 0x3F for n in nals] == [32, 33, 34]
|
||||
|
||||
|
||||
@@ -109,13 +97,9 @@ def test_hevc_init_structure():
|
||||
assert boxes[0][1] + boxes[1][1] == len(init)
|
||||
assert b"hvcC" in init
|
||||
assert b"hvc1" in init
|
||||
# Unencrypted: no protection scheme boxes.
|
||||
assert b"encv" not in init and b"sinf" not in init
|
||||
|
||||
|
||||
# Boxes whose payload is purely child boxes, so their size must span the children
|
||||
# exactly. stsd is excluded: its payload starts with a count, and sample entries
|
||||
# carry a fixed prefix before any child box.
|
||||
CONTAINER_BOXES = {"moov", "trak", "mdia", "minf", "stbl", "dinf", "mvex", "sinf", "schi"}
|
||||
|
||||
|
||||
@@ -157,8 +141,6 @@ def sample_entry_bounds(init: bytes) -> tuple[int, int]:
|
||||
return stsd + 16, stsd + 16 + entry_size
|
||||
|
||||
|
||||
# The two-entry stsd is unconditional, so every stream type and codec the builder
|
||||
# emits needs covering, encrypted and clear alike.
|
||||
STSD_CASES = [
|
||||
("video", "HVC1", VIDEO_HEVC_CPD, KID, b"encv", {"width": 3840, "height": 2160}),
|
||||
("video", "HVC1", VIDEO_HEVC_CPD, None, b"hvc1", {"width": 3840, "height": 2160}),
|
||||
@@ -171,8 +153,6 @@ STSD_CASES = [
|
||||
|
||||
@pytest.mark.parametrize("stream_type,fourcc,cpd,kid,expected_4cc,extra", STSD_CASES)
|
||||
def test_stsd_carries_two_entries_for_sample_description_index_2(stream_type, fourcc, cpd, kid, expected_4cc, extra):
|
||||
# A single entry leaves tfhd sample_description_index=2 dangling, and mp4decrypt
|
||||
# skips those fragments without a word: exit 0, empty stderr, still encrypted.
|
||||
init = build_init_segment(
|
||||
stream_type=stream_type,
|
||||
fourcc=fourcc,
|
||||
@@ -190,9 +170,7 @@ def test_stsd_carries_two_entries_for_sample_description_index_2(stream_type, fo
|
||||
entries.append(init[cursor : cursor + size])
|
||||
cursor += size
|
||||
assert [e[4:8] for e in entries] == [expected_4cc, expected_4cc]
|
||||
# stsd must span its header, count and both entries exactly.
|
||||
assert struct.unpack_from(">I", init, offset)[0] == 16 + sum(len(e) for e in entries)
|
||||
# The same has to hold for every container box wrapping it.
|
||||
walk_box(init, 0, len(init))
|
||||
|
||||
|
||||
@@ -219,7 +197,7 @@ def test_aac_audio_init_structure():
|
||||
sampling_rate=48000,
|
||||
)
|
||||
assert b"mp4a" in init and b"esds" in init
|
||||
assert b"smhd" in init # sound media header, not video
|
||||
assert b"smhd" in init
|
||||
|
||||
|
||||
def test_encrypted_init_has_cenc_boxes():
|
||||
@@ -232,18 +210,14 @@ def test_encrypted_init_has_cenc_boxes():
|
||||
height=1600,
|
||||
kid=KID,
|
||||
)
|
||||
# Encrypted sample entry is wrapped: encv -> sinf(frma+schm+schi(tenc)).
|
||||
assert b"encv" in init
|
||||
assert b"sinf" in init and b"frma" in init and b"tenc" in init
|
||||
assert b"cenc" in init
|
||||
# The 16-byte default_KID must be embedded verbatim for shaka to map the key.
|
||||
assert KID in init
|
||||
# Original codec preserved inside frma for the muxer.
|
||||
assert b"hvc1" in init
|
||||
|
||||
|
||||
def test_unsupported_codec_raises():
|
||||
# Unknown FourCC (e.g. VC-1); caller soft-fails to raw concat.
|
||||
with pytest.raises(NotImplementedError):
|
||||
build_init_segment(
|
||||
stream_type="video",
|
||||
@@ -263,9 +237,8 @@ def test_ec3_init_embeds_dec3_from_codec_private_data():
|
||||
sampling_rate=48000,
|
||||
)
|
||||
assert b"ec-3" in init
|
||||
# dec3 payload = CodecPrivateData past the 22-byte WAVEFORMATEXTENSIBLE header.
|
||||
assert box(b"dec3", bytes.fromhex(EC3_CPD)[22:]) in init
|
||||
assert b"esds" not in init # no MPEG-4 descriptor inside an ec-3 entry
|
||||
assert b"esds" not in init
|
||||
|
||||
|
||||
def test_ec3_encrypted_wraps_enca_with_frma():
|
||||
@@ -283,8 +256,6 @@ def test_ec3_encrypted_wraps_enca_with_frma():
|
||||
|
||||
|
||||
def test_ec3_dec3_found_in_full_waveformatextensible():
|
||||
# Some services ship the full WAVEFORMATEX header (18 bytes) before the
|
||||
# extension; the dec3 payload still follows the DD+ GUID.
|
||||
full = b"\xfe\xff" + b"\x00" * 16 + bytes.fromhex(EC3_CPD)
|
||||
payload = bytes.fromhex(EC3_CPD)[22:]
|
||||
assert build_dec3(full) == box(b"dec3", payload)
|
||||
@@ -303,15 +274,13 @@ def test_ec3_without_dolby_guid_builds_bare_entry():
|
||||
|
||||
|
||||
def test_aac_codec_private_data_synthesis_matches_real_manifest():
|
||||
# 48 kHz stereo AAC-LC must produce 0x1190, the exact ASC real manifests carry.
|
||||
assert synthesize_aac_codec_private_data("AACL", 48000, 2).hex() == "1190"
|
||||
|
||||
|
||||
def test_aach_synthesis_signals_sbr():
|
||||
asc = synthesize_aac_codec_private_data("AACH", 24000, 2)
|
||||
assert len(asc) == 4
|
||||
assert asc[0] >> 3 == 0x05 # AOT 5 = SBR (HE-AAC)
|
||||
# Extension sampling frequency = core * 2 = 48 kHz (index 3).
|
||||
assert asc[0] >> 3 == 0x05
|
||||
assert ((asc[1] & 0x01) << 1) | (asc[2] >> 7) == 0x03
|
||||
|
||||
|
||||
@@ -352,7 +321,6 @@ def test_davc_maps_to_avc1():
|
||||
|
||||
|
||||
def test_lowercase_fourcc_normalized():
|
||||
# Real manifests ship FourCC="hvc1" in lowercase.
|
||||
init = build_init_segment(
|
||||
stream_type="video",
|
||||
fourcc="hvc1",
|
||||
@@ -364,30 +332,28 @@ def test_lowercase_fourcc_normalized():
|
||||
|
||||
def test_avcc_selects_sps_pps_by_nal_type_not_position():
|
||||
nals = split_nal_units(bytes.fromhex(VIDEO_AVC_CPD))
|
||||
swapped = NAL_START_CODE + nals[1] + NAL_START_CODE + nals[0] # PPS first
|
||||
swapped = NAL_START_CODE + nals[1] + NAL_START_CODE + nals[0]
|
||||
avcc = build_avcc(swapped)
|
||||
# Profile/compat/level must still come from the SPS body.
|
||||
assert avcc[9:12] == nals[0][1:4]
|
||||
|
||||
|
||||
def test_nal_length_field_respected():
|
||||
avcc = build_avcc(bytes.fromhex(VIDEO_AVC_CPD), nal_length_size=2)
|
||||
# avcC payload byte 4 low 2 bits = lengthSizeMinusOne.
|
||||
assert avcc[12] & 0x03 == 1
|
||||
|
||||
|
||||
def test_parse_hevc_sps_format_8bit():
|
||||
sps = split_nal_units(bytes.fromhex(VIDEO_HEVC_CPD))[1]
|
||||
assert parse_hevc_sps_format(remove_emulation_prevention(sps)) == (1, 0, 0) # 4:2:0, 8-bit
|
||||
assert parse_hevc_sps_format(remove_emulation_prevention(sps)) == (1, 0, 0)
|
||||
|
||||
|
||||
def test_hvcc_signals_10bit_from_sps():
|
||||
sps = next(n for n in split_nal_units(bytes.fromhex(VIDEO_HEVC10_CPD)) if (n[0] >> 1) & 0x3F == 33)
|
||||
assert parse_hevc_sps_format(remove_emulation_prevention(sps)) == (1, 2, 2) # 4:2:0, 10-bit
|
||||
payload = build_hvcc(bytes.fromhex(VIDEO_HEVC10_CPD))[8:] # strip box header
|
||||
assert payload[16] == 0xFC | 0x01 # chromaFormat 4:2:0
|
||||
assert payload[17] == 0xF8 | 0x02 # bitDepthLumaMinus8 = 2
|
||||
assert payload[18] == 0xF8 | 0x02 # bitDepthChromaMinus8 = 2
|
||||
assert parse_hevc_sps_format(remove_emulation_prevention(sps)) == (1, 2, 2)
|
||||
payload = build_hvcc(bytes.fromhex(VIDEO_HEVC10_CPD))[8:]
|
||||
assert payload[16] == 0xFC | 0x01
|
||||
assert payload[17] == 0xF8 | 0x02
|
||||
assert payload[18] == 0xF8 | 0x02
|
||||
|
||||
|
||||
def test_ttml_init_structure():
|
||||
@@ -399,7 +365,7 @@ def test_ttml_init_structure():
|
||||
language="eng",
|
||||
)
|
||||
assert b"stpp" in init
|
||||
assert b"sthd" in init # subtitle media header
|
||||
assert b"sthd" in init
|
||||
assert b"subt" in init and b"SubtitleHandler\0" in init
|
||||
assert b"http://www.w3.org/ns/ttml\0" in init
|
||||
|
||||
@@ -414,10 +380,9 @@ def test_constant_iv_tenc_form():
|
||||
kid=KID,
|
||||
constant_iv=constant_iv,
|
||||
)
|
||||
# Constant-IV form: default_Per_Sample_IV_Size = 0, then size + IV after the KID.
|
||||
assert KID + bytes([len(constant_iv)]) + constant_iv in init
|
||||
tenc_at = init.index(b"tenc")
|
||||
assert init[tenc_at + 4 + 4 + 3] == 0 # default_Per_Sample_IV_Size
|
||||
assert init[tenc_at + 4 + 4 + 3] == 0
|
||||
|
||||
|
||||
def make_fragment(senc: bytes = b"", saiz: bytes = b"") -> bytes:
|
||||
@@ -427,20 +392,17 @@ def make_fragment(senc: bytes = b"", saiz: bytes = b"") -> bytes:
|
||||
|
||||
|
||||
def test_iv_size_from_piff_senc_override_flag():
|
||||
# PIFF senc uuid with flags&1: AlgorithmID(3) + IV_size(1) + KID(16) override.
|
||||
payload = b"\x00\x00\x00\x01" + b"\x00\x00\x01" + bytes([16]) + KID + struct.pack(">I", 0)
|
||||
senc = box(b"uuid", PIFF_SENC_UUID + payload)
|
||||
assert read_per_sample_iv_size(make_fragment(senc=senc)) == 16
|
||||
|
||||
|
||||
def test_iv_size_from_senc_payload_length():
|
||||
# Standard senc, no subsamples: 3 samples x 8-byte IVs.
|
||||
senc = full_box(b"senc", 0, 0, struct.pack(">I", 3) + b"\x11" * 24)
|
||||
assert read_per_sample_iv_size(make_fragment(senc=senc)) == 8
|
||||
|
||||
|
||||
def test_iv_size_from_senc_with_subsamples():
|
||||
# senc flags&2: per sample IV(8) + entry_count(2) + 6 bytes per entry.
|
||||
sample = b"\x22" * 8 + struct.pack(">H", 1) + b"\x00" * 6
|
||||
senc = full_box(b"senc", 0, 2, struct.pack(">I", 2) + sample * 2)
|
||||
assert read_per_sample_iv_size(make_fragment(senc=senc)) == 8
|
||||
@@ -458,7 +420,6 @@ def test_iv_size_undetermined_returns_none():
|
||||
def test_hvcc_embeds_vps_sps_pps():
|
||||
hvcc = build_hvcc(bytes.fromhex(VIDEO_HEVC_CPD))
|
||||
nals = split_nal_units(bytes.fromhex(VIDEO_HEVC_CPD))
|
||||
# Each original NAL unit (VPS/SPS/PPS) is embedded verbatim in the arrays.
|
||||
for nal in nals:
|
||||
assert nal in hvcc
|
||||
|
||||
@@ -469,7 +430,6 @@ 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)
|
||||
traf = box(b"traf", tfhd)
|
||||
moof = box(b"moof", traf)
|
||||
@@ -482,16 +442,13 @@ def test_read_track_id_missing_returns_none():
|
||||
|
||||
|
||||
def test_remove_emulation_prevention():
|
||||
# 00 00 03 XX -> the 0x03 emulation byte is dropped.
|
||||
assert remove_emulation_prevention(b"\x00\x00\x03\x01") == b"\x00\x00\x01"
|
||||
assert remove_emulation_prevention(b"\x00\x00\x03\x00\x00\x03\x96") == b"\x00\x00\x00\x00\x96"
|
||||
# The byte after a consumed escape is data, even another 0x03.
|
||||
assert remove_emulation_prevention(b"\x00\x00\x03\x03") == b"\x00\x00\x03"
|
||||
assert remove_emulation_prevention(b"\x00\x00\x03\x03\x00\x00\x03\x01") == b"\x00\x00\x03\x00\x00\x01"
|
||||
|
||||
|
||||
def test_two_letter_or_uppercase_language_falls_back_to_und():
|
||||
# mdhd packs three a-z letters; "en"/"ENG" must not crash struct.pack.
|
||||
for lang in ("en", "ENG", "", "e1x"):
|
||||
init = build_init_segment(
|
||||
stream_type="audio",
|
||||
@@ -504,7 +461,6 @@ def test_two_letter_or_uppercase_language_falls_back_to_und():
|
||||
|
||||
|
||||
def test_high_sampling_rate_does_not_overflow():
|
||||
# 96 kHz exceeds the 16.16 integer field; written as 0 like ffmpeg does.
|
||||
init = build_init_segment(
|
||||
stream_type="audio",
|
||||
fourcc="AACL",
|
||||
@@ -516,13 +472,12 @@ def test_high_sampling_rate_does_not_overflow():
|
||||
|
||||
|
||||
def test_read_track_id_truncated_tfhd_returns_none():
|
||||
tfhd = full_box(b"tfhd", 0, 0, b"\x00\x00") # too short for a track_ID
|
||||
tfhd = full_box(b"tfhd", 0, 0, b"\x00\x00")
|
||||
fragment = box(b"moof", box(b"traf", tfhd))
|
||||
assert read_track_id(fragment) is None
|
||||
|
||||
|
||||
def test_parse_colour_hevc_pq():
|
||||
# PQ master: bt2020 primaries (9), smpte2084 transfer (16), bt2020nc matrix (9).
|
||||
assert parse_codec_private_data_colour("HVC1", bytes.fromhex(VIDEO_HEVC_PQ_CPD)) == (9, 16, 9)
|
||||
|
||||
|
||||
@@ -532,21 +487,19 @@ def test_parse_colour_hevc_hlg():
|
||||
|
||||
def test_parse_colour_hevc_bt709():
|
||||
assert parse_codec_private_data_colour("HVC1", bytes.fromhex(VIDEO_HEVC_SDR_CPD)) == (1, 1, 1)
|
||||
# The real-manifest 8-bit sample also signals BT.709 explicitly.
|
||||
assert parse_codec_private_data_colour("HVC1", bytes.fromhex(VIDEO_HEVC_CPD)) == (1, 1, 1)
|
||||
|
||||
|
||||
def test_parse_colour_dv_is_unspecified():
|
||||
# DV carries no usable CICP; the DV decision must come from the FourCC.
|
||||
assert parse_codec_private_data_colour("DVHE", bytes.fromhex(VIDEO_HEVC_DV_CPD)) == (2, 2, 2)
|
||||
|
||||
|
||||
def test_dv_cpd_with_vps_last_builds_init():
|
||||
cpd = bytes.fromhex(VIDEO_HEVC_DV_CPD)
|
||||
nals = split_nal_units(cpd)
|
||||
assert [(n[0] >> 1) & 0x3F for n in nals] == [33, 34, 32] # SPS, PPS, VPS
|
||||
assert [(n[0] >> 1) & 0x3F for n in nals] == [33, 34, 32]
|
||||
sps = remove_emulation_prevention(nals[0])
|
||||
assert parse_hevc_sps_format(sps) == (1, 2, 2) # 4:2:0, 10-bit
|
||||
assert parse_hevc_sps_format(sps) == (1, 2, 2)
|
||||
hvcc = build_hvcc(cpd)
|
||||
for nal in nals:
|
||||
assert nal in hvcc
|
||||
@@ -562,9 +515,7 @@ def test_dv_cpd_with_vps_last_builds_init():
|
||||
|
||||
|
||||
def test_parse_colour_absent_or_unknown_returns_none():
|
||||
# Real sample without a VUI colour description.
|
||||
assert parse_codec_private_data_colour("HVC1", bytes.fromhex(VIDEO_HEVC10_CPD)) is None
|
||||
# Non-HEVC codecs (AVC has no HDR deployment) and truncated data must not raise.
|
||||
assert parse_codec_private_data_colour("H264", bytes.fromhex(VIDEO_AVC_CPD)) is None
|
||||
assert parse_codec_private_data_colour("WVC1", bytes.fromhex(VIDEO_AVC_CPD)) is None
|
||||
assert parse_codec_private_data_colour("HVC1", b"\x00\x00\x00\x01\x42") is None
|
||||
@@ -573,16 +524,13 @@ def test_parse_colour_absent_or_unknown_returns_none():
|
||||
def test_parse_vui_fps():
|
||||
assert parse_codec_private_data_vui("HVC1", bytes.fromhex(VIDEO_HEVC_CPD))[1] == pytest.approx(24000 / 1001)
|
||||
assert parse_codec_private_data_vui("HVC1", bytes.fromhex(VIDEO_HEVC_PQ_CPD))[1] == 25.0
|
||||
# VUI timing can be present even when colour info is absent.
|
||||
assert parse_codec_private_data_vui("HVC1", bytes.fromhex(VIDEO_HEVC10_CPD)) == (None, 25.0)
|
||||
# AVC is deliberately untrusted for fps (field-based VUI timing).
|
||||
assert parse_codec_private_data_vui("H264", bytes.fromhex(VIDEO_AVC_CPD)) == (None, None)
|
||||
|
||||
|
||||
def test_hvcc_profile_tier_level_is_nonzero():
|
||||
# De-emulated PTL must yield real profile/level, not the off-by-one garbage.
|
||||
hvcc = build_hvcc(bytes.fromhex(VIDEO_HEVC_CPD))
|
||||
payload = hvcc[8:] # strip box header
|
||||
payload = hvcc[8:]
|
||||
profile_idc = payload[1] & 0x1F
|
||||
level_idc = payload[12]
|
||||
assert profile_idc != 0
|
||||
@@ -595,13 +543,12 @@ def piff_fragment(flags: int = 0x0, override: bool = False) -> bytes:
|
||||
senc_payload = struct.pack(">I", 2) + ivs
|
||||
if override:
|
||||
flags |= 0x1
|
||||
senc_payload = b"\x00\x00\x01" + bytes([8]) + KID + senc_payload # AlgorithmID + IV_size + KID
|
||||
senc_payload = b"\x00\x00\x01" + bytes([8]) + KID + senc_payload
|
||||
uuid_box = box(b"uuid", PIFF_SENC_UUID + bytes([0]) + flags.to_bytes(3, "big") + senc_payload)
|
||||
tfhd = full_box(b"tfhd", 0, 0x20000, struct.pack(">I", 1))
|
||||
trun = full_box(b"trun", 0, 0x1, struct.pack(">II", 2, 0)) # data_offset placeholder
|
||||
trun = full_box(b"trun", 0, 0x1, struct.pack(">II", 2, 0))
|
||||
traf = box(b"traf", tfhd + trun + uuid_box)
|
||||
moof = box(b"moof", full_box(b"mfhd", 0, 0, struct.pack(">I", 1)) + traf)
|
||||
# patch trun data_offset to the real moof-relative start of the mdat payload
|
||||
moof = moof.replace(struct.pack(">II", 2, 0), struct.pack(">II", 2, len(moof) + 8), 1)
|
||||
return moof + box(b"mdat", b"\xab" * 64)
|
||||
|
||||
@@ -609,14 +556,12 @@ def piff_fragment(flags: int = 0x0, override: bool = False) -> bytes:
|
||||
def test_piff_senc_rewritten_to_cenc_senc():
|
||||
frag = piff_fragment()
|
||||
out = piff_senc_to_cenc(frag)
|
||||
# trun's data_offset is moof-relative; shrinking the box misaims decryption
|
||||
assert len(out) == len(frag)
|
||||
assert PIFF_SENC_UUID not in out
|
||||
assert b"senc" in out and b"free" in out
|
||||
assert struct.pack(">I", 2) + b"".join(bytes([i]) * 8 for i in range(1, 3)) in out
|
||||
# moof size unchanged => the recorded data_offset still resolves
|
||||
assert out[:8] == frag[:8]
|
||||
assert out[len(out) - 72 :] == frag[len(frag) - 72 :] # mdat untouched
|
||||
assert out[len(out) - 72 :] == frag[len(frag) - 72 :]
|
||||
|
||||
|
||||
def test_piff_senc_override_header_stripped():
|
||||
@@ -625,13 +570,12 @@ def test_piff_senc_override_header_stripped():
|
||||
assert len(out) == len(frag)
|
||||
assert PIFF_SENC_UUID not in out
|
||||
senc = out.index(b"senc")
|
||||
assert out[senc + 4] == 0 # version
|
||||
assert int.from_bytes(out[senc + 5 : senc + 8], "big") & 0x1 == 0 # override flag cleared
|
||||
assert out[senc + 8 : senc + 12] == struct.pack(">I", 2) # sample_count directly follows
|
||||
assert out[senc + 4] == 0
|
||||
assert int.from_bytes(out[senc + 5 : senc + 8], "big") & 0x1 == 0
|
||||
assert out[senc + 8 : senc + 12] == struct.pack(">I", 2)
|
||||
|
||||
|
||||
def test_piff_subsample_flag_survives_override_strip():
|
||||
# losing 0x2 is silent: no subsample map, so clear NAL headers get encrypted too
|
||||
frag = piff_fragment(flags=0x2, override=True)
|
||||
out = piff_senc_to_cenc(frag)
|
||||
senc = out.index(b"senc")
|
||||
@@ -647,7 +591,6 @@ def test_piff_rewrite_leaves_non_piff_fragments_alone():
|
||||
|
||||
|
||||
def test_piff_rewrite_skips_traf_that_already_has_senc():
|
||||
# a second senc would leave the decrypter to choose between them
|
||||
ivs = b"".join(bytes([i]) * 8 for i in range(1, 3))
|
||||
senc = full_box(b"senc", 0, 0, struct.pack(">I", 2) + ivs)
|
||||
uuid_box = box(b"uuid", PIFF_SENC_UUID + bytes([0]) + (0).to_bytes(3, "big") + struct.pack(">I", 2) + ivs)
|
||||
@@ -664,7 +607,6 @@ def test_piff_rewrite_covers_every_moof_and_traf():
|
||||
|
||||
|
||||
def test_piff_rewrite_refuses_non_ctr_algorithm_id():
|
||||
# AlgorithmID 2 is AES-CBC but the sample entry says 'cenc'; rewriting yields garbage
|
||||
ivs = b"".join(bytes([i]) * 8 for i in range(1, 3))
|
||||
payload = (2).to_bytes(3, "big") + bytes([8]) + KID + struct.pack(">I", 2) + ivs
|
||||
uuid_box = box(b"uuid", PIFF_SENC_UUID + bytes([0]) + (0x1).to_bytes(3, "big") + payload)
|
||||
@@ -690,14 +632,12 @@ def traf_children_tile_exactly(frag: bytes) -> bool:
|
||||
|
||||
|
||||
def test_piff_rewrite_keeps_traf_children_tiling_exactly():
|
||||
# a mis-sized senc still "decrypts", just off the wrong bytes, so assert the sizes too
|
||||
assert traf_children_tile_exactly(piff_fragment())
|
||||
for frag in (piff_fragment(), piff_fragment(flags=0x2), piff_fragment(flags=0x2, override=True)):
|
||||
assert traf_children_tile_exactly(piff_senc_to_cenc(frag)), "rewritten traf no longer tiles"
|
||||
|
||||
|
||||
def test_piff_rewrite_refuses_override_iv_size_mismatch():
|
||||
# tenc is the only IV width a decrypter consults; a disagreeing override misparses silently
|
||||
ivs = b"".join(bytes([i]) * 16 for i in range(1, 3))
|
||||
payload = (1).to_bytes(3, "big") + bytes([16]) + KID + struct.pack(">I", 2) + ivs
|
||||
uuid_box = box(b"uuid", PIFF_SENC_UUID + bytes([0]) + (0x1).to_bytes(3, "big") + payload)
|
||||
@@ -707,13 +647,12 @@ def test_piff_rewrite_refuses_override_iv_size_mismatch():
|
||||
|
||||
|
||||
def test_piff_rewrite_never_grows_output_on_malformed_boxes():
|
||||
# A declared size running past the buffer would extend the output over the mdat.
|
||||
good = piff_fragment()
|
||||
truncations = [good[:n] for n in range(8, len(good), 7)]
|
||||
oversized = bytearray(good)
|
||||
struct.pack_into(">I", oversized, 0, len(good) + 4096) # moof claims more than exists
|
||||
struct.pack_into(">I", oversized, 0, len(good) + 4096)
|
||||
for frag in [*truncations, bytes(oversized), b"", b"\x00" * 12]:
|
||||
out = piff_senc_to_cenc(frag) # must not raise
|
||||
out = piff_senc_to_cenc(frag)
|
||||
assert len(out) == len(frag), f"output grew: {len(frag)} -> {len(out)}"
|
||||
|
||||
|
||||
@@ -733,7 +672,6 @@ def text_fragment(seq: int, begin: str, end: str, text: str, sdi: int) -> bytes:
|
||||
|
||||
|
||||
def test_unity_matrix_is_nine_int32s():
|
||||
# extras shift every later field (mvhd next_track_ID, tkhd width/height) and desync pymp4
|
||||
from unshackle.core.manifests.ism_init import UNITY_MATRIX
|
||||
|
||||
assert len(UNITY_MATRIX) == 36
|
||||
@@ -741,7 +679,6 @@ def test_unity_matrix_is_nine_int32s():
|
||||
|
||||
@pytest.mark.parametrize("stream_type", ["video", "audio", "text"])
|
||||
def test_mvhd_tkhd_sizes_match_iso_layout(stream_type):
|
||||
# a declared size over the spec payload makes parsers under-read and stop at the moov
|
||||
kwargs = {
|
||||
"video": dict(fourcc="H264", codec_private_data=VIDEO_AVC_CPD, width=1920, height=1080),
|
||||
"audio": dict(fourcc="AACL", codec_private_data=AAC_LC_CPD),
|
||||
@@ -753,14 +690,11 @@ def test_mvhd_tkhd_sizes_match_iso_layout(stream_type):
|
||||
for name in (b"mvhd", b"tkhd"):
|
||||
at = init.index(name) - 4
|
||||
sizes[name] = struct.unpack(">I", init[at : at + 4])[0]
|
||||
# version-1 mvhd: 8 header + 4 version/flags + 28 time fields + 80 trailer
|
||||
assert sizes[b"mvhd"] == 120
|
||||
# version-1 tkhd: 8 header + 4 version/flags + 32 time fields + 60 trailer
|
||||
assert sizes[b"tkhd"] == 104
|
||||
|
||||
|
||||
def test_tkhd_carries_video_dimensions():
|
||||
# width/height sit after the matrix, so a mis-sized matrix silently zeroes them
|
||||
init = build_init_segment(
|
||||
stream_type="video", fourcc="H264", codec_private_data=VIDEO_AVC_CPD, width=1920, height=1080
|
||||
)
|
||||
@@ -771,7 +705,6 @@ def test_tkhd_carries_video_dimensions():
|
||||
|
||||
|
||||
def test_pymp4_consumes_whole_init_and_reaches_fragments():
|
||||
# pymp4 must reach the mdat here, or Subtitle.parse finds nothing to yield cues from
|
||||
from io import BytesIO
|
||||
|
||||
from pymp4.parser import MP4
|
||||
@@ -806,9 +739,6 @@ def test_fttml_subtitle_parse_yields_cues():
|
||||
[("HEV1", b"hev1"), ("hev1", b"hev1"), ("HVC1", b"hvc1"), ("hvc1", b"hvc1"), ("HEVC", b"hvc1"), ("H265", b"hvc1")],
|
||||
)
|
||||
def test_hevc_sample_entry_honours_manifest_fourcc(fourcc, expected):
|
||||
# hev1 permits in-band parameter sets where hvc1 requires them in the sample
|
||||
# entry. Real Smooth manifests ship FourCC="hev1", so relabelling it hvc1
|
||||
# misdescribes the stream.
|
||||
init = build_init_segment(
|
||||
stream_type="video", fourcc=fourcc, codec_private_data=VIDEO_HEVC_CPD, width=3840, height=2160
|
||||
)
|
||||
@@ -817,8 +747,6 @@ def test_hevc_sample_entry_honours_manifest_fourcc(fourcc, expected):
|
||||
|
||||
|
||||
def test_encrypted_hev1_frma_carries_the_same_fourcc():
|
||||
# frma names the original format the sinf wraps; if it drifts from the sample
|
||||
# entry, a decrypter restores the wrong sample entry type.
|
||||
init = build_init_segment(
|
||||
stream_type="video", fourcc="HEV1", codec_private_data=VIDEO_HEVC_CPD, kid=KID, width=3840, height=2160
|
||||
)
|
||||
@@ -827,26 +755,21 @@ def test_encrypted_hev1_frma_carries_the_same_fourcc():
|
||||
|
||||
|
||||
def test_dolby_vision_sample_entry_carries_dvcc():
|
||||
# a dvh1 sample entry without dvcC describes itself as plain HEVC, so every reader
|
||||
# downstream loses the Dolby Vision signalling even though the RPU NAL units are in
|
||||
# the elementary stream.
|
||||
init = build_init_segment(
|
||||
stream_type="video", fourcc="dvhe", codec_private_data=VIDEO_HEVC_CPD, width=3840, height=2160
|
||||
)
|
||||
offset = find_stsd(init)
|
||||
assert init[offset + 20 : offset + 24] == b"dvh1"
|
||||
|
||||
# readers cannot reach a dvcC outside the sample entry, so byte presence alone
|
||||
# proves nothing.
|
||||
entry_start, entry_end = sample_entry_bounds(init)
|
||||
assert entry_start <= init.index(b"dvcC") < entry_end
|
||||
|
||||
payload = init[init.index(b"dvcC") + 4 :][:24]
|
||||
assert payload[0] == 1 and payload[1] == 0
|
||||
flags = struct.unpack(">H", payload[2:4])[0]
|
||||
assert flags >> 9 == 5 # profile 5: base layer carries no usable colour description
|
||||
assert (flags >> 3) & 0x3F == 6 # level 6: 3840x2160 at 24 fps
|
||||
assert flags & 0b111 == 0b101 # RPU present, no enhancement layer, base layer present
|
||||
assert flags >> 9 == 5
|
||||
assert (flags >> 3) & 0x3F == 6
|
||||
assert flags & 0b111 == 0b101
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -860,9 +783,6 @@ def test_dolby_vision_sample_entry_carries_dvcc():
|
||||
def test_dolby_vision_profile_follows_the_base_layer_colour(
|
||||
cpd, expected_box, expected_profile, expected_compat, expected_entry
|
||||
):
|
||||
# a base layer with no usable colour description is profile 5; one that stays readable as
|
||||
# HDR10 or HLG is a cross-compatible profile, which readers expect under dvvC, not dvcC.
|
||||
# The sample entry follows base-layer decodability: hvc1 for a compliant base, dvh1 otherwise.
|
||||
init = build_init_segment(stream_type="video", fourcc="DVH1", codec_private_data=cpd, width=3840, height=2160)
|
||||
assert expected_box in init
|
||||
entry_start, entry_end = sample_entry_bounds(init)
|
||||
@@ -875,8 +795,6 @@ def test_dolby_vision_profile_follows_the_base_layer_colour(
|
||||
|
||||
|
||||
def test_dolby_vision_profile_8_dvhe_takes_hev1_and_frma_follows():
|
||||
# DVHE maps to the in-band-parameter-set entry (hev1) when the base layer is
|
||||
# HEVC-decodable, and the frma inside sinf must carry the same fourcc.
|
||||
init = build_init_segment(
|
||||
stream_type="video", fourcc="dvhe", codec_private_data=VIDEO_HEVC_PQ_CPD, width=3840, height=2160
|
||||
)
|
||||
@@ -894,9 +812,6 @@ def test_dolby_vision_profile_8_dvhe_takes_hev1_and_frma_follows():
|
||||
|
||||
|
||||
def test_encrypted_dolby_vision_wraps_encv_with_dvcc_before_sinf():
|
||||
# the encrypted entry must keep the dvcC inside the encv wrapper and ahead of the
|
||||
# sinf, or tooling that decrypts and remuxes drops the Dolby Vision config with the
|
||||
# wrapper.
|
||||
init = build_init_segment(
|
||||
stream_type="video", fourcc="DVH1", codec_private_data=VIDEO_HEVC_DV_CPD, width=3840, height=2160, kid=KID
|
||||
)
|
||||
@@ -914,9 +829,9 @@ def test_encrypted_dolby_vision_wraps_encv_with_dvcc_before_sinf():
|
||||
(24.0, 6),
|
||||
(30.0, 7),
|
||||
(48.0, 8),
|
||||
(60.0, 9), # same 4K frame, higher rate: the pixel-rate limit must move the level
|
||||
(60.0, 9),
|
||||
(120.0, 10),
|
||||
(None, 7), # no VUI timing: the 25 fps assumption sits one level above 2160p24
|
||||
(None, 7),
|
||||
],
|
||||
)
|
||||
def test_dolby_vision_level_scales_with_frame_rate(fps, expected_level):
|
||||
@@ -926,8 +841,6 @@ def test_dolby_vision_level_scales_with_frame_rate(fps, expected_level):
|
||||
|
||||
|
||||
def test_dolby_vision_ftyp_carries_dby1_brand():
|
||||
# Dolby ISOBMFF requires the dby1 compatible brand on files with a Dolby Vision
|
||||
# config box; plain HEVC must not claim it.
|
||||
dv_init = build_init_segment(
|
||||
stream_type="video", fourcc="DVH1", codec_private_data=VIDEO_HEVC_DV_CPD, width=3840, height=2160
|
||||
)
|
||||
@@ -941,8 +854,6 @@ def test_dolby_vision_ftyp_carries_dby1_brand():
|
||||
|
||||
|
||||
def test_hevc_cpd_without_vps_builds_init():
|
||||
# MS-SSTR HEVC CodecPrivateData is SPS+PPS only (no VPS); the hvcC must build
|
||||
# from what is there, and the encrypted path must still produce sinf/tenc.
|
||||
nals = split_nal_units(bytes.fromhex(VIDEO_HEVC_PQ_CPD))
|
||||
cpd = b"".join(b"\x00\x00\x00\x01" + n for n in nals if (n[0] >> 1) & 0x3F != 32).hex()
|
||||
|
||||
@@ -954,7 +865,6 @@ def test_hevc_cpd_without_vps_builds_init():
|
||||
)
|
||||
assert b"sinf" in init and b"tenc" in init
|
||||
|
||||
# SPS and PPS stay mandatory: dropping the SPS must still raise.
|
||||
no_sps = b"".join(b"\x00\x00\x00\x01" + n for n in nals if (n[0] >> 1) & 0x3F not in (32, 33)).hex()
|
||||
with pytest.raises(ValueError):
|
||||
build_init_segment(stream_type="video", fourcc="HVC1", codec_private_data=no_sps, width=1920, height=1080)
|
||||
@@ -963,10 +873,10 @@ def test_hevc_cpd_without_vps_builds_init():
|
||||
@pytest.mark.parametrize(
|
||||
"width,height,expected_level",
|
||||
[
|
||||
(1920, 1080, 3), # 1080p24
|
||||
(3840, 2160, 6), # 2160p24
|
||||
(7680, 4320, 11), # 8K24 falls in the level that shares 4K120's pixel rate
|
||||
(3840, 600, 5), # a pixel rate that fits level 4, a width that does not
|
||||
(1920, 1080, 3),
|
||||
(3840, 2160, 6),
|
||||
(7680, 4320, 11),
|
||||
(3840, 600, 5),
|
||||
],
|
||||
)
|
||||
def test_dolby_vision_level_needs_both_pixel_rate_and_width(width, height, expected_level):
|
||||
|
||||
@@ -25,12 +25,10 @@ def test_placeholder_spellings_repeat_and_audiotag_fallback() -> None:
|
||||
"https://cdn.example/x.ism/QualityLevels(128000)/Fragments(audio=20000000)",
|
||||
"https://cdn.example/x.ism/QualityLevels(128000)/Fragments(audio=40000000)",
|
||||
]
|
||||
assert audio.codec == Audio.Codec.AAC # AudioTag 255 means AACL
|
||||
assert audio.codec == Audio.Codec.AAC
|
||||
|
||||
|
||||
def test_duration_fallback_when_next_fragment_omits_time() -> None:
|
||||
# A d-less <c> whose successor also omits t must fall back to the manifest
|
||||
# duration (int(None) used to raise TypeError past the except clause).
|
||||
sparse = MANIFEST.replace('<c t="0" d="20000000" r="2"/>', '<c t="0"/>')
|
||||
tracks = ISM.from_text(sparse, "https://cdn.example/x.ism/manifest").to_tracks()
|
||||
assert tracks.audio[0].data["ism"]["segments"] == [
|
||||
@@ -40,7 +38,6 @@ def test_duration_fallback_when_next_fragment_omits_time() -> None:
|
||||
|
||||
|
||||
def test_missing_language_without_fallback_raises() -> None:
|
||||
# MS-SSTR Language is optional; video StreamIndexes commonly omit it.
|
||||
no_lang = MANIFEST.replace(' Language="en"', "")
|
||||
with pytest.raises(ValueError, match="fallback language"):
|
||||
ISM.from_text(no_lang, "https://cdn.example/x.ism/manifest").to_tracks()
|
||||
|
||||
@@ -43,7 +43,6 @@ def test_bt709_codec_private_data_stays_sdr() -> None:
|
||||
|
||||
|
||||
def test_colourless_codec_private_data_defaults_sdr() -> None:
|
||||
# Real 10-bit sample without a VUI colour description: unspecified -> SDR.
|
||||
assert parse_video(VIDEO_HEVC10_CPD).range == Video.Range.SDR
|
||||
|
||||
|
||||
@@ -53,8 +52,6 @@ def test_get_video_range_dolby_vision_fourcc() -> None:
|
||||
|
||||
|
||||
def test_dv_track_from_real_smooth_cpd() -> None:
|
||||
# Live manifests ship lowercase "dvhe"; its VUI is Unspecified so the
|
||||
# FourCC short-circuit is the only thing standing between DV and SDR.
|
||||
video = parse_video(VIDEO_HEVC_DV_CPD, fourcc="dvhe")
|
||||
assert video.range == Video.Range.DV
|
||||
assert ISM.get_video_range("hvc1", VIDEO_HEVC_DV_CPD) == Video.Range.SDR
|
||||
|
||||
@@ -100,11 +100,11 @@ def test_each_kid_maps_to_its_own_fragments(tmp_path: Path) -> None:
|
||||
path = tmp_path / "enc.mp4"
|
||||
path.write_bytes(
|
||||
movie(encv(A), encv(B))
|
||||
+ moof(1, 5000) # lead under A
|
||||
+ moof(2, 7000) # the rest under B
|
||||
+ moof(1, 5000)
|
||||
+ moof(2, 7000)
|
||||
+ moof(2, 9000)
|
||||
+ moof(1, 11000, *local(C)) # a seig group overrides the sample entry's KID
|
||||
+ moof(1, 13000, *local(A, protected=False)) # a clear seig group names no KID
|
||||
+ moof(1, 11000, *local(C))
|
||||
+ moof(1, 13000, *local(A, protected=False))
|
||||
)
|
||||
assert kid_windows(path) == KidMap({A: [(0.0, 2.0)], B: [(2.0, 6.0), (4.0, 6.0)], C: [(6.0, 8.0)]}, True)
|
||||
|
||||
@@ -113,7 +113,6 @@ def test_windows_run_through_a_kid_but_stop_at_another_or_after_the_longest() ->
|
||||
long_run = [(t * 2.0, t * 2.0 + 2) for t in range(20)]
|
||||
assert pick_windows(long_run, longest=10.0) == [(0.0, 10.0), (20.0, 30.0), (30.0, 40.0)]
|
||||
assert pick_windows(long_run) == [(0.0, 4.0), (20.0, 24.0), (36.0, 40.0)]
|
||||
# a gap is another KID or a clear stretch: no window crosses it, and the last one ends the last run
|
||||
assert pick_windows([(0, 2), (2, 4), (10, 12), (12, 14), (14, 16)], longest=10.0) == [(0, 4), (10, 16)]
|
||||
assert pick_windows([(0, 2), (2, 4), (10, 12), (12, 14), (14, 16)]) == [(0, 4), (10, 14.0), (12, 16)]
|
||||
|
||||
|
||||
@@ -50,12 +50,10 @@ def test_selection_takes_only_the_variant_a_bare_tag_means():
|
||||
|
||||
|
||||
def test_exact_match_prefers_the_string_equal_tag():
|
||||
# same string preference as selection: an exact 'es' only takes 'es' when it exists
|
||||
assert matched_language_tags(["es"], ["es", "es-ES", "es-419"], exact=True) == {"es"}
|
||||
|
||||
|
||||
def test_exact_match_falls_back_to_the_paradigm_variant():
|
||||
# no literal 'es' available, so 'es' resolves the way an exact '-sl es' selection would
|
||||
assert matched_language_tags(["es"], ["es-ES", "es-419"], exact=True) == {"es-ES"}
|
||||
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ def episode(season: int, number: int, part: Optional[int] = None) -> Episode:
|
||||
|
||||
|
||||
def series() -> Series:
|
||||
# out of order on purpose: the Series sorts itself
|
||||
return Series(episode(s, n) for s, n in [(2, 1), (1, 1), (2, 3), (1, 2), (2, 2)])
|
||||
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@ from unshackle.core.utils.xml import load_xml
|
||||
CORPUS = Path(__file__).resolve().parent.parent / "fixtures" / "manifests"
|
||||
INDEX: list[dict[str, Any]] = json.loads((CORPUS / "index.json").read_text(encoding="utf-8"))
|
||||
|
||||
# file -> reason; strict, so a fix that makes one parse fails here until its entry is removed
|
||||
KNOWN_FAILURES: dict[str, str] = {}
|
||||
|
||||
|
||||
@@ -60,7 +59,6 @@ def test_manifest_parses_to_tracks(entry: dict[str, Any]) -> None:
|
||||
|
||||
assert tracks.videos or tracks.audio or tracks.subtitles
|
||||
for track in tracks:
|
||||
# HLS CODECS is only a SHOULD (RFC 8216 4.3.4.2), so an HLS track can honestly have none
|
||||
assert track.codec is not None or entry["kind"] == "hls", track
|
||||
assert track.language, track
|
||||
|
||||
|
||||
@@ -100,7 +100,6 @@ def test_dts_uhd_audio_routes_the_mux_to_mp4(tmp_path: Path, monkeypatch: pytest
|
||||
assert command[:2] == ["MP4Box", "-for-test"]
|
||||
assert command[-2:] == ["-new", str(out)]
|
||||
assert f"{tmp_path / 'a.mp4'}:lang=en" in command
|
||||
# the child must not inherit the terminal that the live progress tree is drawing on
|
||||
assert captured[0].kwargs["stdout"] is subprocess.PIPE
|
||||
assert captured[0].kwargs["stderr"] is subprocess.STDOUT
|
||||
|
||||
@@ -110,8 +109,6 @@ def test_other_audio_still_muxes_with_mkvmerge(tmp_path: Path, monkeypatch: pyte
|
||||
monkeypatch.setattr("unshackle.core.tracks.tracks.binaries.MKVToolNix", None)
|
||||
|
||||
tracks = build_tracks(tmp_path, b"dtsh")
|
||||
# reaching the mkvmerge requirement proves the DTS-UHD branch was not taken; MP4Box
|
||||
# is None here too, so the MP4 branch would have raised about MP4Box instead
|
||||
with pytest.raises(RuntimeError, match="MKVToolNix"):
|
||||
tracks.mux("Title", delete=False, output_path=tmp_path / "out.muxed.mkv")
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ def encode(path: Path, encoder: str, *extra_args: str) -> Path:
|
||||
"-c:a",
|
||||
encoder,
|
||||
"-strict",
|
||||
"-2", # flac and opus in mp4 are flagged experimental by the muxer
|
||||
"-2",
|
||||
*extra_args,
|
||||
str(path),
|
||||
],
|
||||
@@ -135,8 +135,7 @@ def test_dolby_digital_plus_takes_the_mp4_muxer(tmp_path: Path) -> None:
|
||||
|
||||
def test_a_failed_remux_keeps_the_source_and_removes_its_partial_file(tmp_path: Path) -> None:
|
||||
"""FFmpeg creates the output before it fails, and nothing else sweeps the temp directory."""
|
||||
# FFmpeg 9.0 writes PCM to MP4 as ipcm, so PCM no longer fails the remux.
|
||||
source = encode(tmp_path / "track.mp4", "adpcm_ms", "-f", "mov") # no MP4 muxer takes ADPCM
|
||||
source = encode(tmp_path / "track.mp4", "adpcm_ms", "-f", "mov")
|
||||
|
||||
track = Audio(id_="a1", url="https://example.test/a1.mp4", language="en", codec=None)
|
||||
track.path = source
|
||||
|
||||
@@ -104,7 +104,7 @@ def test_year_from_value(value: Any, expected: int) -> None:
|
||||
("value", "expected"),
|
||||
[
|
||||
(250, 250.0),
|
||||
(250000, 250.0), # treated as milliseconds
|
||||
(250000, 250.0),
|
||||
("180", 180.0),
|
||||
(None, None),
|
||||
("nope", None),
|
||||
@@ -136,7 +136,7 @@ def test_format_duration(value: Any, expected: str) -> None:
|
||||
("value", "sep", "expected"),
|
||||
[
|
||||
(["Alice", "Bob"], ", ", "Alice, Bob"),
|
||||
(["Alice", "Alice"], ", ", "Alice"), # de-dupes
|
||||
(["Alice", "Alice"], ", ", "Alice"),
|
||||
([{"profile": {"name": "DJ"}}], ", ", "DJ"),
|
||||
({"items": [{"name": "X"}, {"name": "Y"}]}, " & ", "X & Y"),
|
||||
("Solo", ", ", "Solo"),
|
||||
@@ -150,7 +150,7 @@ def test_format_names(value: Any, sep: str, expected: str) -> None:
|
||||
("raw_kind", "count", "expected"),
|
||||
[
|
||||
("single", 1, "single"),
|
||||
("single", 3, "ep"), # multi-track "single" -> EP
|
||||
("single", 3, "ep"),
|
||||
("EP", None, "ep"),
|
||||
("Extended Play", None, "ep"),
|
||||
("ep-single", 1, "single"),
|
||||
@@ -200,7 +200,7 @@ def test_build_music_from_songs() -> None:
|
||||
assert isinstance(music, Music)
|
||||
assert music.kind == "album"
|
||||
assert music.title == "Greatest"
|
||||
assert music.artist == "The Band" # album_artist preferred over artist
|
||||
assert music.artist == "The Band"
|
||||
assert music.year == 2019
|
||||
assert music.total_tracks == 2
|
||||
assert music.total_discs == 1
|
||||
|
||||
@@ -59,7 +59,6 @@ def test_albums_template_used(reset_folder_config):
|
||||
reset_folder_config.folder_templates = {"albums": "{album_artist} - {album} ({year})"}
|
||||
result = make_song().get_filename(StubMediaInfo(), folder=True)
|
||||
assert result == sanitize_filename("Example Artist - Example Album (2025)", " ")
|
||||
# Album folder must NOT carry per-track info like the song file name does.
|
||||
assert "01" not in result
|
||||
|
||||
|
||||
@@ -70,7 +69,6 @@ def test_albums_preferred_over_songs(reset_folder_config):
|
||||
|
||||
|
||||
def test_songs_folder_used_when_no_albums(reset_folder_config):
|
||||
# Backward compatibility: the legacy "songs" folder kind still names the album folder.
|
||||
reset_folder_config.folder_templates = {"songs": "SS-{album}"}
|
||||
result = make_song().get_filename(StubMediaInfo(), folder=True)
|
||||
assert result.startswith("SS-")
|
||||
@@ -78,7 +76,7 @@ def test_songs_folder_used_when_no_albums(reset_folder_config):
|
||||
|
||||
def test_validation_accepts_music_variables_and_albums_kind():
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error") # any warning becomes a test failure
|
||||
warnings.simplefilter("error")
|
||||
Config(
|
||||
output_template={
|
||||
"songs": "{track_number}. {title}",
|
||||
@@ -89,7 +87,6 @@ def test_validation_accepts_music_variables_and_albums_kind():
|
||||
|
||||
def test_validation_warns_on_unknown_folder_kind():
|
||||
with pytest.warns(UserWarning, match="Unknown folder template kind"):
|
||||
# A non-folder key is required so output-template validation actually runs.
|
||||
Config(output_template={"songs": "{track_number}. {title}", "folder": {"bogus": "{album}"}})
|
||||
|
||||
|
||||
@@ -103,15 +100,15 @@ def test_undated_single_degrades_cleanly(reset_folder_config):
|
||||
album="Example Album",
|
||||
track=1,
|
||||
album_artist="Example Artist",
|
||||
) # no disc, no year: both are optional
|
||||
)
|
||||
|
||||
assert str(song) == "Example Artist - Example Album (?) / 01. Example Track"
|
||||
assert song.get_filename(StubMediaInfo(), folder=True) == sanitize_filename("Example Artist - Example Album", " ")
|
||||
assert song.get_filename(StubMediaInfo()) == "01.Example.Track" # spacer applies to the title too
|
||||
assert song.get_filename(StubMediaInfo()) == "01.Example.Track"
|
||||
|
||||
context = song.build_template_context(StubMediaInfo())
|
||||
assert context["year"] == ""
|
||||
assert context["disc"] == "" # a lone disc is never numbered
|
||||
assert context["disc"] == ""
|
||||
assert context["track_number"] == "01"
|
||||
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ from unshackle.core.tracks import Attachment
|
||||
|
||||
pytestmark = pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="requires ffmpeg")
|
||||
|
||||
PNG_STUB = b"\x89PNG\r\n\x1a\n" + b"\x00" * 16 # magic only; Pillow dimension probing soft-fails
|
||||
PNG_STUB = b"\x89PNG\r\n\x1a\n" + b"\x00" * 16
|
||||
|
||||
|
||||
class DummyService:
|
||||
|
||||
@@ -120,7 +120,6 @@ def test_two_distinct_headers_are_both_licensed_and_keys_merged() -> None:
|
||||
|
||||
assert cdm.challenged == [[KID_A], [KID_B]]
|
||||
assert drm.content_keys == {KID_A: KEY_A, KID_B: KEY_B}
|
||||
# a remote CDM sends whatever set_pssh_b64 gave it, so each round carries only its own header
|
||||
assert [len(PSSH(b).wrm_headers) for b in cdm.pssh_b64s] == [1, 1]
|
||||
for pro_b64 in cdm.pssh_b64s:
|
||||
pro = base64.b64decode(pro_b64)
|
||||
@@ -221,7 +220,6 @@ def test_repeated_get_drm_for_cdm_does_not_grow_the_header_list() -> None:
|
||||
|
||||
from unshackle.core.tracks import Video
|
||||
|
||||
# a KID-less header is exempt from the KID-set dedupe, so only identity-level idempotence protects it
|
||||
first = _drm(_wrm_header(KID_A))
|
||||
second = PlayReady(pssh=PSSH(_pro(_wrm_header(la_url="https://kidless.invalid/"))), kid=KID_B)
|
||||
track = Video(
|
||||
@@ -245,7 +243,6 @@ def test_absorb_keeps_every_sibling_under_concurrent_calls() -> None:
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
first = _drm(_wrm_header(KID_A))
|
||||
# each call brings a sibling nobody else brings, so a lost update shows as a missing header
|
||||
siblings = [PlayReady(pssh=PSSH(_pro(_wrm_header(la_url=f"https://x{i}.invalid/"))), kid=KID_B) for i in range(64)]
|
||||
|
||||
with ThreadPoolExecutor(8) as pool:
|
||||
@@ -321,7 +318,6 @@ def test_customattributes_kids_follow_the_header_kids() -> None:
|
||||
|
||||
drm = PlayReady(pssh=PSSH(_pro(header)), pssh_b64=_pro_b64(header))
|
||||
|
||||
# the header KID leads (it is what the licence server acts on); CUSTOMATTRIBUTES KIDs stay reachable
|
||||
assert drm.kids == [KID_A, KID_B, kid_c]
|
||||
assert drm.kid == KID_A
|
||||
|
||||
@@ -387,7 +383,6 @@ def test_a_header_that_yielded_nothing_is_not_sent_again_by_the_same_object() ->
|
||||
drm = _drm(_wrm_header(KID_A), _wrm_header(KID_B))
|
||||
cdm = FakeCdm({KID_A: KEY_A})
|
||||
|
||||
# every track of a title calls this on the shared object; the second call must not repeat B
|
||||
drm.get_content_keys(cdm=cdm, certificate=_cert, licence=_licence)
|
||||
drm.get_content_keys(cdm=cdm, certificate=_cert, licence=_licence)
|
||||
|
||||
|
||||
@@ -360,7 +360,6 @@ def test_pinned_port_relays_over_verified_tls(
|
||||
c.sendall(b"CONNECT example.com:443 HTTP/1.1\r\n\r\n")
|
||||
assert c.recv(65536) == b"CONNECT example.com:443 HTTP/1.1\r\n\r\n"
|
||||
|
||||
# a hostname the certificate does not name fails the TLS check, and the client sees the connection close
|
||||
with socket.create_connection(("127.0.0.1", surfsharkvpn.pinned("127.0.0.1", "evil.example.com"))) as c:
|
||||
c.settimeout(5)
|
||||
c.sendall(b"CONNECT example.com:443 HTTP/1.1\r\n\r\n")
|
||||
|
||||
@@ -36,7 +36,6 @@ def windscribe(monkeypatch: pytest.MonkeyPatch) -> WindscribeVPN:
|
||||
|
||||
@pytest.mark.parametrize("query", ["us-bos", "us_yyz", "zz", "us"])
|
||||
def test_nordvpn(nordvpn: NordVPN, query: str) -> None:
|
||||
# "us" has no recommended servers in the fixture
|
||||
assert nordvpn.get_proxy(query) is None
|
||||
|
||||
|
||||
|
||||
@@ -62,7 +62,6 @@ def licence_sent(cdm: Any, remote_id_key: str, licence: str) -> bytes:
|
||||
ENVELOPE,
|
||||
'<?xml version="1.0" encoding="utf-8"?>' + ENVELOPE,
|
||||
"\n " + ENVELOPE,
|
||||
# Each length makes a different count of base64 characters, so one of them decodes without an error.
|
||||
*(ENVELOPE.replace("AAAA", "A" * n) for n in range(5, 8)),
|
||||
],
|
||||
)
|
||||
|
||||
@@ -32,7 +32,7 @@ def set_pssh(cdm: CustomRemoteCDM, session_id: bytes, pssh_b64: str) -> None:
|
||||
"""Store a PSSH the way ``PlayReady.get_content_keys`` does."""
|
||||
try:
|
||||
cdm.set_pssh_b64(pssh_b64, session_id=session_id)
|
||||
except TypeError: # CDM predating the per-session signature
|
||||
except TypeError:
|
||||
cdm.set_pssh_b64(pssh_b64)
|
||||
|
||||
|
||||
@@ -45,7 +45,6 @@ def test_a_later_session_does_not_inherit_the_earlier_pssh() -> None:
|
||||
assert cdm.get_init_data_from_pssh(FakePssh(b"ignored")) == "FIRST_TITLE_PSSH"
|
||||
cdm.close(first)
|
||||
|
||||
# The second title has no PSSH of its own, so nothing calls set_pssh_b64.
|
||||
cdm.open()
|
||||
init_data = cdm.get_init_data_from_pssh(FakePssh(b"second"))
|
||||
|
||||
|
||||
@@ -50,30 +50,30 @@ def quality(width: Optional[int], height: Optional[int], scan_type: str = "Progr
|
||||
(1920, 1080, 1080),
|
||||
(1280, 720, 720),
|
||||
(2560, 1440, 1440),
|
||||
(1920, 1088, 1080), # padded to a multiple of 16
|
||||
(1920, 1088, 1080),
|
||||
(960, 544, 540),
|
||||
(640, 368, 360),
|
||||
(1916, 1076, 1080), # a few lines short
|
||||
(1916, 1076, 1080),
|
||||
(3836, 2156, 2160),
|
||||
(1920, 800, 1080), # scope crop
|
||||
(1920, 1036, 1080), # flat crop
|
||||
(1920, 800, 1080),
|
||||
(1920, 1036, 1080),
|
||||
(3840, 1600, 2160),
|
||||
(1280, 544, 720),
|
||||
(4096, 2160, 2160), # DCI
|
||||
(4096, 2160, 2160),
|
||||
(4096, 1716, 2160),
|
||||
(2048, 858, 1080),
|
||||
(1440, 1080, 1080), # 4:3 pillarbox
|
||||
(1440, 1080, 1080),
|
||||
(960, 720, 720),
|
||||
(720, 576, 576), # anamorphic SD
|
||||
(720, 576, 576),
|
||||
(704, 576, 576),
|
||||
(720, 480, 480),
|
||||
(854, 480, 480),
|
||||
(1080, 1920, 1080), # portrait
|
||||
(1080, 1920, 1080),
|
||||
(1080, 1350, 1080),
|
||||
(720, 1280, 720),
|
||||
(2560, 1080, 1080), # ultrawide
|
||||
(2560, 1080, 1080),
|
||||
(3440, 1440, 1440),
|
||||
(1600, 900, 900), # no standard height near it
|
||||
(1600, 900, 900),
|
||||
],
|
||||
)
|
||||
def test_standard_resolution(width: int, height: int, expected: int) -> None:
|
||||
|
||||
@@ -55,7 +55,6 @@ def patch_providers(monkeypatch: pytest.MonkeyPatch, available: dict[str, FakePr
|
||||
|
||||
|
||||
def test_supplied_ids_survive_a_providers_own_answer(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
# tmdb answers with a different imdb id; the one the user gave must win
|
||||
tmdb = FakeProvider(
|
||||
"tmdb",
|
||||
MetadataResult(title="Inception", year=2010, kind="movie", external_ids=ExternalIds(imdb_id="tt9999999")),
|
||||
@@ -120,7 +119,6 @@ def test_per_kind_order_puts_tvdb_first_for_tv(monkeypatch: pytest.MonkeyPatch)
|
||||
assert result is not None
|
||||
assert result.title == "Futurama"
|
||||
assert tmdb.asked == []
|
||||
# movies keep the default order, so tmdb is consulted before tvdb there
|
||||
assert [cls.NAME for cls in providers.provider_order("movie")] == list(providers.DEFAULT_ORDER)
|
||||
|
||||
|
||||
@@ -215,7 +213,6 @@ def test_an_anime_hint_falls_through_to_the_normal_order_on_a_miss(monkeypatch:
|
||||
|
||||
assert result is not None
|
||||
assert result.title == "One Piece"
|
||||
# the imdb id is in no namespace anilist consumes, so it is never asked
|
||||
assert anilist.asked == []
|
||||
assert imdb.asked == ["tt0388629"]
|
||||
|
||||
@@ -243,8 +240,6 @@ def test_all_supplied_ids_survive_together(monkeypatch: pytest.MonkeyPatch) -> N
|
||||
assert result is not None
|
||||
assert result.external_ids.tvdb_id == 81797
|
||||
assert result.external_ids.imdb_id == "tt0388629"
|
||||
# a mal: ref the provider never resolved contributes no anilist_id; a bare id
|
||||
# would have been forced back in
|
||||
assert result.external_ids.anilist_id is None
|
||||
|
||||
result = providers.resolve_by_ids(tvdb_id=81797, anilist_id=21, kind="tv")
|
||||
|
||||
@@ -42,9 +42,6 @@ def test_changed_url_path_changes_digest():
|
||||
|
||||
|
||||
def test_query_carried_identity_is_not_collapsed():
|
||||
# all segments share a path and differ only in the query (e.g. $Time$ as a query
|
||||
# param): stripping must not collapse them into false matches; the digest goes
|
||||
# verbatim and distinct segmentations stay distinct
|
||||
a = [("https://cdn/seg?t=0", None), ("https://cdn/seg?t=100", None)]
|
||||
b = [("https://cdn/seg?t=0", None), ("https://cdn/seg?t=200", None)]
|
||||
assert resume.fingerprint(MPD, a) != resume.fingerprint(MPD, b)
|
||||
@@ -65,11 +62,11 @@ def test_reusable_roundtrip(tmp_path: Path):
|
||||
def test_reusable_never_raises(tmp_path: Path):
|
||||
save_dir = tmp_path / "Video_x_segments"
|
||||
digest = resume.fingerprint(MPD, SEGMENTS)
|
||||
assert resume.reusable(save_dir, digest) is False # no sidecar
|
||||
assert resume.reusable(save_dir, digest) is False
|
||||
resume.sidecar_path(save_dir).write_text("{not json", encoding="utf-8")
|
||||
assert resume.reusable(save_dir, digest) is False # malformed
|
||||
assert resume.reusable(save_dir, digest) is False
|
||||
resume.sidecar_path(save_dir).write_text(json.dumps({"version": 1}), encoding="utf-8")
|
||||
assert resume.reusable(save_dir, digest) is False # no digest key
|
||||
assert resume.reusable(save_dir, digest) is False
|
||||
|
||||
|
||||
def test_clear_sidecar(tmp_path: Path):
|
||||
@@ -78,7 +75,7 @@ def test_clear_sidecar(tmp_path: Path):
|
||||
resume.write_sidecar(save_dir, digest)
|
||||
resume.clear_sidecar(save_dir)
|
||||
assert resume.reusable(save_dir, digest) is False
|
||||
resume.clear_sidecar(save_dir) # idempotent on a missing file
|
||||
resume.clear_sidecar(save_dir)
|
||||
|
||||
|
||||
def test_sidecar_is_never_inside_save_dir(tmp_path: Path):
|
||||
|
||||
@@ -106,7 +106,6 @@ def make_ctx(tmp_path):
|
||||
def test_hls_second_run_reuses_completed_segments(server, tmp_path):
|
||||
server.routes["/media.m3u8"] = media_playlist()
|
||||
server.routes["/part0.bin"] = PART0
|
||||
# part1.bin missing -> run 1 completes part0 then dies during the download phase
|
||||
|
||||
ctx = make_ctx(tmp_path)
|
||||
with pytest.raises(Exception):
|
||||
@@ -130,7 +129,6 @@ def test_hls_aes128_content_never_writes_sidecar(server, tmp_path):
|
||||
server.routes["/media.m3u8"] = media_playlist(key_line)
|
||||
server.routes["/key.bin"] = AES_KEY
|
||||
server.routes["/part0.bin"] = PART0
|
||||
# part1.bin missing -> crash mid-download, the state resume would normally preserve
|
||||
|
||||
ctx = make_ctx(tmp_path)
|
||||
with pytest.raises(Exception):
|
||||
|
||||
@@ -66,8 +66,6 @@ def server():
|
||||
@pytest.fixture(autouse=True)
|
||||
def resume_enabled(monkeypatch):
|
||||
monkeypatch.setattr(config, "continue_downloads", True)
|
||||
# fail fast on the deliberately-missing segment instead of the full retry ladder
|
||||
# (import via importlib: the downloaders package exports a same-named function)
|
||||
monkeypatch.setattr(importlib.import_module("unshackle.core.downloaders.requests"), "MAX_ATTEMPTS", 1)
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
yield
|
||||
@@ -105,7 +103,6 @@ def make_ctx(tmp_path):
|
||||
save_path=tmp_path / "out.mp4",
|
||||
save_dir=tmp_path / "v0_segments",
|
||||
progress=partial(lambda **kw: None),
|
||||
# sequential: part0 must be complete before the deliberate part1 failure aborts run 1
|
||||
max_workers=1,
|
||||
)
|
||||
|
||||
@@ -113,7 +110,6 @@ def make_ctx(tmp_path):
|
||||
def test_second_run_reuses_completed_segments(server, tmp_path):
|
||||
server.routes["/init.bin"] = INIT
|
||||
server.routes["/part0.bin"] = PART0
|
||||
# part1.bin is missing -> the first run completes part0 then dies on part1
|
||||
|
||||
ctx = make_ctx(tmp_path)
|
||||
with pytest.raises(Exception):
|
||||
@@ -143,7 +139,6 @@ def test_changed_segmentation_wipes_stale_segments(server, tmp_path):
|
||||
assert (ctx.save_dir / "0.mp4").exists()
|
||||
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
# different final segment path -> different digest -> stale part0 must be re-fetched
|
||||
server.routes["/part2.bin"] = PART1
|
||||
part0_fetches_run1 = server.requests.count("/part0.bin")
|
||||
DASH.download_track(make_track(mpd(server, part1="part2.bin"), server), ctx)
|
||||
|
||||
@@ -99,7 +99,6 @@ def test_flag_off_wipes_segments_and_sidecar(tmp_path, monkeypatch):
|
||||
def test_flag_off_clears_orphaned_sidecar_without_dir(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(config, "continue_downloads", False)
|
||||
save_dir = tmp_path / "Video_t1.mp4_segments"
|
||||
# a kill between a parser's dir removal and its sidecar clear leaves exactly this
|
||||
resume.write_sidecar(save_dir, "f" * 64)
|
||||
track = make_track()
|
||||
|
||||
|
||||
@@ -40,7 +40,6 @@ def test_http_date_retry_after_honoured(session):
|
||||
|
||||
|
||||
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")
|
||||
assert 5 <= session.get_sleep_time(response(when), 1) <= 10
|
||||
|
||||
|
||||
@@ -38,7 +38,6 @@ PARTS = [bytes([0xA0 + i]) * (150 + 37 * i) for i in range(5)]
|
||||
KID = UUID(hex="11111111111111111111111111111111")
|
||||
AES_KEY = bytes(range(16))
|
||||
DECRYPTED_INIT = b"decrypted-init" * 8
|
||||
# one PIFF fragment per index, each with its own mdat payload so a misordered append shows up
|
||||
PIFF_PARTS = [piff_fragment().replace(b"\xab" * 64, bytes([0xC0 + i]) * 64) for i in range(len(PARTS))]
|
||||
|
||||
|
||||
@@ -113,7 +112,6 @@ def hls_track(srv, discontinuity: bool):
|
||||
|
||||
|
||||
def ism_track(srv):
|
||||
# audio: the init synthesis needs only CodecPrivateData, no first-segment parse
|
||||
manifest = f"""<?xml version="1.0"?>
|
||||
<SmoothStreamingMedia MajorVersion="2" MinorVersion="0" Duration="{len(PARTS) * 20000000}" TimeScale="10000000">
|
||||
<StreamIndex Type="audio" Name="audio" Language="en" Url="part{{start_time}}.m4s">
|
||||
@@ -136,7 +134,6 @@ def download_both_ways(parser, make, tmp_path, monkeypatch, expect_rolling: bool
|
||||
rolling = make_ctx(tmp_path, "rolling.mp4")
|
||||
parser.download_track(make(), rolling)
|
||||
assert not rolling.save_dir.exists() or not list(rolling.save_dir.glob("*"))
|
||||
# the rolling path never reports a Merging phase; an ineligible track must still report one
|
||||
assert ("Merging" not in rolling.statuses) == expect_rolling
|
||||
return plain.save_path.read_bytes(), rolling.save_path.read_bytes()
|
||||
|
||||
@@ -162,7 +159,6 @@ def test_ism_rolling_matches_post_merge(server, tmp_path, monkeypatch):
|
||||
@pytest.mark.parametrize("parser, make", [(HLS, hls_track), (ISM, lambda srv, _d=None: ism_track(srv))])
|
||||
def test_incomplete_rolling_merge_raises_and_leaves_no_output(server, tmp_path, monkeypatch, parser, make):
|
||||
monkeypatch.setattr(config, "merge_segments", True)
|
||||
# a drain that never reaches the end must not ship a short file as a finished track
|
||||
monkeypatch.setattr(RollingMerge, "add", lambda self, *a, **kw: None)
|
||||
ctx = make_ctx(tmp_path, "short.mp4")
|
||||
with pytest.raises(FileNotFoundError, match="Rolling merge appended 0 of"):
|
||||
@@ -199,7 +195,6 @@ class FakeSegmentDecrypter:
|
||||
|
||||
|
||||
def no_decrypt(monkeypatch, module):
|
||||
# the merged file is compared byte for byte, so the decrypt step and its check are stubbed
|
||||
monkeypatch.setattr(module, "decrypt_track", lambda *a, **kw: None)
|
||||
monkeypatch.setattr(module, "assert_fragments_decrypted", lambda *a, **kw: None)
|
||||
|
||||
@@ -216,7 +211,6 @@ def test_ism_encrypted_rolling_matches_post_merge(server, tmp_path, monkeypatch)
|
||||
|
||||
plain, rolling = download_both_ways(ISM, make, tmp_path, monkeypatch, True)
|
||||
assert rolling == plain
|
||||
# every fragment went through the PIFF to CENC rewrite, and the head carries the KID
|
||||
assert PIFF_SENC_UUID not in rolling
|
||||
assert rolling.count(b"senc") == len(PIFF_PARTS)
|
||||
assert bytes.fromhex(KID.hex) in rolling
|
||||
@@ -251,7 +245,6 @@ def test_hls_segment_decrypt_rolling_writes_decrypted_init(server, tmp_path, mon
|
||||
|
||||
|
||||
def test_hls_aes128_keeps_post_merge(server, tmp_path, monkeypatch):
|
||||
# AES-128 with no IV attribute: each segment's IV is its media sequence number
|
||||
for i, part in enumerate(PARTS):
|
||||
server.routes[f"/part{i}.m4s"] = AES.new(AES_KEY, AES.MODE_CBC, i.to_bytes(16, "big")).encrypt(pad(part, 16))
|
||||
server.routes["/key.bin"] = AES_KEY
|
||||
@@ -285,7 +278,6 @@ def test_hls_rekey_takes_the_kid_from_the_init_segment_of_the_new_key(server, tm
|
||||
lines += ["#EXT-X-DISCONTINUITY", '#EXT-X-MAP:URI="init2.mp4"', key_line(b"b")]
|
||||
lines += ["#EXTINF:4.0,", f"part{i}.m4s"]
|
||||
server.routes["/media.m3u8"] = "\n".join(lines + ["#EXT-X-ENDLIST"]).encode()
|
||||
# the real probe needs FFprobe and a tenc box; the KID follows the init bytes the parser hands over
|
||||
monkeypatch.setattr(
|
||||
type(track), "get_key_id", lambda self, init_data=None, **kw: {later_init: later_kid}.get(init_data, KID)
|
||||
)
|
||||
|
||||
@@ -161,11 +161,11 @@ def test_an_exempt_http_session_does_not_warn(caplog, exempt):
|
||||
|
||||
def test_service_instance_uses_the_proxy_of_its_own_run(caplog):
|
||||
with caplog.at_level(logging.WARNING):
|
||||
Svc().lookup("direct.example") # a run with no proxy
|
||||
Svc().lookup("direct.example")
|
||||
first, second = Svc(PROXY), Svc(PROXY)
|
||||
first.lookup("leak.example")
|
||||
first.lookup("leak.example")
|
||||
second.lookup("leak.example") # a second run warns again
|
||||
second.lookup("leak.example")
|
||||
assert leaks(caplog) == [leaks(caplog)[0]] * 2
|
||||
assert "leak.example" in leaks(caplog)[0]
|
||||
assert {r.name for r in caplog.records if r.getMessage() in leaks(caplog)} == {"Svc"}
|
||||
@@ -175,7 +175,7 @@ def test_a_reloaded_service_class_uses_the_proxy_of_its_own_run(caplog):
|
||||
"""A service reload makes a new class from the same directory; the watch still holds the old one."""
|
||||
reloaded = type("Svc", (), {"__init__": Svc.__init__, "lookup": Svc.lookup})
|
||||
with caplog.at_level(logging.WARNING):
|
||||
reloaded().lookup("direct.example") # a run with no proxy
|
||||
reloaded().lookup("direct.example")
|
||||
reloaded(PROXY).lookup("leak.example")
|
||||
assert len(leaks(caplog)) == 1
|
||||
assert "leak.example" in leaks(caplog)[0]
|
||||
@@ -208,7 +208,7 @@ def test_fallback_session_takes_the_proxy_of_the_calling_run():
|
||||
session = Svc("http://own.example:1").fallback()
|
||||
assert session.proxies == {"all": "http://own.example:1"}
|
||||
assert session.trust_env is False
|
||||
assert run_proxy.fallback_session().proxies == {"all": PROXY} # this module, with one watched run
|
||||
assert run_proxy.fallback_session().proxies == {"all": PROXY}
|
||||
|
||||
|
||||
def test_fallback_session_without_a_service_frame(monkeypatch):
|
||||
@@ -218,13 +218,13 @@ def test_fallback_session_without_a_service_frame(monkeypatch):
|
||||
run_as(os.path.join(run_proxy.CORE_DIR, "core", "x.py"), source, run_proxy=run_proxy, result=found)
|
||||
return found[0]
|
||||
|
||||
monkeypatch.setattr(Svc, "__module__", "elsewhere") # no frame in this file is service code now
|
||||
monkeypatch.setattr(Svc, "__module__", "elsewhere")
|
||||
run_proxy.watched[next(iter(run_proxy.watched))].directory = "/nowhere/"
|
||||
assert from_core().proxies == {"all": PROXY} # one watched run, as in a CLI download thread
|
||||
assert from_core().proxies == {"all": PROXY}
|
||||
run_proxy.watch(Svc, "http://second.example:1")
|
||||
run_proxy.watched["/nowhere/"] = run_proxy.watched.popitem()[1]
|
||||
run_proxy.watched["/nowhere/"].proxies.append("http://second.example:1")
|
||||
assert from_core().proxies == {} # two runs: no way to tell which one
|
||||
assert from_core().proxies == {}
|
||||
|
||||
|
||||
def test_pin_keeps_the_env_ca_bundle(monkeypatch):
|
||||
|
||||
@@ -6,9 +6,6 @@ from unshackle.core.api.sanitize import safe_cache_key
|
||||
|
||||
|
||||
def test_safe_cache_key_rejects_backslash_traversal():
|
||||
# On POSIX, backslash is a plain character, so pathlib.Path treats
|
||||
# "..\\..\\secret" as one filename; written as "<key>.json" it escapes the
|
||||
# cache dir on Windows. PureWindowsPath handling must reject it everywhere.
|
||||
assert safe_cache_key("..\\..\\secret") is None
|
||||
assert safe_cache_key("sub\\..\\secret") is None
|
||||
|
||||
@@ -38,8 +35,6 @@ def test_safe_cache_key_accepts_plain_filename():
|
||||
|
||||
|
||||
def test_safe_cache_key_accepts_nested_key_and_normalises_separators():
|
||||
# A Cacher key with a subdirectory ("session_web/<sha1>") keeps its
|
||||
# posix form; a backslash from a Windows peer names the same nested file.
|
||||
assert safe_cache_key("session_web/abc") == "session_web/abc"
|
||||
assert safe_cache_key("MSL/a/b") == "MSL/a/b"
|
||||
assert safe_cache_key("session_web\\abc") == "session_web/abc"
|
||||
|
||||
@@ -14,18 +14,18 @@ import pytest
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.utilities import sanitize_filename
|
||||
|
||||
THAI = "\u0e40\u0e1b\u0e47\u0e19\u0e15\u0e48\u0e2d" # a Thai title with vowel and tone marks
|
||||
THAI = "\u0e40\u0e1b\u0e47\u0e19\u0e15\u0e48\u0e2d"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name",
|
||||
[
|
||||
THAI,
|
||||
"\u0e01\u0e31\u0e49\u0e19", # Thai: a tone mark stacked on an upper vowel
|
||||
"\u0939\u093f\u0902\u0926\u0940", # Devanagari
|
||||
"\u09b0\u200d\u09cd\u09af\u09be\u09ac", # Bengali: the virama follows a zero width joiner
|
||||
"\u1040\u102d\u102f\u1004\u103a\u1038", # Burmese: a mark on digit zero, typed for the letter wa
|
||||
"\u0e19\u0e49\u0e33", # Thai sara am, which NFKC would split into two characters
|
||||
"\u0e01\u0e31\u0e49\u0e19",
|
||||
"\u0939\u093f\u0902\u0926\u0940",
|
||||
"\u09b0\u200d\u09cd\u09af\u09be\u09ac",
|
||||
"\u1040\u102d\u102f\u1004\u103a\u1038",
|
||||
"\u0e19\u0e49\u0e33",
|
||||
],
|
||||
)
|
||||
def test_unicode_filenames_keep_marks(name: str) -> None:
|
||||
@@ -35,7 +35,6 @@ def test_unicode_filenames_keep_marks(name: str) -> None:
|
||||
@pytest.mark.parametrize(
|
||||
("name", "expected"),
|
||||
[
|
||||
# Decomposed and composed spellings give the same name.
|
||||
("Cafe\u0301", "Caf\u00e9"),
|
||||
("Caf\u00e9", "Caf\u00e9"),
|
||||
("Show \u2764\ufe0f", "Show.\u2764\ufe0f"),
|
||||
@@ -51,7 +50,6 @@ def test_unicode_filenames_use_nfc_and_drop_control_characters(name: str, expect
|
||||
[
|
||||
("Cafe\u0301 Name", "Cafe.Name"),
|
||||
("Caf\u00e9 Name", "Cafe.Name"),
|
||||
# Katakana with separate voicing marks transliterates like the composed spelling.
|
||||
("\u30ab\u3099\u30f3\u30bf\u3099\u30e0", "gandamu"),
|
||||
("\u30ac\u30f3\u30c0\u30e0", "gandamu"),
|
||||
("Some\x07Title", "SomeTitle"),
|
||||
@@ -69,7 +67,6 @@ def test_config_option_decides_when_unicode_is_not_passed(monkeypatch: pytest.Mo
|
||||
|
||||
|
||||
def test_sanitising_a_name_again_does_not_change_it() -> None:
|
||||
# The removed "?" sits between the letter and its mark.
|
||||
once = sanitize_filename("e?\u0301", unicode=True)
|
||||
assert once == "\u00e9"
|
||||
assert sanitize_filename(once, unicode=True) == once
|
||||
|
||||
@@ -31,7 +31,6 @@ def test_is_repo_spec(value, expected):
|
||||
|
||||
|
||||
def test_is_repo_spec_existing_path_wins(tmp_path):
|
||||
# an owner/repo-looking value that exists locally is a path, not a repo
|
||||
local = tmp_path / "owner" / "repo"
|
||||
local.mkdir(parents=True)
|
||||
assert service_repo.is_repo_spec(str(local)) is False
|
||||
@@ -51,7 +50,6 @@ def test_parse_spec(spec, url, branch, dest):
|
||||
|
||||
|
||||
def test_slug_distinguishes_hosts():
|
||||
# same owner/repo on different hosts must not share a clone dir
|
||||
a = service_repo.parse_spec("https://github.com/owner/repo")[2]
|
||||
b = service_repo.parse_spec("https://gitlab.com/owner/repo")[2]
|
||||
assert a != b
|
||||
@@ -66,11 +64,11 @@ def test_repos_base_uses_configured_local_dir(monkeypatch, tmp_path):
|
||||
|
||||
def test_is_stale(tmp_path):
|
||||
stamp = tmp_path / "stamp"
|
||||
assert service_repo.is_stale(stamp, ttl=10) is True # missing → stale
|
||||
assert service_repo.is_stale(stamp, ttl=10) is True
|
||||
stamp.write_text(str(time.time()))
|
||||
assert service_repo.is_stale(stamp, ttl=10) is False # fresh
|
||||
assert service_repo.is_stale(stamp, ttl=10) is False
|
||||
stamp.write_text(str(time.time() - 100))
|
||||
assert service_repo.is_stale(stamp, ttl=10) is True # old
|
||||
assert service_repo.is_stale(stamp, ttl=10) is True
|
||||
|
||||
|
||||
def test_clone_invokes_git(monkeypatch, tmp_path):
|
||||
@@ -81,7 +79,7 @@ def test_clone_invokes_git(monkeypatch, tmp_path):
|
||||
|
||||
def fake_run(args, **kw):
|
||||
calls.append(args)
|
||||
(tmp_path / "github.com__owner__repo").mkdir(parents=True, exist_ok=True) # simulate clone output
|
||||
(tmp_path / "github.com__owner__repo").mkdir(parents=True, exist_ok=True)
|
||||
return subprocess.CompletedProcess(args, 0, b"", b"")
|
||||
|
||||
monkeypatch.setattr(service_repo.subprocess, "run", fake_run)
|
||||
@@ -90,7 +88,7 @@ def test_clone_invokes_git(monkeypatch, tmp_path):
|
||||
assert dest == tmp_path / "github.com__owner__repo"
|
||||
assert calls[0][:4] == ["git", "clone", "--depth", "1"]
|
||||
assert "-b" in calls[0] and "main" in calls[0]
|
||||
assert service_repo.stamp_for(dest).exists() # stamp written (beside the clone, not inside)
|
||||
assert service_repo.stamp_for(dest).exists()
|
||||
|
||||
|
||||
def test_clone_missing_git_returns_none(monkeypatch, tmp_path):
|
||||
@@ -119,7 +117,7 @@ def git_stub(porcelain=b"", ahead=b"0"):
|
||||
return subprocess.CompletedProcess(args, 0, porcelain, b"")
|
||||
if sub == "rev-list":
|
||||
return subprocess.CompletedProcess(args, 0, ahead, b"")
|
||||
return subprocess.CompletedProcess(args, 0, b"", b"") # pull
|
||||
return subprocess.CompletedProcess(args, 0, b"", b"")
|
||||
|
||||
return run
|
||||
|
||||
@@ -143,7 +141,6 @@ def test_is_dirty_clean(monkeypatch):
|
||||
|
||||
|
||||
def test_is_dirty_ignores_untracked_files(monkeypatch):
|
||||
# status must ask git to skip untracked files so importing services (__pycache__) isn't "dirty"
|
||||
seen = []
|
||||
monkeypatch.setattr(service_repo.binaries, "Git", "git")
|
||||
|
||||
@@ -162,7 +159,7 @@ def test_auto_refresh_refuses_dirty_clone(monkeypatch, tmp_path):
|
||||
"""Auto path (force=False): a stale clone with local edits raises instead of clobbering."""
|
||||
dest = tmp_path / "github.com__a__b"
|
||||
dest.mkdir(parents=True)
|
||||
service_repo.stamp_for(dest).write_text("0") # stale → refresh due
|
||||
service_repo.stamp_for(dest).write_text("0")
|
||||
monkeypatch.setattr(service_repo, "repos_base", lambda: tmp_path)
|
||||
monkeypatch.setattr(service_repo.binaries, "Git", "git")
|
||||
monkeypatch.setattr(service_repo.subprocess, "run", git_stub(porcelain=b" M f\n"))
|
||||
@@ -184,12 +181,12 @@ def test_manual_refresh_force_overwrites(monkeypatch, tmp_path):
|
||||
lambda args, **kw: (calls.append(args[3]), subprocess.CompletedProcess(args, 0, b"", b""))[1],
|
||||
)
|
||||
assert service_repo.resolve_service_repo("a/b", force=True) == dest
|
||||
assert "fetch" in calls and "reset" in calls # force-sync ran
|
||||
assert "status" not in calls # no dirty gate on the force path
|
||||
assert "fetch" in calls and "reset" in calls
|
||||
assert "status" not in calls
|
||||
calls.clear()
|
||||
service_repo.write_stamp(service_repo.stamp_for(dest)) # fresh stamp, inside the TTL
|
||||
service_repo.write_stamp(service_repo.stamp_for(dest))
|
||||
assert service_repo.resolve_service_repo("a/b", force=True) == dest
|
||||
assert calls == [] # no network before the TTL expires
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_changed_services_groups_by_top_dir(monkeypatch):
|
||||
@@ -228,10 +225,10 @@ def test_refresh_reports_discarded_local_edits(monkeypatch, tmp_path):
|
||||
|
||||
def run(args, **kw):
|
||||
if "diff" in args and "--name-only" in args:
|
||||
return subprocess.CompletedProcess(args, 0, b"EXAMPLE/__init__.py\n", b"") # local edit present
|
||||
return subprocess.CompletedProcess(args, 0, b"EXAMPLE/__init__.py\n", b"")
|
||||
if "rev-parse" in args:
|
||||
return subprocess.CompletedProcess(args, 0, b"samehead\n", b"") # upstream did not advance
|
||||
return subprocess.CompletedProcess(args, 0, b"", b"") # fetch/reset/diff
|
||||
return subprocess.CompletedProcess(args, 0, b"samehead\n", b"")
|
||||
return subprocess.CompletedProcess(args, 0, b"", b"")
|
||||
|
||||
monkeypatch.setattr(service_repo.subprocess, "run", run)
|
||||
_, changes = service_repo.refresh_repo("a/b")
|
||||
@@ -240,7 +237,6 @@ def test_refresh_reports_discarded_local_edits(monkeypatch, tmp_path):
|
||||
|
||||
def test_changed_services_up_to_date(monkeypatch):
|
||||
monkeypatch.setattr(service_repo.binaries, "Git", "git")
|
||||
# same HEAD before/after → no diff computed at all
|
||||
monkeypatch.setattr(service_repo.subprocess, "run", lambda *a, **k: pytest.fail("no git diff when HEAD unchanged"))
|
||||
assert service_repo.changed_services(Path("/x"), "same", "same") == []
|
||||
|
||||
@@ -318,7 +314,7 @@ def test_collision_first_source_wins(tmp_path, order):
|
||||
|
||||
seen: dict = {}
|
||||
shadowed: list = []
|
||||
for name in order: # services.py preserves config order
|
||||
for name in order:
|
||||
for path in dirs[name].glob("*/__init__.py"):
|
||||
tag = path.parent.stem
|
||||
if tag in seen:
|
||||
|
||||
@@ -20,7 +20,6 @@ def write_service(root: Path, version: int) -> None:
|
||||
pkg.mkdir(exist_ok=True)
|
||||
init = pkg / "__init__.py"
|
||||
init.write_text(f"class FOO:\n VERSION = {version}\n ALIASES = ('foo{version}',)\n")
|
||||
# the bytecode cache keys on mtime and size; same-second rewrites of equal length would reuse the stale .pyc
|
||||
os.utime(init, (time.time() + version, time.time() + version))
|
||||
|
||||
|
||||
@@ -98,7 +97,6 @@ def test_apply_pending_never_reports_a_failed_reimport_as_applied(
|
||||
assert services.apply_pending(busy=set()) == []
|
||||
assert services.MODULES["FOO"].VERSION == 1
|
||||
assert services.LOAD_ERRORS and services.LOAD_ERRORS[0].startswith("FOO: ")
|
||||
# The commit must still name the code that is running, not the one that failed to import.
|
||||
assert services.LOADED_COMMITS["FOO"] == "old-head"
|
||||
|
||||
write_service(service_dir, 3)
|
||||
|
||||
@@ -27,8 +27,6 @@ class Recorder(BaseHTTPRequestHandler):
|
||||
|
||||
def do_GET(self) -> None:
|
||||
type(self).received.append({k.lower(): v for k, v in self.headers.items()})
|
||||
# rnet sends one Cookie header per cookie on HTTP/1.1, so a dict of the headers
|
||||
# keeps only the last one and hides a cookie that leaked.
|
||||
type(self).cookies_sent.append("; ".join(self.headers.get_all("Cookie") or []))
|
||||
body = b"ok"
|
||||
self.send_response(200)
|
||||
|
||||
@@ -20,7 +20,7 @@ from unshackle.core.utils import tags as tags_module
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
SESSION = object() # sentinel: tag_file must hand this straight to the music tagger
|
||||
SESSION = object()
|
||||
|
||||
|
||||
class DummyService:
|
||||
@@ -48,7 +48,7 @@ def calls(monkeypatch: pytest.MonkeyPatch) -> Calls:
|
||||
|
||||
monkeypatch.setattr(tags_module, "write_music_metadata", fake_write_music_metadata)
|
||||
monkeypatch.setattr(tags_module, "apply_tags", fake_apply_tags)
|
||||
monkeypatch.setattr(config, "tag_imdb_tmdb", False) # keep provider lookups out of a unit test
|
||||
monkeypatch.setattr(config, "tag_imdb_tmdb", False)
|
||||
return recorded
|
||||
|
||||
|
||||
|
||||
@@ -169,6 +169,5 @@ def test_clear_directory_removes_stale_task_dir(temp_root: Path) -> None:
|
||||
files_count, freed_bytes = clear_directory(temp_root)
|
||||
assert not task_dir.exists()
|
||||
assert temp_root.is_dir()
|
||||
# glob("**/*") never matches dotfiles, so .lock is not counted
|
||||
assert files_count == 1
|
||||
assert freed_bytes == 5
|
||||
|
||||
@@ -21,13 +21,10 @@ from unshackle.core.utils.template_formatter import TemplateFormatter, detect_sp
|
||||
@pytest.mark.parametrize(
|
||||
("template", "context", "expected"),
|
||||
[
|
||||
# An omitted conditional inside brackets must take the whole group with it.
|
||||
("{title} ({year?})", {"title": "Some Movie", "year": ""}, "Some Movie"),
|
||||
("{title} [{quality?}]", {"title": "Some Movie", "quality": ""}, "Some Movie"),
|
||||
("{title} ({year?}) [{quality?}]", {"title": "T", "year": "", "quality": ""}, "T"),
|
||||
# The group survives when the value is present.
|
||||
("{title} ({year?})", {"title": "Some Movie", "year": "2024"}, "Some Movie (2024)"),
|
||||
# #107: the dash wins, so the release tag stays attached.
|
||||
(
|
||||
"{title}.{year}.{atmos?}-{tag}",
|
||||
{"title": "Some Movie", "year": "2024", "atmos": "", "tag": "GRP"},
|
||||
@@ -38,9 +35,7 @@ from unshackle.core.utils.template_formatter import TemplateFormatter, detect_sp
|
||||
{"title": "Some Movie", "year": "2024", "atmos": "Atmos", "tag": "GRP"},
|
||||
"Some.Movie.2024.Atmos-GRP",
|
||||
),
|
||||
# A conditional between two dashes must not leave a doubled separator.
|
||||
("{title} - {edition?} - {year}", {"title": "A", "edition": "", "year": "2024"}, "A - 2024"),
|
||||
# Consecutive omitted conditionals collapse to nothing.
|
||||
("{a?} {b?} {title}", {"a": "", "b": "", "title": "T"}, "T"),
|
||||
("{show} S{season}E{ep} {name?}", {"show": "Show", "season": "01", "ep": "02", "name": ""}, "Show S01E02"),
|
||||
],
|
||||
@@ -94,25 +89,21 @@ def test_sanitize_filename_keeps_interior_dots():
|
||||
@pytest.mark.parametrize(
|
||||
("template", "context", "expected"),
|
||||
[
|
||||
# Space-separated style.
|
||||
("{title} ({year})", {"title": "Some Movie", "year": "2024"}, "Some Movie (2024)"),
|
||||
(
|
||||
"{title} {year} {quality} {source}",
|
||||
{"title": "Some Movie", "year": "2024", "quality": "1080p", "source": "WEB-DL"},
|
||||
"Some Movie 2024 1080p WEB-DL",
|
||||
),
|
||||
# Dot-separated style.
|
||||
(
|
||||
"{title}.{year}.{quality}.{source}",
|
||||
{"title": "Some Movie", "year": "2024", "quality": "1080p", "source": "WEB-DL"},
|
||||
"Some.Movie.2024.1080p.WEB-DL",
|
||||
),
|
||||
# Interior dots in the title itself survive both styles.
|
||||
("{title}.{year}", {"title": "Mr. Robot", "year": "2015"}, "Mr.Robot.2015"),
|
||||
("{title} ({year})", {"title": "Mr. Robot", "year": "2015"}, "Mr. Robot (2015)"),
|
||||
("{title}.{year}", {"title": "S.W.A.T.", "year": "2017"}, "S.W.A.T.2017"),
|
||||
("{title} ({year})", {"title": "S.W.A.T.", "year": "2017"}, "S.W.A.T. (2017)"),
|
||||
# A decimal inside a codec name is not a separator.
|
||||
(
|
||||
"{title}.{year}.{audio}-{tag}",
|
||||
{"title": "Some Movie", "year": "2024", "audio": "DDP5.1", "tag": "GRP"},
|
||||
@@ -240,8 +231,6 @@ def test_series_folder_handles_both_separator_styles(folder_config, template, ex
|
||||
@pytest.mark.parametrize(
|
||||
("template", "expected"),
|
||||
[
|
||||
# A segment with one variable has no gap to judge by, so it follows the whole
|
||||
# path's style instead of falling back to a dot.
|
||||
("Music/{artist}/{album} ({year?})", "Music/Some Artist/Some Album (2025)"),
|
||||
("Music/{artist}/{album}.{year?}", "Music/Some.Artist/Some.Album.2025"),
|
||||
("{artist}/{album}", "Some.Artist/Some.Album"),
|
||||
@@ -262,7 +251,7 @@ def test_single_variable_segments_follow_the_whole_path(folder_config, template,
|
||||
("{title} ({year})", " "),
|
||||
("Movies/{title} ({year?})", " "),
|
||||
("Shows/{title}.{year?}/Season.{season}", "."),
|
||||
("{title}", "."), # nothing between two variables, so scene style wins
|
||||
("{title}", "."),
|
||||
],
|
||||
)
|
||||
def test_detect_spacer(template, expected):
|
||||
@@ -272,8 +261,6 @@ def test_detect_spacer(template, expected):
|
||||
@pytest.mark.parametrize(
|
||||
("series_template", "expected"),
|
||||
[
|
||||
# Deriving a show folder strips the episode tokens, so the template ends on a
|
||||
# separator once {episode_name?} goes too.
|
||||
("{title}.{year?}.{season_episode}.{episode_name?}", "Some.Show.S01"),
|
||||
("{title} {year?} {season_episode} {episode_name?}", "Some Show S01"),
|
||||
],
|
||||
|
||||
+3
-15
@@ -15,8 +15,6 @@ REMOTE_IDS = [
|
||||
{"id": "615", "type": 12, "sourceName": "TheMovieDB.com"},
|
||||
]
|
||||
|
||||
# Futurama: aired S1 stops at E9, the four held-back episodes open aired S2.
|
||||
# DVD order folds them back into S1 as E10-E13.
|
||||
AIRED = [
|
||||
{"id": 1, "seasonNumber": 1, "number": 9, "name": "Hell Is Other Robots"},
|
||||
{"id": 2, "seasonNumber": 2, "number": 1, "name": "A Flight to Remember"},
|
||||
@@ -49,7 +47,6 @@ def test_order_map_joins_on_episode_id(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
assert mapping[(1, 9)] == (1, 9, "Hell Is Other Robots")
|
||||
assert mapping[(2, 1)] == (1, 10, "A Flight to Remember")
|
||||
assert mapping[(2, 2)] == (1, 11, "Mars University")
|
||||
# an episode absent from the target order is left out, so it keeps its own numbering
|
||||
assert (2, 3) not in mapping
|
||||
|
||||
|
||||
@@ -74,7 +71,6 @@ def test_order_map_empty_when_order_missing(monkeypatch: pytest.MonkeyPatch) ->
|
||||
def test_detect_order_picks_the_order_the_numbering_matches(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
p = TVDBProvider()
|
||||
stub(p, monkeypatch)
|
||||
# a service may number a series in a non-aired order, so detection must not assume aired
|
||||
assert p.detect_order(73871, [(1, 10), (1, 11)]) == "dvd"
|
||||
assert p.detect_order(73871, [(2, 1), (2, 2), (2, 3)]) == "official"
|
||||
|
||||
@@ -85,7 +81,6 @@ def test_detect_order_falls_back_to_aired(monkeypatch: pytest.MonkeyPatch) -> No
|
||||
assert p.detect_order(73871, [(1, 1)]) == "official"
|
||||
|
||||
|
||||
# TVDB holds both Battlestar Galactica series; the 2003 revival is filed under year 2005
|
||||
BSG = [
|
||||
{"name": "Battlestar Galactica", "year": "1978", "tvdb_id": "71173"},
|
||||
{"name": "Battlestar Galactica (2003)", "year": "2005", "tvdb_id": "73545"},
|
||||
@@ -93,7 +88,6 @@ BSG = [
|
||||
|
||||
|
||||
def test_pick_match_prefers_the_right_era() -> None:
|
||||
# exact title match on the 1978 series must not beat the era the caller asked for
|
||||
best, _, _ = pick_match(BSG, "Battlestar Galactica", 2004)
|
||||
assert best["tvdb_id"] == "73545"
|
||||
best, _, _ = pick_match(BSG, "Battlestar Galactica", 1978)
|
||||
@@ -110,7 +104,6 @@ def test_pick_match_returns_nothing_when_no_year_fits() -> None:
|
||||
|
||||
|
||||
def test_tvdb2_tag_follows_the_matroska_spec() -> None:
|
||||
# TVDB2 IDs are prefixed by entity type: matroska.org/technical/tagging.html
|
||||
from unshackle.core.providers import ExternalIds
|
||||
|
||||
assert build_tags_from_ids(ExternalIds(tvdb_id=73871), "tv")["TVDB2"] == "series/73871"
|
||||
@@ -124,15 +117,12 @@ def test_provider_order_defaults(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
|
||||
def test_provider_order_is_configurable(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(config, "metadata_providers", ["TVDB", "tmdb", "nope", "tvdb"])
|
||||
# unknown entries dropped, duplicates collapsed, case ignored, order kept
|
||||
assert [c.NAME for c in providers.provider_order()] == ["tvdb", "tmdb"]
|
||||
|
||||
|
||||
def test_enrichment_authority_is_fixed(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
# search order must not demote TMDB below SIMKL for cross-validation tie-breaks
|
||||
monkeypatch.setattr(config, "metadata_providers", [])
|
||||
assert providers.enrichment_providers() == ["tmdb", "simkl", "tvdb"]
|
||||
# `metadata_providers` filters the set but does not re-rank the trust order
|
||||
monkeypatch.setattr(config, "metadata_providers", ["tvdb", "simkl"])
|
||||
assert providers.enrichment_providers() == ["simkl", "tvdb"]
|
||||
|
||||
@@ -149,7 +139,6 @@ def test_cached_tvdb_result_keeps_enriched_ids() -> None:
|
||||
assert result.external_ids.tvdb_id == 73871
|
||||
assert result.external_ids.imdb_id == "tt0149460"
|
||||
assert result.external_ids.tmdb_id == 615
|
||||
# remote_ids stay authoritative over the enriched copies
|
||||
cached["remote_ids"] = REMOTE_IDS
|
||||
cached["_enriched_ids"] = {"imdb_id": "tt9999999", "tmdb_id": 1}
|
||||
result = providers.cached_to_result(cached, "tvdb", "tv")
|
||||
@@ -182,7 +171,6 @@ def test_get_episodes_fails_closed_on_a_truncated_listing(monkeypatch: pytest.Mo
|
||||
p = TVDBProvider()
|
||||
pages: dict[int, object] = {0: {"episodes": [{"id": n} for n in range(500)]}, 1: None}
|
||||
monkeypatch.setattr(p, "api_get", lambda _path, params: pages[params["page"]])
|
||||
# page 1 fails mid-listing: a partial list would renumber wrongly
|
||||
assert p.get_episodes(73871, "official") == []
|
||||
assert p._episodes == {}
|
||||
|
||||
@@ -244,7 +232,7 @@ def test_parts_of_one_episode_renumber_together(monkeypatch: pytest.MonkeyPatch)
|
||||
def test_a_real_collision_still_bails(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Dedupe must not disable the guard: two distinct episodes on one slot still refuses."""
|
||||
episodes = [ep(1, 1), ep(1, 2)]
|
||||
mapping = {(1, 2): (1, 1, "Clash")} # (1, 1) is unmapped and keeps the slot (1, 2) moves onto
|
||||
mapping = {(1, 2): (1, 1, "Clash")}
|
||||
titles, errors = renumber(monkeypatch, episodes, mapping)
|
||||
assert errors # refused, with the "two episodes each" error
|
||||
assert [(t.season, t.number) for t in titles] == [(1, 1), (1, 2)] # numbering untouched
|
||||
assert errors
|
||||
assert [(t.season, t.number) for t in titles] == [(1, 1), (1, 2)]
|
||||
|
||||
@@ -39,11 +39,10 @@ def test_flagged_pair_is_skipped_and_named(tmp_path: Path) -> None:
|
||||
|
||||
assert vaults.get_key(KID) == (BAD, poisoned)
|
||||
assert vaults.sources[KID] == (BAD, poisoned)
|
||||
local.add_key("SVC", KID, BAD) # the cross-vault copy that happened before verification
|
||||
local.add_key("SVC", KID, BAD)
|
||||
|
||||
vaults.flag_bad_key(KID, BAD)
|
||||
|
||||
# both the local copy and every later remote hit of that pair are gone
|
||||
assert local.get_key(KID, "SVC") is None
|
||||
assert vaults.get_key(KID) == (None, None)
|
||||
assert local.is_bad_key(KID, BAD)
|
||||
@@ -51,13 +50,11 @@ def test_flagged_pair_is_skipped_and_named(tmp_path: Path) -> None:
|
||||
row = local.conn_factory.get().execute("SELECT service, source FROM bad_keys").fetchone()
|
||||
assert row == ("SVC", "poisoned")
|
||||
|
||||
# another vault with a different key for the same KID still answers
|
||||
other = Remote("other", tmp_path / "other.db")
|
||||
other.add_key("SVC", KID, GOOD)
|
||||
vaults.vaults.append(other)
|
||||
assert vaults.get_key(KID) == (GOOD, other)
|
||||
|
||||
# a flagged row that comes back (kv copy from an old export) is invisible to the lookup
|
||||
local.conn_factory.get().execute("INSERT OR IGNORE INTO `SVC` (kid, key_) VALUES (?, ?)", (KID.hex, BAD))
|
||||
local.conn_factory.get().commit()
|
||||
assert local.get_key(KID, "SVC") is None
|
||||
@@ -74,7 +71,6 @@ class FakeDRM:
|
||||
|
||||
def decrypt(self, path: Path) -> None:
|
||||
self.decrypted_with.append(dict(self.content_keys))
|
||||
# like the real decrypters: write a new file, then replace the input
|
||||
out = path.with_stem(path.stem + "_decrypted")
|
||||
out.write_bytes(b"plain:" + self.content_keys[KID].encode())
|
||||
path.unlink()
|
||||
@@ -115,7 +111,7 @@ def test_decrypt_verified_flags_and_retries(tmp_path: Path, monkeypatch: pytest.
|
||||
|
||||
def licence(drm: FakeDRM, track_kid: UUID) -> None:
|
||||
assert KID not in drm.content_keys
|
||||
assert vaults.get_key(KID) == (None, None) # the flagged pair is skipped on the retry
|
||||
assert vaults.get_key(KID) == (None, None)
|
||||
vaults.vaults.append(other)
|
||||
drm.content_keys[KID] = vaults.get_key(KID)[0]
|
||||
|
||||
@@ -125,11 +121,10 @@ def test_decrypt_verified_flags_and_retries(tmp_path: Path, monkeypatch: pytest.
|
||||
assert path.read_bytes() == b"plain:" + GOOD.encode()
|
||||
assert drm.decrypted_with == [{KID: BAD}, {KID: GOOD}]
|
||||
assert local.is_bad_key(KID, BAD)
|
||||
assert local.get_key(KID, "SVC") == GOOD # the key that proved itself on the retry is kept locally
|
||||
assert local.get_key(KID, "SVC") == GOOD
|
||||
assert KID not in dl.LICENSE_KEY_CACHE
|
||||
assert not (tmp_path / "video.mp4.enc").exists()
|
||||
|
||||
# a sibling track that still carries the poisoned key is checked too and takes the cached good key
|
||||
sibling = tmp_path / "audio.mp4"
|
||||
sibling.write_bytes(b"cipher")
|
||||
drm2 = FakeDRM({KID: BAD})
|
||||
@@ -149,12 +144,12 @@ def test_no_local_vault_raises_instead_of_reusing_the_poison(tmp_path: Path, mon
|
||||
drm = FakeDRM({KID: BAD})
|
||||
|
||||
def licence(drm: FakeDRM, track_kid: UUID) -> None:
|
||||
key, _ = vaults.get_key(KID) # nothing holds the flag, so the same pair comes back
|
||||
key, _ = vaults.get_key(KID)
|
||||
drm.content_keys[KID] = key
|
||||
|
||||
with pytest.raises(ValueError, match="no other source"):
|
||||
cmd.decrypt_verified(drm, path, licence, KID)
|
||||
assert path.read_bytes() == b"cipher" # ciphertext restored, nothing written with the poison
|
||||
assert path.read_bytes() == b"cipher"
|
||||
assert not (tmp_path / "video.mp4.enc").exists()
|
||||
|
||||
|
||||
@@ -210,7 +205,7 @@ def test_every_poisoned_vault_is_burned_then_the_cdm_answers(tmp_path: Path, mon
|
||||
cmd.decrypt_verified(drm, path, licence, KID)
|
||||
assert path.read_bytes() == b"plain:" + GOOD.encode()
|
||||
assert cdm_calls == 1
|
||||
assert len(drm.decrypted_with) == 4 # three vault keys burned, then the CDM key
|
||||
assert len(drm.decrypted_with) == 4
|
||||
assert all(local.is_bad_key(KID, f"{i + 1:02x}" * 16) for i in range(3))
|
||||
|
||||
|
||||
@@ -226,7 +221,6 @@ def test_kv_copy_never_moves_the_flag_table(tmp_path: Path) -> None:
|
||||
assert list(src.get_services()) == ["SVC"]
|
||||
assert copy_service_data(dst, src, "bad_keys", logging.getLogger("t")) == 0
|
||||
assert list(dst.get_services()) == []
|
||||
# a flagged pair in the source never reaches a destination that knows it is bad
|
||||
kid2 = UUID("22222222-2222-3333-4444-555555555555")
|
||||
src.add_key("SVC", kid2, BAD)
|
||||
dst.flag_bad_key("SVC", kid2, BAD, "poisoned")
|
||||
@@ -241,7 +235,6 @@ def test_retry_takes_the_next_parallel_answer_without_a_new_request(tmp_path: Pa
|
||||
|
||||
class Fast(FakeVault):
|
||||
def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
|
||||
# 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)
|
||||
|
||||
@@ -258,7 +251,7 @@ def test_retry_takes_the_next_parallel_answer_without_a_new_request(tmp_path: Pa
|
||||
|
||||
assert vaults.get_key(KID) == (BAD, fast)
|
||||
vaults.flag_bad_key(KID, BAD)
|
||||
release.set() # the slow answer lands in candidates after the first call returned
|
||||
release.set()
|
||||
deadline = time.monotonic() + 5
|
||||
while len(vaults.candidates.get(KID, [])) < 2 and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
@@ -285,9 +278,9 @@ def test_cdm_returning_the_flagged_key_clears_the_flag(
|
||||
def licence(drm: FakeDRM, track_kid: UUID) -> None:
|
||||
assert vaults.get_key(KID) == (None, None)
|
||||
if replace:
|
||||
drm.content_keys = {KID: BAD} # a CDM licence builds a new dict
|
||||
drm.content_keys = {KID: BAD}
|
||||
else:
|
||||
drm.content_keys[KID] = BAD # the CDM answers with the same key
|
||||
drm.content_keys[KID] = BAD
|
||||
|
||||
cmd.decrypt_verified(drm, path, licence, KID)
|
||||
assert path.read_bytes() == b"plain:" + BAD.encode()
|
||||
@@ -425,8 +418,8 @@ def test_flag_on_a_read_only_vault_keeps_its_rows(tmp_path: Path) -> None:
|
||||
ro.add_key("SVC", KID, BAD)
|
||||
ro.flag_bad_key("SVC", KID, BAD, "poisoned")
|
||||
assert ro.is_bad_key(KID, BAD)
|
||||
assert ro.get_key(KID, "SVC") is None # the lookup still skips the flagged pair
|
||||
assert list(ro.get_keys("SVC")) == [(KID.hex, BAD)] # but the row itself is untouched
|
||||
assert ro.get_key(KID, "SVC") is None
|
||||
assert list(ro.get_keys("SVC")) == [(KID.hex, BAD)]
|
||||
|
||||
|
||||
def test_flag_moves_the_row_and_blocks_it_coming_back(tmp_path: Path) -> None:
|
||||
@@ -438,7 +431,7 @@ def test_flag_moves_the_row_and_blocks_it_coming_back(tmp_path: Path) -> None:
|
||||
assert local.add_key("SVC", KID, BAD) is False
|
||||
assert local.add_keys("SVC", {KID: BAD}) == 0
|
||||
assert list(local.get_keys("SVC")) == []
|
||||
assert local.add_key("SVC", KID, GOOD) # the KID itself is not blocked, only the pair
|
||||
assert local.add_key("SVC", KID, GOOD)
|
||||
|
||||
|
||||
def test_a_licence_key_clears_a_flag_from_an_earlier_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
@@ -494,7 +487,7 @@ def test_only_the_kid_whose_window_fails_is_flagged(tmp_path: Path, monkeypatch:
|
||||
lead = UUID(int=7)
|
||||
local = SQLite("local", tmp_path / "local.db")
|
||||
poisoned = Remote("poisoned", tmp_path / "poisoned.db")
|
||||
poisoned.add_key("SVC", lead, BAD) # the same wrong key under both KIDs
|
||||
poisoned.add_key("SVC", lead, BAD)
|
||||
poisoned.add_key("SVC", KID, BAD)
|
||||
other = Remote("other", tmp_path / "other.db")
|
||||
other.add_key("SVC", KID, GOOD)
|
||||
@@ -567,8 +560,8 @@ def test_a_kid_absent_from_the_map_is_judged_by_the_fallback(tmp_path: Path, mon
|
||||
assert drm.content_keys == {lead: GOOD, KID: GOOD}
|
||||
assert local.is_bad_key(KID, BAD)
|
||||
assert not local.is_bad_key(lead, GOOD)
|
||||
assert (4.0, 2.0, True) in calls # the window is capped at the fragment's end
|
||||
assert (None, 3, True) in calls # the fallback knows the track is video
|
||||
assert (4.0, 2.0, True) in calls
|
||||
assert (None, 3, True) in calls
|
||||
|
||||
|
||||
def test_a_wrong_mapped_key_does_not_flag_a_kid_the_file_does_not_carry(
|
||||
@@ -640,8 +633,8 @@ def test_a_kid_the_file_does_not_carry_is_not_judged_by_it(tmp_path: Path, monke
|
||||
@pytest.mark.parametrize(
|
||||
("served", "decodes", "told"),
|
||||
[
|
||||
(GOOD, False, False), # broken FFmpeg, the CDM returns the same key
|
||||
(BAD, True, True), # the CDM returns another key
|
||||
(GOOD, False, False),
|
||||
(BAD, True, True),
|
||||
],
|
||||
)
|
||||
def test_a_remote_vault_is_told_only_when_another_key_replaces_its_pair(
|
||||
@@ -780,7 +773,7 @@ def test_a_sibling_verdict_during_the_decrypt_still_triggers_the_retry(
|
||||
vaults.vaults = [local]
|
||||
vaults.sources[KID] = (BAD, local)
|
||||
cmd = make_cmd(monkeypatch, vaults)
|
||||
dl.LICENSE_KEY_CACHE[KID] = GOOD # the sibling's retry already licensed the good key
|
||||
dl.LICENSE_KEY_CACHE[KID] = GOOD
|
||||
|
||||
path = tmp_path / "audio.mp4"
|
||||
path.write_bytes(b"cipher")
|
||||
@@ -802,7 +795,7 @@ def test_a_sibling_verdict_during_the_decrypt_still_triggers_the_retry(
|
||||
|
||||
assert path.read_bytes() == b"plain:" + GOOD.encode()
|
||||
assert drm.decrypted_with == [{KID: BAD}, {KID: GOOD}]
|
||||
assert licences == [GOOD] # the good key in the run cache survives the flag of the bad one
|
||||
assert licences == [GOOD]
|
||||
|
||||
|
||||
def test_api_vault_reports_the_pair_upstream(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None:
|
||||
@@ -928,7 +921,7 @@ def test_an_unreachable_vault_costs_one_attempt_per_run(monkeypatch: pytest.Monk
|
||||
monkeypatch.setattr(vault.session, "post", down)
|
||||
with pytest.raises(requests.ConnectTimeout):
|
||||
vault.add_keys("SVC", {KID: GOOD, SIBLING: BAD})
|
||||
assert len(calls) == 2 # no batch step-down, no single-key fallback
|
||||
assert len(calls) == 2
|
||||
|
||||
calls.clear()
|
||||
vaults = Vaults("SVC")
|
||||
|
||||
@@ -53,7 +53,7 @@ def test_remote_vaults_run_together_and_first_hit_wins() -> None:
|
||||
start = time.monotonic()
|
||||
key, vault = make(local, slow, fast).get_key("kid")
|
||||
assert (key, vault) == ("dd" * 16, fast)
|
||||
assert time.monotonic() - start < 0.9 # did not wait for the slow vault
|
||||
assert time.monotonic() - start < 0.9
|
||||
assert slow.calls == 1 and local.calls == 1
|
||||
assert slow.threads != fast.threads
|
||||
|
||||
|
||||
@@ -8,10 +8,9 @@ import requests as rq
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED
|
||||
from unshackle.core.downloaders.requests import download
|
||||
|
||||
# the package re-exports the `requests` function, shadowing the module of the same name
|
||||
downloader = sys.modules[download.__module__]
|
||||
|
||||
BODY = bytes(range(256)) * 256 # 64 KiB
|
||||
BODY = bytes(range(256)) * 256
|
||||
CUT_AFTER = 10 * 1024
|
||||
CHUNK = 16 * 1024
|
||||
|
||||
@@ -29,7 +28,7 @@ class _CutServer(ThreadingHTTPServer):
|
||||
super().__init__(("127.0.0.1", 0), _CutHandler)
|
||||
self.url = f"http://127.0.0.1:{self.server_address[1]}/seg.mp4"
|
||||
|
||||
def handle_error(self, request, client_address): # the client hanging up is expected here
|
||||
def handle_error(self, request, client_address):
|
||||
pass
|
||||
|
||||
|
||||
@@ -84,10 +83,7 @@ def test_a_cut_body_bounds_the_following_requests(tmp_path, server):
|
||||
list(download(url=server.url, save_path=save_path, session=rq.Session()))
|
||||
|
||||
assert save_path.read_bytes() == BODY
|
||||
# the open-ended first request is cut, the chunk-sized one after it is cut too, and the
|
||||
# halved chunk fits under the host's limit, so every later request completes whole
|
||||
assert server.cuts == 2
|
||||
spans = [r.removeprefix("bytes=").split("-") for r in server.ranges if r and r.split("-")[-1]]
|
||||
assert spans and all(int(end) - int(start) + 1 <= CHUNK for start, end in spans)
|
||||
# the bounded requests are cheap because they share one pooled connection
|
||||
assert server.connections < len(server.ranges)
|
||||
|
||||
@@ -60,14 +60,14 @@ class _Handler(BaseHTTPRequestHandler):
|
||||
else:
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args): # keep the test output quiet
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
class _Server(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
|
||||
def handle_error(self, request, client_address): # cancelled readers close mid-write
|
||||
def handle_error(self, request, client_address):
|
||||
pass
|
||||
|
||||
|
||||
@@ -121,7 +121,6 @@ def test_dispatch_parts_does_not_finalize_on_global_cancel(server, tmp_path):
|
||||
canceller.join(timeout=10)
|
||||
|
||||
assert not any("file_downloaded" in ev for ev in events)
|
||||
# the control file must survive so the next run restarts instead of trusting the file
|
||||
assert save_path.with_name(f"{save_path.name}.!dev").exists()
|
||||
|
||||
|
||||
@@ -143,11 +142,10 @@ def test_backoff_wait_exits_promptly_on_batch_abort(server, tmp_path, monkeypatc
|
||||
worker = threading.Thread(target=consume)
|
||||
start = time.monotonic()
|
||||
worker.start()
|
||||
time.sleep(0.5) # let the first attempt fail and enter the backoff wait
|
||||
time.sleep(0.5)
|
||||
abort.set()
|
||||
worker.join(timeout=10)
|
||||
assert not worker.is_alive()
|
||||
# generous bound: far below the 30s nap, so the wait was interrupted, not slept out
|
||||
assert time.monotonic() - start < 10
|
||||
|
||||
|
||||
@@ -171,5 +169,4 @@ def test_cancelled_batch_raises_instead_of_finishing_or_hanging(server, tmp_path
|
||||
|
||||
assert not worker.is_alive(), "requests() never returned on a cancelled batch"
|
||||
assert isinstance(result[0], DownloadCancelled)
|
||||
# returning short here would hand the caller an empty segment dir to merge
|
||||
assert not list(tmp_path.iterdir())
|
||||
|
||||
@@ -153,6 +153,5 @@ def test_rnet_encoded_body_discards_a_partial_instead_of_range_resuming(tmp_path
|
||||
save_path = tmp_path / "sub.vtt"
|
||||
save_path.with_name("sub.vtt.!dev").write_bytes(PLAIN[:5000])
|
||||
list(download(url="http://127.0.0.1:1/sub.vtt", save_path=save_path, session=session))
|
||||
# the encoded 206 must be dropped, not appended; the clean restart fetches the whole body
|
||||
assert session.range_requests == 1
|
||||
assert save_path.read_bytes() == PLAIN
|
||||
|
||||
@@ -18,9 +18,9 @@ import pytest
|
||||
|
||||
dl = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
|
||||
PARENT = bytes(range(256)) * 256 # 64KiB parent resource, distinctive bytes
|
||||
PARENT = bytes(range(256)) * 256
|
||||
SLICE_START = 1024
|
||||
SLICE_END = 5119 # inclusive; 4KiB slice
|
||||
SLICE_END = 5119
|
||||
|
||||
|
||||
class _Handler(BaseHTTPRequestHandler):
|
||||
@@ -48,7 +48,7 @@ class _Handler(BaseHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
if server.truncate_first and nth == 1:
|
||||
self.wfile.write(body[: len(body) // 2])
|
||||
return # connection closes mid-body -> client sees a short read
|
||||
return
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
@@ -111,13 +111,10 @@ def test_range_item_ignored_by_server_fails_not_corrupts(server, tmp_path, monke
|
||||
urls = [{"url": url(server), "headers": {"Range": f"bytes={SLICE_START}-{SLICE_END}"}}]
|
||||
with pytest.raises(Exception):
|
||||
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"))
|
||||
|
||||
|
||||
def test_range_item_spanning_whole_resource_accepts_200(server, tmp_path):
|
||||
# RFC 9110 lets a server ignore Range and answer 200 with the whole resource; when the
|
||||
# slice spans that resource the body is byte-identical to the 206 and must be kept
|
||||
server.honor_range = False
|
||||
urls = [{"url": url(server), "headers": {"Range": f"bytes=0-{len(PARENT) - 1}"}}]
|
||||
files = run(server, tmp_path, urls, max_workers=1)
|
||||
@@ -131,7 +128,6 @@ def test_range_item_retry_rewrites_slice(server, tmp_path, monkeypatch):
|
||||
urls = [{"url": url(server), "headers": {"Range": f"bytes={SLICE_START}-{SLICE_END}"}}]
|
||||
files = run(server, tmp_path, urls, max_workers=1)
|
||||
assert files[0].read_bytes() == PARENT[SLICE_START : SLICE_END + 1]
|
||||
# the retry must re-send the item's own Range, never a resume Range from the partial
|
||||
ranges = [r.get("Range") for r in server.requests]
|
||||
assert ranges == [f"bytes={SLICE_START}-{SLICE_END}"] * len(ranges)
|
||||
assert len(ranges) >= 2
|
||||
@@ -150,7 +146,7 @@ def exc_with_headers(headers):
|
||||
|
||||
def test_retry_sleep_honors_numeric_retry_after():
|
||||
assert dl.retry_sleep(exc_with_headers({"Retry-After": "3"}), 1) == 3.0
|
||||
assert dl.retry_sleep(exc_with_headers({"Retry-After": "9999"}), 1) == 60.0 # session.MAX_BACKOFF cap
|
||||
assert dl.retry_sleep(exc_with_headers({"Retry-After": "9999"}), 1) == 60.0
|
||||
|
||||
|
||||
def test_retry_sleep_honors_http_date_retry_after():
|
||||
@@ -159,10 +155,9 @@ def test_retry_sleep_honors_http_date_retry_after():
|
||||
|
||||
|
||||
def test_retry_sleep_exponential_backoff_with_jitter():
|
||||
# no response on the failure: exponential from RETRY_WAIT with up to 10% jitter
|
||||
for attempts, base in ((1, dl.RETRY_WAIT), (2, dl.RETRY_WAIT * 2), (3, dl.RETRY_WAIT * 4)):
|
||||
assert base <= dl.retry_sleep(Exception("reset"), attempts) <= base * 1.1
|
||||
assert dl.retry_sleep(Exception("reset"), 30) == 60.0 # capped
|
||||
assert dl.retry_sleep(Exception("reset"), 30) == 60.0
|
||||
|
||||
|
||||
def test_retry_sleep_invalid_retry_after_falls_back():
|
||||
@@ -171,7 +166,6 @@ 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))
|
||||
assert when.endswith("-0000")
|
||||
v = dl.retry_sleep(exc_with_headers({"Retry-After": when}), 1)
|
||||
@@ -179,20 +173,17 @@ def test_retry_sleep_naive_http_date_treated_as_utc():
|
||||
|
||||
|
||||
def test_retry_sleep_nan_retry_after_falls_back():
|
||||
# float("nan") parses; a non-finite wait must fall back to the exponential path
|
||||
v = dl.retry_sleep(exc_with_headers({"Retry-After": "nan"}), 1)
|
||||
assert dl.RETRY_WAIT <= v <= dl.RETRY_WAIT * 1.1
|
||||
|
||||
|
||||
def test_retry_sleep_honors_retry_after_on_wrapped_cause():
|
||||
# RnetSession raises MaxRetriesError whose __cause__ HTTPError carries the response
|
||||
exc = Exception("max retries exceeded")
|
||||
exc.__cause__ = exc_with_headers({"Retry-After": "3"})
|
||||
assert dl.retry_sleep(exc, 1) == 3.0
|
||||
|
||||
|
||||
def test_transient_429_with_retry_after_does_not_abort_track(server, tmp_path, monkeypatch):
|
||||
# a short rate-limit window must retry the segment, not kill the whole batch
|
||||
dl.DOWNLOAD_CANCELLED.clear()
|
||||
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
|
||||
server.fail_429_first = 2
|
||||
@@ -200,12 +191,10 @@ def test_transient_429_with_retry_after_does_not_abort_track(server, tmp_path, m
|
||||
assert len(files) == 3
|
||||
assert all(f.read_bytes() == PARENT for f in files)
|
||||
assert not dl.DOWNLOAD_CANCELLED.is_set()
|
||||
assert len(server.requests) == 5 # 3 successes + 2 rate-limited attempts
|
||||
assert len(server.requests) == 5
|
||||
|
||||
|
||||
def test_session_retry_does_not_nest_inside_an_attempt(server, tmp_path, monkeypatch):
|
||||
# a service session mounts urllib3 Retry with a 429 forcelist; download() owns segment
|
||||
# retries, so the two must not multiply (MAX_ATTEMPTS requests, not MAX_ATTEMPTS x 6)
|
||||
from requests import Session
|
||||
from requests.adapters import HTTPAdapter, Retry
|
||||
|
||||
@@ -223,5 +212,4 @@ def test_session_retry_does_not_nest_inside_an_attempt(server, tmp_path, monkeyp
|
||||
run(server, tmp_path, [{"url": url(server)}], max_workers=1, session=session)
|
||||
|
||||
assert len(server.requests) == dl.MAX_ATTEMPTS
|
||||
# the caller's session keeps its own retry policy
|
||||
assert session.get_adapter("http://x/").max_retries.total == 5
|
||||
|
||||
@@ -16,10 +16,9 @@ import requests as rq
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED
|
||||
from unshackle.core.downloaders.requests import download
|
||||
|
||||
# the package re-exports the `requests` function, shadowing the module of the same name
|
||||
downloader = sys.modules[download.__module__]
|
||||
|
||||
BODY = bytes(range(256)) * 256 # 64 KiB
|
||||
BODY = bytes(range(256)) * 256
|
||||
CUT_AFTER = 10 * 1024
|
||||
CHUNK = 16 * 1024
|
||||
DEADLINE = 30
|
||||
@@ -36,7 +35,7 @@ class _EmptyRangeServer(ThreadingHTTPServer):
|
||||
super().__init__(("127.0.0.1", 0), _EmptyRangeHandler)
|
||||
self.url = f"http://127.0.0.1:{self.server_address[1]}/seg.mp4"
|
||||
|
||||
def handle_error(self, request, client_address): # the client hanging up is expected here
|
||||
def handle_error(self, request, client_address):
|
||||
pass
|
||||
|
||||
|
||||
@@ -55,7 +54,6 @@ class _EmptyRangeHandler(BaseHTTPRequestHandler):
|
||||
start, end = int(start_s), (int(end_s) if end_s else len(BODY) - 1)
|
||||
bounded = bool(end_s)
|
||||
if bounded:
|
||||
# a valid response: the chunked terminator closes a zero-length body, so requests raises nothing
|
||||
self.send_response(206)
|
||||
self.send_header("Content-Range", f"bytes {start}-{end}/{len(BODY)}")
|
||||
self.send_header("Transfer-Encoding", "chunked")
|
||||
@@ -68,7 +66,6 @@ class _EmptyRangeHandler(BaseHTTPRequestHandler):
|
||||
self.send_header("Content-Range", f"bytes {start}-{end}/{len(BODY)}")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
# the cut teaches the downloader to bound the requests that follow
|
||||
self.wfile.write(body[:CUT_AFTER])
|
||||
self.close_connection = True
|
||||
|
||||
@@ -98,7 +95,6 @@ def test_empty_sub_range_fails_instead_of_looping(tmp_path, server):
|
||||
except BaseException as exc:
|
||||
result.append(exc)
|
||||
|
||||
# a hard deadline: a regression hangs this thread, and the suite must fail, not stall
|
||||
worker = threading.Thread(target=run, daemon=True)
|
||||
worker.start()
|
||||
worker.join(timeout=DEADLINE)
|
||||
|
||||
@@ -9,7 +9,6 @@ from unshackle.core.constants import DOWNLOAD_CANCELLED
|
||||
from unshackle.core.downloaders.requests import download, has_range_header, parse_content_range, request_range
|
||||
from unshackle.core.downloaders.requests import requests as requests_downloader
|
||||
|
||||
# the package re-exports the `requests` function, shadowing the module of the same name
|
||||
downloader = sys.modules[download.__module__]
|
||||
|
||||
BODY = b"".join(f"{i:05d} payload\n".encode() for i in range(500))
|
||||
@@ -57,8 +56,6 @@ class _Server:
|
||||
elif not ranged:
|
||||
self.plain_hits += 1
|
||||
if self.mode.startswith("resume_") and self.plain_hits == 1:
|
||||
# promise the full body but hang up early: leaves a CUT-byte
|
||||
# partial behind so the next attempt sends a resume Range
|
||||
conn.sendall(
|
||||
f"HTTP/1.1 200 OK\r\nContent-Length: {len(BODY)}\r\nConnection: close\r\n\r\n".encode()
|
||||
+ BODY[:CUT]
|
||||
@@ -69,20 +66,16 @@ class _Server:
|
||||
+ BODY
|
||||
)
|
||||
elif self.mode == "resume_whole_body_206":
|
||||
# ignores the requested start: a 206 carrying the entire resource
|
||||
self.send_206(conn, BODY, f"bytes 0-{len(BODY) - 1}/{len(BODY)}")
|
||||
elif self.mode == "resume_alien_206":
|
||||
# a 206 starting neither at the requested offset nor at zero
|
||||
self.send_206(conn, BODY[5:], f"bytes 5-{len(BODY) - 1}/{len(BODY)}")
|
||||
elif self.mode == "resume_missing_content_range":
|
||||
self.send_206(conn, BODY)
|
||||
elif self.mode == "range_clamped_206":
|
||||
# RFC 9110: a range end at or past the last byte clamps to it, so the whole slice arrives
|
||||
start, _, end = headers["range"].removeprefix("bytes=").partition("-")
|
||||
start, end = int(start), min(int(end), len(BODY) - 1)
|
||||
self.send_206(conn, BODY[start : end + 1], f"bytes {start}-{end}/{len(BODY)}")
|
||||
elif self.mode == "range_capped_206":
|
||||
# honors the requested start but caps the span, as size-capping CDNs do
|
||||
start, _, end = headers["range"].removeprefix("bytes=").partition("-")
|
||||
start, end = int(start), int(end)
|
||||
capped = start + (end - start) // 2
|
||||
@@ -102,8 +95,6 @@ class _Server:
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_cancel():
|
||||
# the batch failure path sets the process-global cancel; leaking it makes every later
|
||||
# test that waits on the event (the speed limiter) return instantly
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
yield
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
@@ -132,7 +123,6 @@ def test_exhausted_retries_raise_instead_of_reporting_success(tmp_path, server):
|
||||
|
||||
@pytest.mark.parametrize("server", ["unavailable"], indirect=True)
|
||||
def test_cancelled_download_stays_silent(tmp_path, server, monkeypatch):
|
||||
# one attempt only, so a cancel check ordered after the exhaustion raise would fail here
|
||||
monkeypatch.setattr(downloader, "MAX_ATTEMPTS", 1)
|
||||
save_path = tmp_path / "0.mp4"
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
@@ -210,7 +200,6 @@ def test_slice_segment_rejects_a_206_for_the_wrong_range(tmp_path, server):
|
||||
|
||||
@pytest.mark.parametrize("server", ["range_clamped_206"], indirect=True)
|
||||
def test_slice_segment_accepts_a_206_clamped_to_the_last_byte(tmp_path, server):
|
||||
# some manifests author a range end past the resource; the clamped 206 is the whole slice
|
||||
save_path = tmp_path / "0.mp4"
|
||||
list(
|
||||
download(
|
||||
@@ -225,8 +214,6 @@ def test_slice_segment_accepts_a_206_clamped_to_the_last_byte(tmp_path, server):
|
||||
|
||||
@pytest.mark.parametrize("server", ["range_capped_206"], indirect=True)
|
||||
def test_slice_segment_rejects_a_206_capped_short_of_the_requested_end(tmp_path, server):
|
||||
# the body is a valid prefix of the slice, so only the Content-Range end catches it;
|
||||
# writing it would finalize a truncated segment and corrupt the merge
|
||||
save_path = tmp_path / "0.mp4"
|
||||
with pytest.raises(OSError):
|
||||
list(
|
||||
@@ -265,7 +252,6 @@ def test_identity_encoding_requested_unless_the_caller_set_one(tmp_path, server)
|
||||
|
||||
@pytest.mark.parametrize("server", ["unavailable"], indirect=True)
|
||||
def test_failed_segment_fails_the_batch(tmp_path, server):
|
||||
# a segment the batch never delivers must raise, not merge short of the segment count
|
||||
with pytest.raises(rq.HTTPError):
|
||||
list(
|
||||
requests_downloader(
|
||||
@@ -280,8 +266,6 @@ def test_failed_segment_fails_the_batch(tmp_path, server):
|
||||
|
||||
@pytest.mark.parametrize("server", ["ok"], indirect=True)
|
||||
def test_batch_larger_than_the_queue_window_downloads_every_segment(tmp_path, server):
|
||||
# a broken top-up livelocks the drain loop instead of erroring, so consume on a thread and
|
||||
# let the timeout fail the test
|
||||
urls = [server.url] * 6
|
||||
advanced = 0
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@ import pytest
|
||||
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED
|
||||
|
||||
# the downloaders package re-exports the requests() function, shadowing the submodule
|
||||
dl = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
|
||||
SEGMENTS = 10
|
||||
@@ -39,7 +38,6 @@ class _Handler(BaseHTTPRequestHandler):
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
if slow_path and nth == 1:
|
||||
# trickle only the first attempt so the hedge retry wins instantly
|
||||
for i in range(0, len(body), TRICKLE_CHUNK):
|
||||
try:
|
||||
self.wfile.write(body[i : i + TRICKLE_CHUNK])
|
||||
@@ -82,7 +80,6 @@ def test_hedge_loser_releases_handles_before_merge(tmp_path, trickle_server, mon
|
||||
slow_hits = trickle_server.counts[f"/seg/{SLOW_INDEX}"]
|
||||
assert slow_hits == 2, "hedge never fired; the race under test was not exercised"
|
||||
|
||||
# the batch must not stall draining the loser's stream (trickle alone takes ~10s)
|
||||
assert wall < 5
|
||||
|
||||
for i in range(SEGMENTS):
|
||||
@@ -101,7 +98,7 @@ def test_hedge_loser_releases_handles_before_merge(tmp_path, trickle_server, mon
|
||||
held = [s.name for s in strays if str(s) in open_targets]
|
||||
assert not held, f"racer still holds open handles at completion: {held}"
|
||||
for stray in strays:
|
||||
stray.unlink() # raises PermissionError (WinError 32) on Windows if a handle is open
|
||||
stray.unlink()
|
||||
|
||||
leaked = [
|
||||
t.name
|
||||
|
||||
@@ -33,7 +33,7 @@ from unshackle.core.utils.sslciphers import SSLCiphers
|
||||
|
||||
dl = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
|
||||
SEG_REPEAT = 32 # 8-digit index * 32 = 256-byte body, distinct per index
|
||||
SEG_REPEAT = 32
|
||||
|
||||
|
||||
def seg_body(index: int) -> bytes:
|
||||
@@ -67,14 +67,14 @@ class _Handler(BaseHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args): # keep the test output quiet
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
class _Server(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
|
||||
def handle_error(self, request, client_address): # a cancelled child closes its socket mid-write
|
||||
def handle_error(self, request, client_address):
|
||||
pass
|
||||
|
||||
|
||||
@@ -92,8 +92,6 @@ def server():
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_cancel():
|
||||
# spawned children carry their own flag, but the parent loop reads this process's flag;
|
||||
# keep it clean so cancel state never leaks between tests
|
||||
dl.DOWNLOAD_CANCELLED.clear()
|
||||
yield
|
||||
dl.DOWNLOAD_CANCELLED.clear()
|
||||
@@ -125,7 +123,6 @@ def url(srv, path):
|
||||
|
||||
|
||||
def test_multiprocess_stride_downloads_all_segments_correctly(server, tmp_path):
|
||||
# >= MP_MIN_SEGMENTS with processes=2 engages the fan-out via the public entry point
|
||||
n = dl.MP_MIN_SEGMENTS
|
||||
urls = [{"url": url(server, f"/seg/{i}.bin")} for i in range(n)]
|
||||
|
||||
@@ -138,14 +135,10 @@ def test_multiprocess_stride_downloads_all_segments_correctly(server, tmp_path):
|
||||
for f in files:
|
||||
index = int(f.stem.split("_")[1])
|
||||
assert f.read_bytes() == seg_body(index), f"segment {index} holds another index's bytes (stride mapping bug)"
|
||||
# parent drops child advances and emits one advance=1 per file_downloaded
|
||||
assert total_advance == n
|
||||
|
||||
|
||||
def test_multiprocess_child_crash_raises(server, tmp_path):
|
||||
# download_multiprocess has no MP_MIN_SEGMENTS gate, so drive it directly with 2 urls.
|
||||
# a dict url without "url" raises KeyError while requests() builds the save path (before
|
||||
# any retry loop), so the child sends __mp_error__ fast; the sibling downloads normally.
|
||||
good = {"url": url(server, "/seg/0.bin")}
|
||||
bad = {"nourl": True}
|
||||
with pytest.raises(RuntimeError):
|
||||
@@ -172,7 +165,7 @@ def test_multiprocess_child_death_raises(tmp_path, monkeypatch):
|
||||
|
||||
|
||||
def test_multiprocess_cancel_terminates_children(server, tmp_path):
|
||||
server.delay = 0.5 # slow segments so cancel lands well before the batch could finish
|
||||
server.delay = 0.5
|
||||
n = dl.MP_MIN_SEGMENTS
|
||||
urls = [{"url": url(server, f"/seg/{i}.bin")} for i in range(n)]
|
||||
|
||||
@@ -184,13 +177,11 @@ def test_multiprocess_cancel_terminates_children(server, tmp_path):
|
||||
if event.get("advance") or event.get("written"):
|
||||
progressed += 1
|
||||
if progressed >= 2:
|
||||
dl.DOWNLOAD_CANCELLED.set() # sibling-track cancel: parent must tear the children down
|
||||
dl.DOWNLOAD_CANCELLED.set()
|
||||
elapsed = time.time() - start
|
||||
|
||||
# cancel stopped the work: nowhere near all segments finished, and no hang
|
||||
assert len(list(tmp_path.glob("seg_*.bin"))) < n
|
||||
assert elapsed < 15
|
||||
# the finally-block join reaps the spawned children promptly
|
||||
deadline = time.time() + 5
|
||||
while time.time() < deadline and len(multiprocessing.active_children()) > baseline:
|
||||
time.sleep(0.05)
|
||||
@@ -207,7 +198,7 @@ def test_speed_limit_forces_single_process(server, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(dl, "download_multiprocess", no_mp)
|
||||
n = dl.MP_MIN_SEGMENTS
|
||||
urls = [{"url": url(server, f"/seg/{i}.bin")} for i in range(n)]
|
||||
dl.set_speed_limit(1_000_000_000) # far above the tiny batch, so the test is not slowed
|
||||
dl.set_speed_limit(1_000_000_000)
|
||||
for _ in dl.requests(urls, output_dir=tmp_path, filename="seg_{i:04}.bin", max_workers=4, processes=2):
|
||||
pass
|
||||
|
||||
|
||||
@@ -30,11 +30,10 @@ from requests import Session
|
||||
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED
|
||||
|
||||
# the package re-exports the `requests` function, shadowing the module of the same name
|
||||
dl = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
|
||||
PAYLOAD = bytes((i * 11 + 3) % 256 for i in range(32 * 1024))
|
||||
BIG = bytes(8 * 1024 * 1024) # larger than any socket buffer, so a full drain is visible
|
||||
BIG = bytes(8 * 1024 * 1024)
|
||||
PROBES = 6
|
||||
AUTH = "let-me-in"
|
||||
|
||||
@@ -45,14 +44,14 @@ class _ProbeServer(ThreadingHTTPServer):
|
||||
|
||||
def __init__(self):
|
||||
self.lock = threading.Lock()
|
||||
self.requests: list = [] # (Range, Accept-Encoding, X-Auth)
|
||||
self.requests: list = []
|
||||
self.connections = 0
|
||||
self.mode = "range"
|
||||
self.written = 0
|
||||
self.broke = False
|
||||
super().__init__(("127.0.0.1", 0), _ProbeHandler)
|
||||
|
||||
def handle_error(self, request, client_address): # the client hanging up is expected here
|
||||
def handle_error(self, request, client_address):
|
||||
pass
|
||||
|
||||
|
||||
@@ -87,7 +86,6 @@ class _ProbeHandler(BaseHTTPRequestHandler):
|
||||
return
|
||||
|
||||
if srv.mode == "fat_206":
|
||||
# a 206 status on a whole-resource body: the status alone cannot bound the drain
|
||||
self.send_response(206)
|
||||
self.send_header("Content-Range", f"bytes 0-{len(BIG) - 1}/{len(BIG)}")
|
||||
self.send_header("Content-Length", str(len(BIG)))
|
||||
@@ -115,7 +113,6 @@ class _ProbeHandler(BaseHTTPRequestHandler):
|
||||
self.wfile.write(body)
|
||||
|
||||
def _write_slowly(self, body):
|
||||
# chunked writes so the count records how far the client actually read
|
||||
srv = self.server
|
||||
try:
|
||||
for at in range(0, len(body), 64 * 1024):
|
||||
@@ -177,7 +174,6 @@ def test_probe_asks_for_identity_encoding(server):
|
||||
assert dl.probe_ranged(url(server), session) == (len(PAYLOAD), True)
|
||||
assert server.requests[-1][1] == "identity"
|
||||
|
||||
# a caller that names its own encoding still wins
|
||||
assert dl.probe_ranged(url(server), session, headers={"Accept-Encoding": "gzip"}) == (0, False)
|
||||
assert server.requests[-1][1] == "gzip"
|
||||
|
||||
@@ -194,7 +190,6 @@ def test_probe_uses_the_url_items_headers(server, tmp_path, monkeypatch):
|
||||
assert save_path.read_bytes() == PAYLOAD
|
||||
probes = [r for r in server.requests if r[0] == "bytes=0-0"]
|
||||
assert probes and all(r[2] == AUTH for r in probes)
|
||||
# the probe was answered, so the ranged path ran instead of one sequential connection
|
||||
assert [r for r in server.requests if r[0] and r[0] != "bytes=0-0"]
|
||||
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ from requests import HTTPError, Session
|
||||
|
||||
dl = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
|
||||
PAYLOAD = bytes(range(256)) * 128 # 32 KiB, distinctive repeating byte pattern
|
||||
PAYLOAD = bytes(range(256)) * 128
|
||||
|
||||
|
||||
class _Resp:
|
||||
@@ -48,7 +48,6 @@ class _RangeHandler(BaseHTTPRequestHandler):
|
||||
mode = srv.mode
|
||||
|
||||
if mode == "gzip_probe":
|
||||
# a 206 that (wrongly) carries a content-encoding: the probe must decline it
|
||||
self.send_response(206)
|
||||
self.send_header("Content-Range", f"bytes 0-0/{len(PAYLOAD)}")
|
||||
self.send_header("Content-Encoding", "gzip")
|
||||
@@ -58,14 +57,11 @@ class _RangeHandler(BaseHTTPRequestHandler):
|
||||
return
|
||||
|
||||
if mode == "deny_parts" and rng != "bytes=0-0":
|
||||
# probe passes, every part window is refused for good (expired token, geo block)
|
||||
self.send_response(403)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
|
||||
# always_200 ignores Range entirely; probe_only_206 answers the 0-0 probe
|
||||
# with a real 206 but hands every wider part window a 200 full body
|
||||
serve_full = mode == "always_200" or not rng or (mode == "probe_only_206" and rng != "bytes=0-0")
|
||||
if serve_full:
|
||||
self.send_response(200)
|
||||
@@ -88,7 +84,6 @@ class _RangeHandler(BaseHTTPRequestHandler):
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_cancelled():
|
||||
# ranged failures must never touch the process-global flag; isolate every test from it
|
||||
dl.DOWNLOAD_CANCELLED.clear()
|
||||
yield
|
||||
dl.DOWNLOAD_CANCELLED.clear()
|
||||
@@ -99,7 +94,7 @@ def server():
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", 0), _RangeHandler)
|
||||
srv.lock = threading.Lock()
|
||||
srv.requests = []
|
||||
srv.mode = "range" # honor every Range with a proper 206
|
||||
srv.mode = "range"
|
||||
thread = threading.Thread(target=srv.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
yield srv
|
||||
@@ -118,16 +113,13 @@ def run(srv, tmp_path, urls, **kwargs):
|
||||
|
||||
|
||||
def test_ranged_parallel_merges_byte_identical(server, tmp_path, monkeypatch):
|
||||
# shrink the thresholds so a 32 KiB payload splits into several parts
|
||||
monkeypatch.setattr(dl, "RANGE_PARALLEL_MIN_SIZE", 8 * 1024)
|
||||
monkeypatch.setattr(dl, "RANGE_PARALLEL_MIN_PART_SIZE", 2 * 1024)
|
||||
files = run(server, tmp_path, [{"url": url(server)}], max_workers=4)
|
||||
assert len(files) == 1
|
||||
assert files[0].read_bytes() == PAYLOAD
|
||||
# the split must actually have happened: >1 distinct window beyond the 0-0 probe
|
||||
windows = {r for r in server.requests if r and r != "bytes=0-0"}
|
||||
assert len(windows) >= 2
|
||||
# control marker removed once the parts finalize
|
||||
assert not files[0].with_name(files[0].name + ".!dev").exists()
|
||||
|
||||
|
||||
@@ -145,8 +137,6 @@ def test_ranged_part_requires_206(server, tmp_path, monkeypatch):
|
||||
with pytest.raises(IOError, match="expected 206 for ranged part"):
|
||||
for _ in gen:
|
||||
pass
|
||||
# not finalized: the control marker survives (completed=False) and the target
|
||||
# is still the pre-truncated zero-fill, never the served bytes
|
||||
assert save_path.with_name(save_path.name + ".!dev").exists()
|
||||
assert save_path.read_bytes() != PAYLOAD
|
||||
|
||||
@@ -166,7 +156,6 @@ def test_ranged_part_failure_stays_local(server, tmp_path, monkeypatch):
|
||||
with pytest.raises(IOError, match="expected 206 for ranged part"):
|
||||
for _ in gen:
|
||||
pass
|
||||
# a failed part rides the local abort event; the global cancel must stay clear
|
||||
assert not dl.DOWNLOAD_CANCELLED.is_set()
|
||||
|
||||
|
||||
@@ -187,12 +176,9 @@ def test_permanent_part_failure_is_not_retried_sequentially(server, tmp_path, mo
|
||||
monkeypatch.setattr(dl, "RANGE_PARALLEL_MIN_PART_SIZE", 8 * 1024)
|
||||
with pytest.raises(HTTPError):
|
||||
run(server, tmp_path, [{"url": url(server)}], max_workers=4)
|
||||
# a sequential fallback would issue a plain unranged GET; only the probe and the
|
||||
# part windows may appear, each part capped at MAX_ATTEMPTS
|
||||
assert [r for r in server.requests if r is None] == []
|
||||
parts = len({r for r in server.requests if r and r != "bytes=0-0"})
|
||||
assert len(server.requests) <= 1 + parts * dl.MAX_ATTEMPTS
|
||||
# nothing half-written is left behind for a later run to mistake for a finished file
|
||||
assert sorted(tmp_path.glob("seg_*")) == []
|
||||
|
||||
|
||||
@@ -212,7 +198,6 @@ def test_permanent_status_unwraps_causes():
|
||||
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
|
||||
# RnetSession wraps the HTTPError one level down as __cause__
|
||||
wrapped = RuntimeError("max retries")
|
||||
wrapped.__cause__ = HTTPError(response=_Resp(404))
|
||||
assert dl.permanent_status(wrapped) == 404
|
||||
@@ -273,8 +258,6 @@ def plan_split(monkeypatch, tmp_path, total_size, max_workers):
|
||||
record: list = []
|
||||
|
||||
def spy(size, max_parts, part_target):
|
||||
# _REAL_SPLIT, not dl.split_ranges: a second call in one test would otherwise
|
||||
# chain through the previous spy and raise before recording
|
||||
record.append((size, max_parts, part_target, _REAL_SPLIT(size, max_parts, part_target)))
|
||||
raise _SplitStop
|
||||
|
||||
@@ -300,7 +283,6 @@ def test_part_count_matches_worker_count(tmp_path, monkeypatch):
|
||||
|
||||
|
||||
def test_part_floor_caps_sliver_count(tmp_path, monkeypatch):
|
||||
# below the 4 MiB floor a part's handshake costs more than its transfer
|
||||
_, _, target, parts = plan_split(monkeypatch, tmp_path, 16 * 1024 * 1024, 64)
|
||||
assert target == 4 * 1024 * 1024
|
||||
assert len(parts) == 4
|
||||
|
||||
@@ -98,7 +98,6 @@ def test_rnet_spec_is_picklable() -> None:
|
||||
assert spec is not None
|
||||
|
||||
loaded = pickle.loads(pickle.dumps(spec))
|
||||
# stdlib Cookie has no __eq__, so compare the cookies by their fields
|
||||
assert [vars(c) for c in loaded.pop("cookies")] == [vars(c) for c in spec.pop("cookies")]
|
||||
assert loaded == spec
|
||||
|
||||
@@ -121,7 +120,7 @@ class _CookieHandler(BaseHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args): # keep the test output quiet
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
|
||||
@@ -30,16 +30,15 @@ from requests import Session
|
||||
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED
|
||||
|
||||
# the package re-exports the `requests` function, shadowing the module of the same name
|
||||
dl = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
|
||||
TOTAL = 256 * 1024
|
||||
PAYLOAD = bytes((i * 37 + 5) % 256 for i in range(TOTAL))
|
||||
|
||||
SEED = 64 * 1024 # bytes a prior run left in the .!dev partial
|
||||
CAP = 32 * 1024 # most the capped server serves for one range
|
||||
OPEN_CAP = 16 * 1024 # most the halving server serves for an open-ended range
|
||||
CUT = 96 * 1024 # where the halving server cuts the unranged body
|
||||
SEED = 64 * 1024
|
||||
CAP = 32 * 1024
|
||||
OPEN_CAP = 16 * 1024
|
||||
CUT = 96 * 1024
|
||||
|
||||
|
||||
class _ShortServer(ThreadingHTTPServer):
|
||||
@@ -52,7 +51,7 @@ class _ShortServer(ThreadingHTTPServer):
|
||||
self.mode = "cap"
|
||||
super().__init__(("127.0.0.1", 0), _ShortHandler)
|
||||
|
||||
def handle_error(self, request, client_address): # the client hanging up is expected here
|
||||
def handle_error(self, request, client_address):
|
||||
pass
|
||||
|
||||
|
||||
@@ -71,7 +70,6 @@ class _ShortHandler(BaseHTTPRequestHandler):
|
||||
|
||||
if header is None:
|
||||
if mode == "fresh206":
|
||||
# a 206 to an un-Ranged request: the complete length is only in Content-Range
|
||||
body = PAYLOAD[:CAP]
|
||||
self.send_response(206)
|
||||
self.send_header("Content-Range", f"bytes 0-{CAP - 1}/{TOTAL}")
|
||||
@@ -80,7 +78,6 @@ class _ShortHandler(BaseHTTPRequestHandler):
|
||||
self.wfile.write(body)
|
||||
return
|
||||
if mode == "chunked200":
|
||||
# no Content-Length: an unknown-length body the downloader cannot size
|
||||
self.send_response(200)
|
||||
self.send_header("Transfer-Encoding", "chunked")
|
||||
self.end_headers()
|
||||
@@ -90,7 +87,6 @@ class _ShortHandler(BaseHTTPRequestHandler):
|
||||
self.send_header("Content-Length", str(TOTAL))
|
||||
self.end_headers()
|
||||
if mode == "halving":
|
||||
# honest length, then cut: download() credits a resume and bounds the next request
|
||||
self.wfile.write(PAYLOAD[:CUT])
|
||||
self.close_connection = True
|
||||
return
|
||||
@@ -117,7 +113,7 @@ class _ShortHandler(BaseHTTPRequestHandler):
|
||||
return
|
||||
|
||||
if want_end is not None:
|
||||
end = min(TOTAL - 1, want_end) # a bounded sub-range is always served whole
|
||||
end = min(TOTAL - 1, want_end)
|
||||
elif mode == "whole_remainder":
|
||||
end = TOTAL - 1
|
||||
elif mode == "halving":
|
||||
@@ -157,7 +153,6 @@ def run(srv, save_path):
|
||||
|
||||
|
||||
def assert_complete(save_path):
|
||||
# size first: a truncation failure then names the byte counts instead of diffing blobs
|
||||
assert save_path.stat().st_size == TOTAL
|
||||
assert save_path.read_bytes() == PAYLOAD
|
||||
|
||||
@@ -195,7 +190,6 @@ def test_short_tail_after_chunk_halving_finishes_the_file(server, tmp_path, monk
|
||||
|
||||
assert_complete(save_path)
|
||||
assert finalized(events) == [TOTAL]
|
||||
# the bounded sub-ranges in the middle were each served whole and continued
|
||||
bounded = [r for r in server.requests if r and r.split("-")[-1]]
|
||||
assert len(bounded) >= 2
|
||||
|
||||
@@ -209,7 +203,6 @@ def test_zero_byte_resume_body_raises_instead_of_spinning(server, tmp_path):
|
||||
run(server, save_path)
|
||||
|
||||
assert not save_path.exists()
|
||||
# an empty body must spend an attempt, not repeat the same request with no bound
|
||||
assert len(server.requests) <= dl.MAX_ATTEMPTS
|
||||
|
||||
|
||||
@@ -235,7 +228,7 @@ def test_stale_partial_416_still_restarts_clean(server, tmp_path):
|
||||
|
||||
assert_complete(save_path)
|
||||
assert finalized(events) == [TOTAL]
|
||||
assert None in server.requests # restarted from byte 0 with an unranged GET
|
||||
assert None in server.requests
|
||||
assert not tmp_file.exists()
|
||||
|
||||
|
||||
@@ -258,7 +251,6 @@ def test_complete_resume_finalizes_without_an_extra_request(server, tmp_path):
|
||||
|
||||
assert_complete(save_path)
|
||||
assert finalized(events) == [TOTAL]
|
||||
# a known complete length that the first response satisfies costs no confirming request
|
||||
assert len(server.requests) == 1
|
||||
|
||||
|
||||
|
||||
@@ -14,8 +14,6 @@ requests_downloader = importlib.import_module("unshackle.core.downloaders.reques
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_cancel():
|
||||
# a failing batch sets the process-global cancel, which TokenBucket.consume waits on;
|
||||
# keep tests independent
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
yield
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
@@ -91,7 +89,6 @@ def test_bucket_holds_aggregate_rate_across_threads():
|
||||
for t in threads:
|
||||
t.join()
|
||||
achieved = sum(totals) / (time.monotonic() - start)
|
||||
# exceeding the limit is a real failure; undershoot is scheduler noise on a loaded box, so no lower bound
|
||||
assert achieved <= rate * 1.1
|
||||
|
||||
|
||||
@@ -109,8 +106,6 @@ def test_bucket_refills_at_the_rate(monkeypatch):
|
||||
|
||||
|
||||
def test_bucket_chunk_larger_than_capacity_does_not_deadlock(monkeypatch):
|
||||
# capture the debt sleep instead of timing it: Event.wait can wake early spuriously,
|
||||
# so a wall-clock lower bound flakes
|
||||
waits: list[float] = []
|
||||
monkeypatch.setattr(requests_downloader, "DOWNLOAD_CANCELLED", SimpleNamespace(wait=waits.append))
|
||||
bucket = TokenBucket(1_000_000)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user