mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-06 07:55:10 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e9470c7ed | ||
|
|
2ee4e25742 | ||
|
|
bd178bc3af | ||
|
|
ce7cb41eac | ||
|
|
3a0a74e694 | ||
|
|
783a2fc185 |
@@ -446,7 +446,8 @@ file on the server travels as base64, and the client writes it to its own temp d
|
||||
"server_cdm": false,
|
||||
"server_cdm_type": "widevine",
|
||||
"sample_decrypt_tracks": [],
|
||||
"fairplay_bridge": false
|
||||
"fairplay_bridge": false,
|
||||
"license_first": false
|
||||
}
|
||||
```
|
||||
|
||||
@@ -461,6 +462,7 @@ The remote session fields (`TracksReply`):
|
||||
| `server_cdm_type` | The DRM system that a server-CDM licence takes first for the tracks of this title. |
|
||||
| `sample_decrypt_tracks` | The IDs of the tracks that the service decrypts itself, through the `samples` route. |
|
||||
| `fairplay_bridge` | `true` when the service licenses FairPlay-only tracks through a bridge on the server. |
|
||||
| `license_first` | The `LICENSE_FIRST` value of the service. When `true`, the client licenses every track of a title before any track downloads, as with `--license-first`. |
|
||||
|
||||
| Status | Error code | Meaning |
|
||||
| --- | --- | --- |
|
||||
|
||||
@@ -208,8 +208,8 @@ Each subclass adds its own required fields on top of `id_` and `service`:
|
||||
options, `-a`/`--acodec` and `--abitrate`, and its usual audio sorting. A movie or an
|
||||
episode uses the same options. `-q`/`--quality` sets the video height only and does not
|
||||
apply to music. The audio sort ranks a hi-res FLAC above a CD FLAC by `bitrate`. Set
|
||||
`bit_depth` and `sample_rate` (Hz) on each `Audio` track, and `--list` shows them as
|
||||
"24-bit / 96 kHz", so do not write that text into `name`. The same two keys in
|
||||
`bit_depth` and `sample_rate` (Hz) on each `Audio` track, and `--list` shows them for a
|
||||
`Song` as "24-bit / 96 kHz", so do not write that text into `name`. The same two keys in
|
||||
`Song.data` give the Hi-Res badge in the release listing.
|
||||
|
||||
When the first song's `Song.data` has no bit depth or sample rate, or a lower one, `dl`
|
||||
|
||||
@@ -216,6 +216,7 @@ Keep only certain track types, or skip certain track types.
|
||||
| `--vaults-only` | Get no licence. A content key that no key vault, export or earlier track gives fails the title. With both flags, the last one wins. |
|
||||
| `--cdm <name>` | Use the named CDM device for this run, and ignore the `cdm` config mapping, its quality and Widevine/PlayReady entries included. Over `--remote`, that device licenses the remote session, not the server CDM. |
|
||||
| `--skip-dl` | Skip the download but still retrieve keys. |
|
||||
| `--license-first` | Get the content keys of every track of a title before any track of that title downloads. A failed licence then stops the run before that title downloads data. Over `--remote` it applies on the client. No effect with `--skip-dl`. A service can turn it on for every run with [`LICENSE_FIRST`](../reference/api/service.md). |
|
||||
| `--all-drm` | License each track with both Widevine and PlayReady. Needs a CDM for each DRM system. Key Vaults are read first; `--cdm-only` sends a challenge for each system. Not for use with `--cdm`. |
|
||||
| `--export` | Write an [export](downloading.md#keys-vaults-and-export) of each title's tracks, DRM init data and content keys to the exports directory. |
|
||||
|
||||
|
||||
@@ -66,6 +66,9 @@ with `--skip-dl`.
|
||||
`--list` prints the tracks a title exposes and stops before selection. `--list-titles`
|
||||
prints every title the service returned and stops before `--wanted`/`--latest-episode`/`--latest-episodes`
|
||||
filtering. `--skip-dl` runs the licence step but skips the segment download.
|
||||
`--license-first` runs the licence step of every track of a title before any segment of that title downloads,
|
||||
so a failed licence stops the run before that title downloads data. The download then sends no second licence.
|
||||
A service can turn it on for every run with [`LICENSE_FIRST`](../reference/api/service.md).
|
||||
|
||||
## Choosing quality
|
||||
|
||||
@@ -324,7 +327,7 @@ unshackle dl -a AAC -ab 320 EXAMPLE 81234567
|
||||
A service can offer both a CD FLAC and a hi-res FLAC. The two have the same codec, so
|
||||
the bitrate is what separates them. Use `--list` to read the bitrates, then give `-ab`
|
||||
the one you want. When the service gives them, `--list` also shows the bit depth and
|
||||
sample rate, such as "24-bit / 96 kHz".
|
||||
sample rate of a song, such as "24-bit / 96 kHz". A movie or an episode does not show them.
|
||||
|
||||
## Languages
|
||||
|
||||
@@ -920,9 +923,9 @@ tracks from those URLs. If such an export does not give the title a language, `o
|
||||
value: select the languages with `-l` and `-vl`.
|
||||
|
||||
Each exported track keeps the values that the service set on it, also when the import parses
|
||||
the manifest again: for example Atmos, the bit depth, the sample rate and the note at the end of
|
||||
its `--list` line. A track that the export does not hold shows only what the manifest gives. A
|
||||
song imports as a song, with its artist, album and track number. An export that an older
|
||||
the manifest again: for example Atmos, the note at the end of its `--list` line, and the bit
|
||||
depth and sample rate of a song. A track that the export does not hold shows only what the
|
||||
manifest gives. A song imports as a song, with its artist, album and track number. An export that an older
|
||||
unshackle wrote records a song as a movie. Its import then stops at the video selection, because
|
||||
a song has no video track. Export the song again.
|
||||
|
||||
|
||||
@@ -56,6 +56,7 @@ Common config keys. This is a useful subset, and every `dl` flag works:
|
||||
| `slow` | str | *(unset)* | Inter-title delay, e.g. `"20-40"`. |
|
||||
| `best_available` | bool | `false` | Warn instead of failing when a requested resolution, range, video language, or audio language is missing, or when one DRM system does not license under `--all-drm`. The CLI flag is `--best-available`, also spelled `--warn-only`. |
|
||||
| `skip_missing` | bool | `false` | Skip a title that misses a required language (`require_audio`, `require_video`, `require_subs`) or a track that a filter asks for, and continue with the next title. A run with one title, or a run that skips every title, still fails. The CLI flag is `--skip-missing`. For REST API jobs, set it in the [`serve`](services.md#serve) block. |
|
||||
| `license_first` | bool | `false` | Get the content keys of every track of a title before any track of that title downloads. A failed licence stops the run before that title downloads data. The CLI flag is `--license-first`. A `false` value does not turn off the [`LICENSE_FIRST`](../api/service.md) of a service. For REST API jobs, set it in the [`serve`](services.md#serve) block or send `license_first` in the request. |
|
||||
| `generate_dv` | bool | `false` | With `-r HYBRID`, make Dolby Vision from the HDR10+ metadata or the decoded video when a title has no DV track. With `-r HDR10` or `-r HDR10P`, make it for that base and ignore a DV track. See [Dolby Vision without a DV track](../../guide/downloading.md#dolby-vision-without-a-dv-track). |
|
||||
| `proxy` | str | *(unset)* | Default proxy URI or 2-letter country. |
|
||||
| `no_folder` | bool | `false` | Do not create a per-title folder. |
|
||||
|
||||
@@ -152,7 +152,7 @@ calls.
|
||||
| Key | Type | Default | Description |
|
||||
|-----|------|---------|-------------|
|
||||
| `theme` | str | `catppuccin-mocha` | Named colour theme for all CLI output: banner, logs, progress bars, and help screens. One of `catppuccin-mocha` (aliases `default`, `catppuccin`, `mocha`), `dracula`, `nord`, `gruvbox`, `one-dark` (alias `onedark`), `tokyo-night` (alias `tokyonight`), `monokai`, `flexoki`, `solarized-dark` (alias `solarized`). Case-insensitive; underscores work in place of hyphens. Unknown names fall back to the default with a warning. Preview them all with `unshackle env theme`. |
|
||||
| `wide_output` | bool | `false` | Print the `dl` title and track listings at the terminal width. When `false`, they fold at 80 columns, the width that logs and progress bars always use. |
|
||||
| `wide_output` | bool | `false` | Print all console output (rules, logs, listings and progress bars) at the terminal width. The download and mux progress bars fill the line. When `false`, the output folds at 80 columns and these bars are 40 cells wide. The `env` listings use the terminal width and uncaught tracebacks use 80 columns, whatever the value. |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ import pytest
|
||||
|
||||
import unshackle.core.cdm as cdm_mod
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.cdm import loader
|
||||
from unshackle.core.config import config
|
||||
|
||||
|
||||
@@ -61,19 +60,6 @@ def test_repeated_calls_build_the_cdm_once(builds, monkeypatch) -> None:
|
||||
assert builds == [("device_a", "EXAMPLE")]
|
||||
|
||||
|
||||
def test_the_title_loop_guard_sees_the_same_object(builds, monkeypatch) -> None:
|
||||
"""The call site keeps its CDM when ``get_cdm`` returns what it already holds."""
|
||||
monkeypatch.setattr(config, "cdm", {"EXAMPLE": "device_a"})
|
||||
runner = make_dl()
|
||||
|
||||
held = runner.get_cdm("EXAMPLE", "default")
|
||||
for _ in range(3):
|
||||
quality_based_cdm = runner.get_cdm("EXAMPLE", "default", drm="widevine", quality=2160)
|
||||
assert not (quality_based_cdm and quality_based_cdm != held)
|
||||
|
||||
assert len(builds) == 1
|
||||
|
||||
|
||||
def test_a_different_service_gets_its_own_cdm(builds, monkeypatch) -> None:
|
||||
"""A CDM is built with its ``service_name``, so two services must not share one."""
|
||||
monkeypatch.setattr(config, "cdm", {"EXAMPLE": "device_a", "OTHER": "device_a"})
|
||||
@@ -86,18 +72,6 @@ def test_a_different_service_gets_its_own_cdm(builds, monkeypatch) -> None:
|
||||
assert builds == [("device_a", "EXAMPLE"), ("device_a", "OTHER")]
|
||||
|
||||
|
||||
def test_a_different_profile_gets_its_own_cdm(builds, monkeypatch) -> None:
|
||||
monkeypatch.setattr(config, "cdm", {"EXAMPLE": {"one": "device_one", "two": "device_two"}})
|
||||
runner = make_dl()
|
||||
|
||||
one = runner.get_cdm("EXAMPLE", "one")
|
||||
two = runner.get_cdm("EXAMPLE", "two")
|
||||
|
||||
assert one is not two
|
||||
assert runner.get_cdm("EXAMPLE", "one") is one
|
||||
assert builds == [("device_one", "EXAMPLE"), ("device_two", "EXAMPLE")]
|
||||
|
||||
|
||||
def test_quality_selection_reuses_the_device_it_resolves_to(builds, monkeypatch) -> None:
|
||||
"""Two spellings of the same device share one CDM; a different device does not."""
|
||||
monkeypatch.setattr(config, "cdm", {"EXAMPLE": {">=1080": "device_hd", "<1080": "device_sd"}})
|
||||
@@ -120,25 +94,3 @@ def test_an_override_is_cached_under_the_name_it_resolves_to(builds, monkeypatch
|
||||
|
||||
assert runner.get_cdm("EXAMPLE", "default") is override
|
||||
assert builds == [("device_b", "EXAMPLE")]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def leaked_shadow(monkeypatch) -> None:
|
||||
"""Reproduce the residue that a ``setattr`` on the CDM package leaves behind.
|
||||
|
||||
``load_cdm`` reaches the package only through its lazy ``__getattr__``. A ``setattr`` on
|
||||
the package writes the real function into the package dict when it undoes, which shadows
|
||||
``__getattr__`` for the rest of the process. Two remote tests do exactly that.
|
||||
"""
|
||||
monkeypatch.setitem(cdm_mod.__dict__, "load_cdm", loader.load_cdm)
|
||||
|
||||
|
||||
def test_a_shadowed_package_attribute_still_reaches_the_stub(leaked_shadow, builds, monkeypatch) -> None:
|
||||
"""The stub intercepts ``get_cdm`` whatever an earlier test left on the CDM package."""
|
||||
monkeypatch.setattr(config, "cdm", {"EXAMPLE": "device_a"})
|
||||
runner = make_dl()
|
||||
|
||||
cdm = runner.get_cdm("EXAMPLE", "default")
|
||||
|
||||
assert isinstance(cdm, StubCdm)
|
||||
assert builds == [("device_a", "EXAMPLE")]
|
||||
|
||||
@@ -45,21 +45,6 @@ def test_a_duplicate_key_blocks_a_write(config_file: Path) -> None:
|
||||
assert config_file.read_text(encoding="utf-8") == original
|
||||
|
||||
|
||||
def test_a_valid_config_still_reads_a_key(config_file: Path) -> None:
|
||||
config_file.write_text("theme: rainbow\n", encoding="utf-8")
|
||||
result = CliRunner().invoke(cfg_module.cfg, ["theme"])
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "rainbow" in result.output
|
||||
|
||||
|
||||
def test_a_duplicate_only_ruamel_sees_still_gives_its_line(config_file: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||
config_file.write_text("a: 1\n1: x\n0x1: y\n", encoding="utf-8")
|
||||
with caplog.at_level(logging.WARNING):
|
||||
result = CliRunner().invoke(cfg_module.cfg, ["a"])
|
||||
assert result.exit_code == 1
|
||||
assert caplog.messages == [f"{config_file}: duplicate key on line 3. Unshackle uses the later one."]
|
||||
|
||||
|
||||
def test_lowercase_true_and_false_are_written_as_booleans_and_no_stays_a_language(config_file: Path) -> None:
|
||||
config_file.write_text("theme: rainbow\n", encoding="utf-8")
|
||||
for key, value in (("wide_output", "false"), ("debug_requests", "TRUE"), ("lang", "no")):
|
||||
|
||||
@@ -5,7 +5,6 @@ from typing import Any
|
||||
|
||||
import click
|
||||
import pytest
|
||||
import rich_click
|
||||
from click.testing import CliRunner
|
||||
from pyplayready import main as prd_upstream
|
||||
from pywidevine import main as wvd_upstream
|
||||
@@ -35,59 +34,6 @@ def files(folder: Path, *names: str) -> Path:
|
||||
return folder
|
||||
|
||||
|
||||
def test_prd_new_from_a_folder_passes_its_files_and_saves_into_the_folder(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
folder = files(tmp_path / "dev", "zgpriv.dat", "bgroupcert.dat")
|
||||
calls = record(monkeypatch, prd_upstream, "create_device")
|
||||
|
||||
result = CliRunner().invoke(prd_module.prd, ["new", str(folder)])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert calls == [
|
||||
{
|
||||
"group_key": folder / "zgpriv.dat",
|
||||
"protected_group_key": None,
|
||||
"group_certificate": folder / "bgroupcert.dat",
|
||||
"encryption_key": None,
|
||||
"signing_key": None,
|
||||
"output": folder,
|
||||
}
|
||||
]
|
||||
assert set(calls[0]) == names(prd_upstream, "create_device")
|
||||
|
||||
|
||||
def test_prd_new_from_two_paths_passes_the_keys_and_output(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
src = files(tmp_path, "key.dat", "cert.dat", "enc.dat", "sig.dat")
|
||||
monkeypatch.setattr(config.directories, "prds", tmp_path / "PRDs")
|
||||
calls = record(monkeypatch, prd_upstream, "create_device")
|
||||
|
||||
result = CliRunner().invoke(
|
||||
prd_module.prd,
|
||||
[
|
||||
"new",
|
||||
str(src / "key.dat"),
|
||||
str(src / "cert.dat"),
|
||||
"-e",
|
||||
str(src / "enc.dat"),
|
||||
"-s",
|
||||
str(src / "sig.dat"),
|
||||
"-o",
|
||||
str(tmp_path / "out.prd"),
|
||||
],
|
||||
)
|
||||
default = CliRunner().invoke(prd_module.prd, ["new", str(src / "key.dat"), str(src / "cert.dat")])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert default.exit_code == 0, default.output
|
||||
assert calls[1]["output"] == tmp_path / "PRDs"
|
||||
assert calls[0]["group_key"] == src / "key.dat"
|
||||
assert calls[0]["group_certificate"] == src / "cert.dat"
|
||||
assert calls[0]["encryption_key"] == src / "enc.dat"
|
||||
assert calls[0]["signing_key"] == src / "sig.dat"
|
||||
assert calls[0]["output"] == tmp_path / "out.prd"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("args", "message"),
|
||||
[
|
||||
@@ -111,53 +57,6 @@ def test_prd_new_refuses_bad_paths_before_the_upstream_command(
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_prd_reprovision_passes_its_arguments(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
device = files(tmp_path, "d.prd") / "d.prd"
|
||||
calls = record(monkeypatch, prd_upstream, "reprovision_device")
|
||||
|
||||
result = CliRunner().invoke(prd_module.prd, ["reprovision", str(device), "-o", str(tmp_path / "new.prd")])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert calls == [{"prd_path": device, "encryption_key": None, "signing_key": None, "output": tmp_path / "new.prd"}]
|
||||
assert set(calls[0]) == names(prd_upstream, "reprovision_device")
|
||||
|
||||
|
||||
def test_prd_test_sends_the_upstream_content_key_type(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
device = files(tmp_path, "d.prd") / "d.prd"
|
||||
calls = record(monkeypatch, prd_upstream, "test")
|
||||
|
||||
result = CliRunner().invoke(prd_module.prd, ["test", str(device), "-c", "AESCBC", "-sl", "3000"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert calls == [{"device": device, "ckt": "AES128BitCBC", "security_level": "3000"}]
|
||||
ckt = next(param for param in prd_upstream.test.params if param.name == "ckt")
|
||||
assert set(prd_module.CONTENT_KEY_TYPES.values()) == set(ckt.type.choices)
|
||||
assert set(calls[0]) == names(prd_upstream, "test")
|
||||
|
||||
|
||||
def test_prd_lists_the_upstream_export_and_inspect_commands() -> None:
|
||||
assert prd_module.prd.commands["export"] is prd_upstream.export_device
|
||||
assert prd_module.prd.commands["inspect"] is prd_upstream.inspect
|
||||
|
||||
|
||||
def test_wvd_dump_exports_each_device_and_resolves_a_bare_name_in_the_wvds_directory(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(config.directories, "wvds", files(tmp_path / "WVDs", "example.wvd"))
|
||||
monkeypatch.chdir(tmp_path)
|
||||
other = files(tmp_path / "elsewhere", "other.wvd") / "other.wvd"
|
||||
calls = record(monkeypatch, wvd_upstream, "export_device")
|
||||
|
||||
result = CliRunner().invoke(wvd_module.wvd, ["dump", "example", str(other), "out"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert calls == [
|
||||
{"wvd_path": tmp_path / "WVDs" / "example.wvd", "out_dir": Path("out")},
|
||||
{"wvd_path": other, "out_dir": Path("out")},
|
||||
]
|
||||
assert set(calls[0]) == names(wvd_upstream, "export_device")
|
||||
|
||||
|
||||
def test_wvd_dump_names_a_missing_device_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(config.directories, "wvds", tmp_path / "WVDs")
|
||||
calls = record(monkeypatch, wvd_upstream, "export_device")
|
||||
@@ -167,18 +66,3 @@ def test_wvd_dump_names_a_missing_device_path(tmp_path: Path, monkeypatch: pytes
|
||||
assert isinstance(result.exception, click.UsageError)
|
||||
assert str(tmp_path / "WVDs" / "missing.wvd") in result.exception.message
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_ctx_invoke_runs_a_command_of_another_package_in_a_sub_context() -> None:
|
||||
seen: list[tuple[str | None, int]] = []
|
||||
foreign = rich_click.RichCommand(
|
||||
"foreign",
|
||||
params=[click.Option(["--value"], type=int, default=5)],
|
||||
callback=click.pass_context(lambda ctx, value: seen.append((ctx.info_name, value))),
|
||||
)
|
||||
outer = click.Command("outer", callback=lambda: click.get_current_context().invoke(foreign))
|
||||
|
||||
result = CliRunner().invoke(outer)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert seen == [("foreign", 5)]
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""The free-space preflight warns before the downloads when the temp volume cannot hold a title's tracks."""
|
||||
|
||||
import threading
|
||||
import time
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
@@ -11,14 +9,13 @@ import m3u8
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from tests.lang_selection import test_kind_only_selection as harness
|
||||
from unshackle.commands import dl as dl_module
|
||||
from unshackle.commands.dl import DiskCheck
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.manifests import DASH, HLS, ISM
|
||||
from unshackle.core.tracks import Audio, Subtitle, Tracks
|
||||
from unshackle.core.tracks import Audio, Tracks
|
||||
from unshackle.core.tracks.track import Track
|
||||
from unshackle.core.utils.bitrate import manifest_seconds, playlist_size
|
||||
from unshackle.core.utils.bitrate import manifest_seconds
|
||||
|
||||
GB = 1_000_000_000
|
||||
|
||||
@@ -95,20 +92,6 @@ def test_a_temp_volume_too_small_for_twice_the_tracks_gets_one_warning_line(
|
||||
assert line == f"Temp volume {tmp_path} has 3.1 GB free, the selected tracks need about 15.0 GB"
|
||||
|
||||
|
||||
def test_enough_free_space_gives_no_warning(free_space: list[int]) -> None:
|
||||
free_space[0] = 15 * GB
|
||||
|
||||
assert low_disk_warning(dash_tracks(mpd(period()))) is None
|
||||
|
||||
|
||||
def test_hls_tracks_count_nothing_before_their_playlist_is_read(free_space: list[int]) -> None:
|
||||
free_space[0] = 0
|
||||
tracks = HLS.from_text(HLS_MASTER, "https://cdn.example/x.m3u8").to_tracks("en")
|
||||
|
||||
assert tracks.videos and manifest_seconds(tracks.videos[0]) is None
|
||||
assert low_disk_warning(tracks) is None
|
||||
|
||||
|
||||
def test_a_dash_track_counts_only_its_content_periods() -> None:
|
||||
manifest = mpd(period('id="ad" duration="PT10M"') + period('id="main" duration="PT50M"'))
|
||||
track = DASH.from_text(manifest, "https://cdn.example/x.mpd").to_tracks("en").videos[0]
|
||||
@@ -117,21 +100,6 @@ def test_a_dash_track_counts_only_its_content_periods() -> None:
|
||||
assert manifest_seconds(track) == 3000
|
||||
|
||||
|
||||
def test_a_dash_track_skips_a_period_that_does_not_carry_it() -> None:
|
||||
other = period('id="b" duration="PT30M"').replace('width="3840" height="2160"', 'width="1920" height="1080"')
|
||||
manifest = mpd(period('id="a" duration="PT30M"') + other)
|
||||
video = dash_tracks(manifest).videos[0]
|
||||
|
||||
assert video.height == 2160
|
||||
assert manifest_seconds(video) == 1800
|
||||
|
||||
|
||||
def test_a_duration_the_parser_cannot_read_gives_no_warning(free_space: list[int]) -> None:
|
||||
free_space[0] = 0
|
||||
|
||||
assert low_disk_warning(dash_tracks(mpd(period(), total="P0DT1H"))) is None
|
||||
|
||||
|
||||
def test_a_dash_period_of_unknown_length_takes_the_presentation_length() -> None:
|
||||
manifest = mpd(period('id="a"') + period('id="b"'), total="PT1H")
|
||||
|
||||
@@ -168,19 +136,6 @@ def test_an_unreadable_temp_volume_gives_no_warning(free_space: list[int], monke
|
||||
assert low_disk_warning(dash_tracks(mpd(period()))) is None
|
||||
|
||||
|
||||
def test_dl_logs_the_warning_once_per_title_and_not_with_skip_dl(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
monkeypatch.setattr(dl_module, "DiskCheck", lambda tracks, warn: warn("Temp volume is short"))
|
||||
|
||||
harness.run(monkeypatch, caplog, {1: {}, 2: {}}, to_end=True, no_mux=True)
|
||||
assert caplog.text.count("Temp volume is short") == 2
|
||||
|
||||
caplog.clear()
|
||||
harness.run(monkeypatch, caplog, {1: {}}, to_end=True, skip_dl=True)
|
||||
assert "Temp volume is short" not in caplog.text
|
||||
|
||||
|
||||
def test_an_hls_track_warns_once_when_its_playlist_is_read(free_space: list[int], tmp_path: Path) -> None:
|
||||
free_space[0] = 3_100_000_000
|
||||
video = HLS.from_text(HLS_MASTER, "https://cdn.example/x.m3u8").to_tracks("en").videos[0]
|
||||
@@ -206,38 +161,6 @@ def test_a_mixed_title_counts_each_track_once_against_one_free_space_reading(
|
||||
assert lines == [f"Temp volume {tmp_path} has 20.0 GB free, the selected tracks need about 21.0 GB"]
|
||||
|
||||
|
||||
def test_a_second_worker_waits_for_the_first_and_gives_no_second_warning(free_space: list[int]) -> None:
|
||||
free_space[0] = GB
|
||||
check, lines = new_check()
|
||||
second_started = threading.Event()
|
||||
|
||||
def first_size() -> float:
|
||||
assert second_started.wait(5)
|
||||
return 2 * GB
|
||||
|
||||
second = threading.Thread(target=lambda: (second_started.set(), check.add(lambda: 2 * GB)))
|
||||
first = threading.Thread(target=check.add, args=(first_size,))
|
||||
first.start()
|
||||
deadline = time.monotonic() + 5
|
||||
while not check.lock.locked() and time.monotonic() < deadline:
|
||||
time.sleep(0.001)
|
||||
second.start()
|
||||
first.join(5)
|
||||
second.join(5)
|
||||
|
||||
assert len(lines) == 1
|
||||
|
||||
|
||||
def test_a_subtitle_counts_nothing(free_space: list[int]) -> None:
|
||||
free_space[0] = 0
|
||||
check, lines = new_check()
|
||||
subtitle = Subtitle(url="https://cdn.example/s.m3u8", language="en", codec=Subtitle.Codec.WebVTT)
|
||||
|
||||
check.add_segments(subtitle, media_segments(3, byterange="1000000000"))
|
||||
|
||||
assert lines == []
|
||||
|
||||
|
||||
def test_an_estimate_error_ends_the_check(free_space: list[int]) -> None:
|
||||
free_space[0] = 0
|
||||
check, lines = new_check()
|
||||
@@ -248,20 +171,6 @@ def test_an_estimate_error_ends_the_check(free_space: list[int]) -> None:
|
||||
assert lines == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("bitrate", "segments", "size"),
|
||||
[
|
||||
(16_000_000, media_segments(3, byterange="1000@0"), 3000),
|
||||
(16_000_000, media_segments(2, byterange="1000@0") + media_segments(1), 16_000_000 * 18 / 8),
|
||||
(8, media_segments(1, byterange="x"), 6),
|
||||
(None, media_segments(3), 0),
|
||||
],
|
||||
ids=["byte ranges", "a segment without a range", "an unreadable range", "no bitrate"],
|
||||
)
|
||||
def test_playlist_size(bitrate: int | None, segments: list[Any], size: float) -> None:
|
||||
assert playlist_size(bitrate, segments) == size
|
||||
|
||||
|
||||
def test_the_hls_step_hands_over_its_wanted_segments_before_any_segment_downloads(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
@@ -293,25 +202,3 @@ def test_the_hls_step_hands_over_its_wanted_segments_before_any_segment_download
|
||||
|
||||
assert handed == [(track, ["seg.m4s"])]
|
||||
assert not list(tmp_path.glob("*_segments/*"))
|
||||
|
||||
|
||||
def test_dl_hands_each_track_download_the_check_of_its_title(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
class Recorder(DiskCheck):
|
||||
def __init__(self, tracks: Tracks, warn: Any) -> None:
|
||||
checks.append(self)
|
||||
|
||||
checks: list[Recorder] = []
|
||||
handed: list[Any] = []
|
||||
monkeypatch.setattr(dl_module, "DiskCheck", Recorder)
|
||||
monkeypatch.setattr(Track, "download", lambda self, *a, **k: handed.append(k["on_segments"]))
|
||||
|
||||
def download_all(tracks: Any, workers: int, run_one: Any, **_: Any) -> None:
|
||||
for i, track in enumerate(tracks):
|
||||
run_one(track, i)
|
||||
|
||||
harness.run(monkeypatch, caplog, {1: {}}, to_end=True, no_mux=True, download=download_all)
|
||||
|
||||
assert len(checks) == 1 and len(handed) == 3
|
||||
assert all(on_segments == checks[0].add_segments for on_segments in handed)
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import click
|
||||
import pytest
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.commands.serve import serve
|
||||
|
||||
CLI_REFERENCE = Path(__file__).parents[2] / "docs" / "guide" / "cli-reference.md"
|
||||
|
||||
COMMANDS = [pytest.param("dl", dl.cli, id="dl"), pytest.param("serve", serve, id="serve")]
|
||||
|
||||
|
||||
def section(command: str) -> str:
|
||||
text = CLI_REFERENCE.read_text(encoding="utf-8")
|
||||
start = text.index(f"## `{command}`")
|
||||
return text[start : text.index("\n## ", start)]
|
||||
|
||||
|
||||
def table_flags(command: str) -> set[str]:
|
||||
"""The flags in the first cell of each table row of one command's section of the CLI reference."""
|
||||
return {
|
||||
flag
|
||||
for line in section(command).splitlines()
|
||||
if line.startswith("|")
|
||||
for flag in re.findall(r"`(--?[a-zA-Z][\w-]*)[` ]", line.split("|")[1])
|
||||
}
|
||||
|
||||
|
||||
def option_flags(command: click.Command) -> set[str]:
|
||||
return {
|
||||
flag
|
||||
for param in command.params
|
||||
if param.param_type_name == "option" and not getattr(param, "hidden", False)
|
||||
for flag in (*param.opts, *param.secondary_opts)
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("name", "command"), COMMANDS)
|
||||
def test_every_option_is_in_the_cli_reference(name: str, command: click.Command) -> None:
|
||||
assert option_flags(command) - table_flags(name) == set()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("name", "command"), COMMANDS)
|
||||
def test_every_flag_in_the_cli_reference_is_an_option(name: str, command: click.Command) -> None:
|
||||
"""Table flags of any length, and long flags anywhere in the section: a short flag in prose can be a value."""
|
||||
long_flags = set(re.findall(r"`(--[a-zA-Z][\w-]*)", section(name)))
|
||||
assert (table_flags(name) | long_flags) - option_flags(command) == set()
|
||||
@@ -39,11 +39,6 @@ def test_dl_starts_a_forwarder_for_a_control_d_resolver(monkeypatch: pytest.Monk
|
||||
assert params["proxy_query"] is None
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("example_service")
|
||||
def test_dl_keeps_a_host_and_port_as_given(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
assert run_dl(monkeypatch, tmp_path, "nas:3128").params["proxy"] == "nas:3128"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("example_service")
|
||||
@pytest.mark.parametrize("proxy", ["nope:us", "us", "controld://bad id@dns.controld.com"])
|
||||
def test_a_dl_proxy_error_is_a_proxy_error(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, proxy: str) -> None:
|
||||
|
||||
@@ -46,29 +46,6 @@ def test_a_nearly_full_temp_volume_is_named_on_the_line(temp: Path, monkeypatch:
|
||||
assert line == f" CalledProcessError: {str(error).rstrip('.')}, 38.0 MB free on {temp}"
|
||||
|
||||
|
||||
def test_enough_free_space_leaves_the_line_as_it_was(temp: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
free_space(monkeypatch, LOW_FREE_SPACE)
|
||||
error = ValueError("boom")
|
||||
|
||||
assert dl.failure_lines(error) == [":x: Download Failed...", " ValueError: boom"]
|
||||
|
||||
|
||||
def test_a_temp_dir_that_cannot_be_read_adds_nothing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path / "missing")
|
||||
|
||||
assert dl.failure_lines(ValueError("boom"))[1] == " ValueError: boom"
|
||||
|
||||
|
||||
def test_a_later_report_reuses_the_first_reading(temp: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
reads = free_space(monkeypatch, 38_000_000)
|
||||
error = OSError(28, "No space left on device")
|
||||
first = dl.failure_lines(error)
|
||||
free_space(monkeypatch, 5 * LOW_FREE_SPACE)
|
||||
|
||||
assert dl.failure_lines(error) == first
|
||||
assert len(reads) == 1
|
||||
|
||||
|
||||
def test_a_click_exception_keeps_only_its_message(temp: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
reads = free_space(monkeypatch, 0)
|
||||
|
||||
|
||||
@@ -148,14 +148,6 @@ def test_with_the_hook_the_fairplay_only_tracks_compete_and_nothing_is_probed(
|
||||
assert service.session.urls == []
|
||||
|
||||
|
||||
def test_a_quality_with_only_fairplay_only_tracks_skips_with_the_existing_reason(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
assert run(monkeypatch, caplog, Example(), quality=[2160]) == 1
|
||||
assert "Left out 2 FairPlay-only tracks" in caplog.text
|
||||
assert "Show S01E01: There's no 2160p Video Track..." in caplog.text
|
||||
|
||||
|
||||
def test_best_available_falls_back_to_the_track_that_licenses(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
"""dl builds its content-key resolution from the run's flags and installs the verified decrypt as the hook."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import create_autospec
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.drm import verify
|
||||
from unshackle.core.export_writer import ExportWriter
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def runner() -> dl:
|
||||
cmd = dl.__new__(dl)
|
||||
cmd.vaults = SimpleNamespace()
|
||||
cmd.service = "EXAMPLE"
|
||||
cmd.debug_logger = None
|
||||
cmd._remote_service = SimpleNamespace()
|
||||
return cmd
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cdm_only, vaults_only, best_available", [(True, False, False), (False, True, True)])
|
||||
def test_the_resolver_takes_the_run_flags_and_becomes_the_decrypt_hook(
|
||||
cdm_only: bool, vaults_only: bool, best_available: bool
|
||||
) -> None:
|
||||
writer = create_autospec(ExportWriter, instance=True)
|
||||
cmd = runner()
|
||||
service = SimpleNamespace()
|
||||
|
||||
cmd.start_key_resolution(
|
||||
service,
|
||||
cdm_only=cdm_only,
|
||||
vaults_only=vaults_only,
|
||||
best_available=best_available,
|
||||
export=writer,
|
||||
)
|
||||
|
||||
keys = cmd.keys
|
||||
assert verify.DECRYPT_HOOK == cmd.keys.decrypt_verified
|
||||
assert (keys.cdm_only, keys.vaults_only, keys.best_available) == (cdm_only, vaults_only, best_available)
|
||||
assert keys.source is cmd._remote_service and keys.service is service and keys.cdms is cmd
|
||||
assert keys.vaults is cmd.vaults and keys.tag == "EXAMPLE"
|
||||
assert keys.export is not None
|
||||
keys.export("title", "track", "drm")
|
||||
writer.record.assert_called_once_with("title", "track", "drm")
|
||||
|
||||
|
||||
def test_no_export_gives_no_export_callback() -> None:
|
||||
cmd = runner()
|
||||
|
||||
cmd.start_key_resolution(SimpleNamespace(), cdm_only=False, vaults_only=True, best_available=False, export=None)
|
||||
|
||||
assert cmd.keys.export is None
|
||||
@@ -180,18 +180,6 @@ def test_kv_add_without_service_writes_the_generic_table(tmp_path: Path, monkeyp
|
||||
assert SQLite("check", dest).get_key(KID, "generic") == KEY
|
||||
|
||||
|
||||
@pytest.mark.parametrize("no_push", [False, True])
|
||||
def test_kv_add_without_vault_stops_when_no_configured_vault_takes_pushes(
|
||||
no_push: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
local_vaults(monkeypatch, no_push=tmp_path / "read_only.db" if no_push else None)
|
||||
|
||||
result = CliRunner().invoke(kv_module.kv, ["add", f"{KID}:{KEY}", "-s", "EXAMPLE"], standalone_mode=False)
|
||||
|
||||
assert isinstance(result.exception, click.ClickException)
|
||||
assert result.exception.message == "No Key Vaults without no_push are configured."
|
||||
|
||||
|
||||
@pytest.mark.parametrize("arg", [f"{KID}:{KEY[:-1]}", f"{KID}{KEY}", "missing.txt"])
|
||||
def test_kv_add_rejects_an_argument_that_is_neither_a_pair_nor_a_file(
|
||||
arg: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
"""dl --license-first: every track of a title holds its content keys before any track downloads."""
|
||||
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
import click
|
||||
import pytest
|
||||
from click.testing import CliRunner, Result
|
||||
|
||||
from unshackle.commands import dl as dl_module
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED
|
||||
from unshackle.core.drm import ClearKeyCENC
|
||||
from unshackle.core.drm.clearkey_cenc import b64url_encode_nopad
|
||||
from unshackle.core.drm.key_resolution import ContentKeyResolver
|
||||
from unshackle.core.manifests import url
|
||||
from unshackle.core.titles import Movie, Movies
|
||||
from unshackle.core.tracks import Audio, Chapters, Track, Tracks, Video
|
||||
|
||||
pytestmark = pytest.mark.usefixtures("example_service")
|
||||
|
||||
KIDS = {"video": UUID(int=1), "audio": UUID(int=2)}
|
||||
|
||||
|
||||
class Run:
|
||||
"""One ``dl EXAMPLE`` run of a movie with an encrypted video and audio track; only the file fetch is fake."""
|
||||
|
||||
def __init__(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, refuse: str | None = None) -> None:
|
||||
self.licences: list[str] = []
|
||||
self.fetched: list[str] = []
|
||||
self.downloaded: list[Path | None] = []
|
||||
self.monkeypatch = monkeypatch
|
||||
self.tmp_path = tmp_path
|
||||
self.refuse = refuse
|
||||
|
||||
def licence(self, *_: Any, challenge: bytes, track: Track, **__: Any) -> dict:
|
||||
self.licences.append(track.id)
|
||||
if track.id == self.refuse:
|
||||
raise click.ClickException(f"Licence refused for track {track.id}")
|
||||
kid = KIDS[track.id]
|
||||
return {
|
||||
"keys": [
|
||||
{"kty": "oct", "kid": b64url_encode_nopad(kid.bytes), "k": b64url_encode_nopad(bytes(range(1, 17)))}
|
||||
]
|
||||
}
|
||||
|
||||
def fetch(self, *, output_dir: Path, filename: str, **_: Any) -> Any:
|
||||
self.fetched.append(filename)
|
||||
(output_dir / filename).write_bytes(b"media bytes")
|
||||
yield {"file_downloaded": output_dir / filename}
|
||||
|
||||
@staticmethod
|
||||
def complete(track: Track, ctx: Any, drm: Any, **_: Any) -> None:
|
||||
"""Hand the fetched file to the track as decrypted, as the media bytes are not CENC."""
|
||||
track.path = ctx.save_path
|
||||
track.drm = None
|
||||
|
||||
def tracks(self) -> Tracks:
|
||||
tracks = Tracks(
|
||||
Video(id_="video", url="https://example.invalid/v.mp4", language="en", codec=Video.Codec.AVC),
|
||||
Audio(id_="audio", url="https://example.invalid/a.mp4", language="en", codec=Audio.Codec.AAC),
|
||||
)
|
||||
for track in tracks:
|
||||
track.drm = [ClearKeyCENC(kids=[KIDS[track.id]])]
|
||||
track.downloader = self.fetch
|
||||
return tracks
|
||||
|
||||
def __call__(self, *args: str) -> Result:
|
||||
from unshackle.core import services
|
||||
|
||||
service = services.ensure_loaded("EXAMPLE")
|
||||
assert service is not None
|
||||
movie = Movie(id_="movie-1", service=service, name="Title", year=2020, language="en")
|
||||
patch = self.monkeypatch.setattr
|
||||
patch(service, "authenticate", lambda self, *a, **k: None)
|
||||
patch(service, "get_titles", lambda self: Movies([movie]))
|
||||
patch(service, "get_tracks", lambda _, title: self.tracks())
|
||||
patch(service, "get_chapters", lambda self, title: Chapters())
|
||||
patch(service, "get_clearkey_license", self.licence)
|
||||
patch(service, "on_track_downloaded", lambda _, track: self.downloaded.append(track.path))
|
||||
patch(Track, "get_key_id", lambda track, *a, **k: KIDS[track.id])
|
||||
patch(url, "complete_track", self.complete)
|
||||
patch(ContentKeyResolver, "LICENSE_KEY_CACHE", {})
|
||||
patch(dl_module.TitleMetadata, "search", lambda self, *a, **k: None)
|
||||
patch(dl_module.config, "key_vaults", [])
|
||||
patch(dl_module.config, "output_template", {"movies": "{title}"})
|
||||
patch(dl_module.config.directories, "temp", self.tmp_path / "temp")
|
||||
patch(dl_module.dl, "get_cdm", lambda self, *a, **k: None)
|
||||
patch(dl_module.dl.cli, "_result_callback", dl_module.dl.cli._result_callback)
|
||||
cli = (
|
||||
"-o",
|
||||
str(self.tmp_path / "out"),
|
||||
"-l",
|
||||
"en",
|
||||
"--downloads",
|
||||
"1",
|
||||
"--no-mux",
|
||||
*args,
|
||||
"EXAMPLE",
|
||||
"--movie",
|
||||
"movie-1",
|
||||
)
|
||||
return CliRunner().invoke(dl_module.dl.cli, cli)
|
||||
|
||||
|
||||
def test_a_licence_failure_stops_the_title_before_any_track_downloads(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
run = Run(monkeypatch, tmp_path, refuse="audio")
|
||||
|
||||
result = run("--license-first")
|
||||
|
||||
assert "Licence refused for track audio" in result.output
|
||||
assert result.exit_code == 1
|
||||
assert run.licences == ["video", "audio"]
|
||||
assert run.fetched == []
|
||||
|
||||
|
||||
def test_without_the_flag_a_track_downloads_before_a_later_licence_fails(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
run = Run(monkeypatch, tmp_path, refuse="audio")
|
||||
|
||||
result = run()
|
||||
|
||||
assert result.exit_code == 1, result.output
|
||||
assert run.fetched == ["Video_video.mp4"], result.output
|
||||
|
||||
|
||||
def test_a_service_with_license_first_licenses_every_track_with_no_flag(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
from unshackle.core import services
|
||||
|
||||
monkeypatch.setattr(services.ensure_loaded("EXAMPLE"), "LICENSE_FIRST", True)
|
||||
run = Run(monkeypatch, tmp_path, refuse="audio")
|
||||
|
||||
result = run()
|
||||
|
||||
assert "Licence refused for track audio" in result.output
|
||||
assert result.exit_code == 1
|
||||
assert run.licences == ["video", "audio"]
|
||||
assert run.fetched == []
|
||||
|
||||
|
||||
def test_the_download_pass_sends_no_second_licence(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
run = Run(monkeypatch, tmp_path)
|
||||
|
||||
result = run("--license-first")
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert run.licences == ["video", "audio"]
|
||||
assert sorted(run.fetched) == ["Audio_audio.mp4", "Video_video.mp4"]
|
||||
assert len(run.downloaded) == 2 and all(run.downloaded)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("cancelled", "shown"),
|
||||
[(False, ["LICENSED"]), (True, ["LICENSED", "[yellow]SKIPPED"])],
|
||||
ids=["licensed", "cancelled"],
|
||||
)
|
||||
def test_the_licence_pass_does_not_end_the_progress_bar(cancelled: bool, shown: list[str]) -> None:
|
||||
states: list[str] = []
|
||||
progress = partial(dl_module.without_skip_states, lambda **kw: states.append(kw["downloaded"]))
|
||||
if cancelled:
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
try:
|
||||
for state in ("[yellow]SKIPPING", "LICENSED", "[yellow]SKIPPED"):
|
||||
progress(downloaded=state)
|
||||
finally:
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
|
||||
assert states == shown
|
||||
@@ -1,62 +0,0 @@
|
||||
"""The search command resolves --proxy with the same grammar as dl."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import click
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
SENT = "controld://efgh456@dns.controld.com"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("example_service")
|
||||
def test_search_starts_a_forwarder_for_a_control_d_resolver(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
from unshackle.commands import search as search_module
|
||||
from unshackle.core.proxies import controld
|
||||
|
||||
monkeypatch.setattr(controld, "local_proxy", lambda uri: "http://127.0.0.1:4000")
|
||||
monkeypatch.setattr(search_module, "load_proxy_providers", lambda: [])
|
||||
monkeypatch.setattr(search_module.Services, "get_path", staticmethod(lambda tag: tmp_path))
|
||||
ctx = click.Context(search_module.search)
|
||||
ctx.invoked_subcommand = "EXAMPLE"
|
||||
ctx.params = {"proxy": SENT, "no_proxy": False}
|
||||
with ctx:
|
||||
assert search_module.search.callback
|
||||
search_module.search.callback(no_proxy=False, proxy=SENT)
|
||||
|
||||
assert ctx.params["proxy"] == "http://127.0.0.1:4000"
|
||||
assert ctx.params["proxy_arg"] == SENT
|
||||
assert ctx.params.get("proxy_query") is None
|
||||
|
||||
|
||||
class Recorder:
|
||||
def __init__(self) -> None:
|
||||
self.asked: list[str] = []
|
||||
|
||||
def get_proxy(self, query: str) -> str:
|
||||
self.asked.append(query)
|
||||
return f"http://{query}.proxy.example:8080"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("example_service")
|
||||
@pytest.mark.parametrize(("remote", "asked"), [(False, ["ca"]), (True, ["us"])])
|
||||
def test_search_resolves_a_mapped_query_once_and_only_on_a_local_run(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, remote: bool, asked: list
|
||||
) -> None:
|
||||
from unshackle.commands import search as search_module
|
||||
|
||||
recorder = Recorder()
|
||||
monkeypatch.setattr(search_module.config, "services", {"example": {"proxy_map": {"us": "ca"}}})
|
||||
monkeypatch.setattr(search_module, "load_proxy_providers", lambda: [recorder])
|
||||
monkeypatch.setattr(search_module.Services, "get_path", staticmethod(lambda tag: tmp_path))
|
||||
ctx = click.Context(search_module.search)
|
||||
ctx.invoked_subcommand = "EXAMPLE"
|
||||
ctx.params = {"proxy": "us", "no_proxy": False, "remote": remote}
|
||||
with ctx:
|
||||
assert search_module.search.callback
|
||||
search_module.search.callback(no_proxy=False, proxy="us", remote=remote)
|
||||
|
||||
assert (recorder.asked, ctx.params["proxy"]) == (asked, f"http://{asked[0]}.proxy.example:8080")
|
||||
@@ -77,6 +77,12 @@ def no_worker_handlers(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(console, "_notice_handler", None)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fixed_console_width(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Hold the shared console at 80 columns, whatever the terminal and the user's ``wide_output``."""
|
||||
monkeypatch.setattr(console.console, "_width", 80)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fresh_proxy_catalogues() -> None:
|
||||
"""Fetch each proxy provider catalogue again, so one test's stub never answers another test."""
|
||||
|
||||
@@ -4,11 +4,9 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.export_name import audio_token
|
||||
from unshackle.core.manifests.dash import DASH
|
||||
from unshackle.core.manifests.hls import HLS
|
||||
from unshackle.core.tracks import Audio, Tracks
|
||||
from unshackle.core.wire import deserialize_audio, serialize_audio_track, track_from_dict, track_to_dict
|
||||
|
||||
VIRTUALIZED = '<SupplementalProperty schemeIdUri="tag:dolby.com,2016:dash:virtualized_content:2016" value="1"/>'
|
||||
|
||||
@@ -60,11 +58,6 @@ def test_an_hls_immersive_stereo_rendition_without_the_atmos_identifier_is_not_a
|
||||
assert audio.channels == 2.0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channels", ["2", "6"])
|
||||
def test_a_plain_hls_ac4_rendition_is_not_atmos(channels: str) -> None:
|
||||
assert not hls_audio(channels, codecs="ac-4.02.01.00").atmos
|
||||
|
||||
|
||||
def test_an_hls_joc_rendition_keeps_its_joc_count() -> None:
|
||||
audio = hls_audio("16/JOC", codecs="ec-3")
|
||||
|
||||
@@ -91,23 +84,5 @@ def test_a_dash_ac4_representation_without_a_cited_atmos_signal_is_not_atmos(
|
||||
assert not audio.atmos
|
||||
|
||||
|
||||
def test_the_export_name_reads_atmos_without_a_joc_count() -> None:
|
||||
assert audio_token(hls_audio("2/IMSA,ATMOS")).endswith("2.0atmos")
|
||||
|
||||
|
||||
def test_atmos_without_a_joc_count_is_part_of_the_track_signature() -> None:
|
||||
assert Tracks.signature(hls_audio("2/IMSA,ATMOS")) != Tracks.signature(hls_audio("2/IMSA"))
|
||||
|
||||
|
||||
def test_atmos_without_a_joc_count_survives_the_export_track_dict() -> None:
|
||||
audio = track_from_dict(track_to_dict(hls_audio("2/IMSA,ATMOS")))
|
||||
|
||||
assert audio.atmos
|
||||
assert not audio.joc
|
||||
|
||||
|
||||
def test_hls_atmos_without_a_joc_count_survives_the_remote_round_trip() -> None:
|
||||
audio = deserialize_audio(serialize_audio_track(hls_audio("2/IMSA,ATMOS")))
|
||||
|
||||
assert audio.atmos
|
||||
assert not audio.joc
|
||||
|
||||
@@ -4,24 +4,17 @@ tests only. No threads, sockets, or real downloads; the clock is supplied explic
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
from functools import partial
|
||||
from itertools import pairwise
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.downloaders.requests import (
|
||||
TAIL_BOOST_MIN_SEGMENT_SIZE,
|
||||
TAIL_BOOST_PART_SIZE,
|
||||
AdaptiveWorkerController,
|
||||
plan_tail_parts,
|
||||
requests,
|
||||
split_ranges,
|
||||
submission_window,
|
||||
tail_boost_engages,
|
||||
)
|
||||
from unshackle.core.tracks.track import DownloadContext
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
@@ -55,13 +48,6 @@ def run_tick(c: AdaptiveWorkerController, rate: float, now: float, errors: int =
|
||||
return c.update(now), now
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
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
|
||||
@@ -122,22 +108,6 @@ def test_halves_and_cooldown_on_error_burst() -> None:
|
||||
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))
|
||||
now = 0.0
|
||||
c.update(now)
|
||||
rate = 1_000_000.0
|
||||
now = fill_window(c, rate, now)
|
||||
seen = [c.update(now)]
|
||||
for _ in range(10):
|
||||
rate *= 2
|
||||
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
|
||||
|
||||
|
||||
def test_error_burst_floors_at_min() -> None:
|
||||
c = AdaptiveWorkerController(cap=16, start=2, tick=TICK, window=WINDOW)
|
||||
now = 0.0
|
||||
@@ -157,15 +127,6 @@ def test_tail_guard_suppresses_increase() -> None:
|
||||
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
|
||||
|
||||
|
||||
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)
|
||||
@@ -195,17 +156,6 @@ def run_scaling(c: AdaptiveWorkerController, now: float, seconds: float, work: i
|
||||
return now
|
||||
|
||||
|
||||
def test_probe_kept_when_the_true_gain_clears_the_bar() -> None:
|
||||
c = AdaptiveWorkerController(cap=16, start=10, tick=TICK, window=WINDOW)
|
||||
now = 0.0
|
||||
c.update(now)
|
||||
rate = 1_000_000.0
|
||||
now = fill_window(c, rate, now)
|
||||
assert c.update(now) == 12 # first evaluation probes 10 -> 12
|
||||
target, now = run_tick(c, rate * 1.2, now)
|
||||
assert target == 14 # probe held, and the controller climbs again
|
||||
|
||||
|
||||
def test_recovers_to_the_cap_after_an_error_burst() -> None:
|
||||
c = AdaptiveWorkerController(cap=16, start=16, tick=TICK, window=WINDOW)
|
||||
now = 0.0
|
||||
@@ -222,30 +172,6 @@ def test_recovers_to_the_cap_after_an_error_burst() -> None:
|
||||
assert c.target == 16, "controller left the cap on a link where every worker still pays"
|
||||
|
||||
|
||||
def test_reverts_when_the_probe_stops_paying_on_a_saturated_link() -> None:
|
||||
c = AdaptiveWorkerController(cap=16, start=8, tick=TICK, window=WINDOW)
|
||||
now = 0.0
|
||||
c.update(now)
|
||||
rate = 8 * PER_WORKER
|
||||
now = fill_window(c, rate, now)
|
||||
seen = [c.update(now, 10_000)]
|
||||
for _ in range(8):
|
||||
rate = min(c.target, 10) * PER_WORKER
|
||||
end = now + TICK
|
||||
while now < end - 1e-9:
|
||||
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 seen[-1] <= 12
|
||||
|
||||
|
||||
def test_submission_window_stages_a_spare_segment_for_every_worker() -> None:
|
||||
assert submission_window(16) == 32
|
||||
for target in (2, 4, 6, 16):
|
||||
assert submission_window(target) == 2 * target
|
||||
|
||||
|
||||
def test_plan_tail_parts_full_coverage_no_gaps() -> None:
|
||||
size = 20 * 1024 * 1024
|
||||
parts = plan_tail_parts(size, spare=8)
|
||||
@@ -265,13 +191,6 @@ def test_plan_tail_parts_respects_spare_cap() -> None:
|
||||
assert parts[0][0] == 0 and parts[-1][1] == size - 1
|
||||
|
||||
|
||||
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
|
||||
@@ -300,25 +219,8 @@ def test_tail_boost_engages_on_idle_capacity() -> None:
|
||||
assert tail_boost_engages(remaining=6, pending=6, target=16) # spare 10 >= 6
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_download_context_adaptive_default_false() -> None:
|
||||
ctx = DownloadContext(save_path=Path("x.mp4"), save_dir=Path("."), progress=partial(lambda **_: None))
|
||||
assert ctx.adaptive_workers is False
|
||||
|
||||
|
||||
def test_requests_accepts_adaptive_kwarg() -> None:
|
||||
sig = inspect.signature(requests)
|
||||
assert "adaptive" in sig.parameters
|
||||
assert sig.parameters["adaptive"].default is False
|
||||
|
||||
@@ -16,9 +16,6 @@ from pywidevine.pssh import PSSH
|
||||
|
||||
from tests.admission import refusal
|
||||
from tests.core.key_resolver import MemoryVault, key_table, resolver, vaults_of
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.api.handlers import load_full_cdm, resolve_server_cdm
|
||||
from unshackle.core.cdm.detect import is_widevine_cdm
|
||||
from unshackle.core.drm import PlayReady, Widevine
|
||||
from unshackle.core.manifests import HLS
|
||||
|
||||
@@ -169,22 +166,6 @@ def test_a_playready_track_with_two_widevine_objects_licenses() -> None:
|
||||
assert run.requests == ["PlayReady", "Widevine"]
|
||||
|
||||
|
||||
def test_cdm_only_licenses_each_drm_system_and_does_not_read_the_vault() -> None:
|
||||
run = Run(vault={KID: VAULT_KEY}, cdm_only=True)
|
||||
wv, pr = run.drm(widevine()), run.drm(playready())
|
||||
|
||||
run.run(wv, pr)
|
||||
|
||||
assert run.requests == ["Widevine", "PlayReady"]
|
||||
assert run.vault_queries == []
|
||||
assert wv.content_keys == {KID: KEY} and pr.content_keys == {KID: KEY}
|
||||
assert is_widevine_cdm(run.keys.cdms.cdm)
|
||||
|
||||
run.run(run.drm(widevine()), run.drm(playready()))
|
||||
|
||||
assert run.requests == ["Widevine", "PlayReady"]
|
||||
|
||||
|
||||
def test_the_other_drm_system_can_return_a_different_set_of_kids() -> None:
|
||||
run = Run()
|
||||
wv = run.drm(widevine())
|
||||
@@ -219,22 +200,6 @@ def test_the_other_drm_system_licenses_only_for_a_kid_with_no_content_key() -> N
|
||||
assert run.requests == ["Widevine"]
|
||||
|
||||
|
||||
def test_the_init_segment_adds_the_drm_system_the_track_does_not_have(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from unshackle.core.tracks import Track
|
||||
|
||||
wv, pr = widevine(), playready()
|
||||
monkeypatch.setattr(PlayReady, "from_init_data", classmethod(lambda cls, data: pr))
|
||||
monkeypatch.setattr(
|
||||
Widevine, "from_init_data", classmethod(lambda cls, data: pytest.fail("the track has Widevine already"))
|
||||
)
|
||||
track = SimpleNamespace(drm=[wv], prefers_playready=lambda cdm: True)
|
||||
track.pssh_order = lambda cdm: Track.pssh_order(track, cdm)
|
||||
|
||||
Track.add_init_drm(track, b"init", None)
|
||||
|
||||
assert track.drm == [wv, pr]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("preference", "found", "read", "expected"),
|
||||
[
|
||||
@@ -265,61 +230,3 @@ def test_drm_from_pssh_reads_the_preferred_system_first(
|
||||
assert tried == read
|
||||
assert track.drm == [expected]
|
||||
assert not caplog.records
|
||||
|
||||
|
||||
def test_drm_from_pssh_without_a_pssh_logs_once_and_keeps_the_drm(caplog: pytest.LogCaptureFixture) -> None:
|
||||
from unshackle.core.tracks import Video
|
||||
|
||||
track = Video("https://cdn.example/v.mp4", language="en")
|
||||
track.drm_preference = "pr"
|
||||
|
||||
def read_pssh(system: Any) -> Any:
|
||||
raise system.Exceptions.PSSHNotFound()
|
||||
|
||||
with caplog.at_level(logging.DEBUG, logger="EXAMPLE"):
|
||||
track.drm_from_pssh(None, read_pssh, logging.getLogger("EXAMPLE"))
|
||||
|
||||
assert track.drm is None
|
||||
assert [r.getMessage() for r in caplog.records] == [
|
||||
"No PlayReady or Widevine PSSH was found for this track, is it DRM free?"
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("entry", "expected"),
|
||||
[
|
||||
({"playready": "pr_device", "widevine": "wv_device"}, "pr_device"),
|
||||
({"widevine": "wv_device", "playready": "pr_device"}, "wv_device"),
|
||||
],
|
||||
)
|
||||
def test_the_first_drm_system_of_the_config_entry_loads_first(
|
||||
monkeypatch: pytest.MonkeyPatch, entry: dict, expected: str
|
||||
) -> None:
|
||||
monkeypatch.setattr("unshackle.commands.dl.config.cdm", {"EXAMPLE": entry})
|
||||
monkeypatch.setattr("unshackle.core.cdm.load_cdm", lambda name, **_: name)
|
||||
monkeypatch.setattr("unshackle.core.config.config.cdm", {"EXAMPLE": entry})
|
||||
cmd = dl.__new__(dl)
|
||||
cmd.vaults = None
|
||||
|
||||
assert cmd.get_cdm("EXAMPLE") == expected
|
||||
assert load_full_cdm("EXAMPLE", None) == expected
|
||||
assert cmd.get_cdm("EXAMPLE", drm="widevine") == "wv_device"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("entry", "expected"),
|
||||
[
|
||||
({"playready": "pr_device", "widevine": "wv_device"}, "playready"),
|
||||
({"widevine": "wv_device", "playready": "pr_device"}, "widevine"),
|
||||
],
|
||||
)
|
||||
def test_the_server_cdm_stub_is_the_first_drm_system_of_the_config_entry(
|
||||
monkeypatch: pytest.MonkeyPatch, entry: dict, expected: str
|
||||
) -> None:
|
||||
monkeypatch.setattr("unshackle.core.config.config.cdm", {"EXAMPLE": entry})
|
||||
monkeypatch.setattr(
|
||||
"unshackle.core.api.handlers.device_system",
|
||||
lambda name, _: "playready" if name == "pr_device" else "widevine",
|
||||
)
|
||||
|
||||
assert is_widevine_cdm(resolve_server_cdm("EXAMPLE", None, None)) is (expected == "widevine")
|
||||
|
||||
@@ -116,26 +116,6 @@ def test_search_prefers_the_requested_year(monkeypatch: pytest.MonkeyPatch) -> N
|
||||
assert result.external_ids.anilist_id == 459
|
||||
|
||||
|
||||
def test_search_prefers_the_requested_kind_without_a_year(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
provider, _ = _provider(monkeypatch, {"data": {"Page": {"media": [ONE_PIECE, ONE_PIECE_MOVIE]}}})
|
||||
|
||||
result = provider.search("one piece", None, "movie")
|
||||
|
||||
assert result is not None
|
||||
assert result.kind == "movie"
|
||||
assert result.external_ids.anilist_id == 459
|
||||
|
||||
|
||||
def test_search_for_tv_is_not_shadowed_by_a_movie(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
provider, _ = _provider(monkeypatch, {"data": {"Page": {"media": [ONE_PIECE_MOVIE, ONE_PIECE]}}})
|
||||
|
||||
result = provider.search("one piece", None, "tv")
|
||||
|
||||
assert result is not None
|
||||
assert result.kind == "tv"
|
||||
assert result.external_ids.anilist_id == 21
|
||||
|
||||
|
||||
def test_search_falls_back_when_no_node_matches_the_kind(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
provider, _ = _provider(monkeypatch, {"data": {"Page": {"media": [ONE_PIECE]}}})
|
||||
|
||||
@@ -145,11 +125,6 @@ def test_search_falls_back_when_no_node_matches_the_kind(monkeypatch: pytest.Mon
|
||||
assert result.external_ids.anilist_id == 21
|
||||
|
||||
|
||||
def test_search_of_a_non_anime_title_returns_none(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
provider, _ = _provider(monkeypatch, {"data": {"Page": {"media": []}}})
|
||||
assert provider.search("The Walking Dead", None, "tv") is None
|
||||
|
||||
|
||||
def test_graphql_errors_are_a_miss_not_a_raise(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
provider, _ = _provider(monkeypatch, {"errors": [{"message": "Not Found."}], "data": {"Media": None}})
|
||||
assert provider.search("one piece", None, "tv") is None
|
||||
@@ -176,12 +151,6 @@ def test_get_by_id_resolves_a_mal_reference_natively(monkeypatch: pytest.MonkeyP
|
||||
assert result.external_ids.anilist_id == 21
|
||||
|
||||
|
||||
def test_get_by_id_rejects_a_foreign_reference(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
provider, sent = _provider(monkeypatch, {"data": {"Media": ONE_PIECE}})
|
||||
assert provider.get_by_id("tt1375666", "tv") is None
|
||||
assert sent == []
|
||||
|
||||
|
||||
def test_get_external_ids_needs_no_lookup_for_a_bare_id(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
provider, sent = _provider(monkeypatch, {"data": {"Media": ONE_PIECE}})
|
||||
|
||||
@@ -215,45 +184,6 @@ def test_title_language_falls_back_when_the_variant_is_unset(monkeypatch: pytest
|
||||
assert result.title == "Koisuru ONE PIECE"
|
||||
|
||||
|
||||
def test_a_title_with_no_variant_at_all_is_a_miss(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
node = {**ONE_PIECE, "title": {"romaji": None, "english": None, "native": None}}
|
||||
provider, _ = _provider(monkeypatch, {"data": {"Media": node}})
|
||||
assert provider.get_by_id(21, "tv") is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("country", "language"),
|
||||
[("JP", "ja"), ("KR", "ko"), ("CN", "zh"), ("TW", "zh"), ("US", None), (None, None)],
|
||||
)
|
||||
def test_country_of_origin_maps_to_a_language(
|
||||
monkeypatch: pytest.MonkeyPatch, country: str | None, language: str | None
|
||||
) -> None:
|
||||
provider, _ = _provider(monkeypatch, {"data": {"Media": {**ONE_PIECE, "countryOfOrigin": country}}})
|
||||
|
||||
result = provider.get_by_id(21, "tv")
|
||||
|
||||
assert result is not None
|
||||
assert result.original_language == language
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("format_", "kind"), [("MOVIE", "movie"), ("TV", "tv"), ("ONA", "tv"), ("SPECIAL", "tv"), (None, "tv")]
|
||||
)
|
||||
def test_format_maps_to_kind(monkeypatch: pytest.MonkeyPatch, format_: str | None, kind: str) -> None:
|
||||
provider, _ = _provider(monkeypatch, {"data": {"Media": {**ONE_PIECE, "format": format_}}})
|
||||
|
||||
result = provider.get_by_id(21, "tv")
|
||||
|
||||
assert result is not None
|
||||
assert result.kind == kind
|
||||
|
||||
|
||||
def test_the_provider_needs_no_api_key() -> None:
|
||||
assert AniListProvider().is_available() is True
|
||||
assert AniListProvider.REQUIRES_KEY is False
|
||||
assert AniListProvider.ID_KIND == "anilist"
|
||||
|
||||
|
||||
def test_a_cached_node_rebuilds_with_the_read_time_title_language(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""The raw node is cached; which title variant it yields follows the config at read time."""
|
||||
from unshackle.core.providers import cached_to_result
|
||||
|
||||
@@ -54,21 +54,6 @@ def test_layouts_without_heights_are_unchanged(layout: str | None, expected: str
|
||||
assert named("E-AC-3", layout)["audio_channels"] == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("fmt", "expected"),
|
||||
[("E-AC-3", "DDP5.1"), ("AC-3", "DD5.1"), ("AC-4", "AC4 5.1"), ("AAC", "AAC5.1")],
|
||||
)
|
||||
def test_a_name_ending_in_a_digit_is_spaced_from_the_channels(fmt: str, expected: str) -> None:
|
||||
assert named(fmt, "L R C LFE Ls Rs")["audio_full"] == expected
|
||||
|
||||
|
||||
def test_codec_names_overrides_the_built_in_name(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""The override is keyed by the name the filename would carry, and AC3 still gets its separator."""
|
||||
monkeypatch.setattr(config, "codec_names", {"DDP": "EAC3", "DD": "AC3"})
|
||||
assert named("E-AC-3", "L R C LFE Ls Rs")["audio_full"] == "EAC3 5.1"
|
||||
assert named("AC-3", "L R C LFE Ls Rs")["audio"] == "AC3"
|
||||
|
||||
|
||||
def test_codec_names_renames_video_and_each_hdr_part(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(config, "codec_names", {"H.265": "HEVC", "HDR10P": "HDR10+", "DTS-X": "DTSX"})
|
||||
video = types.SimpleNamespace(
|
||||
@@ -86,7 +71,3 @@ def test_codec_names_renames_video_and_each_hdr_part(monkeypatch: pytest.MonkeyP
|
||||
context = movie.build_base_template_context(types.SimpleNamespace(video_tracks=[video], audio_tracks=[]))
|
||||
assert (context["video"], context["hdr"]) == ("HEVC", "DV.HDR10+")
|
||||
assert named("DTS-UHD", "L C R LFE Ls Rs")["audio_full"] == "DTSX 5.1", "a renamed DTS-X keeps its separator"
|
||||
|
||||
|
||||
def test_a_missing_audio_format_does_not_break_naming() -> None:
|
||||
assert named(None, "L R", channel_s=2)["audio_full"] == "2.0" # type: ignore[arg-type]
|
||||
|
||||
@@ -3,12 +3,15 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from rich.text import Text
|
||||
|
||||
from tests.core.test_music_renderer import flac_release, run_release
|
||||
from tests.lang_selection.test_kind_only_selection import FakeService
|
||||
from unshackle.core.manifests.dash import DASH
|
||||
from unshackle.core.manifests.hls import HLS
|
||||
from unshackle.core.manifests.ism import ISM
|
||||
from unshackle.core.music.renderer import MusicRenderer
|
||||
from unshackle.core.tracks import Audio, Tracks
|
||||
from unshackle.core.tracks import Audio, Tracks, Video
|
||||
|
||||
|
||||
def dash_audio(set_attrs: str = "", rep_attrs: str = "") -> Audio:
|
||||
@@ -73,19 +76,49 @@ def test_hls_reads_bit_depth_and_sample_rate_when_the_playlist_states_them(
|
||||
assert (audio.bit_depth, audio.sample_rate) == expected
|
||||
|
||||
|
||||
def listing(audio: Audio, music: bool) -> str:
|
||||
"""The audio line of the track listing as plain text."""
|
||||
(node,) = Tracks([audio]).tree(music=music)[0].children[0].children
|
||||
return Text.from_markup(str(node.label)).plain
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("bit_depth", "sample_rate", "label"),
|
||||
[(24, 96000, "24-bit / 96 kHz"), (16, 44100, "16-bit / 44.1 kHz"), (None, 48000, "48 kHz"), (24, None, "24-bit")],
|
||||
)
|
||||
def test_the_listing_shows_bit_depth_and_sample_rate(
|
||||
def test_a_music_listing_shows_bit_depth_and_sample_rate(
|
||||
bit_depth: int | None, sample_rate: int | None, label: str
|
||||
) -> None:
|
||||
audio = Audio(url="https://cdn.example/a.flac", language="en", bit_depth=bit_depth, sample_rate=sample_rate)
|
||||
assert f" | {label}" in str(audio)
|
||||
audio = Audio(
|
||||
url="https://cdn.example/a.flac", language="en", bitrate=900_000, bit_depth=bit_depth, sample_rate=sample_rate
|
||||
)
|
||||
assert f"| 900 kb/s | {label} | English" in listing(audio, music=True)
|
||||
|
||||
|
||||
def test_the_listing_shows_neither_when_unset() -> None:
|
||||
assert "bit" not in str(Audio(url="https://cdn.example/a.flac", language="en"))
|
||||
def test_a_music_listing_shows_neither_when_unset() -> None:
|
||||
assert "bit" not in listing(Audio(url="https://cdn.example/a.flac", language="en"), music=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("list_", [True, False], ids=["list", "download"])
|
||||
@pytest.mark.parametrize("song", [True, False], ids=["song", "episode"])
|
||||
def test_dl_shows_the_label_only_for_a_song(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, song: bool, list_: bool
|
||||
) -> None:
|
||||
album, tracks = flac_release()
|
||||
titles = album if song else FakeService({1: {}}).get_titles()
|
||||
if not song:
|
||||
tracks.add(Video(id_="v", url="https://x/v", language="en", codec=Video.Codec.AVC, range_=Video.Range.SDR))
|
||||
monkeypatch.setattr("unshackle.commands.dl.mux_title", lambda *a, **k: ([], []))
|
||||
out = run_release(monkeypatch, caplog, titles, tracks, list_=list_, to_end=True) # type: ignore[arg-type]
|
||||
assert "3075 kb/s" in out
|
||||
assert ("3075 kb/s | 24-bit / 96 kHz" in out) is song
|
||||
|
||||
|
||||
def test_a_video_listing_shows_neither() -> None:
|
||||
audio = Audio(url="https://cdn.example/a.mp4", language="en", bit_depth=24, sample_rate=48000)
|
||||
text = listing(audio, music=False)
|
||||
assert "English" in text
|
||||
assert "kHz" not in text and "24-bit" not in text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["24", 24.0])
|
||||
@@ -109,22 +142,3 @@ def test_hires_is_decided_by_the_fields_before_the_label(
|
||||
label: str, bit_depth: int | None, sample_rate: int | None, hires: bool
|
||||
) -> None:
|
||||
assert MusicRenderer.is_hires_quality(label, bit_depth, sample_rate) is hires
|
||||
|
||||
|
||||
def test_a_song_with_fields_and_no_quality_label_shows_them_with_the_badge() -> None:
|
||||
from tests.core.test_music_renderer import song
|
||||
|
||||
line = MusicRenderer().option_from_song(song(1, "A", None, data={"bit_depth": 24, "sample_rate": 96000}))
|
||||
assert line.plain.startswith("24-bit / 96 kHz")
|
||||
assert "Hi-Res" in line.plain
|
||||
|
||||
|
||||
def test_the_header_reads_hires_from_the_fields() -> None:
|
||||
assert MusicRenderer.quality_summary("FLAC", bit_depth=24, sample_rate=48000) == "Hi-Res Lossless"
|
||||
assert MusicRenderer.quality_summary("FLAC", bit_depth=16, sample_rate=44100) == "Lossless"
|
||||
assert MusicRenderer.quality_summary("", bit_depth=24, sample_rate=96000) == "24-bit / 96 kHz"
|
||||
|
||||
|
||||
def test_tracks_that_differ_only_in_bit_depth_are_both_kept() -> None:
|
||||
a, b = (Audio(id_=str(n), url="https://cdn.example/a.flac", language="en", bit_depth=n) for n in (16, 24))
|
||||
assert Tracks.signature(a) != Tracks.signature(b)
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.binaries import binary_version, parse_version, probe_output
|
||||
from unshackle.core.binaries import binary_version, parse_version
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -54,26 +52,3 @@ def test_bare_call_only_for_listed_tools(monkeypatch: pytest.MonkeyPatch) -> Non
|
||||
calls.clear()
|
||||
assert binary_version(Path("/opt/bin/othertool")) is None
|
||||
assert calls == [["--version"], ["-version"]]
|
||||
|
||||
|
||||
def test_timeout_stops_the_probe(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
calls: list[list[str]] = []
|
||||
monkeypatch.setattr(binaries, "probe_output", fake_probe({"--version": None}, calls))
|
||||
|
||||
assert binary_version(Path("/opt/bin/othertool")) is None
|
||||
assert calls == [["--version"]]
|
||||
|
||||
|
||||
def test_timeout_kills_the_whole_tree(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
monkeypatch.setattr(binaries, "PROBE_TIMEOUT", 0.5)
|
||||
if sys.platform == "win32":
|
||||
tool = tmp_path / "wrapper.bat"
|
||||
tool.write_text("@echo off\r\nping -n 30 127.0.0.1 >nul\r\n")
|
||||
else:
|
||||
tool = tmp_path / "wrapper"
|
||||
tool.write_text("#!/bin/sh\nsleep 30 &\nsleep 30\n")
|
||||
tool.chmod(0o755)
|
||||
|
||||
start = time.monotonic()
|
||||
assert probe_output(tool, ["--version"]) is None
|
||||
assert time.monotonic() - start < 10
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from uuid import UUID
|
||||
@@ -10,7 +9,7 @@ from uuid import UUID
|
||||
import click
|
||||
import pytest
|
||||
|
||||
from tests.core.key_resolver import MemoryVault, resolver, vaults_of
|
||||
from tests.core.key_resolver import resolver, vaults_of
|
||||
from tests.core.test_vault_bad_keys import BAD, GOOD, KID, FakeDRM, Remote
|
||||
from unshackle.core.drm import key_resolution
|
||||
from unshackle.core.drm.key_resolution import ContentKeyResolver
|
||||
@@ -112,30 +111,3 @@ def test_a_bad_vault_key_of_a_bridged_track_gives_way_to_the_licence_key_which_i
|
||||
assert drm.decrypted_with == [{KID: BAD}, {KID: GOOD}]
|
||||
assert path.read_bytes() == b"plain:" + GOOD.encode()
|
||||
assert len(decodes) == 2 and vaults.vaults[0].is_bad_key(KID, BAD)
|
||||
|
||||
|
||||
def test_the_flag_of_a_bad_licence_key_waits_for_the_licence_write(tmp_path: Path, decodes: list[Path]) -> None:
|
||||
order: list[str] = []
|
||||
storing = threading.Event()
|
||||
|
||||
class Recording(MemoryVault):
|
||||
def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
|
||||
assert storing.wait(10)
|
||||
order.append("store")
|
||||
return super().add_keys(service, kid_keys)
|
||||
|
||||
def flag_bad_key(self, service: str, kid: UUID | str, key: str, source: str) -> None:
|
||||
order.append("flag")
|
||||
|
||||
vaults = vaults_of(Recording(), service="SVC")
|
||||
keys = resolver(vaults, tag="SVC")
|
||||
vaults.licensed({KID: BAD})
|
||||
path = tmp_path / "track.mp4"
|
||||
path.write_bytes(b"cipher")
|
||||
|
||||
with pytest.raises(click.ClickException, match="does not decrypt track vid"):
|
||||
keys.decrypt_verified(BridgedDRM({KID: BAD}), path, None, KID, True, TRACK) # type: ignore[arg-type]
|
||||
storing.set()
|
||||
keys.wait_vault_writes()
|
||||
|
||||
assert order == ["store", "flag"]
|
||||
|
||||
@@ -66,12 +66,6 @@ def test_unusable_value_raises_value_error(value: object) -> None:
|
||||
Cacher.resolve_datetime(value) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_zero_seconds_expires_now(cache: Cacher) -> None:
|
||||
entry = cache.get("key")
|
||||
entry.set({"a": 1}, expiration=0)
|
||||
assert entry.expired
|
||||
|
||||
|
||||
def test_expired_jwt_is_stored_as_expired(cache: Cacher) -> None:
|
||||
entry = cache.get("key")
|
||||
entry.set(jwt.encode({"exp": int(time.time()) - 60}, "k" * 32, algorithm="HS256"))
|
||||
|
||||
@@ -15,7 +15,7 @@ import unshackle.core.cdm as cdm_mod
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.api import handlers, server_keys
|
||||
from unshackle.core.api.key_policy import KeyPolicy
|
||||
from unshackle.core.cdm.choice import choose_cdm, drm_system
|
||||
from unshackle.core.cdm.choice import choose_cdm
|
||||
from unshackle.core.cdm.detect import is_playready_cdm
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
@@ -383,27 +383,7 @@ EXPECTED: dict[str, dict[str, Any]] = {
|
||||
}
|
||||
|
||||
|
||||
def test_every_row_has_a_pinned_answer() -> None:
|
||||
assert ROWS.keys() == EXPECTED.keys()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ROWS)
|
||||
def test_each_ladder_gives_the_pinned_choice(monkeypatch: pytest.MonkeyPatch, devices: None, name: str) -> None:
|
||||
cdm, profile, key_cdm = ROWS[name]
|
||||
assert answers(monkeypatch, cdm, profile, key_cdm) == EXPECTED[name]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("name", "system"),
|
||||
[("wv", "widevine"), ("PlayReady", "playready"), ("PR", "playready"), ("clearkey", None), (5, None), (None, None)],
|
||||
)
|
||||
def test_drm_system_reads_each_name_of_a_system(name: Any, system: str | None) -> None:
|
||||
assert drm_system(name) == system
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("entry", "system"),
|
||||
[({"widevine": "wv_dev"}, "widevine"), (DUAL, None), ({"default": "pr_dev"}, None), ("pr_dev", None)],
|
||||
)
|
||||
def test_the_entry_settles_a_system_only_when_it_names_one(entry: Any, system: str | None) -> None:
|
||||
assert choose_cdm({"EXAMPLE": entry}, "EXAMPLE").system == system
|
||||
|
||||
@@ -10,10 +10,8 @@ from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.commands.dl import cdm_summary
|
||||
from unshackle.core.api import server_keys
|
||||
from unshackle.core.cdm.client_relay import ClientDeviceCdm
|
||||
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_remote_cdm, is_widevine_cdm
|
||||
from unshackle.core.cdm.detect import is_playready_cdm, is_remote_cdm, is_widevine_cdm
|
||||
from unshackle.core.cdm.loader import device_system, load_cdm
|
||||
from unshackle.core.config import config
|
||||
|
||||
@@ -49,17 +47,6 @@ def app_config(tmp_path, entries=(), cdm=None):
|
||||
return SimpleNamespace(remote_cdm=list(entries), directories=folders, cdm=cdm or {})
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("entry", "system"), ENTRIES)
|
||||
def test_config_and_the_built_cdm_agree(entry, system, tmp_path, monkeypatch):
|
||||
entry = {"name": "x", **entry}
|
||||
assert device_system("x", app_config(tmp_path, [entry])) == system
|
||||
|
||||
monkeypatch.setattr(config, "remote_cdm", [entry])
|
||||
cdm = load_cdm("x", service_name="EXAMPLE")
|
||||
assert cdm_system(cdm) == system
|
||||
assert is_remote_cdm(cdm)
|
||||
|
||||
|
||||
def test_the_server_settles_a_service_on_its_remote_device_system(tmp_path):
|
||||
entry = {"name": "x", "type": "decrypt_labs", "secret": "s", "device_name": "SL3000"}
|
||||
assert (
|
||||
@@ -87,13 +74,6 @@ def test_an_unknown_name_is_no_device(tmp_path, monkeypatch):
|
||||
load_cdm("x")
|
||||
|
||||
|
||||
def test_stand_ins_carry_their_system():
|
||||
assert cdm_system(cdm_type_stub("playready")) == "playready"
|
||||
assert cdm_system(cdm_type_stub("None")) == "widevine"
|
||||
assert cdm_system(ClientDeviceCdm(SimpleNamespace(), is_playready=True)) == "playready"
|
||||
assert not is_remote_cdm(cdm_type_stub("widevine"))
|
||||
|
||||
|
||||
def test_library_cdms_are_known_by_class():
|
||||
from pyplayready.cdm import Cdm as PlayReadyCdm
|
||||
from pyplayready.remote.remotecdm import RemoteCdm as PlayReadyRemoteCdm
|
||||
@@ -105,21 +85,3 @@ def test_library_cdms_are_known_by_class():
|
||||
assert is_widevine_cdm(object.__new__(WidevineCdm))
|
||||
assert is_widevine_cdm(remote_wv) and is_remote_cdm(remote_wv)
|
||||
assert is_remote_cdm(object.__new__(PlayReadyRemoteCdm))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cdm", [None, object()])
|
||||
def test_no_cdm_is_neither_system(cdm):
|
||||
assert cdm_system(cdm) is None
|
||||
assert not is_playready_cdm(cdm) and not is_widevine_cdm(cdm) and not is_remote_cdm(cdm)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("device", "drm_type"), [({"type": "PLAYREADY", "name": "pr"}, "PlayReady"), ({"name": "wv"}, "Widevine")]
|
||||
)
|
||||
def test_the_load_log_names_a_custom_remote_cdm_by_its_system(device, drm_type):
|
||||
from unshackle.core.cdm.custom_remote_cdm import CustomRemoteCDM
|
||||
|
||||
summary = cdm_summary(CustomRemoteCDM(host="http://h.invalid", device=device))
|
||||
assert summary["drm_type"] == drm_type
|
||||
assert summary["remote"] is True
|
||||
assert summary["device"] == device["name"]
|
||||
|
||||
@@ -15,7 +15,6 @@ from __future__ import annotations
|
||||
import base64
|
||||
from pathlib import Path
|
||||
|
||||
import m3u8
|
||||
import pytest
|
||||
import requests
|
||||
from Cryptodome.Cipher import AES
|
||||
@@ -179,29 +178,6 @@ def test_raw_data_uri_key_materialises_and_validates() -> None:
|
||||
assert drm.key == KEY
|
||||
|
||||
|
||||
def test_raw_data_uri_key_wrong_length_rejected() -> None:
|
||||
with pytest.raises(ValueError, match="Unexpected Length"):
|
||||
ClearKey.from_m3u_key(data_key(b"\x01" * 8, base64_encoded=False))
|
||||
|
||||
|
||||
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(
|
||||
method="AES-128",
|
||||
uri=f"data:application/octet-stream;base64,{b64}",
|
||||
base_uri="",
|
||||
keyformat=None,
|
||||
keyformatversions=None,
|
||||
iv=None,
|
||||
)
|
||||
drm = ClearKey.from_m3u_key(key)
|
||||
assert drm.key == raw
|
||||
|
||||
|
||||
SEQ_PLAYLIST = """#EXTM3U
|
||||
#EXT-X-VERSION:3
|
||||
#EXT-X-TARGETDURATION:6
|
||||
@@ -217,29 +193,3 @@ seg2.ts
|
||||
seg3.ts
|
||||
#EXT-X-ENDLIST
|
||||
"""
|
||||
|
||||
|
||||
def test_sequence_number_iv_uses_absolute_media_sequence() -> None:
|
||||
"""IV must be the segment's absolute media sequence number, not the download index.
|
||||
|
||||
Mirrors the derivation in ``HLS.download_track``: filtered segments are dropped, the
|
||||
surviving segments are named by post-filter download index, and the IV comes from the
|
||||
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")
|
||||
|
||||
@@ -92,11 +92,6 @@ def test_no_signature_is_refused() -> None:
|
||||
ClearKeyCTR(lambda: KEY, IV, b"")
|
||||
|
||||
|
||||
def test_negative_skip_is_refused() -> None:
|
||||
with pytest.raises(ValueError, match="skip"):
|
||||
keyed(skip=-1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("header_size", [167, (1 << 20) + 167], ids=["short", "longer-than-one-chunk"])
|
||||
def test_skip_drops_a_header_in_front_of_the_media(tmp_path: Path, header_size: int) -> None:
|
||||
header, plain = os.urandom(header_size), MAGIC + os.urandom((1 << 20) + 5)
|
||||
@@ -120,16 +115,6 @@ def test_skip_past_the_end_raises_and_keeps_the_input(tmp_path: Path) -> None:
|
||||
assert path.read_bytes() == encrypted
|
||||
|
||||
|
||||
def test_magic_accepts_the_expected_signature(tmp_path: Path) -> None:
|
||||
path = tmp_path / "track.flac"
|
||||
path.write_bytes(ctr_encrypt(b"fLaC" + os.urandom(5000)))
|
||||
|
||||
keyed(magic=b"fLaC").decrypt(path)
|
||||
|
||||
assert path.read_bytes().startswith(b"fLaC")
|
||||
assert list(tmp_path.iterdir()) == [path]
|
||||
|
||||
|
||||
TRIMMABLE = header(FIRST, total=7081, first_record=config_record(true=1000)) + FIRST
|
||||
|
||||
|
||||
|
||||
@@ -9,13 +9,9 @@ import pytest
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
from unshackle.core.tracks.video import Video
|
||||
from unshackle.core.utils.click_types import (
|
||||
AUDIO_CODEC_LIST,
|
||||
LANGUAGE_RANGE,
|
||||
QUALITY_LIST,
|
||||
SLOW_DELAY_RANGE,
|
||||
SUBTITLE_CODEC,
|
||||
VIDEO_CODEC_LIST,
|
||||
MultipleChoice,
|
||||
SeasonRange,
|
||||
SubtitleCodecChoice,
|
||||
)
|
||||
@@ -41,10 +37,6 @@ def test_codecs_still_map(value, expected):
|
||||
assert choice.convert(value) == expected
|
||||
|
||||
|
||||
def test_empty_is_none():
|
||||
assert choice.convert(None) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value,expected",
|
||||
[
|
||||
@@ -71,34 +63,10 @@ def test_slow_delay_range_accepts_bool(value, expected):
|
||||
assert SLOW_DELAY_RANGE.convert(value, None, None) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value,expected",
|
||||
[
|
||||
("all,-es", ["all", "-es"]),
|
||||
("-es", ["-es"]),
|
||||
("all, -es ; -fr", ["all", "-es", "-fr"]),
|
||||
(["all", "-es"], ["all", "-es"]),
|
||||
],
|
||||
)
|
||||
def test_language_range_passes_exclusion_tokens_through(value, expected):
|
||||
"""The '-' prefix is resolved at filter time, so the type must keep the token intact."""
|
||||
assert LANGUAGE_RANGE.convert(value) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [[None], ["en", 1], [{"x": "en"}]])
|
||||
def test_language_range_refuses_a_list_item_that_is_not_a_string(value):
|
||||
with pytest.raises(click.BadParameter):
|
||||
LANGUAGE_RANGE.convert(value)
|
||||
|
||||
|
||||
def parse(*tokens: str) -> list[str]:
|
||||
return SeasonRange().parse_tokens(*tokens)
|
||||
|
||||
|
||||
def test_single_episode_token_is_unchanged():
|
||||
assert parse("S01E01") == ["1x1"]
|
||||
|
||||
|
||||
def test_bare_season_spans_the_whole_episode_range():
|
||||
"""A bare S01 reads the one match object with a different default per side."""
|
||||
keys = parse("S01")
|
||||
@@ -118,15 +86,6 @@ def test_exclusions_are_unchanged():
|
||||
assert len(keys) == 3999 # 5 seasons less all of S03 less 2x1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tokens", [("S01E01",), ("S01",), ("S01-S05", "-S03", "-S02E01"), ("S02E03-S02E05",)])
|
||||
def test_part_less_tokens_never_emit_a_part_or_exclusion_key(tokens):
|
||||
assert all("." not in k and "!" not in k for k in parse(*tokens))
|
||||
|
||||
|
||||
def test_part_token():
|
||||
assert parse("S01E01.2") == ["1x1.2"]
|
||||
|
||||
|
||||
def test_part_range_within_one_episode():
|
||||
assert sorted(parse("S01E01.1-S01E01.3")) == ["1x1.1", "1x1.2", "1x1.3"]
|
||||
|
||||
@@ -161,14 +120,6 @@ def test_bad_part_tokens_fail(token):
|
||||
parse(token)
|
||||
|
||||
|
||||
def test_single_date_token_is_its_own_key():
|
||||
assert parse("2026-08-11") == ["2026-08-11"]
|
||||
|
||||
|
||||
def test_date_range_expands_every_day_inclusive():
|
||||
assert sorted(parse("2026-08-01:2026-08-03")) == ["2026-08-01", "2026-08-02", "2026-08-03"]
|
||||
|
||||
|
||||
def test_date_range_crosses_a_month():
|
||||
assert sorted(parse("2026-01-30:2026-02-02")) == ["2026-01-30", "2026-01-31", "2026-02-01", "2026-02-02"]
|
||||
|
||||
@@ -199,46 +150,7 @@ def test_bad_date_tokens_fail(token):
|
||||
parse(token)
|
||||
|
||||
|
||||
def test_audio_metavar_lists_every_accepted_spelling():
|
||||
"""--help must not advertise fewer codecs than convert() takes, aliases included."""
|
||||
metavar = AUDIO_CODEC_LIST.get_metavar()
|
||||
assert metavar.startswith("[") and metavar.endswith("]")
|
||||
listed = metavar[1:-1].split("|")
|
||||
assert listed == AUDIO_CODEC_LIST.choices
|
||||
for spelling in ("ddp", "eac3", "vorbis", "ac-4", "vorb"):
|
||||
assert spelling in listed
|
||||
assert AUDIO_CODEC_LIST.convert(spelling)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("param_type", [AUDIO_CODEC_LIST, VIDEO_CODEC_LIST, SUBTITLE_CODEC])
|
||||
def test_no_duplicate_choices(param_type):
|
||||
"""A codec whose name and value are the same word (VP9, AV1) is listed once."""
|
||||
lowered = [choice.lower() for choice in param_type.choices]
|
||||
assert len(lowered) == len(set(lowered))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["avc,,hevc", ["avc", "", "hevc"], " avc , hevc "])
|
||||
def test_empty_video_codec_tokens_are_skipped(value):
|
||||
"""A None in the list reaches track filtering and crashes it, so blanks must drop out."""
|
||||
assert VIDEO_CODEC_LIST.convert(value) == [Video.Codec.AVC, Video.Codec.HEVC]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("spelling", ["H264", "h265", "H.265", "hevc", "H266", "h.266", "vvc"])
|
||||
def test_video_codec_aliases_resolve(spelling):
|
||||
"""The API advertised H264/H265 while dropping them; both paths now resolve the same."""
|
||||
assert VIDEO_CODEC_LIST.convert(spelling)[0] in (Video.Codec.AVC, Video.Codec.HEVC, Video.Codec.VVC)
|
||||
|
||||
|
||||
def test_audio_codec_list_shell_complete():
|
||||
"""--acodec offered no completion at all; it now completes the segment after the last comma."""
|
||||
assert [c.value for c in AUDIO_CODEC_LIST.shell_complete(None, None, "fl")] == ["flac"]
|
||||
assert [c.value for c in AUDIO_CODEC_LIST.shell_complete(None, None, "AAC,e")] == ["AAC,ec3", "AAC,eac3"]
|
||||
assert AUDIO_CODEC_LIST.shell_complete(None, None, "zzz") == []
|
||||
|
||||
|
||||
def test_multiple_choice_shell_complete():
|
||||
"""super(self) raised TypeError, so every --range completion crashed instead of completing."""
|
||||
range_choice = MultipleChoice(Video.Range, case_sensitive=False)
|
||||
assert [c.value for c in range_choice.shell_complete(None, None, "hd")] == ["hdr10", "hdr10p"]
|
||||
assert [c.value for c in range_choice.shell_complete(None, None, "sdr,hd")] == ["sdr,hdr10", "sdr,hdr10p"]
|
||||
assert range_choice.shell_complete(None, None, "zzz") == []
|
||||
|
||||
@@ -40,11 +40,6 @@ def test_load_client_cookies_reads_what_local_dl_reads():
|
||||
assert [(c.name, c.value) for c in jar] == [("session-id", "123-456")]
|
||||
|
||||
|
||||
def test_load_client_cookies_without_a_blob():
|
||||
assert load_client_cookies(None) is None
|
||||
assert load_client_cookies("") is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("blob", ["not base64!", base64.b64encode(b"not zlib").decode(), transport_blob("garbage")])
|
||||
def test_load_client_cookies_rejects_a_malformed_blob(blob):
|
||||
with pytest.raises(APIError) as exc_info:
|
||||
|
||||
@@ -9,7 +9,7 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
import unshackle.core
|
||||
from unshackle.core import __code_hash__, code_files, code_hash
|
||||
from unshackle.core import code_files, code_hash
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
@@ -21,10 +21,6 @@ def test_is_hex_and_stable() -> None:
|
||||
assert first == code_hash()
|
||||
|
||||
|
||||
def test_exported_value_is_the_short_form() -> None:
|
||||
assert __code_hash__ == code_hash()[:7]
|
||||
|
||||
|
||||
def test_covers_the_framework_dirs_only() -> None:
|
||||
rels = code_files()
|
||||
assert "__main__.py" in rels
|
||||
@@ -52,21 +48,6 @@ def test_path_is_part_of_the_hash() -> None:
|
||||
)
|
||||
|
||||
|
||||
def test_file_order_does_not_matter_to_the_caller() -> None:
|
||||
"""code_files() sorts, so two orderings of the same set must agree once sorted."""
|
||||
blobs = {"core/a.py": b"x", "core/b.py": b"y"}
|
||||
assert code_hash(files=sorted(blobs), read=blobs.__getitem__) == code_hash(
|
||||
files=sorted(reversed(list(blobs))), read=blobs.__getitem__
|
||||
)
|
||||
|
||||
|
||||
def test_unreadable_source_yields_empty_string() -> None:
|
||||
def unreadable(rel: str) -> bytes:
|
||||
raise PermissionError(rel)
|
||||
|
||||
assert code_hash(files=["core/__init__.py"], read=unreadable) == ""
|
||||
|
||||
|
||||
def test_unwalkable_source_yields_empty_string(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""A dir os.walk cannot enter must yield "", not a valid-looking hash of fewer files."""
|
||||
(tmp_path / "__main__.py").write_bytes(b"")
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from langcodes import Language
|
||||
|
||||
from unshackle.core.config import Config
|
||||
@@ -50,28 +49,13 @@ def test_bool_shaped_tags_survive_every_language_key(tmp_path: Path) -> None:
|
||||
assert config.audio["language_priority"] == ["no", "da"]
|
||||
|
||||
|
||||
def test_a_real_boolean_option_stays_false(tmp_path: Path) -> None:
|
||||
assert _load(tmp_path).update_checks is False
|
||||
|
||||
|
||||
def test_a_no_rule_tags_a_norwegian_track(tmp_path: Path) -> None:
|
||||
rules = _load(tmp_path).language_tags["rules"]
|
||||
assert evaluate_language_tag(rules, [Language.get("no")], []) == "NORDIC"
|
||||
|
||||
|
||||
def test_a_no_entry_survives_in_an_audio_contain_all_list(tmp_path: Path) -> None:
|
||||
assert _load(tmp_path).language_tags["rules"][1]["audio_contain_all"] == ["no", "da"]
|
||||
|
||||
|
||||
def test_tag_rules_keep_their_own_booleans(tmp_path: Path) -> None:
|
||||
"""tag_rules matches text and warns about a bare bool itself."""
|
||||
path = tmp_path / "unshackle.yaml"
|
||||
path.write_text("tag_rules:\n - when:\n video: no\n tag: T\n", encoding="utf8")
|
||||
assert Config.from_yaml(path).tag_rules[0]["when"]["video"] is False
|
||||
|
||||
|
||||
def test_a_cross_type_template_variable_warns_at_load(tmp_path: Path) -> None:
|
||||
path = tmp_path / "unshackle.yaml"
|
||||
path.write_text('output_template:\n movies: "{title}.{artist}"\n', encoding="utf8")
|
||||
with pytest.warns(UserWarning, match="not available in the movies template"):
|
||||
Config.from_yaml(path)
|
||||
|
||||
@@ -7,7 +7,7 @@ import pytest
|
||||
import yaml
|
||||
from ruamel.yaml import YAML
|
||||
|
||||
from unshackle.core.config import Config, duplicate_key_lines, load_yaml
|
||||
from unshackle.core.config import duplicate_key_lines, load_yaml
|
||||
|
||||
ALIASES = "base: &b\n x: 1\n x: 2\n self: *b\nother: *b\nlist:\n - y: 1\n y: 2\n"
|
||||
|
||||
@@ -30,14 +30,6 @@ def test_load_yaml_warns_once_with_lines_and_keeps_the_later_copy(
|
||||
assert "EXAMPLE" not in caplog.text and "secret" not in caplog.text
|
||||
|
||||
|
||||
def test_config_from_yaml_warns_on_a_duplicate_key(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||
path = tmp_path / "unshackle.yaml"
|
||||
path.write_text("tag: first\ntag: second\n", encoding="utf-8")
|
||||
with caplog.at_level(logging.WARNING, logger="config"):
|
||||
assert Config.from_yaml(path).tag == "second"
|
||||
assert "duplicate key on lines 1 and 2" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text",
|
||||
["a: 1\nb: [1, 2]\n", "", "a: &a\n x: 1\nb: &b\n y: 2\nc:\n <<: *a\n <<: *b\n"],
|
||||
|
||||
@@ -10,27 +10,10 @@ from __future__ import annotations
|
||||
import pytest
|
||||
|
||||
from unshackle.core.config import Config, resolve_cdm_name, resolve_decryption
|
||||
from unshackle.core.utils.collections import ci_get
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def test_ci_get_exact_and_case_insensitive():
|
||||
m = {"DEMO": "a", "Default": "b"}
|
||||
assert ci_get(m, "DEMO") == "a"
|
||||
assert ci_get(m, "demo") == "a"
|
||||
assert ci_get(m, "default") == "b"
|
||||
assert ci_get(m, "missing") is None
|
||||
assert ci_get(m, "missing", "fallback") == "fallback"
|
||||
assert ci_get({}, "DEMO", "fallback") == "fallback"
|
||||
|
||||
|
||||
def test_decryption_map_keys_upper_cased_on_build():
|
||||
c = Config(decryption={"example": "mp4decrypt", "default": "shaka"})
|
||||
assert c.decryption_map == {"EXAMPLE": "mp4decrypt", "DEFAULT": "shaka"}
|
||||
assert c.decryption == "shaka"
|
||||
|
||||
|
||||
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"
|
||||
@@ -47,11 +30,6 @@ def test_decryption_scalar_form():
|
||||
assert resolve_decryption(c.decryption_map, c.decryption, "ANY") == "mp4decrypt"
|
||||
|
||||
|
||||
def test_cdm_keys_preserved_on_build():
|
||||
c = Config(cdm={"demo": "dev_a", "default": "dev_b"})
|
||||
assert c.cdm == {"demo": "dev_a", "default": "dev_b"}
|
||||
|
||||
|
||||
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"})
|
||||
|
||||
@@ -44,13 +44,6 @@ def test_a_vault_that_fails_is_left_out_and_named_with_its_error() -> None:
|
||||
assert isinstance(failed["gone"], ValueError)
|
||||
|
||||
|
||||
def test_an_entry_without_a_type_fails_like_any_other() -> None:
|
||||
vaults, failed = load_config_vaults("EXAMPLE", [{"name": "untyped"}, {"type": "API", "name": "ok"}])
|
||||
|
||||
assert [v.name for v in vaults] == ["ok"]
|
||||
assert list(failed) == ["untyped"]
|
||||
|
||||
|
||||
def test_a_critical_vault_that_fails_raises() -> None:
|
||||
with pytest.raises(ValueError):
|
||||
load_config_vaults("EXAMPLE", [{"type": "Missing", "name": "gone"}], critical={"missing"})
|
||||
@@ -104,34 +97,3 @@ def test_server_vaults_read_the_global_decrypt_labs_key(monkeypatch: pytest.Monk
|
||||
vaults = server_keys.load_server_vaults("EXAMPLE")
|
||||
|
||||
assert [v.kwargs.get("token") for v in vaults] == ["global"]
|
||||
|
||||
|
||||
def test_the_health_probe_reports_the_load_error_without_logging_it(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
from unshackle.core.api import handlers
|
||||
|
||||
class Broken:
|
||||
def __init__(self, name: str, **kwargs: Any) -> None:
|
||||
raise ConnectionError("cannot reach the vault")
|
||||
|
||||
monkeypatch.setitem(vaults_module.MODULES, "Broken", Broken)
|
||||
monkeypatch.setattr(config, "key_vaults", [{"type": "Broken", "name": "down"}])
|
||||
|
||||
with caplog.at_level("ERROR"):
|
||||
checks = {c["id"]: c for c in handlers.run_health_checks()}
|
||||
|
||||
assert checks["vault:down"]["status"] == "fail"
|
||||
assert checks["vault:down"]["detail"] == "ConnectionError: cannot reach the vault"
|
||||
assert not caplog.records
|
||||
|
||||
|
||||
def test_kv_names_the_vault_that_failed(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
import click
|
||||
|
||||
from unshackle.commands.kv import load_vaults
|
||||
|
||||
monkeypatch.setattr(config, "key_vaults", [{"type": "Missing", "name": "gone"}])
|
||||
|
||||
with pytest.raises(click.ClickException, match=r"Failed to load vault \(gone\)"):
|
||||
load_vaults(["gone"])
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
"""Rich measures Indic spacing marks as one cell, so a panel border stays aligned after such a label."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
from rich.cells import cell_len
|
||||
from rich.console import Console
|
||||
from rich.panel import Panel
|
||||
|
||||
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("ไทย") == 3
|
||||
|
||||
|
||||
def test_panel_pads_an_indic_label_to_the_border() -> None:
|
||||
out = io.StringIO()
|
||||
Console(file=out, width=20, color_system=None).print(Panel("हिंदी"))
|
||||
|
||||
assert out.getvalue().splitlines()[1] == "│ हिंदी" + " " * 12 + " │"
|
||||
|
||||
|
||||
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
|
||||
@@ -0,0 +1,55 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SCRIPT = """
|
||||
import rich.console
|
||||
rich.console.detect_legacy_windows = lambda: False
|
||||
from unshackle.core.config import config
|
||||
config.wide_output = {wide}
|
||||
from rich.padding import Padding
|
||||
from rich.table import Table
|
||||
from unshackle.core.console import console
|
||||
from unshackle.core.tracks import Audio, Tracks, Video
|
||||
print(console.width)
|
||||
tracks = Tracks([Video(url="https://example.test/v.mpd", language="en"), Audio(url="https://example.test/a.mpd", language="en")])
|
||||
tree, (video, audio) = tracks.tree(add_progress=True)
|
||||
video(downloaded="Downloaded")
|
||||
audio(total=None, downloaded="1 MB/s")
|
||||
grid = Table.grid()
|
||||
grid.add_row(tree)
|
||||
for line in console.render_lines(Padding(grid, (1, 5)), pad=False):
|
||||
text = "".join(s.text for s in line)
|
||||
if "━" in text:
|
||||
print(text.count("━"), text.rfind("━"))
|
||||
"""
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("wide", "width"), [(True, 120), (False, 80)])
|
||||
def test_console_follows_wide_output(wide: bool, width: int) -> None:
|
||||
"""With wide_output the console takes the terminal width and track bars fill the line to one right edge.
|
||||
|
||||
Without it the console holds 80 columns and each bar 40 cells. Both are read at import, hence the subprocess.
|
||||
The child turns off Rich legacy Windows mode, which on a Windows pipe drops one column and draws ASCII bars.
|
||||
"""
|
||||
out = subprocess.run(
|
||||
[sys.executable, "-c", SCRIPT.format(wide=wide)],
|
||||
env={**os.environ, "COLUMNS": "120"},
|
||||
cwd=Path(__file__).parents[2],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=True,
|
||||
timeout=60,
|
||||
)
|
||||
console_width, *bars = out.stdout.strip().splitlines()[-3:]
|
||||
(full, full_end), (pulse, pulse_end) = (map(int, bar.split()) for bar in bars)
|
||||
assert int(console_width) == width
|
||||
if wide:
|
||||
assert full > 40 and pulse > 40 and full_end == pulse_end
|
||||
else:
|
||||
assert full == pulse == 40
|
||||
@@ -48,10 +48,6 @@ def test_specials_keep_their_numbers():
|
||||
assert numbers([(0, 1), (1, 1), (1, 2), (2, 1)]) == [(0, 1), (1, 1), (1, 2), (2, 3)]
|
||||
|
||||
|
||||
def test_already_continuous_season_is_kept():
|
||||
assert numbers([(1, 1), (1, 2), (2, 3), (2, 4), (3, 1)]) == [(1, 1), (1, 2), (2, 3), (2, 4), (3, 5)]
|
||||
|
||||
|
||||
def test_episode_zero_keeps_its_number_and_a_second_run_changes_nothing():
|
||||
once = numbers([(1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2)])
|
||||
assert once == [(1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 5), (2, 6)]
|
||||
|
||||
@@ -30,7 +30,7 @@ from unshackle.core.proxies.controld import (
|
||||
local_proxy,
|
||||
parse_a_records,
|
||||
)
|
||||
from unshackle.core.proxies.resolve import REGION_QUERY, resolve_proxy, resolve_proxy_value
|
||||
from unshackle.core.proxies.resolve import resolve_proxy
|
||||
from unshackle.core.utilities import get_free_port
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
@@ -457,14 +457,3 @@ def test_a_server_gets_the_typed_proxy_only_when_this_machine_resolved_it_to_loo
|
||||
assert server_proxy_arg({"proxy": "https://u:p@ca1.example:89", "proxy_arg": "nordvpn:ca"}) == (
|
||||
"https://u:p@ca1.example:89"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["ca", "us:seattle", "us-ny", "uk1", "yul", "jfk", "res_yyz", "nordvpn:ca"])
|
||||
def test_a_region_query_matches(query: str) -> None:
|
||||
assert REGION_QUERY.fullmatch(query)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("uri", ["nas:3128", "localhost:8080", "proxy.example.com:8080", "1.2.3.4:8080", "us:1080"])
|
||||
def test_a_host_and_port_is_never_a_region_query(uri: str) -> None:
|
||||
resolved = resolve_proxy_value(uri, [])
|
||||
assert resolved.uri == uri and resolved.query is None
|
||||
|
||||
@@ -81,9 +81,3 @@ def test_only_an_hevc_track_with_an_hevc_dv_supplemental_codec_is_dv_composite(
|
||||
codec: Video.Codec | None, codecs: str | None, supplemental: str, expected: bool
|
||||
) -> None:
|
||||
assert Video.is_dv_composite(codec, codecs, supplemental) is expected
|
||||
|
||||
|
||||
def test_an_hdr10p_track_with_a_dv_rpu_lists_as_hdr10p_plus_dv() -> None:
|
||||
video = Video(url="https://example.test/v.mp4", language="en", codec=Video.Codec.HEVC, range_=Video.Range.HDR10P)
|
||||
video.dv_compatible_bitstream = True
|
||||
assert "[H.265, HDR10P+DV]" in str(video)
|
||||
|
||||
@@ -95,25 +95,6 @@ def base(srv) -> str:
|
||||
return f"http://127.0.0.1:{srv.server_address[1]}/"
|
||||
|
||||
|
||||
def template_mpd(srv) -> str:
|
||||
periods = "\n".join(
|
||||
f""" <Period id="{i}" duration="PT1S">
|
||||
<AdaptationSet contentType="video" mimeType="video/mp4" lang="en">
|
||||
<Representation id="v0" codecs="avc1.640028" bandwidth="1000000" width="1920" height="1080">
|
||||
<SegmentTemplate timescale="1" duration="1" startNumber="1"
|
||||
initialization="p{i}/init.bin" media="p{i}/$Number$.bin"/>
|
||||
</Representation>
|
||||
</AdaptationSet>
|
||||
</Period>"""
|
||||
for i in (0, 1)
|
||||
)
|
||||
return f"""<?xml version="1.0"?>
|
||||
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" mediaPresentationDuration="PT2S">
|
||||
<BaseURL>{base(srv)}</BaseURL>
|
||||
{periods}
|
||||
</MPD>"""
|
||||
|
||||
|
||||
def base_mpd(srv) -> str:
|
||||
periods = "\n".join(
|
||||
f""" <Period id="{i}" duration="PT1S">
|
||||
@@ -147,27 +128,6 @@ def make_ctx(tmp_path):
|
||||
)
|
||||
|
||||
|
||||
def test_segment_template_init_is_fetched_once_for_two_periods(server, probes, licence_only, tmp_path):
|
||||
track = make_track(template_mpd(server), server)
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_segment_base_keeps_each_request_but_probes_once(server, probes, licence_only, tmp_path):
|
||||
track = make_track(base_mpd(server), server)
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_segment_base_range_survives_a_skipped_probe(server, probes):
|
||||
tree = load_xml(base_mpd(server).encode())
|
||||
period = tree.findall("Period")[1]
|
||||
@@ -188,25 +148,3 @@ def test_segment_base_range_survives_a_skipped_probe(server, probes):
|
||||
assert segments == [(f"{base(server)}p1.mp4", f"{INIT_LEN}-{len(MEDIA) - 1}")]
|
||||
assert track_kid is None
|
||||
assert not probes
|
||||
|
||||
|
||||
def test_segment_base_init_on_another_file_is_not_fetched_without_a_probe(server, probes):
|
||||
mpd = base_mpd(server).replace(f'range="0-{INIT_LEN - 1}"', 'sourceURL="p1/init.bin"')
|
||||
tree = load_xml(mpd.encode())
|
||||
period = tree.findall("Period")[1]
|
||||
aset = period.find("AdaptationSet")
|
||||
|
||||
init_data, segments, *_ = DASH.get_period_segments(
|
||||
period,
|
||||
aset,
|
||||
aset.find("Representation"),
|
||||
tree,
|
||||
Track(url=base(server), language="en"),
|
||||
f"{base(server)}manifest.mpd",
|
||||
requests.Session(),
|
||||
probe_kid=False,
|
||||
)
|
||||
|
||||
assert init_data is None
|
||||
assert segments == [(f"{base(server)}p1.mp4", None)]
|
||||
assert not server.requests
|
||||
|
||||
@@ -2,11 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.core.test_manifest_corpus import CORPUS, INDEX, KNOWN_FAILURES, parse
|
||||
from unshackle.core.manifests import DASH
|
||||
from unshackle.core.utils.xml import load_xml
|
||||
|
||||
@@ -140,26 +137,3 @@ def test_non_integer_bandwidth_does_not_raise():
|
||||
f'<AdaptationSet id="1" contentType="video">{video("v1", "5e6")}</AdaptationSet>',
|
||||
)
|
||||
assert resolve(mpd, 0, "v1") == (None, "v1", "avc1.640028")
|
||||
|
||||
|
||||
def multi_period(entry: dict[str, Any]) -> bool:
|
||||
periods = load_xml((CORPUS / entry["file"]).read_bytes()).findall("Period")
|
||||
return sum(DASH.is_content_period(p, []) for p in periods) > 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"entry",
|
||||
[e for e in INDEX if e["kind"] == "dash" and e["file"] not in KNOWN_FAILURES and multi_period(e)],
|
||||
ids=lambda e: e["file"],
|
||||
)
|
||||
def test_corpus_matches_never_cross_codec_or_size(entry: dict[str, Any]):
|
||||
shape = ("codecs", "width", "height")
|
||||
for track in parse(entry):
|
||||
data = track.data["dash"]
|
||||
want = tuple(DASH.get_attr(a, data["adaptation_set"], data["representation"]) for a in shape)
|
||||
for period in data["manifest"].findall("Period"):
|
||||
if period is data["period"] or not DASH.is_content_period(period, []):
|
||||
continue
|
||||
found = DASH.resolve_representation(period, data["representation_id"], data["adaptation_set"])
|
||||
if found is not None:
|
||||
assert tuple(DASH.get_attr(a, *found) for a in shape) == want
|
||||
|
||||
@@ -494,11 +494,3 @@ def test_trim_overlaps_bounds_the_sample_count(tmp_path: Path) -> None:
|
||||
path = tmp_path / "audio.mp4"
|
||||
path.write_bytes(init_segment(48000) + huge + audio_fragment(100, 2))
|
||||
assert trim_overlaps(path, {100}) == 0
|
||||
|
||||
|
||||
def test_trim_overlaps_logs_a_fragment_it_cannot_rewrite(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||
path = tmp_path / "audio.mp4"
|
||||
path.write_bytes(init_segment(48000) + overlapping(extra=box(b"sdtp", b"\0" * 4)))
|
||||
with caplog.at_level("DEBUG", logger="DASH"):
|
||||
assert trim_overlaps(path, {JOIN}) == 0
|
||||
assert "1 overlapping audio fragments" in caplog.text
|
||||
|
||||
@@ -18,7 +18,6 @@ from unshackle.core.utilities import (
|
||||
timed_operation,
|
||||
)
|
||||
from unshackle.core.utils.redact import (
|
||||
redact_all,
|
||||
redact_path,
|
||||
redact_secrets,
|
||||
redact_text,
|
||||
@@ -137,12 +136,6 @@ def test_body_numbers_stay_unique_across_threads(debug_log: Path):
|
||||
assert sorted(numbers) == list(range(1, 1601))
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_timed_operation_logs_success_and_duration(debug_log: Path):
|
||||
with timed_operation("work", level="INFO", context={"k": "v"}):
|
||||
pass
|
||||
@@ -164,13 +157,6 @@ def test_timed_operation_logs_error_and_reraises(debug_log: Path):
|
||||
assert e["error"]["type"] == "ValueError"
|
||||
|
||||
|
||||
def test_timed_operation_noop_when_disabled():
|
||||
close_debug_logger()
|
||||
with timed_operation("disabled_block"): # must not raise, must still run body
|
||||
value = 1 + 1
|
||||
assert value == 2
|
||||
|
||||
|
||||
def test_sanitize_redacts_sensitive_key_names(debug_log: Path):
|
||||
dl = get_debug_logger()
|
||||
cleaned = dl.sanitize_data(
|
||||
@@ -318,14 +304,6 @@ def test_redact_path_disabled_by_config(monkeypatch):
|
||||
assert redact_path(full) == "<unshackle>/temp/Audio.mp4"
|
||||
|
||||
|
||||
def test_redact_all_composes_secrets_urls_and_paths():
|
||||
root = str(Path(__import__("unshackle.core.utils.redact", fromlist=["x"]).__file__).resolve().parents[3])
|
||||
out = redact_all(f"dl https://u:p@cdn.x/seg.mp4?token=t into {root}/temp")
|
||||
assert "cdn.x" not in out
|
||||
assert "redacted.mp4" in out
|
||||
assert "<unshackle>/temp" in out
|
||||
|
||||
|
||||
def test_redact_secrets_keeps_the_url_but_drops_credentials_and_paths():
|
||||
root = str(Path(__import__("unshackle.core.utils.redact", fromlist=["x"]).__file__).resolve().parents[3])
|
||||
out = redact_secrets(f"404 Not Found: https://u:p@cdn.x/a/b.mpd?token=t (cwd {root}/temp)")
|
||||
@@ -353,12 +331,6 @@ def test_log_drm_operation_accepts_message_and_level_override(debug_log: Path):
|
||||
assert e["drm_type"] == "Widevine"
|
||||
|
||||
|
||||
def test_log_drm_operation_default_message(debug_log: Path):
|
||||
get_debug_logger().log_drm_operation("PlayReady", "license_response")
|
||||
e = find(read_entries(debug_log), "drm_license_response")
|
||||
assert e["message"] == "PlayReady license_response"
|
||||
|
||||
|
||||
def test_log_vault_query_accepts_message_override(debug_log: Path):
|
||||
get_debug_logger().log_vault_query("local", "get_key", message="hit", key_found=True)
|
||||
e = find(read_entries(debug_log), "vault_get_key")
|
||||
@@ -388,8 +360,3 @@ def test_log_tool_run_failure_is_error(debug_log: Path):
|
||||
e = find(read_entries(debug_log), "tool_run")
|
||||
assert e["level"] == "ERROR"
|
||||
assert "failed" in e["message"]
|
||||
|
||||
|
||||
def test_log_tool_run_noop_when_disabled():
|
||||
close_debug_logger()
|
||||
log_tool_run("ffmpeg", "ffmpeg", 0) # must not raise
|
||||
|
||||
@@ -54,14 +54,6 @@ def test_parses_json_after_a_preamble(monkeypatch: pytest.MonkeyPatch, tmp_path:
|
||||
assert calls[0][1:] == ["info", "-i", str(tmp_path / "RPU.bin"), "-f", "0"]
|
||||
|
||||
|
||||
def test_frame_number_is_passed_through(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
calls = patch_run(monkeypatch, FakeCompleted(0, RPU_JSON))
|
||||
|
||||
dovi.info_frame(tmp_path / "RPU.bin", frame=12)
|
||||
|
||||
assert calls[0][-2:] == ["-f", "12"]
|
||||
|
||||
|
||||
def test_non_zero_return_code_raises(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
patch_run(monkeypatch, FakeCompleted(1, "", "boom"))
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Service-independent completion archive matching and persistence."""
|
||||
|
||||
import json
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import replace
|
||||
|
||||
import pytest
|
||||
@@ -107,19 +105,6 @@ def test_history_and_file_deletion_have_no_effect(tmp_path):
|
||||
assert "output.mkv" not in text and "api_history" not in text
|
||||
|
||||
|
||||
def test_concurrent_append_and_truncated_receipt(tmp_path):
|
||||
archive = DownloadArchive(tmp_path)
|
||||
entries = [ArchiveEntry("EXAMPLE", f"episode-{n}", 720, "SDR", "H.264") for n in range(20)]
|
||||
archive.path.parent.mkdir(parents=True)
|
||||
archive.path.write_text('{"version":1,"service":"unfinished')
|
||||
with ThreadPoolExecutor(4) as pool:
|
||||
list(pool.map(lambda entry: DownloadArchive(tmp_path).record([entry]), entries))
|
||||
assert archive.contains(entries)
|
||||
archive.record(entries)
|
||||
valid = [json.loads(line) for line in archive.path.read_text().splitlines()[1:] if line]
|
||||
assert len(valid) == len(entries)
|
||||
|
||||
|
||||
def test_existing_reader_observes_another_writer(tmp_path):
|
||||
archive = DownloadArchive(tmp_path)
|
||||
first = ArchiveEntry("EXAMPLE", "episode-1", 720, "SDR", "H.264")
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
import inspect
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -12,7 +10,6 @@ import requests
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.console import console
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY
|
||||
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
|
||||
from unshackle.core.download_archive import DownloadArchive
|
||||
@@ -187,13 +184,6 @@ def test_failed_publication_does_not_record(monkeypatch, run):
|
||||
assert not DownloadArchive(config.directories.cache).path.exists()
|
||||
|
||||
|
||||
def test_all_archived_titles_complete_successfully(run):
|
||||
run(count=2)
|
||||
result = run(count=2)
|
||||
assert len(result.already_present) == 2
|
||||
assert not result.completed_files and not result.skipped_titles
|
||||
|
||||
|
||||
def test_api_scopes_and_unowned_worker_do_not_use_cli_archive(run):
|
||||
run()
|
||||
assert run(scope="api-" + "a" * 64).completed_files
|
||||
@@ -277,24 +267,6 @@ def test_partial_publication_of_multiple_variants_does_not_record(monkeypatch, r
|
||||
assert not DownloadArchive(config.directories.cache).path.exists()
|
||||
|
||||
|
||||
def test_wall_clock_step_back_prints_no_negative_elapsed_time(run, monkeypatch):
|
||||
import unshackle.commands.dl as module
|
||||
|
||||
download = module.download_tracks_in_passes
|
||||
wall = time.time
|
||||
|
||||
def download_then_step_back(*args, **kwargs):
|
||||
download(*args, **kwargs)
|
||||
monkeypatch.setattr(time, "time", lambda: wall() - 3)
|
||||
|
||||
monkeypatch.setattr(module, "download_tracks_in_passes", download_then_step_back)
|
||||
with console.capture() as captured:
|
||||
run()
|
||||
elapsed = re.findall(r"(?:finished|downloaded|titles) in (-?[\dhms]+)", captured.get())
|
||||
assert len(elapsed) == 3
|
||||
assert all(re.fullmatch(r"0m\d+s", value) for value in elapsed), elapsed
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def get_tracks_calls(monkeypatch):
|
||||
calls = []
|
||||
|
||||
@@ -23,12 +23,6 @@ class FakeDRM:
|
||||
self.content_id = content_id
|
||||
|
||||
|
||||
class NamelessDRM:
|
||||
"""No kids and no content_id, so the class name is the only key left."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_locks() -> Any:
|
||||
ContentKeyResolver.DRM_LOCKS.clear()
|
||||
@@ -42,11 +36,6 @@ def test_same_kid_set_shares_one_lock() -> None:
|
||||
assert ContentKeyResolver.drm_lock(FakeDRM(kids=[KID_A, KID_B])) is lock
|
||||
|
||||
|
||||
def test_kid_order_does_not_matter() -> None:
|
||||
first = ContentKeyResolver.drm_lock(FakeDRM(kids=[KID_A, KID_B]))
|
||||
assert ContentKeyResolver.drm_lock(FakeDRM(kids=[KID_B, KID_A])) is first
|
||||
|
||||
|
||||
def test_different_kids_get_different_locks() -> None:
|
||||
assert ContentKeyResolver.drm_lock(FakeDRM(kids=[KID_A])) is not ContentKeyResolver.drm_lock(FakeDRM(kids=[KID_B]))
|
||||
assert len(ContentKeyResolver.DRM_LOCKS) == 2
|
||||
@@ -57,14 +46,3 @@ def test_no_kids_falls_back_to_content_id() -> None:
|
||||
assert ContentKeyResolver.drm_lock(FakeDRM(content_id="EXAMPLE")) is lock
|
||||
assert ContentKeyResolver.drm_lock(FakeDRM(content_id="OTHER")) is not lock
|
||||
assert set(ContentKeyResolver.DRM_LOCKS) == {"EXAMPLE", "OTHER"}
|
||||
|
||||
|
||||
def test_no_kids_and_no_content_id_falls_back_to_class_name() -> None:
|
||||
lock = ContentKeyResolver.drm_lock(NamelessDRM())
|
||||
assert ContentKeyResolver.drm_lock(NamelessDRM()) is lock
|
||||
assert set(ContentKeyResolver.DRM_LOCKS) == {"NamelessDRM"}
|
||||
|
||||
|
||||
def test_empty_content_id_still_falls_back_to_class_name() -> None:
|
||||
ContentKeyResolver.drm_lock(FakeDRM(content_id=""))
|
||||
assert set(ContentKeyResolver.DRM_LOCKS) == {"FakeDRM"}
|
||||
|
||||
@@ -11,17 +11,16 @@ from uuid import UUID
|
||||
import click
|
||||
import pytest
|
||||
|
||||
from tests.drm_plugins import EXAMPLE, ExampleDevice
|
||||
from unshackle.commands.dl import cdm_summary
|
||||
from tests.drm_plugins import ExampleDevice
|
||||
from unshackle.core import plugins
|
||||
from unshackle.core.cdm import loader
|
||||
from unshackle.core.cdm.choice import choose_cdm, drm_system
|
||||
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub
|
||||
from unshackle.core.cdm.detect import cdm_system
|
||||
from unshackle.core.drm import ClearKeyCTR, CustomDRM, held_key, own_cipher
|
||||
from unshackle.core.plugins import DrmPlugin, load_folder
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.tracks import Video
|
||||
from unshackle.core.wire import drm_from_dict, export_system
|
||||
from unshackle.core.wire import drm_from_dict
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
@@ -116,10 +115,6 @@ def test_a_second_plugin_with_the_same_id_is_skipped(tmp_path: Path, caplog) ->
|
||||
assert caplog.messages == ["DRM plugin second.zip repeats the id 'example', skipped"]
|
||||
|
||||
|
||||
def test_a_missing_plugin_folder_loads_nothing(tmp_path: Path) -> None:
|
||||
assert load_folder(tmp_path / "absent") == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"facts",
|
||||
[{"id": "widevine"}, {"id": "Bad-Id"}, {"licensing": "remote"}, {"mode": "file"}, {"device_suffix": ".exd"}],
|
||||
@@ -166,28 +161,6 @@ def test_a_plugin_device_is_an_entry_of_the_cdm_catalogue(example_plugins: None,
|
||||
assert isinstance(cdm, ExampleDevice) and cdm_system(cdm) == "example"
|
||||
|
||||
|
||||
def test_the_load_log_names_a_plugin_cdm_by_its_label_and_device_name(example_plugins: None, tmp_path: Path) -> None:
|
||||
cdm = ExampleDevice(tmp_path / "EXAMPLE_DEVICE.exd")
|
||||
assert cdm_summary(cdm) == {"drm_type": "EXAMPLE", "remote": False, "device": "EXAMPLE_DEVICE"}
|
||||
del cdm.device_name
|
||||
assert cdm_summary(cdm)["device"] == "EXAMPLE"
|
||||
|
||||
cdm.security_level = "v5"
|
||||
assert cdm_summary(cdm)["security_level"] == "v5"
|
||||
|
||||
|
||||
def test_a_stub_of_a_plugin_system_is_that_system(example_plugins: None) -> None:
|
||||
assert cdm_system(cdm_type_stub("example")) == "example"
|
||||
assert cdm_system(cdm_type_stub("None")) == "widevine"
|
||||
|
||||
|
||||
def test_a_client_with_a_plugin_cdm_is_a_stand_in_of_its_system(example_plugins: None) -> None:
|
||||
from unshackle.core.api.handlers import client_device_cdm
|
||||
|
||||
cdm = client_device_cdm({"cdm_type": "example"}, input_bridge=SimpleNamespace())
|
||||
assert cdm_system(cdm) == "example"
|
||||
|
||||
|
||||
def test_a_plugin_device_licenses_a_plugin_drm(example_plugins: None, tmp_path: Path) -> None:
|
||||
device = tmp_path / "EXAMPLE_DEVICE.exd"
|
||||
device.write_bytes(bytes(range(16)))
|
||||
@@ -236,19 +209,3 @@ def test_the_export_form_of_a_plugin_drm_round_trips_without_its_keys(example_pl
|
||||
{"key": "aa" * 16},
|
||||
{},
|
||||
)
|
||||
|
||||
|
||||
def test_an_export_of_a_plugin_that_is_not_loaded_stops_the_track() -> None:
|
||||
with pytest.raises(click.ClickException, match=r"^Unknown DRM system 'example' in the export$"):
|
||||
export_system("example")
|
||||
|
||||
|
||||
def test_the_registry_loads_the_plugin_folder_once(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
plugin_folder(tmp_path, "example_pkg")
|
||||
monkeypatch.setattr(plugins, "PLUGINS", None)
|
||||
from unshackle.core.config import config
|
||||
|
||||
monkeypatch.setattr(config.directories, "plugins", tmp_path)
|
||||
|
||||
assert plugins.get("example") is not None and plugins.get("example") is plugins.plugins()["example"]
|
||||
assert plugins.get(EXAMPLE) is None
|
||||
|
||||
@@ -78,13 +78,6 @@ def test_strict_multi(strict_mode):
|
||||
assert c["dubbed"] == ""
|
||||
|
||||
|
||||
def test_strict_two_unknown_original(strict_mode):
|
||||
c = ctx(None, ["en", "es"])
|
||||
assert c["dual"] == ""
|
||||
assert c["multi"] == ""
|
||||
assert c["dubbed"] == ""
|
||||
|
||||
|
||||
def test_strict_dubbed(strict_mode):
|
||||
c = ctx("en", ["es"])
|
||||
assert c["dubbed"] == "DUBBED"
|
||||
@@ -92,13 +85,6 @@ def test_strict_dubbed(strict_mode):
|
||||
assert c["multi"] == ""
|
||||
|
||||
|
||||
def test_strict_single_unknown_original_no_dubbed(strict_mode):
|
||||
c = ctx(None, ["es"])
|
||||
assert c["dubbed"] == ""
|
||||
assert c["dual"] == ""
|
||||
assert c["multi"] == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("language", "languages", "tags"),
|
||||
[
|
||||
@@ -133,13 +119,6 @@ def test_count_dual_ignores_original(count_mode):
|
||||
assert c["dubbed"] == ""
|
||||
|
||||
|
||||
def test_count_multi(count_mode):
|
||||
c = ctx(None, ["es", "fr", "de"])
|
||||
assert c["multi"] == "MULTi"
|
||||
assert c["dual"] == ""
|
||||
assert c["dubbed"] == ""
|
||||
|
||||
|
||||
def test_count_never_dubbed(count_mode):
|
||||
c = ctx("en", ["es"])
|
||||
assert c["dubbed"] == ""
|
||||
|
||||
@@ -32,13 +32,6 @@ def test_imdb_language_takes_the_first_spoken_language() -> None:
|
||||
assert imdb_language(data) == "ja"
|
||||
|
||||
|
||||
def test_imdb_language_is_alpha_2() -> None:
|
||||
"""IMDb's GraphQL language ids are alpha-2."""
|
||||
data = {"spokenLanguages": {"spokenLanguages": [{"id": "ko", "text": "Korean"}]}}
|
||||
assert parse_language(imdb_language(data)) is not None
|
||||
assert str(parse_language(imdb_language(data))) == "ko"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"data",
|
||||
[
|
||||
|
||||
@@ -46,14 +46,6 @@ def reset_template():
|
||||
config.output_template, config.folder_templates, config.folder_template, config.tag = saved
|
||||
|
||||
|
||||
def test_absolute_defaults_to_none():
|
||||
assert make_episode().absolute is None
|
||||
|
||||
|
||||
def test_int_absolute_is_kept():
|
||||
assert make_episode(absolute=27).absolute == 27
|
||||
|
||||
|
||||
def test_digit_string_absolute_coerces():
|
||||
assert make_episode(absolute="27").absolute == 27
|
||||
|
||||
@@ -70,12 +62,6 @@ def test_non_int_absolute_rejected(bad):
|
||||
make_episode(absolute=bad)
|
||||
|
||||
|
||||
def test_bool_absolute_rejected():
|
||||
"""bool is an int subclass; True would render as '001' in filenames."""
|
||||
with pytest.raises(TypeError):
|
||||
make_episode(absolute=True)
|
||||
|
||||
|
||||
def test_old_cache_entry_reads_as_absolute_less():
|
||||
"""jsonpickle restores by populating __dict__; an older entry has no 'absolute' key."""
|
||||
restored = Episode.__new__(Episode)
|
||||
@@ -87,14 +73,6 @@ def test_absolute_token_is_three_wide(reset_template):
|
||||
assert make_episode(absolute=7).build_template_context(StubMediaInfo())["absolute"] == "007"
|
||||
|
||||
|
||||
def test_absolute_token_does_not_truncate_past_three_digits(reset_template):
|
||||
assert make_episode(absolute=1042).build_template_context(StubMediaInfo())["absolute"] == "1042"
|
||||
|
||||
|
||||
def test_absolute_token_is_empty_without_a_value(reset_template):
|
||||
assert make_episode().build_template_context(StubMediaInfo())["absolute"] == ""
|
||||
|
||||
|
||||
def test_filename_renders_the_absolute_number(reset_template):
|
||||
assert make_episode(absolute=7).get_filename(StubMediaInfo()) == "The.Show.S01E01.007.DummyService-GROUP"
|
||||
|
||||
@@ -105,11 +83,6 @@ def test_optional_absolute_token_drops_out(reset_template):
|
||||
assert make_episode(absolute=7).get_filename(StubMediaInfo()) == "The.Show.S01E01.007.DummyService-GROUP"
|
||||
|
||||
|
||||
def test_absolute_is_a_known_template_variable(reset_template, recwarn):
|
||||
reset_template.validate_output_templates()
|
||||
assert not [w for w in recwarn.list if "absolute" in str(w.message)]
|
||||
|
||||
|
||||
def test_str_and_sorting_ignore_the_absolute_number():
|
||||
assert str(make_episode(absolute=7)) == "The Show S01E01 The Reckoning"
|
||||
series = Series([make_episode(number=2, absolute=1), make_episode(number=1, absolute=2)])
|
||||
@@ -164,42 +137,3 @@ def test_a_service_already_in_absolute_order_fills_from_its_own_numbers(monkeypa
|
||||
titles, fake, _ = fill(monkeypatch, episodes, {}, order="absolute")
|
||||
assert [t.absolute for t in titles] == [26, 27]
|
||||
assert fake.orders == []
|
||||
|
||||
|
||||
def test_fill_never_touches_season_or_number(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
episodes = [make_episode(season=2, number=1)]
|
||||
titles, _, _ = fill(monkeypatch, episodes, MAPPING)
|
||||
assert [(t.season, t.number) for t in titles] == [(2, 1)]
|
||||
|
||||
|
||||
def test_a_service_set_absolute_number_wins(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
episodes = [make_episode(season=1, number=1, absolute=99), make_episode(season=1, number=2)]
|
||||
titles, _, _ = fill(monkeypatch, episodes, MAPPING)
|
||||
assert [t.absolute for t in titles] == [99, 2]
|
||||
|
||||
|
||||
def test_an_unmapped_episode_keeps_no_absolute_number(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
episodes = [make_episode(season=9, number=9)]
|
||||
titles, _, _ = fill(monkeypatch, episodes, MAPPING)
|
||||
assert titles[0].absolute is None
|
||||
|
||||
|
||||
def test_fill_skips_silently_without_an_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
episodes = [make_episode(season=1, number=1)]
|
||||
titles, _, logged = fill(monkeypatch, episodes, MAPPING, provider=False)
|
||||
assert titles[0].absolute is None
|
||||
assert [level for level, _ in logged] == ["debug"]
|
||||
|
||||
|
||||
def test_fill_skips_silently_without_a_tvdb_id(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
episodes = [make_episode(season=1, number=1)]
|
||||
titles, _, logged = fill(monkeypatch, episodes, MAPPING, tvdb_id=None)
|
||||
assert titles[0].absolute is None
|
||||
assert [level for level, _ in logged] == ["debug"]
|
||||
|
||||
|
||||
def test_fill_skips_silently_when_tvdb_has_no_absolute_order(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
episodes = [make_episode(season=1, number=1)]
|
||||
titles, _, logged = fill(monkeypatch, episodes, {})
|
||||
assert titles[0].absolute is None
|
||||
assert [level for level, _ in logged] == ["debug"]
|
||||
|
||||
@@ -55,12 +55,6 @@ def test_air_date_replaces_season_episode_dotted(reset_template):
|
||||
assert ctx["date"] == "2024-06-30" # ISO regardless of separator
|
||||
|
||||
|
||||
def test_air_date_uses_space_separator(reset_template):
|
||||
reset_template.output_template = {"series": "{title} {season_episode} {quality}-{tag}"}
|
||||
ep = make_episode(air_date=date(2024, 6, 30))
|
||||
assert ep.build_template_context(StubMediaInfo())["season_episode"] == "2024 06 30"
|
||||
|
||||
|
||||
def test_iso_string_air_date_coerced(reset_template):
|
||||
ep = make_episode(air_date="2024-06-30")
|
||||
assert isinstance(ep.air_date, date)
|
||||
@@ -75,14 +69,6 @@ def test_year_always_dropped_in_file_when_dated(reset_template):
|
||||
assert ctx["season_episode"] == "2013.10.30"
|
||||
|
||||
|
||||
def test_yearless_title_takes_year_from_date(reset_template):
|
||||
"""A title with no year still names cleanly; the date supplies the year."""
|
||||
ep = make_episode(year=None, air_date=date(2026, 6, 28))
|
||||
ctx = ep.build_template_context(StubMediaInfo())
|
||||
assert ctx["year"] == ""
|
||||
assert ctx["season_episode"] == "2026.06.28"
|
||||
|
||||
|
||||
def test_datetime_normalized_to_date(reset_template):
|
||||
"""A datetime (subclass of date) must not leak its time into the {date} token."""
|
||||
ep = make_episode(air_date=datetime(2024, 6, 30, 13, 0, 0))
|
||||
@@ -138,21 +124,6 @@ def test_a_season_episode_exclusion_beats_the_date_key():
|
||||
assert not make_episode(air_date=date(2024, 6, 30)).matches_wanted({"2024-06-30", "!2024x181"})
|
||||
|
||||
|
||||
def test_an_undated_episode_is_unaffected_by_date_keys():
|
||||
episode = make_episode()
|
||||
assert not episode.matches_wanted({"2024-06-30"})
|
||||
assert episode.matches_wanted({"2024x181"})
|
||||
|
||||
|
||||
def test_a_pre_1970_air_date_is_rejected():
|
||||
with pytest.raises(ValueError):
|
||||
make_episode(air_date=date(1969, 12, 31))
|
||||
|
||||
|
||||
def test_a_future_air_date_is_accepted():
|
||||
future = date.today().replace(year=date.today().year + 1)
|
||||
assert make_episode(air_date=future).air_date == future
|
||||
|
||||
|
||||
def test_an_unparseable_air_date_string_is_kept_as_is():
|
||||
assert make_episode(air_date="soon").air_date == "soon"
|
||||
|
||||
@@ -44,10 +44,6 @@ def reset_template():
|
||||
config.output_template, config.folder_templates, config.folder_template, config.tag = saved
|
||||
|
||||
|
||||
def test_part_defaults_to_none():
|
||||
assert make_episode().part is None
|
||||
|
||||
|
||||
def test_digit_string_part_coerces():
|
||||
assert make_episode(part="2").part == 2
|
||||
|
||||
@@ -63,28 +59,6 @@ def test_non_int_part_rejected():
|
||||
make_episode(part="x")
|
||||
|
||||
|
||||
def test_bool_part_rejected():
|
||||
"""bool is an int subclass; True would render as '.True' in keys and filenames."""
|
||||
with pytest.raises(TypeError):
|
||||
make_episode(part=True)
|
||||
|
||||
|
||||
def test_old_cache_entry_reads_as_part_less():
|
||||
"""jsonpickle restores by populating __dict__; an older entry has no 'part' key."""
|
||||
restored = Episode.__new__(Episode)
|
||||
restored.__dict__.update(title="The Show", season=1, number=1, name=None, year=None)
|
||||
assert restored.part is None
|
||||
|
||||
|
||||
def test_str_is_unchanged_without_a_part():
|
||||
without = make_episode()
|
||||
assert str(without) == "The Show S01E01 The Reckoning"
|
||||
|
||||
|
||||
def test_str_shows_the_selection_syntax():
|
||||
assert str(make_episode(part=2)) == "The Show S01E01.2 The Reckoning"
|
||||
|
||||
|
||||
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
|
||||
@@ -92,21 +66,6 @@ def test_str_tells_dated_parts_apart():
|
||||
assert str(make_episode(air_date="2024-05-06")) == "The Show 2024.05.06 The Reckoning"
|
||||
|
||||
|
||||
def test_tree_label_carries_the_part_on_dated_content():
|
||||
series = Series([make_episode(part=1, air_date="2024-05-06"), make_episode(part=2, air_date="2024-05-06")])
|
||||
labels = [node.label for node in series.tree(verbose=True).children[0].children]
|
||||
assert labels == [
|
||||
"[bold]2024.05.06.1.[/] [bright_black]The Reckoning",
|
||||
"[bold]2024.05.06.2.[/] [bright_black]The Reckoning",
|
||||
]
|
||||
|
||||
|
||||
def test_tree_label_carries_the_part():
|
||||
series = Series([make_episode(part=1), make_episode(part=2)])
|
||||
labels = [node.label for node in series.tree(verbose=True).children[0].children]
|
||||
assert labels == ["[bold]1.1.[/] [bright_black]The Reckoning", "[bold]1.2.[/] [bright_black]The Reckoning"]
|
||||
|
||||
|
||||
def test_series_sorts_parts_within_their_episode():
|
||||
series = Series(
|
||||
[
|
||||
@@ -142,10 +101,6 @@ def test_template_context_leaves_the_season_token_alone(reset_template):
|
||||
assert ctx["part"] == 2
|
||||
|
||||
|
||||
def test_part_token_is_empty_without_a_part(reset_template):
|
||||
assert make_episode().build_template_context(StubMediaInfo())["part"] == ""
|
||||
|
||||
|
||||
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}"
|
||||
@@ -153,12 +108,6 @@ def test_parts_share_one_season_folder(reset_template):
|
||||
assert folders == {"The.Show/S01E01"}
|
||||
|
||||
|
||||
def test_parts_share_one_derived_season_folder(reset_template):
|
||||
folders = {make_episode(part=p).get_filename(StubMediaInfo(), folder=True) for p in (1, 2)}
|
||||
assert len(folders) == 1
|
||||
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),
|
||||
@@ -182,7 +131,3 @@ def test_a_part_exclusion_leaves_the_other_parts_alone():
|
||||
wanted = SeasonRange().parse_tokens("S01", "-S01E01.2")
|
||||
assert make_episode(part=1).matches_wanted(wanted) is True
|
||||
assert make_episode(part=3).matches_wanted(wanted) is True
|
||||
|
||||
|
||||
def test_asking_for_a_part_of_an_unsplit_episode_selects_nothing():
|
||||
assert make_episode().matches_wanted(SeasonRange().parse_tokens("S01E01.2")) is False
|
||||
|
||||
@@ -6,7 +6,7 @@ from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.config import Config, config
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.titles.episode import Episode
|
||||
from unshackle.core.wire import build_title, serialize_title, title_to_meta
|
||||
|
||||
@@ -95,8 +95,3 @@ def test_the_sport_flag_survives_the_export_round_trip():
|
||||
|
||||
def test_a_non_sport_episode_sends_no_sport_key():
|
||||
assert "sport" not in serialize_title(make_episode(sport=False), None)
|
||||
|
||||
|
||||
def test_sports_templates_validate_without_warnings(recwarn):
|
||||
Config(output_template={"sports": SPORTS, "folder": {"sports": "{title}.{year?}.{date?}"}})
|
||||
assert not [str(w.message) for w in recwarn if "template" in str(w.message).lower()]
|
||||
|
||||
@@ -474,37 +474,6 @@ def test_an_export_without_content_periods_imports_every_period(
|
||||
assert video.data["dash"]["filtered_period_ids"] == []
|
||||
|
||||
|
||||
def test_import_keeps_every_period_when_no_exported_period_is_left(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""A re-fetch that names every period anew has nothing to match, so the import warns and filters nothing."""
|
||||
from unshackle.core.manifests import DASH
|
||||
|
||||
export = export_service_filtered_title(tmp_path, AD_MPD_URL)
|
||||
renamed = ad_mpd("ad-1").replace('id="main"', 'id="main-2"')
|
||||
monkeypatch.setattr(DASH, "from_url", lambda url, session=None, **kw: DASH.from_text(renamed, url))
|
||||
|
||||
svc = ImportService(import_ctx(), "EXAMPLE", "movie-1", str(export))
|
||||
with caplog.at_level(logging.WARNING):
|
||||
video = svc.get_tracks(next(iter(svc.get_titles()))).videos[0]
|
||||
|
||||
assert video.data["dash"]["filtered_period_ids"] == []
|
||||
assert "keeping every period" in caplog.text
|
||||
|
||||
|
||||
def test_a_3d_video_stays_3d_through_export_and_import(tmp_path: Path) -> None:
|
||||
writer = make_writer(tmp_path)
|
||||
title = make_title()
|
||||
title.tracks.videos[0].stereo = True
|
||||
for track in [*title.tracks.videos, *title.tracks.audio]:
|
||||
writer.record(title, track)
|
||||
export = written(writer)
|
||||
assert [row.get("stereo") for row in entry(export)["tracks"]][0] is True
|
||||
svc = ImportService(import_ctx(), "EXAMPLE", "movie-1", str(export))
|
||||
movie = next(iter(svc.get_titles()))
|
||||
assert svc.get_tracks(movie).videos[0].stereo
|
||||
|
||||
|
||||
def test_atmos_without_a_joc_count_stays_atmos_through_export_and_import(tmp_path: Path) -> None:
|
||||
writer = make_writer(tmp_path)
|
||||
title = make_title()
|
||||
@@ -536,43 +505,6 @@ def test_the_service_metadata_provider_survives_export_and_import(tmp_path: Path
|
||||
assert (movie.metadata_provider, movie.anime) == ("tmdb", True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proxy_requested, region", [(True, "us"), (False, None)])
|
||||
def test_the_region_is_recorded_only_for_a_proxy_run(tmp_path: Path, proxy_requested: bool, region: str | None) -> None:
|
||||
writer = make_writer(tmp_path, SimpleNamespace(session=None, current_region="us"), proxy_requested)
|
||||
title = make_title()
|
||||
|
||||
writer.record(title, title.tracks.videos[0])
|
||||
|
||||
assert read_export(written(writer)).get("region") == region
|
||||
|
||||
|
||||
def test_the_log_lines_read_the_named_file(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||
writer = make_writer(tmp_path)
|
||||
title = make_title()
|
||||
with caplog.at_level(logging.INFO, logger="download"):
|
||||
writer.log_summary()
|
||||
writer.record(title, title.tracks.videos[0], StubDRM())
|
||||
writer.log_title(title)
|
||||
writer.log_summary()
|
||||
|
||||
assert caplog.messages[0] == "Nothing was exported"
|
||||
assert f"Saved the export to {written(writer)}: 1 title, 1 key" in caplog.messages
|
||||
assert "The export holds content keys: keep it private" in caplog.messages
|
||||
|
||||
|
||||
def test_a_title_with_no_record_logs_that_nothing_was_exported(
|
||||
tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
writer = make_writer(tmp_path)
|
||||
first, second = make_title(), make_title()
|
||||
second.id = "movie-2"
|
||||
writer.record(first, first.tracks.videos[0])
|
||||
with caplog.at_level(logging.WARNING, logger="download"):
|
||||
writer.log_title(second)
|
||||
|
||||
assert caplog.messages == ["Exported nothing for 'Example Movie' (2024)"]
|
||||
|
||||
|
||||
def test_a_song_stays_a_song_of_an_album_through_export_and_import(tmp_path: Path) -> None:
|
||||
writer = make_writer(tmp_path)
|
||||
title = Song(
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
|
||||
@@ -87,10 +86,6 @@ def test_movie_name_has_year_and_no_scope() -> None:
|
||||
assert name == "Example.Movie.2024.1080p.h264.sdr.dash.hls.aac2.0-EXAMPLE"
|
||||
|
||||
|
||||
def test_movie_without_year() -> None:
|
||||
assert export_name([movie(year=None)], [video()], "EXAMPLE") == "Example.Movie.1080p.h264.sdr.dash-EXAMPLE"
|
||||
|
||||
|
||||
def test_full_season_is_the_season_number() -> None:
|
||||
titles = [episode(1, n) for n in range(1, 4)]
|
||||
name = export_name(titles, [video(), audio(codec=Audio.Codec.AC3, channels="5.1")], "EXAMPLE", seasons_of((1, 3)))
|
||||
@@ -113,11 +108,6 @@ def test_many_runs_are_cut_short() -> None:
|
||||
assert name == "Example.Show.S01E01.S01E03.S01E05.+3-EXAMPLE"
|
||||
|
||||
|
||||
def test_unknown_season_list_uses_ranges() -> None:
|
||||
titles = [episode(1, n) for n in (1, 2, 3)]
|
||||
assert export_name(titles, [], "EXAMPLE") == "Example.Show.S01E01-E03-EXAMPLE"
|
||||
|
||||
|
||||
def test_whole_seasons_in_a_row_collapse() -> None:
|
||||
titles = [episode(s, n) for s in (1, 2, 3) for n in (1, 2)]
|
||||
assert export_name(titles, [], "EXAMPLE", seasons_of((1, 2), (2, 2), (3, 2))) == "Example.Show.S01-S03-EXAMPLE"
|
||||
@@ -204,45 +194,5 @@ def test_export_is_renamed_as_titles_arrive_and_stays_valid(tmp_path: Path) -> N
|
||||
assert [e.id for e in mediaexport.read(final).titles] == ["ep-1-1", "ep-1-2"]
|
||||
|
||||
|
||||
def test_export_messages(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||
writer = make_writer(tmp_path)
|
||||
title = movie()
|
||||
title.tracks.add(video())
|
||||
title.tracks.add(audio())
|
||||
title.tracks.add(audio("a2"))
|
||||
|
||||
with caplog.at_level(logging.INFO, logger="download"):
|
||||
for track in title.tracks:
|
||||
writer.record(title, track, StubDRM() if isinstance(track, Video) else None)
|
||||
writer.log_title(title)
|
||||
writer.log_summary()
|
||||
|
||||
lines = [r.getMessage() for r in caplog.records]
|
||||
assert "Exporting to Example.Movie.2024.1080p.h264.sdr.dash.aac2.0-EXAMPLE.json" in lines
|
||||
assert "Exported 'Example Movie' (2024): 1 video, 2 audio, 0 subtitles, 1 key" in lines
|
||||
final = tmp_path / "Example.Movie.2024.1080p.h264.sdr.dash.aac2.0-EXAMPLE.json"
|
||||
assert f"Saved the export to {final}: 1 title, 1 key" in lines
|
||||
assert any("content keys" in line for line in lines)
|
||||
|
||||
|
||||
def test_episode_message_names_the_episode(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||
writer = make_writer(tmp_path)
|
||||
title = episode(1, 5, "Example Episode")
|
||||
title.tracks.add(video())
|
||||
writer.record(title, title.tracks.videos[0])
|
||||
|
||||
with caplog.at_level(logging.INFO, logger="download"):
|
||||
writer.log_title(title)
|
||||
|
||||
assert "Exported S01E05 'Example Episode': 1 video, 0 audio, 0 subtitles, 0 keys" in caplog.messages
|
||||
|
||||
|
||||
def test_summary_when_nothing_was_exported(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||
writer = make_writer(tmp_path)
|
||||
with caplog.at_level(logging.INFO, logger="download"):
|
||||
writer.log_summary()
|
||||
assert "Nothing was exported" in caplog.messages
|
||||
|
||||
|
||||
def test_a_range_value_with_a_space_has_none_in_the_name() -> None:
|
||||
assert "hdrvivid" in quality_parts([video(codec=Video.Codec.HEVC, range_=Video.Range.VIVID)])
|
||||
|
||||
@@ -57,28 +57,6 @@ def test_audio_only_passes_fallback(tmp_path: Path) -> None:
|
||||
assert ffmpeg_decodes(audio, video=False)
|
||||
|
||||
|
||||
def test_mpegts_video_passes_fallback(tmp_path: Path) -> None:
|
||||
ts = video(tmp_path / "v.ts", *GOP)
|
||||
assert ffmpeg_decodes(ts)
|
||||
assert ffmpeg_decodes(ts, video=True)
|
||||
|
||||
|
||||
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))
|
||||
|
||||
|
||||
def test_open_gop_hevc_passes_windows(tmp_path: Path) -> None:
|
||||
og = video(
|
||||
tmp_path / "og.mp4",
|
||||
"-x265-params",
|
||||
f"open-gop=1:{GOP_PARAMS}:log-level=none",
|
||||
codec="libx265",
|
||||
)
|
||||
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.
|
||||
|
||||
@@ -99,23 +99,12 @@ def test_an_unusable_aired_value_is_skipped(monkeypatch: pytest.MonkeyPatch, air
|
||||
assert series[0].air_date is None
|
||||
|
||||
|
||||
def test_a_pre_1970_date_is_skipped(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
series, _ = fill(monkeypatch, [make_episode(number=1)], [tvdb_episode(1, 1, "1900-01-01")])
|
||||
assert series[0].air_date is None
|
||||
|
||||
|
||||
def test_a_future_placeholder_date_is_skipped(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
future = (date.today() + timedelta(days=30)).isoformat()
|
||||
series, _ = fill(monkeypatch, [make_episode(number=1)], [tvdb_episode(1, 1, future)])
|
||||
assert series[0].air_date is None
|
||||
|
||||
|
||||
def test_tomorrow_still_fills(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
tomorrow = date.today() + timedelta(days=1)
|
||||
series, _ = fill(monkeypatch, [make_episode(number=1)], [tvdb_episode(1, 1, tomorrow.isoformat())])
|
||||
assert series[0].air_date == tomorrow
|
||||
|
||||
|
||||
def test_a_datetime_stamped_aired_value_keeps_the_date(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
series, _ = fill(monkeypatch, [make_episode(number=1)], [tvdb_episode(1, 1, "2026-08-10T20:00:00Z")])
|
||||
assert series[0].air_date == date(2026, 8, 10)
|
||||
@@ -133,12 +122,6 @@ def test_fill_skips_silently_without_a_tvdb_id(monkeypatch: pytest.MonkeyPatch)
|
||||
assert [level for level, _ in logged] == ["debug"]
|
||||
|
||||
|
||||
def test_fill_skips_silently_when_tvdb_lists_no_episodes(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
series, logged = fill(monkeypatch, [make_episode(number=1)], [])
|
||||
assert series[0].air_date is None
|
||||
assert [level for level, _ in logged] == ["debug"]
|
||||
|
||||
|
||||
def test_nothing_is_filled_when_no_title_is_daily(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
series, logged = fill(monkeypatch, [make_episode(number=1)], LISTING, daily=False)
|
||||
assert series[0].air_date is None
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import warnings
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
@@ -9,30 +8,11 @@ from unshackle.core.tracks import Tracks, Video
|
||||
from unshackle.core.utilities import FPS
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("expr", "expected"),
|
||||
[
|
||||
("24", 24),
|
||||
("23.976", pytest.approx(23.976)),
|
||||
("30000/1001", pytest.approx(29.97, abs=0.001)),
|
||||
],
|
||||
)
|
||||
def test_parse_pins_results_without_deprecation_warnings(expr: str, expected: object) -> None:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", DeprecationWarning)
|
||||
assert FPS.parse(expr) == expected
|
||||
|
||||
|
||||
def test_parse_rejects_non_numeric_constant() -> None:
|
||||
with pytest.raises(ValueError, match="Invalid fps value"):
|
||||
FPS.parse("'24'")
|
||||
|
||||
|
||||
def test_parse_rejects_non_division_operation() -> None:
|
||||
with pytest.raises(ValueError, match="Invalid operation"):
|
||||
FPS.parse("24+1")
|
||||
|
||||
|
||||
def test_dash_frame_rate_with_zero_denominator_gives_no_fps() -> None:
|
||||
mpd = """<?xml version="1.0"?>
|
||||
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" mediaPresentationDuration="PT10S">
|
||||
|
||||
@@ -24,11 +24,6 @@ class Both(Service):
|
||||
GEOBLOCK = ("GB",)
|
||||
|
||||
|
||||
def test_no_restrictions_allows_everything():
|
||||
assert Service.is_region_allowed("xx")
|
||||
assert Service.is_region_allowed(None)
|
||||
|
||||
|
||||
def test_geoblock_refuses_listed_region_any_case():
|
||||
assert Blocked.is_region_allowed("de")
|
||||
assert not Blocked.is_region_allowed("gb")
|
||||
@@ -45,11 +40,6 @@ def test_geoblock_wins_over_geofence():
|
||||
assert not Both.is_region_allowed("gb")
|
||||
|
||||
|
||||
def test_unknown_region_is_allowed():
|
||||
assert Blocked.is_region_allowed("")
|
||||
assert Blocked.is_region_allowed(None)
|
||||
|
||||
|
||||
def warnings_for(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
exit_region: str | None,
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
import threading
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from unshackle.core.utilities import get_boxes
|
||||
@@ -18,27 +17,3 @@ def test_get_boxes_finds_the_tenc() -> None:
|
||||
kid = uuid4()
|
||||
(box,) = get_boxes(tenc_init(kid, 1, 0x19), b"tenc")
|
||||
assert box.key_ID == kid
|
||||
|
||||
|
||||
def test_get_boxes_is_right_when_tracks_parse_at_the_same_time() -> None:
|
||||
cases = [(uuid4(), version, crypt_skip) for version, crypt_skip in ((0, 0), (1, 0x19), (1, 0x91), (1, 0x55))] * 2
|
||||
failures: list[str] = []
|
||||
|
||||
def parse(kid: UUID, version: int, crypt_skip: int) -> None:
|
||||
data = tenc_init(kid, version, crypt_skip)
|
||||
for _ in range(1500):
|
||||
try:
|
||||
boxes = list(get_boxes(data, b"tenc"))
|
||||
except Exception as e:
|
||||
failures.append(repr(e))
|
||||
continue
|
||||
if [box.key_ID for box in boxes] != [kid]:
|
||||
failures.append("wrong or missing tenc")
|
||||
|
||||
threads = [threading.Thread(target=parse, args=case) for case in cases]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join(timeout=120)
|
||||
assert not failures, failures[:3]
|
||||
assert not any(thread.is_alive() for thread in threads)
|
||||
|
||||
@@ -114,12 +114,6 @@ def test_plain_hdr10_ends_stop_after_the_sample(monkeypatch: pytest.MonkeyPatch)
|
||||
assert len(probed) == 4
|
||||
|
||||
|
||||
def test_two_encodes_at_one_resolution_are_all_probed(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
videos, probed = ladder(monkeypatch, "++-++", heights=[2160, 1440, 1080, 1080, 720])
|
||||
assert ranges(videos) == "++-++"
|
||||
assert len(probed) == 5
|
||||
|
||||
|
||||
def test_a_dv_ladder_keeps_its_range_and_is_sampled_apart_from_hdr10(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
hdr = [hevc(f"h{i}-", 2160 - 100 * i, 100 - i) for i in range(6)]
|
||||
dv = [hevc(f"d{i}+", 2160 - 100 * i, 100 - i, Video.Range.DV) for i in range(6)]
|
||||
@@ -199,35 +193,11 @@ def test_probed_tracks_leaves_a_remote_service_to_its_server(monkeypatch: pytest
|
||||
assert probe_calls(monkeypatch, remote, workers=3) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workers", [-1, "8"])
|
||||
def test_a_bad_workers_count_is_an_error(monkeypatch: pytest.MonkeyPatch, workers: Any) -> None:
|
||||
service = SimpleNamespace(
|
||||
get_tracks=lambda title: SimpleNamespace(videos=[hevc("v", 2160)], audio=[]), session=None
|
||||
)
|
||||
with pytest.raises(ValueError, match="workers"):
|
||||
probe_calls(monkeypatch, service, workers=workers)
|
||||
|
||||
|
||||
def test_a_quoted_hdr10plus_probe_value_is_an_error() -> None:
|
||||
with pytest.raises(SystemExit, match="hdr10plus_probe"):
|
||||
Config(hdr10plus_probe="false")
|
||||
|
||||
|
||||
def test_a_fragment_inside_the_first_window_needs_one_request(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
media = fragment(nal(32, b"vps"), sei(4, HDR10PLUS_T35 + b"\x00" * 8), nal(1, b"\xff" * 64))
|
||||
data = box(b"sidx", b"\x00" * 40) + media
|
||||
ranges_asked: list[str] = []
|
||||
|
||||
def fake_get(url: str, session: Any, byte_range: str, accept_200: bool) -> bytes:
|
||||
ranges_asked.append(byte_range)
|
||||
return data
|
||||
|
||||
monkeypatch.setattr(hdr10plus, "first_segment", lambda track, session: ("https://cdn/v.mp4", 0))
|
||||
monkeypatch.setattr(hdr10plus, "ranged_get", fake_get)
|
||||
assert fragment_has_t35(hdr10plus.first_fragment(hevc("v", 2160), None) or b"", HDR10PLUS_T35) is True # type: ignore[arg-type]
|
||||
assert len(ranges_asked) == 1
|
||||
|
||||
|
||||
def test_a_quoted_dl_workers_value_works_like_the_cli(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
service = SimpleNamespace(
|
||||
get_tracks=lambda title: SimpleNamespace(videos=[hevc("v", 2160)], audio=[]), session=None
|
||||
@@ -236,12 +206,6 @@ def test_a_quoted_dl_workers_value_works_like_the_cli(monkeypatch: pytest.Monkey
|
||||
assert probe_calls(monkeypatch, service) == [8]
|
||||
|
||||
|
||||
def test_a_dv_track_with_an_hdr10_base_lists_as_dv_plus_hdr10() -> None:
|
||||
video = Video(url="https://x/v.mp4", language="en", codec=Video.Codec.HEVC, range_=Video.Range.DV, hdr10_base=True)
|
||||
assert "[H.265, DV+HDR10]" in str(video)
|
||||
assert track_from_dict(track_to_dict(video)).hdr10_base
|
||||
|
||||
|
||||
def ts_packet(pid: int, section: bytes) -> bytes:
|
||||
body = b"\x00" + section
|
||||
return bytes([0x47, 0x40 | (pid >> 8), pid & 0xFF, 0x10]) + body + b"\xff" * (184 - len(body))
|
||||
@@ -324,13 +288,6 @@ def test_audio_without_a_codec_takes_it_from_the_ts_stream_type(monkeypatch: pyt
|
||||
assert "[Audio Vivid]" in str(Audio(url="https://x/a.m3u8", language="zh", codec=Audio.Codec.AV3A))
|
||||
|
||||
|
||||
def test_an_avsa_registration_names_audio_vivid(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
serve_segments(monkeypatch, {"a": ts((0x06, b"AVSA"))})
|
||||
track = SimpleNamespace(id="a", codec=None, session=None)
|
||||
hdr10plus.probe_audio_codecs([track], None, log=logging.getLogger("test"), workers=1) # type: ignore[arg-type,list-item]
|
||||
assert track.codec == Audio.Codec.AV3A
|
||||
|
||||
|
||||
def test_vivid_imports_by_value_and_matches_its_unprobed_reparse() -> None:
|
||||
assert video_range("HDR Vivid") == video_range("vivid") == Video.Range.VIVID
|
||||
for local, remote in ((Video.Range.HDR10, Video.Range.VIVID), (Video.Range.HLG, Video.Range.VIVID)):
|
||||
@@ -523,10 +480,3 @@ def test_a_t35_message_after_a_payload_type_128_message_is_found() -> None:
|
||||
t35 = bytes([4, len(CUVA_T35) + 4]) + CUVA_T35 + b"\x00" * 4
|
||||
data = nal(39, sop + t35 + b"\x80")
|
||||
assert fragment_has_t35(fragment(data, nal(1, b"\xff")), CUVA_T35) is True
|
||||
|
||||
|
||||
def test_hevc_and_vvc_tracks_are_separate_ladders(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
videos = [hevc(f"v{i}{mark}", 2160 - 100 * i, 100 - i) for i, mark in enumerate("++-++")]
|
||||
videos[2].codec = Video.Codec.VVC
|
||||
assert len(probe(monkeypatch, videos)) == 5
|
||||
assert ranges(videos) == "++-++"
|
||||
|
||||
@@ -135,14 +135,6 @@ def test_key_spans(tags: dict[int, list[str]], wanted: Any, expected: list[Any])
|
||||
assert found == expected
|
||||
|
||||
|
||||
def test_dropped_tags_leave_no_span_with_a_key() -> None:
|
||||
manifest = m3u8.loads(playlist({0: [SKD, DISCONTINUITY_SEQUENCE]}))
|
||||
|
||||
assert HLS.drop_unsupported_keys(manifest)
|
||||
|
||||
assert [span.keys for span in key_spans(manifest, manifest.segments)] == [[]]
|
||||
|
||||
|
||||
def keys_requested(server: Any) -> list[str]:
|
||||
return [path[1:] for path in server.requests if path[1:] in KEYS]
|
||||
|
||||
|
||||
@@ -148,38 +148,6 @@ def test_licence_only_skips_the_key_of_a_filtered_segment(tmp_path: Path) -> Non
|
||||
assert licence_only(segment_uri_filter(unwanted)) == (licensed, unwanted)
|
||||
|
||||
|
||||
def test_licence_only_warns_when_no_dropped_segment_is_in_the_playlist(tmp_path: Path, caplog: Any) -> None:
|
||||
"""A changed host or path makes an exported list match nothing, and the download then keeps every segment."""
|
||||
playlist = tmp_path / "media.m3u8"
|
||||
playlist.write_text(PLAYLIST, encoding="utf-8")
|
||||
track = Video(
|
||||
url="https://example.test/media.m3u8",
|
||||
language="en",
|
||||
descriptor=Track.Descriptor.HLS,
|
||||
codec=Video.Codec.HEVC,
|
||||
)
|
||||
track.from_file = playlist
|
||||
stale = ["https://other.example/moved.m4s"]
|
||||
track.OnSegmentFilter = segment_uri_filter(stale)
|
||||
track.data["hls"]["unwanted_segments"] = stale
|
||||
ctx = DownloadContext(
|
||||
save_path=tmp_path / "video.mp4",
|
||||
save_dir=tmp_path / "video_segments",
|
||||
progress=lambda **_: None,
|
||||
license_widevine=lambda drm, track_kid=None: None,
|
||||
cdm=None,
|
||||
)
|
||||
|
||||
DOWNLOAD_LICENCE_ONLY.set()
|
||||
try:
|
||||
with caplog.at_level("WARNING", logger="HLS"):
|
||||
HLS.download_track(track=track, ctx=ctx)
|
||||
finally:
|
||||
DOWNLOAD_LICENCE_ONLY.clear()
|
||||
|
||||
assert "keeps every segment" in caplog.text
|
||||
|
||||
|
||||
def test_licence_only_fetches_no_aes_128_key(tmp_path: Path, monkeypatch: Any) -> None:
|
||||
"""An AES-128 key with an IV on each segment is a new key each time, and licence-only must not fetch them."""
|
||||
playlist = tmp_path / "media.m3u8"
|
||||
|
||||
@@ -70,21 +70,6 @@ def test_failed_ffmpeg_concat_writes_nothing_to_the_terminal(
|
||||
assert save_path.read_bytes() == b"segment-0segment-1segment-2"
|
||||
|
||||
|
||||
def test_failed_ffmpeg_concat_logs_the_reason(
|
||||
tmp_path: Path, segments: list[Path], monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
def fake_run(args, **kwargs):
|
||||
raise subprocess.CalledProcessError(1, args, output="", stderr=FFMPEG_ERROR)
|
||||
|
||||
monkeypatch.setattr("unshackle.core.manifests.hls.binaries.FFMPEG", Path("ffmpeg"))
|
||||
monkeypatch.setattr("unshackle.core.manifests.hls.subprocess.run", fake_run)
|
||||
|
||||
with caplog.at_level("DEBUG", logger="HLS"):
|
||||
HLS.merge_segments(segments=segments, save_path=tmp_path / "Audio.mp4")
|
||||
|
||||
assert FFMPEG_ERROR in caplog.text
|
||||
|
||||
|
||||
def test_binary_concat_advances_progress_per_segment(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""FFmpeg concat reports nothing, so the fallback is the only place a count can come from."""
|
||||
segments = []
|
||||
@@ -106,15 +91,6 @@ def test_binary_concat_advances_progress_per_segment(tmp_path: Path, monkeypatch
|
||||
assert (tmp_path / "out.mp4").stat().st_size == 4 * 16
|
||||
|
||||
|
||||
def test_merge_segments_without_progress_still_works(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""progress stays optional; other callers pass nothing."""
|
||||
seg = tmp_path / "seg0.mp4"
|
||||
seg.write_bytes(b"\x01" * 8)
|
||||
monkeypatch.setattr("unshackle.core.manifests.hls.binaries.FFMPEG", None)
|
||||
size = HLS.merge_segments(segments=[seg], save_path=tmp_path / "out.mp4")
|
||||
assert size == 8
|
||||
|
||||
|
||||
def test_cleanup_never_climbs_past_the_segment_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""
|
||||
A download directory may itself say "_segments". Only the track's own segment store
|
||||
@@ -172,15 +148,3 @@ def test_segment_delete_error_after_ffmpeg_success_keeps_the_output(
|
||||
|
||||
assert size == len(b"merged")
|
||||
assert save_path.read_bytes() == b"merged"
|
||||
|
||||
|
||||
def test_ffmpeg_timeout_grows_with_input_size(tmp_path: Path, segments: list[Path], ffmpeg_ok: list[dict]) -> None:
|
||||
HLS.merge_segments(segments=segments, save_path=tmp_path / "small.mp4")
|
||||
|
||||
segments[0].parent.mkdir(exist_ok=True)
|
||||
for i, path in enumerate(segments):
|
||||
path.write_bytes(f"segment-{i}".encode())
|
||||
segments[0].write_bytes(b"\0" * 10 * 1024 * 1024)
|
||||
HLS.merge_segments(segments=segments, save_path=tmp_path / "large.mp4")
|
||||
|
||||
assert [call["timeout"] for call in ffmpeg_ok] == [300, 302]
|
||||
|
||||
@@ -37,22 +37,10 @@ def test_a_media_entry_listed_twice_gets_one_track() -> None:
|
||||
assert [str(audio.url) for audio in result.audio] == ["https://example.test/audio/en.m3u8"]
|
||||
|
||||
|
||||
def test_variants_with_the_same_attributes_and_other_links_stay_apart() -> None:
|
||||
result = tracks(variant(5_000_000, "video/uhd.m3u8") + variant(5_000_000, "mirror/uhd.m3u8"))
|
||||
|
||||
assert len(result.videos) == 2
|
||||
|
||||
|
||||
PLAIN = '#EXT-X-STREAM-INF:BANDWIDTH=5000000,RESOLUTION=3840x2160,CODECS="hvc1.2.4.L153.B0",VIDEO-RANGE=PQ'
|
||||
COMPOSITE = PLAIN + ',SUPPLEMENTAL-CODECS="dvh1.08.06/db1p"'
|
||||
|
||||
|
||||
def test_variants_of_one_link_with_another_video_range_stay_apart() -> None:
|
||||
result = tracks(f"{PLAIN}\nuhd.m3u8\n" + f"{PLAIN.replace('=PQ', '=SDR')}\nuhd.m3u8\n")
|
||||
|
||||
assert len(result.videos) == 2
|
||||
|
||||
|
||||
def test_variants_with_other_supplemental_codecs_and_other_links_stay_apart() -> None:
|
||||
result = tracks(f"{PLAIN}\nhdr10.m3u8\n{COMPOSITE}\ndv.m3u8\n")
|
||||
|
||||
|
||||
@@ -15,14 +15,12 @@ from __future__ import annotations
|
||||
import codecs
|
||||
import subprocess
|
||||
import threading
|
||||
from functools import partial
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.manifests import HLS
|
||||
from unshackle.core.tracks.track import DownloadContext
|
||||
|
||||
SEGMENT_ONE = b"WEBVTT\n\n00:00:00.000 --> 00:00:04.000\nhello\n"
|
||||
SEGMENT_TWO = b"WEBVTT\n\n00:00:04.000 --> 00:00:08.000\nworld\n"
|
||||
@@ -107,37 +105,3 @@ part0.vtt
|
||||
part1.vtt
|
||||
#EXT-X-ENDLIST
|
||||
"""
|
||||
|
||||
|
||||
def test_unchanged_subtitle_segments_are_not_rewritten(server, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Plain UTF-8 WebVTT survives the transform untouched, so nothing needs writing back."""
|
||||
port = server.server_address[1]
|
||||
server.routes["/subs.m3u8"] = SUBS_PLAYLIST
|
||||
server.routes["/part0.vtt"] = SEGMENT_ONE
|
||||
server.routes["/part1.vtt"] = SEGMENT_TWO
|
||||
|
||||
track = HLS.from_text(MASTER, url=f"http://127.0.0.1:{port}/master.m3u8").to_tracks(language="en").subtitles[0]
|
||||
|
||||
save_dir = tmp_path / "s0_segments"
|
||||
rewritten: list[str] = []
|
||||
real_write_bytes = Path.write_bytes
|
||||
|
||||
def spy_write_bytes(self, data):
|
||||
if save_dir in self.parents:
|
||||
rewritten.append(self.name)
|
||||
return real_write_bytes(self, data)
|
||||
|
||||
monkeypatch.setattr(Path, "write_bytes", spy_write_bytes)
|
||||
|
||||
HLS.download_track(
|
||||
track,
|
||||
DownloadContext(
|
||||
save_path=tmp_path / "out.vtt",
|
||||
save_dir=save_dir,
|
||||
progress=partial(lambda **kw: None),
|
||||
max_workers=1,
|
||||
),
|
||||
)
|
||||
|
||||
assert (tmp_path / "out.vtt").read_bytes() == SEGMENT_ONE + SEGMENT_TWO
|
||||
assert rewritten == [], f"unchanged subtitle segments were rewritten: {rewritten}"
|
||||
|
||||
@@ -170,10 +170,6 @@ def test_the_server_builds_no_stub_for_an_identity_sample_aes_track(tmp_path: Pa
|
||||
assert "init.mp4" not in session.requests
|
||||
|
||||
|
||||
def test_a_playlist_with_no_key_tag_is_left_alone() -> None:
|
||||
assert not HLS.drop_unsupported_keys(m3u8.loads(playlist()))
|
||||
|
||||
|
||||
def test_the_drm_of_the_service_licenses_the_track(tmp_path: Path) -> None:
|
||||
track = hls_video(tmp_path, playlist(SKD_KEY))
|
||||
track.drm = [drm_stub("playready", [KID.hex])]
|
||||
@@ -515,14 +511,6 @@ def test_an_all_zero_key_id_from_ffprobe_reads_the_pssh(tmp_path: Path, monkeypa
|
||||
]
|
||||
|
||||
|
||||
def test_a_stitched_playlist_with_two_keys_is_refused(tmp_path: Path) -> None:
|
||||
text = stitched("lead.mp4", "init.mp4", "lead.mp4")
|
||||
text = text.replace("#EXTINF:6.0,\n2.m4s", f"{SKD_KEY.replace('asset', 'other')}\n#EXTINF:6.0,\n2.m4s")
|
||||
|
||||
with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"):
|
||||
download(hls_video(tmp_path, text), cdm_type_stub("playready"), session=InitServer())
|
||||
|
||||
|
||||
def test_a_first_init_segment_that_cannot_be_read_stops_the_reads(tmp_path: Path) -> None:
|
||||
session = InitServer(init=None)
|
||||
manifest = m3u8.loads(stitched("lead.mp4", "init.mp4", "tail.mp4"), "https://example.test/media.m3u8")
|
||||
|
||||
@@ -44,11 +44,6 @@ def _key(method: str, keyformat: str | None = None) -> m3u8.model.Key:
|
||||
return m3u8.model.Key(method=method, base_uri="", uri=KEY_URI, keyformat=keyformat)
|
||||
|
||||
|
||||
def test_session_data_playready_urn_key_is_kept() -> None:
|
||||
keys = HLS.parse_session_data_keys(_master(_b64([_item("SAMPLE-AES-CTR", PR_URN)])))
|
||||
assert [k.keyformat for k in keys] == [PR_URN]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "keyformat"),
|
||||
[
|
||||
|
||||
@@ -31,17 +31,6 @@ def test_restarting_blocks_move_to_their_playlist_start() -> None:
|
||||
assert [starts(t) for t in out] == [["00:00:01.000", "00:06:10.000"], ["00:06:12.956"], ["00:12:27.166"]]
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_a_late_first_cue_still_restarts() -> None:
|
||||
texts = [block("00:00:01.000"), block("00:00:40.000")]
|
||||
assert starts(rebase(texts, [0, 60000, 120000])[1]) == ["00:01:40.000"]
|
||||
|
||||
|
||||
def test_a_cue_carried_over_a_short_block_is_not_a_restart() -> None:
|
||||
carried = "WEBVTT\n\n00:00:01.000 --> 00:00:08.000\nt\n\n00:00:20.000 --> 00:00:21.000\nt\n"
|
||||
texts = [block("00:00:01.000"), carried]
|
||||
@@ -53,10 +42,6 @@ def test_local_time_marks_the_block_start() -> None:
|
||||
assert starts(rebase(texts, [0, 60000, 120000])[1]) == ["00:01:02.000"]
|
||||
|
||||
|
||||
def test_shift_clamps_at_zero() -> None:
|
||||
assert starts(shift_webvtt(block("00:00:01.000"), -5000)) == ["00:00:00.000"]
|
||||
|
||||
|
||||
def test_discontinuity_files_are_rewritten(tmp_path: Path) -> None:
|
||||
segments = [SimpleNamespace(discontinuity=d, duration=t) for d, t in ((True, 5), (False, 5), (True, 5))]
|
||||
files = [tmp_path / "0.vtt", tmp_path / "1.vtt"]
|
||||
|
||||
@@ -82,12 +82,6 @@ def licensed(cdm: StubCdm, *kids: UUID) -> dict[UUID, str]:
|
||||
return {k.kid: k.key.hex() for k in cdm.get_keys(session_id, "CONTENT")}
|
||||
|
||||
|
||||
def test_cached_keys_covering_every_kid_need_no_licence() -> None:
|
||||
cdm = StubCdm(cached=[key(KID_A, KEY_A)])
|
||||
assert licensed(cdm, KID_A) == {KID_A: KEY_A}
|
||||
assert cdm.bodies == []
|
||||
|
||||
|
||||
def test_partial_cached_keys_merge_with_the_licence() -> None:
|
||||
cdm = StubCdm(cached=[key(KID_A, KEY_A)], licence=[key(KID_A, KEY_X), key(KID_B, KEY_B)])
|
||||
assert licensed(cdm, KID_A, KID_B) == {KID_A: KEY_A, KID_B: KEY_B}
|
||||
|
||||
@@ -13,7 +13,6 @@ from unshackle.core.mux_step import hybrid_source_tracks
|
||||
from unshackle.core.tracks import Video
|
||||
from unshackle.core.tracks import dv_fixup as dv_fixup_mod
|
||||
from unshackle.core.tracks.dv_fixup import apply_dv_fixup
|
||||
from unshackle.core.tracks.selection import select_hybrid_bases
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
@@ -72,15 +71,3 @@ def test_hybrid_step_reads_the_container_after_the_fixup(fake_demux: None, tmp_p
|
||||
assert base.path == tmp_path / "base.dv.hevc"
|
||||
assert hybrid_base.path == tmp_path / "base.mp4"
|
||||
assert hybrid_dv.path == dv.path
|
||||
|
||||
|
||||
def test_one_hybrid_base_for_each_height(tmp_path: Path) -> None:
|
||||
videos = [
|
||||
fake_video(tmp_path, "sdr", Video.Range.SDR, 1080),
|
||||
fake_video(tmp_path, "low", Video.Range.HDR10, 1080),
|
||||
fake_video(tmp_path, "high", Video.Range.HDR10P, 2160),
|
||||
fake_video(tmp_path, "high2", Video.Range.HDR10, 2160),
|
||||
fake_video(tmp_path, "dv", Video.Range.DV, 2160),
|
||||
]
|
||||
|
||||
assert [v.id for v in select_hybrid_bases(videos)] == ["high", "low"]
|
||||
|
||||
@@ -5,11 +5,8 @@ dovi_tool, hdr10plus_tool or FFmpeg."""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import gc
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import weakref
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
@@ -24,7 +21,6 @@ from unshackle.core import mux_step, temp
|
||||
from unshackle.core.api import download_manager, handlers, key_policy
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.mux_step import hybrid_plan, hybrid_source_tracks, hybrid_step_error, missing_hybrid_error
|
||||
from unshackle.core.run_plan import session_request
|
||||
from unshackle.core.service import Service, TrackRequest
|
||||
from unshackle.core.services import Services
|
||||
from unshackle.core.tracks import Audio, Chapter, Subtitle, Tracks, Video
|
||||
@@ -36,13 +32,11 @@ from unshackle.core.tracks.hybrid import (
|
||||
hdr10plus_shots,
|
||||
measured_shots,
|
||||
nits_to_pq,
|
||||
pq_to_nits,
|
||||
)
|
||||
from unshackle.core.tracks.selection import (
|
||||
generated_dv_ranges,
|
||||
hybrid_gate_failure,
|
||||
keep_generated_dv_bases,
|
||||
select_hybrid_bases,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
@@ -91,13 +85,6 @@ def test_pq_matches_the_st2084_reference_points() -> None:
|
||||
assert round(nits_to_pq(0)) == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("active", [1.0, 0.75])
|
||||
def test_a_flat_histogram_averages_to_its_own_level(active: float) -> None:
|
||||
values = {index: 120.0 for index in INDEXES}
|
||||
mean = hdr10plus_mean_pq(values, active)
|
||||
assert mean is not None and mean == pytest.approx(nits_to_pq(120.0))
|
||||
|
||||
|
||||
def test_the_slots_outside_the_distribution_do_not_move_the_mean() -> None:
|
||||
"""Index 5 is a luminance-Y value and index 10 a pixel share, so neither is a maxRGB percentile."""
|
||||
base = hdr10plus_mean_pq(histogram({5: 50.0, 10: 50.0}))
|
||||
@@ -131,18 +118,6 @@ def test_a_scene_with_no_black_pixels_keeps_its_whole_frame() -> None:
|
||||
assert hdr10plus_mean_pq(full_frame, 0.75) == hdr10plus_mean_pq(full_frame, 1.0)
|
||||
|
||||
|
||||
def test_a_ten_slot_histogram_uses_the_same_lookup() -> None:
|
||||
nine = histogram({99: 300.0})
|
||||
ten = {**nine, 98: 250.0}
|
||||
assert hdr10plus_mean_pq(ten) == hdr10plus_mean_pq(nine)
|
||||
|
||||
|
||||
def test_a_histogram_without_a_distribution_slot_has_no_mean() -> None:
|
||||
values = histogram({})
|
||||
del values[75]
|
||||
assert hdr10plus_mean_pq(values) is None
|
||||
|
||||
|
||||
def test_each_scene_becomes_one_shot_with_its_own_cut() -> None:
|
||||
meta = metadata([(3, histogram({99: 200.0})), (5, histogram({99: 800.0}))], first_frame=1000)
|
||||
|
||||
@@ -277,61 +252,6 @@ def test_active_area_share(top: int, expected: float | None, quiet: None, monkey
|
||||
assert area[1] == pytest.approx(expected)
|
||||
|
||||
|
||||
def test_each_crop_sample_evaluates_enough_frames(quiet: None, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""cropdetect ignores its first two frames (skip=2) and only grows the picture over the rest."""
|
||||
cropdetect_calls: list[list[str]] = []
|
||||
|
||||
def fake_run(args: list[Any], **kwargs: Any) -> SimpleNamespace:
|
||||
if "format=duration" in args:
|
||||
return SimpleNamespace(returncode=0, stdout='{"format": {"duration": "100"}}', stderr="")
|
||||
if "stream=width,height" in args:
|
||||
return SimpleNamespace(returncode=0, stdout='{"streams": [{"width": 3840, "height": 2160}]}', stderr="")
|
||||
cropdetect_calls.append([str(a) for a in args])
|
||||
return SimpleNamespace(returncode=0, stdout="", stderr="crop=3840:1600:0:280")
|
||||
|
||||
monkeypatch.setattr(hybrid_mod.subprocess, "run", fake_run)
|
||||
|
||||
make_hybrid().detect_active_area(Path("base.mkv"))
|
||||
|
||||
assert cropdetect_calls
|
||||
for args in cropdetect_calls:
|
||||
filtergraph = args[args.index("-vf") + 1]
|
||||
skip_match = re.search(r"skip=(\d+)", filtergraph)
|
||||
skip = int(skip_match.group(1)) if skip_match else 2
|
||||
assert int(args[args.index("-vframes") + 1]) - skip >= 8
|
||||
|
||||
|
||||
def test_the_parsed_metadata_is_released_before_dovi_tool_runs(
|
||||
quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
"""hdr10plus_tool writes one entry per frame, so a film's parsed JSON is hundreds of MB of objects."""
|
||||
|
||||
class Tracked(dict): # type: ignore[type-arg]
|
||||
pass
|
||||
|
||||
(tmp_path / "HDR10Plus.json").write_text(json.dumps(metadata([(2, histogram({}))])))
|
||||
hybrid = make_hybrid()
|
||||
monkeypatch.setattr(hybrid, "probe_hdr_metadata", lambda: (1000, 1, 0, 0))
|
||||
real_load = json.load
|
||||
refs: list[weakref.ReferenceType[Tracked]] = []
|
||||
|
||||
def tracked_load(fp: Any) -> Tracked:
|
||||
loaded = Tracked(real_load(fp))
|
||||
refs.append(weakref.ref(loaded))
|
||||
return loaded
|
||||
|
||||
def fake_generate(config_json: Path, output: Path, **kwargs: Any) -> bytes:
|
||||
gc.collect()
|
||||
assert refs and refs[0]() is None, "the parsed HDR10+ metadata is still alive"
|
||||
output.write_bytes(b"rpu")
|
||||
return b""
|
||||
|
||||
monkeypatch.setattr(hybrid_mod.json, "load", tracked_load)
|
||||
monkeypatch.setattr(hybrid_mod.dovi, "generate", fake_generate)
|
||||
|
||||
hybrid.convert_hdr10plus_to_dv()
|
||||
|
||||
|
||||
def test_conversion_writes_a_cm29_config_with_shots_and_cleans_up(
|
||||
quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
@@ -525,11 +445,6 @@ def test_two_frame_rates_make_no_hybrid(base: str | None, dv: str, refused: bool
|
||||
Hybrid.check_base(*tracks)
|
||||
|
||||
|
||||
def test_a_raw_stream_has_no_frame_rate_to_compare() -> None:
|
||||
base = hybrid_track(Path("b.hevc"), Video.Range.HDR10, avg_frame_rate="25/1")
|
||||
Hybrid.check_base(base, hybrid_track(Path("d.mp4"), Video.Range.DV, avg_frame_rate="24/1"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"probe",
|
||||
[{"transfer": "arib-std-b67"}, {"side_data_list": [{"dv_profile": 8, "dv_bl_signal_compatibility_id": 4}]}],
|
||||
@@ -540,16 +455,6 @@ def test_an_hlg_dv_track_makes_no_hybrid(probe: dict[str, Any]) -> None:
|
||||
Hybrid.check_base(base, hybrid_track(Path("d.mp4"), Video.Range.DV, **probe))
|
||||
|
||||
|
||||
def test_vivid_is_the_last_choice_of_hybrid_base_and_takes_no_generate_dv_range() -> None:
|
||||
videos = [
|
||||
video("v2160", Video.Range.VIVID),
|
||||
video("h2160", Video.Range.HDR10),
|
||||
video("v1080", Video.Range.VIVID, 1080),
|
||||
]
|
||||
assert [v.id for v in select_hybrid_bases(videos)] == ["h2160", "v1080"]
|
||||
assert generated_dv_ranges([Video.Range.VIVID], True) == ([Video.Range.VIVID], [])
|
||||
|
||||
|
||||
def test_an_hdr10plus_label_without_metadata_is_measured(
|
||||
quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
@@ -605,11 +510,6 @@ def test_a_cut_on_the_first_frame_or_inside_a_flash_burst_opens_no_shot() -> Non
|
||||
assert [(s["start"], s["duration"]) for s in shots] == [(0, 12), (12, 12), (24, 1)]
|
||||
|
||||
|
||||
def test_pq_to_nits_is_the_inverse_of_nits_to_pq() -> None:
|
||||
for nits in (0.005, 1.0, 100.0, 1000.0, 10000.0):
|
||||
assert pq_to_nits(nits_to_pq(nits)) == pytest.approx(nits, rel=1e-6)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream, expected", [((0, 0), (1000, 400)), ((800, 200), (800, 200))])
|
||||
def test_measured_light_levels_fill_only_what_the_stream_does_not_state(
|
||||
stream: tuple[int, int], expected: tuple[int, int], quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
@@ -700,19 +600,6 @@ def test_a_base_range_with_the_flag_runs_as_a_hybrid_of_that_base_alone() -> Non
|
||||
assert hybrid_gate_failure(keep_generated_dv_bases(videos, [R.HDR10]), True) is None
|
||||
|
||||
|
||||
def test_hdr10plus_is_the_base_before_hdr10_at_one_height() -> None:
|
||||
videos = [video("h", Video.Range.HDR10), video("p", Video.Range.HDR10P), video("h1080", Video.Range.HDR10, 1080)]
|
||||
assert [v.id for v in hybrid_plan(videos, True)[0]] == ["p", "h1080"]
|
||||
assert [v.id for v in select_hybrid_bases(videos[::-1])] == ["p", "h1080"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("to_dv", [False, True])
|
||||
def test_an_hdr10_base_without_dv_is_planned_only_with_the_flag(to_dv: bool) -> None:
|
||||
videos = [video("h", Video.Range.HDR10)]
|
||||
assert (hybrid_gate_failure(videos, to_dv) is None) is to_dv
|
||||
assert [v.id for v in hybrid_plan(videos, to_dv)[0]] == (["h"] if to_dv else [])
|
||||
|
||||
|
||||
def test_a_failed_resolution_removes_its_crop_edits_and_keeps_the_dv_files(
|
||||
quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
@@ -830,13 +717,6 @@ def test_a_title_without_a_hybrid_file_fails() -> None:
|
||||
assert missing_hybrid_error(bases, 0) == ("Every hybrid failed (2160p, 1080p), so the title has no hybrid file")
|
||||
|
||||
|
||||
def test_only_hevc_tracks_are_hybrid_bases() -> None:
|
||||
av1 = SimpleNamespace(id="av1", height=2160, range=Video.Range.HDR10P, codec=Video.Codec.AV1)
|
||||
hevc = SimpleNamespace(id="hevc", height=1080, range=Video.Range.HDR10P, codec=Video.Codec.HEVC)
|
||||
|
||||
assert [v.id for v in select_hybrid_bases([av1, hevc])] == ["hevc"] # type: ignore[list-item]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"dv_available, to_dv, hdr10_gives, fetched, kept",
|
||||
[
|
||||
@@ -925,12 +805,6 @@ def test_a_rest_job_gives_the_flag_to_the_service_ctx_and_to_dl(
|
||||
assert exc.value.args == (to_dv, to_dv)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("to_dv", [False, True])
|
||||
def test_the_remote_client_forwards_the_flag_only_when_set(to_dv: bool) -> None:
|
||||
data = session_request({"generate_dv": to_dv}, {})
|
||||
assert data.get("generate_dv", False) is to_dv
|
||||
|
||||
|
||||
@pytest.mark.parametrize("to_dv", [False, True])
|
||||
def test_a_remote_session_puts_the_flag_in_the_service_ctx(monkeypatch: pytest.MonkeyPatch, to_dv: bool) -> None:
|
||||
seen: dict[str, Any] = {}
|
||||
@@ -967,12 +841,6 @@ def test_hybrid_fails_with_neither_a_base_nor_dv() -> None:
|
||||
assert hybrid_gate_failure([], True) == "HYBRID needs HDR10/HDR10+/VIVID and DV tracks, available ranges: none"
|
||||
|
||||
|
||||
def test_hybrid_fails_with_dv_only() -> None:
|
||||
assert hybrid_gate_failure([video("dv", Video.Range.DV)], True) == (
|
||||
"HYBRID needs HDR10/HDR10+/VIVID and DV tracks, available ranges: DV"
|
||||
)
|
||||
|
||||
|
||||
def test_hybrid_goes_on_without_dv_when_the_flag_has_an_hdr10plus_base() -> None:
|
||||
assert hybrid_gate_failure([video("p", Video.Range.HDR10P), video("h", Video.Range.HDR10)], True) is None
|
||||
|
||||
|
||||
@@ -101,12 +101,6 @@ def test_probe_falls_back_on_failed_ffprobe(monkeypatch: pytest.MonkeyPatch) ->
|
||||
assert make_hybrid().probe_hdr_metadata() == (1000, 1, 0, 0)
|
||||
|
||||
|
||||
def test_probe_falls_back_on_garbage_output(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
patch_probe_run(monkeypatch, FakeCompleted(0, "not json at all"))
|
||||
|
||||
assert make_hybrid().probe_hdr_metadata() == (1000, 1, 0, 0)
|
||||
|
||||
|
||||
def rpu_info(max_cll: int, max_fall: int, max_mdl: int, min_mdl: int) -> dict:
|
||||
return {
|
||||
"vdr_dm_data": {
|
||||
|
||||
@@ -62,17 +62,6 @@ def _provider(monkeypatch: pytest.MonkeyPatch, responses: list[dict]) -> tuple[I
|
||||
NOT_FOUND = {"errors": [{"message": "PersistedQueryNotFound", "extensions": {"code": "PERSISTED_QUERY_NOT_FOUND"}}]}
|
||||
|
||||
|
||||
def test_is_available_without_any_key() -> None:
|
||||
assert IMDBProvider().is_available() is True
|
||||
|
||||
|
||||
def test_cache_hit_uses_one_get(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
p, session = _provider(monkeypatch, [{"data": {"title": node()}}])
|
||||
result = p.get_by_id("tt3581920", "tv")
|
||||
assert result is not None and result.title == "The Last of Us"
|
||||
assert len(session.gets) == 1 and session.posts == []
|
||||
|
||||
|
||||
def test_persisted_query_miss_falls_back_to_one_post(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
p, session = _provider(monkeypatch, [NOT_FOUND, {"data": {"title": node()}}])
|
||||
result = p.get_by_id("tt3581920", "tv")
|
||||
@@ -128,15 +117,6 @@ def test_search_uses_its_own_operation_and_one_get_on_a_cache_hit(monkeypatch: p
|
||||
assert session.posts == []
|
||||
|
||||
|
||||
def test_search_query_text_carries_the_constraints(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
p, session = _provider(monkeypatch, [NOT_FOUND, edges(node())])
|
||||
p.search("The Last of Us", 2023, "tv")
|
||||
query = session.posts[0]["query"]
|
||||
assert 'searchTerm: "The Last of Us"' in query
|
||||
assert 'start: "2023-01-01", end: "2023-12-31"' in query
|
||||
assert '["tvSeries", "tvMiniSeries"]' in query or '["tvSeries","tvMiniSeries"]' in query
|
||||
|
||||
|
||||
def test_search_omits_the_year_range_when_unknown(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
p, session = _provider(monkeypatch, [NOT_FOUND, edges(node(title_type="movie"))])
|
||||
p.search("Inception", None, "movie")
|
||||
@@ -197,12 +177,6 @@ def test_a_trailing_number_that_is_not_the_year_stays_in_the_search_term(monkeyp
|
||||
assert 'searchTerm: "EXAMPLE 2049"' in session.posts[0]["query"]
|
||||
|
||||
|
||||
def test_a_hit_in_the_year_does_not_retry(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
p, session = _provider(monkeypatch, [edges(node())])
|
||||
assert p.search("The Last of Us", 2023, "tv") is not None
|
||||
assert len(session.gets) == 1
|
||||
|
||||
|
||||
def test_search_term_drops_a_year_suffix(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
p, session = _provider(monkeypatch, [NOT_FOUND, edges(node())])
|
||||
assert p.search("The Last of Us (2023)", 2023, "tv") is not None
|
||||
@@ -217,7 +191,3 @@ def test_search_term_with_a_quote_stays_inside_the_string(monkeypatch: pytest.Mo
|
||||
p, session = _provider(monkeypatch, [NOT_FOUND, edges(node(text='The "Best" Show'))])
|
||||
p.search('The "Best" Show', None, "tv")
|
||||
assert 'searchTerm: "The \\"Best\\" Show"' in session.posts[0]["query"]
|
||||
|
||||
|
||||
def test_get_external_ids_echoes_the_id() -> None:
|
||||
assert IMDBProvider().get_external_ids("tt1375666", "movie").imdb_id == "tt1375666"
|
||||
|
||||
@@ -167,21 +167,6 @@ def test_hls_import_never_refetches_the_master_playlist(tmp_path: Path, monkeypa
|
||||
assert len(list(tracks)) == 4
|
||||
|
||||
|
||||
def test_hls_tracks_tolerate_the_empty_manifest_data(tmp_path: Path) -> None:
|
||||
"""HLS.download_track assigns into track.data["hls"] without creating it first.
|
||||
|
||||
Track.data is a defaultdict, so the assignment auto-vivifies rather than raising. Pin that,
|
||||
because a plain dict here would turn every HLS import into a KeyError mid-download.
|
||||
"""
|
||||
original = HLS.from_text(HLS_MANIFEST, HLS_URL).to_tracks(language="en")
|
||||
_, tracks = import_tracks(export_tracks(tmp_path, original, HLS_URL))
|
||||
|
||||
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
|
||||
assert track.data["hls"]["segment_durations"] == [1, 2, 3]
|
||||
|
||||
|
||||
def test_hls_round_trip_keeps_the_dropped_segments(tmp_path: Path) -> None:
|
||||
"""An import has no service to run the segment filter, so the export carries the dropped URIs."""
|
||||
original = HLS.from_text(HLS_MANIFEST, HLS_URL).to_tracks(language="en")
|
||||
|
||||
@@ -17,8 +17,6 @@ import pytest
|
||||
from pywidevine.pssh import PSSH
|
||||
|
||||
from tests.core.key_resolver import key_table, resolver, vaults_of
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core import temp
|
||||
from unshackle.core.drm import Widevine, key_resolution
|
||||
from unshackle.core.drm.key_resolution import ContentKeyResolver
|
||||
from unshackle.core.import_service import ImportService
|
||||
@@ -117,13 +115,3 @@ def test_the_retry_after_a_bad_vault_key_ends_in_the_import_error(
|
||||
assert calls == ["licence"]
|
||||
assert drm.decrypted_with == [{KID: BAD, OTHER: OTHER_KEY}]
|
||||
assert not (tmp_path / "video.mp4.enc").exists()
|
||||
|
||||
|
||||
def test_a_download_stopped_by_a_click_exception_reports_only_its_message(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(temp, "LOW_FREE_SPACE", 0)
|
||||
error = ImportService.missing_key(SimpleNamespace(drm=[FakeDRM({})]))
|
||||
|
||||
lines = dl.failure_lines(error)
|
||||
|
||||
assert lines == [":x: Download Failed...", f" {error.format_message()}"]
|
||||
assert dl.failure_lines(ValueError("boom")) == [":x: Download Failed...", " ValueError: boom"]
|
||||
|
||||
@@ -124,13 +124,6 @@ def test_original_language_track_gives_the_title_language(tmp_path: Path) -> Non
|
||||
assert str(next(iter(service.get_titles())).language) == "de"
|
||||
|
||||
|
||||
def test_exported_url_subtitles_replace_the_manifests(tmp_path: Path) -> None:
|
||||
"""Services drop the manifest's subtitles and side-load their own; importing both duplicates them."""
|
||||
tracks = get_tracks(make_service(tmp_path, "ja", {"sideloaded-en": URL_SUBTITLE}), MPD_WITH_LANG)
|
||||
assert [(t.id, t.descriptor.name) for t in tracks.subtitles] == [("sideloaded-en", "URL")]
|
||||
assert len(tracks.videos) == 1
|
||||
|
||||
|
||||
def test_direct_url_subtitles_win_over_every_manifest_one(tmp_path: Path) -> None:
|
||||
"""One side-loaded subtitle condemns the whole re-parsed set, including other languages."""
|
||||
manifest_sub = {
|
||||
@@ -291,13 +284,6 @@ def test_each_file_track_gets_only_the_keys_for_its_kids(tmp_path: Path) -> None
|
||||
assert not tracks.subtitles[0].drm
|
||||
|
||||
|
||||
def test_a_file_row_can_name_its_codec_and_range_by_name(tmp_path: Path) -> None:
|
||||
row = {"id": "v", "type": "video", "url": "https://example.invalid/v.mp4", "codec": "hevc", "range": "hdr10p"}
|
||||
service = file_export(tmp_path, [row])
|
||||
video = service.get_tracks(next(iter(service.get_titles()))).videos[0]
|
||||
assert (video.codec, video.range) == (Video.Codec.HEVC, Video.Range.HDR10P)
|
||||
|
||||
|
||||
def test_a_file_row_marked_stereo_imports_as_a_3d_video(tmp_path: Path) -> None:
|
||||
service = file_export(tmp_path, [{**FILE_ROWS[0], "stereo": True}])
|
||||
assert service.get_tracks(next(iter(service.get_titles()))).videos[0].stereo
|
||||
|
||||
@@ -89,12 +89,6 @@ def top_level_boxes(data: bytes) -> list[tuple[str, int]]:
|
||||
return boxes
|
||||
|
||||
|
||||
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]
|
||||
|
||||
|
||||
def test_hevc_init_structure():
|
||||
init = build_init_segment(
|
||||
stream_type="video",
|
||||
@@ -196,32 +190,6 @@ def test_stsd_carries_two_entries_for_sample_description_index_2(stream_type, fo
|
||||
walk_box(init, 0, len(init))
|
||||
|
||||
|
||||
def test_avc_init_structure():
|
||||
init = build_init_segment(
|
||||
stream_type="video",
|
||||
fourcc="H264",
|
||||
codec_private_data=VIDEO_AVC_CPD,
|
||||
timescale=10000000,
|
||||
width=1280,
|
||||
height=720,
|
||||
)
|
||||
assert init[4:8] == b"ftyp"
|
||||
assert b"avcC" in init and b"avc1" in init
|
||||
|
||||
|
||||
def test_aac_audio_init_structure():
|
||||
init = build_init_segment(
|
||||
stream_type="audio",
|
||||
fourcc="AACL",
|
||||
codec_private_data=AAC_LC_CPD,
|
||||
timescale=10000000,
|
||||
channels=2,
|
||||
sampling_rate=48000,
|
||||
)
|
||||
assert b"mp4a" in init and b"esds" in init
|
||||
assert b"smhd" in init # sound media header, not video
|
||||
|
||||
|
||||
def test_encrypted_init_has_cenc_boxes():
|
||||
init = build_init_segment(
|
||||
stream_type="video",
|
||||
@@ -328,40 +296,6 @@ def test_aac_init_without_codec_private_data_synthesizes_asc():
|
||||
assert bytes.fromhex(AAC_LC_CPD) in init
|
||||
|
||||
|
||||
def test_dolby_vision_uses_dvh1_sample_entry():
|
||||
init = build_init_segment(
|
||||
stream_type="video",
|
||||
fourcc="DVH1",
|
||||
codec_private_data=VIDEO_HEVC_CPD,
|
||||
timescale=10000000,
|
||||
width=3840,
|
||||
height=1600,
|
||||
)
|
||||
assert b"dvh1" in init and b"hvcC" in init
|
||||
assert b"hvc1" not in init
|
||||
|
||||
|
||||
def test_davc_maps_to_avc1():
|
||||
init = build_init_segment(
|
||||
stream_type="video",
|
||||
fourcc="DAVC",
|
||||
codec_private_data=VIDEO_AVC_CPD,
|
||||
timescale=10000000,
|
||||
)
|
||||
assert b"avc1" in init and b"avcC" in init
|
||||
|
||||
|
||||
def test_lowercase_fourcc_normalized():
|
||||
# Real manifests ship FourCC="hvc1" in lowercase.
|
||||
init = build_init_segment(
|
||||
stream_type="video",
|
||||
fourcc="hvc1",
|
||||
codec_private_data=VIDEO_HEVC_CPD,
|
||||
timescale=10000000,
|
||||
)
|
||||
assert b"hvcC" in init
|
||||
|
||||
|
||||
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
|
||||
@@ -390,20 +324,6 @@ def test_hvcc_signals_10bit_from_sps():
|
||||
assert payload[18] == 0xF8 | 0x02 # bitDepthChromaMinus8 = 2
|
||||
|
||||
|
||||
def test_ttml_init_structure():
|
||||
init = build_init_segment(
|
||||
stream_type="text",
|
||||
fourcc="TTML",
|
||||
codec_private_data="",
|
||||
timescale=10000000,
|
||||
language="eng",
|
||||
)
|
||||
assert b"stpp" in init
|
||||
assert b"sthd" in init # subtitle media header
|
||||
assert b"subt" in init and b"SubtitleHandler\0" in init
|
||||
assert b"http://www.w3.org/ns/ttml\0" in init
|
||||
|
||||
|
||||
def test_constant_iv_tenc_form():
|
||||
constant_iv = bytes(range(16))
|
||||
init = build_init_segment(
|
||||
@@ -455,19 +375,6 @@ def test_iv_size_undetermined_returns_none():
|
||||
assert read_per_sample_iv_size(make_fragment()) is 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
|
||||
|
||||
|
||||
def test_avcc_requires_sps_and_pps():
|
||||
with pytest.raises(ValueError):
|
||||
build_avcc(b"\x00\x00\x00\x01\x67only_sps")
|
||||
|
||||
|
||||
def test_read_track_id_from_fragment():
|
||||
# Minimal moof/traf/tfhd carrying track_ID = 7.
|
||||
tfhd = full_box(b"tfhd", 0, 0, struct.pack(">I", 7) + b"\x00" * 4)
|
||||
@@ -477,10 +384,6 @@ def test_read_track_id_from_fragment():
|
||||
assert read_track_id(moof + mdat) == 7
|
||||
|
||||
|
||||
def test_read_track_id_missing_returns_none():
|
||||
assert read_track_id(box(b"mdat", b"\x00\x00")) is 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"
|
||||
@@ -490,52 +393,6 @@ def test_remove_emulation_prevention():
|
||||
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",
|
||||
fourcc="AACL",
|
||||
codec_private_data=AAC_LC_CPD,
|
||||
timescale=10000000,
|
||||
language=lang,
|
||||
)
|
||||
assert init[4:8] == b"ftyp"
|
||||
|
||||
|
||||
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",
|
||||
codec_private_data="",
|
||||
timescale=10000000,
|
||||
sampling_rate=96000,
|
||||
)
|
||||
assert b"mp4a" in init
|
||||
|
||||
|
||||
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
|
||||
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)
|
||||
|
||||
|
||||
def test_parse_colour_hevc_hlg():
|
||||
assert parse_codec_private_data_colour("HVC1", bytes.fromhex(VIDEO_HEVC_HLG_CPD)) == (9, 18, 9)
|
||||
|
||||
|
||||
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)
|
||||
@@ -732,33 +589,6 @@ def text_fragment(seq: int, begin: str, end: str, text: str, sdi: int) -> bytes:
|
||||
return box(b"moof", mfhd + box(b"traf", tfhd + tfdt + trun)) + box(b"mdat", payload)
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
@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),
|
||||
"text": dict(fourcc="TTML", codec_private_data=""),
|
||||
}[stream_type]
|
||||
init = build_init_segment(stream_type=stream_type, duration=6_000_000_000, language="eng", **kwargs)
|
||||
|
||||
sizes = {}
|
||||
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(
|
||||
@@ -770,20 +600,6 @@ def test_tkhd_carries_video_dimensions():
|
||||
assert (width >> 16, height >> 16) == (1920, 1080)
|
||||
|
||||
|
||||
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
|
||||
|
||||
init = build_init_segment(
|
||||
stream_type="text", fourcc="TTML", codec_private_data="", duration=6_000_000_000, language="eng"
|
||||
)
|
||||
data = init + text_fragment(1, "00:00:01.000", "00:00:02.000", "first", sdi=1)
|
||||
types = [b.type for b in MP4.parse_stream(BytesIO(data))]
|
||||
assert types == [b"ftyp", b"moov", b"moof", b"mdat"]
|
||||
|
||||
|
||||
def test_fttml_subtitle_parse_yields_cues():
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
|
||||
|
||||
@@ -2,13 +2,11 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.core.test_rolling_merge_hls_ism import base, ism_track, make_ctx
|
||||
from tests.core.test_rolling_merge_hls_ism import base, make_ctx
|
||||
from tests.core.test_rolling_merge_hls_ism import no_cancel as no_cancel # noqa: F401
|
||||
from tests.core.test_rolling_merge_hls_ism import server as server # noqa: F401
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.manifests import ISM
|
||||
from unshackle.core.manifests import ism as ism_module
|
||||
from unshackle.core.tracks.segment_store import SegmentStore
|
||||
|
||||
CUES = [b"1\n00:00:00,000 --> 00:00:01,000\n‎one\n\n", b"2\n00:00:02,000 --> 00:00:03,000\n‏two\n\n"]
|
||||
|
||||
@@ -41,14 +39,3 @@ def test_a_text_subtitle_merges_behind_its_init_with_the_entities_as_characters(
|
||||
assert ctx.save_path.read_bytes() == b"INIT" + b"".join(CUES).replace(b"‎", "\u200e".encode()).replace(
|
||||
b"‏", "\u200f".encode()
|
||||
)
|
||||
|
||||
|
||||
def test_the_rolling_merge_ends_the_download_phase_before_it_checks_the_count(server, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(config, "merge_segments", True)
|
||||
calls: list[str] = []
|
||||
monkeypatch.setattr(SegmentStore, "merging", lambda self: calls.append("merging"))
|
||||
monkeypatch.setattr(ism_module, "check_merged", lambda *args: calls.append("check_merged"))
|
||||
|
||||
ISM.download_track(ism_track(server), make_ctx(tmp_path, "audio.mp4"))
|
||||
|
||||
assert calls == ["merging", "check_merged"]
|
||||
|
||||
@@ -47,20 +47,9 @@ def test_colourless_codec_private_data_defaults_sdr() -> None:
|
||||
assert parse_video(VIDEO_HEVC10_CPD).range == Video.Range.SDR
|
||||
|
||||
|
||||
def test_get_video_range_dolby_vision_fourcc() -> None:
|
||||
assert ISM.get_video_range("DVH1", VIDEO_HEVC_PQ_CPD) == Video.Range.DV
|
||||
assert ISM.get_video_range("DVHE", "") == Video.Range.DV
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_get_video_range_malformed_data_soft_fails_sdr() -> None:
|
||||
assert ISM.get_video_range("HVC1", "not-hex") == Video.Range.SDR
|
||||
assert ISM.get_video_range("HVC1", "") == Video.Range.SDR
|
||||
assert ISM.get_video_range("", VIDEO_HEVC_PQ_CPD) == Video.Range.SDR
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from langcodes import Language
|
||||
|
||||
from unshackle.core.utilities import matched_language_tags, partition_exclusions
|
||||
from unshackle.core.utils.click_types import LANGUAGE_RANGE
|
||||
@@ -28,15 +27,6 @@ def test_partition_keeps_the_written_order_and_drops_repeats():
|
||||
assert partition_exclusions(["ja", "en", "ja", "-es", "-es"]) == (["ja", "en"], ["es"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("token", ["-", " - ", "", " "])
|
||||
def test_partition_skips_tokens_with_no_value(token):
|
||||
assert partition_exclusions(["en", token]) == (["en"], [])
|
||||
|
||||
|
||||
def test_partition_trims_whitespace_around_a_token():
|
||||
assert partition_exclusions([" en ", "- es "]) == (["en"], ["es"])
|
||||
|
||||
|
||||
def test_partition_reads_the_tokens_language_range_produces():
|
||||
assert partition_exclusions(LANGUAGE_RANGE.convert("all,-es;-fr")) == (["all"], ["es", "fr"])
|
||||
|
||||
@@ -59,21 +49,5 @@ def test_exact_match_falls_back_to_the_paradigm_variant():
|
||||
assert matched_language_tags(["es"], ["es-ES", "es-419"], exact=True) == {"es-ES"}
|
||||
|
||||
|
||||
def test_exact_match_keeps_an_unnamed_regional_variant():
|
||||
assert matched_language_tags(["es-ES"], ["es-ES", "es-419"], exact=True) == {"es-ES"}
|
||||
|
||||
|
||||
def test_language_objects_are_accepted():
|
||||
assert matched_language_tags(["es"], [Language.get("es")]) == {"es"}
|
||||
|
||||
|
||||
def test_an_untagged_track_is_never_excluded():
|
||||
assert matched_language_tags(["es"], [None, "en-US"]) == set()
|
||||
|
||||
|
||||
def test_no_exclusions_excludes_nothing():
|
||||
assert matched_language_tags([], ["es-419", "en-US"]) == set()
|
||||
|
||||
|
||||
def test_an_unmatched_language_is_kept():
|
||||
assert matched_language_tags(["es", "fr"], ["en-US", "ja-JP"]) == set()
|
||||
|
||||
@@ -43,11 +43,6 @@ def test_audio_contain_all_tags_a_release_with_every_listed_language() -> None:
|
||||
assert evaluate_language_tag(rules, [en, fr_fr], []) == "VFF"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("condition", ["audio_contain_all", "subs_contain_all"])
|
||||
def test_an_empty_contain_all_list_matches_nothing(condition) -> None:
|
||||
assert evaluate_language_tag([{condition: [], "tag": "ALL"}], JA, EN_ES) == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["japanese", 1, [["ja"]], {"ja": 1}])
|
||||
def test_an_invalid_rule_value_is_no_match_not_a_crash(bad, caplog) -> None:
|
||||
rules = [{"audio": bad, "tag": "BAD"}, {"audio": "ja", "tag": "OK"}]
|
||||
@@ -77,14 +72,6 @@ def test_a_state_condition_combines_with_a_language() -> None:
|
||||
assert evaluate_language_tag(rules, JA, [], states) == "DUAL"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["yes", "false", 1])
|
||||
def test_a_non_boolean_state_value_skips_the_rule(bad, caplog) -> None:
|
||||
rules = [{"dubbed": bad, "tag": "BAD"}, {"audio": "ja", "tag": "OK"}]
|
||||
assert evaluate_language_tag(rules, JA, [], {"dubbed": True}) == "OK"
|
||||
assert evaluate_language_tag(rules, JA, [], {"dubbed": False}) == "OK"
|
||||
assert "must be true or false" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("typo", ["dubed", "subs_contains"])
|
||||
def test_a_typo_in_a_condition_name_skips_the_rule(typo, caplog) -> None:
|
||||
rules = [{"audio": "ja", typo: True, "tag": "BAD"}, {"audio": "ja", "tag": "OK"}]
|
||||
|
||||
@@ -12,7 +12,6 @@ import click
|
||||
import pytest
|
||||
from pywidevine.pssh import PSSH
|
||||
from rich.table import Table
|
||||
from rich.tree import Tree
|
||||
|
||||
from tests.core.key_resolver import MemoryVault, key_table, resolver, vaults_of
|
||||
from tests.core.test_all_drm import playready
|
||||
@@ -53,19 +52,6 @@ def licences(monkeypatch: pytest.MonkeyPatch) -> Licences:
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
|
||||
|
||||
class TrackVault(MemoryVault):
|
||||
"""An empty key vault; a lookup by the second track sets ``looked_up``."""
|
||||
|
||||
def __init__(self, looked_up: threading.Event) -> None:
|
||||
super().__init__()
|
||||
self.looked_up = looked_up
|
||||
|
||||
def get_key(self, kid: UUID | str, service: str) -> str | None:
|
||||
if threading.current_thread().name == "track-1":
|
||||
self.looked_up.set()
|
||||
return super().get_key(kid, service)
|
||||
|
||||
|
||||
def widevine(*kids: UUID) -> Widevine:
|
||||
return Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=list(kids)))
|
||||
|
||||
@@ -74,41 +60,6 @@ def prepare(keys: ContentKeyResolver, drm: Any, track_kid: UUID | None, table: T
|
||||
keys.licence_for(SimpleNamespace(drm=[drm]), None, table, all_drm)(drm, track_kid=track_kid)
|
||||
|
||||
|
||||
def run_together(keys: ContentKeyResolver, *jobs: tuple[Widevine, UUID]) -> tuple[Table, list[BaseException]]:
|
||||
table = key_table()
|
||||
errors: list[BaseException] = []
|
||||
|
||||
def run(drm: Widevine, kid: UUID) -> None:
|
||||
try:
|
||||
prepare(keys, drm, kid, table)
|
||||
except BaseException as e:
|
||||
errors.append(e)
|
||||
|
||||
threads = [threading.Thread(target=run, args=job, name=f"track-{i}") for i, job in enumerate(jobs)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
return table, errors
|
||||
|
||||
|
||||
def tree_labels(table: Table, kid: UUID) -> list[str]:
|
||||
trees = [cell for cell in table.columns[0].cells if isinstance(cell, Tree)]
|
||||
return [str(child.label) for tree in trees for child in tree.children if kid.hex in str(child.label)]
|
||||
|
||||
|
||||
def test_one_licence_for_two_pssh_with_different_kids(licences: Licences) -> None:
|
||||
keys = resolver(vaults_of(TrackVault(licences.second_track_looked_up)))
|
||||
first, second = widevine(KID_A, KID_B), widevine(KID_C)
|
||||
|
||||
table, errors = run_together(keys, (first, KID_A), (second, KID_C))
|
||||
|
||||
assert not errors
|
||||
assert len(licences) == 1
|
||||
assert first.content_keys[KID_A] == KEYS[KID_A] and second.content_keys[KID_C] == KEYS[KID_C]
|
||||
assert any(label.endswith(" from cache") for kid in (KID_A, KID_C) for label in tree_labels(table, kid))
|
||||
|
||||
|
||||
def test_a_track_waiting_for_its_turn_sends_no_licence_after_a_failure(licences: Licences) -> None:
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
|
||||
@@ -118,30 +69,6 @@ def test_a_track_waiting_for_its_turn_sends_no_licence_after_a_failure(licences:
|
||||
assert licences == []
|
||||
|
||||
|
||||
def test_force_licenses_again_although_the_keys_are_cached(licences: Licences) -> None:
|
||||
keys = resolver(cdm_only=True)
|
||||
ContentKeyResolver.LICENSE_KEY_CACHE.update(KEYS)
|
||||
|
||||
prepare(keys, widevine(KID_C), KID_C, key_table(), all_drm=True)
|
||||
|
||||
assert len(licences) == 1
|
||||
|
||||
|
||||
def test_a_key_label_is_added_once_with_its_marker_and_source(licences: Licences) -> None:
|
||||
keys = resolver()
|
||||
ContentKeyResolver.LICENSE_KEY_CACHE[KID_A] = KEYS[KID_A]
|
||||
table = key_table()
|
||||
|
||||
prepare(keys, widevine(KID_A, KID_B), KID_B, table)
|
||||
|
||||
tree = list(table.columns[0].cells)[-1]
|
||||
assert [str(child.label) for child in tree.children] == [
|
||||
f"[text2]{KID_A.hex}:{KEYS[KID_A]} from cache",
|
||||
f"[text2]{KID_B.hex}:{KEYS[KID_B]}*",
|
||||
f"[text2]{KID_C.hex}:{KEYS[KID_C]}",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"drm_class, build, cdm",
|
||||
[
|
||||
|
||||
@@ -4,7 +4,7 @@ from langcodes import Language
|
||||
|
||||
from unshackle.commands.dl import load_tracks
|
||||
from unshackle.core.title_metadata import Enrichment, apply_enrich
|
||||
from unshackle.core.titles import Episode, Movie, Song
|
||||
from unshackle.core.titles import Movie, Song
|
||||
from unshackle.core.tracks import Chapters, Tracks
|
||||
from unshackle.core.wire import apply_title_fields
|
||||
|
||||
@@ -26,13 +26,6 @@ def test_enrich_wins_over_a_movie_title_set_in_get_tracks():
|
||||
assert (movie.name, movie.year, str(movie.language)) == ("The Gold Seekers", 2017, "es")
|
||||
|
||||
|
||||
def test_enrich_wins_over_a_series_title_set_in_get_tracks():
|
||||
episode = Episode(id_="episode-0001", service=SERVICE, title="English", season=1, number=1, name="Pilot")
|
||||
service = refreshing_service({"series_title": "Local", "name": "Pilot", "year": 2016})
|
||||
load_tracks(service, episode, enrichment=Enrichment("English", 2017))
|
||||
assert (episode.title, episode.name, episode.year) == ("English", "Pilot", 2017)
|
||||
|
||||
|
||||
def test_no_enrich_keeps_the_title_from_get_tracks():
|
||||
movie = Movie(id_="movie-0001", service=SERVICE, name="Old", year=2016)
|
||||
load_tracks(refreshing_service({"name": "New", "year": 2017}), movie)
|
||||
|
||||
@@ -14,13 +14,6 @@ def _names(jar) -> dict:
|
||||
return {c.name: c.value for c in jar}
|
||||
|
||||
|
||||
def test_space_separated_cookie_file(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_text(HEADER + ".example.com TRUE / TRUE 1234567890 sid abc123\n", "utf8")
|
||||
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
|
||||
|
||||
def test_tab_separated_value_keeps_spaces(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_text(
|
||||
@@ -30,20 +23,6 @@ def test_tab_separated_value_keeps_spaces(tmp_path: Path) -> None:
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": "a b c"}
|
||||
|
||||
|
||||
def test_space_separated_empty_value(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_text(HEADER + ".example.com TRUE / TRUE 1234567890 sid \n", "utf8")
|
||||
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": ""}
|
||||
|
||||
|
||||
def test_space_separated_httponly(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_text(HEADER + "#HttpOnly_.example.com TRUE / TRUE 1234567890 sid abc123\n", "utf8")
|
||||
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
|
||||
|
||||
def test_mixed_separators_in_one_file(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_text(
|
||||
@@ -86,20 +65,6 @@ def test_json_export_gives_clear_error(tmp_path: Path) -> None:
|
||||
login.load_cookie_file(file)
|
||||
|
||||
|
||||
def test_leading_blank_line_is_not_json(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_text("\n" + HEADER + ".example.com TRUE / TRUE 1234567890 sid abc123\n", "utf8")
|
||||
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
|
||||
|
||||
def test_dot_flag_mismatch_does_not_abort_file(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_text(HEADER + "example.com\tTRUE\t/\tTRUE\t1\tsid\tv\n", "utf8")
|
||||
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": "v"}
|
||||
|
||||
|
||||
def test_the_users_file_is_never_rewritten(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
original = ".example.com TRUE / TRUE 1234567890 sid abc123\n"
|
||||
|
||||
@@ -6,25 +6,11 @@ import io
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
from click.testing import CliRunner
|
||||
|
||||
from unshackle.core import __version__
|
||||
from unshackle.core.__main__ import main, print_banner
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.__main__ import print_banner
|
||||
from unshackle.core.console import force_utf8_streams
|
||||
|
||||
|
||||
@pytest.mark.parametrize("args", [["--help"], ["env", "--help"]])
|
||||
def test_help_prints_the_banner_once(monkeypatch: pytest.MonkeyPatch, args: list[str]) -> None:
|
||||
monkeypatch.setattr(config, "update_checks", False)
|
||||
|
||||
result = CliRunner().invoke(main, args)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert result.output.count(f"v {__version__}") == 1
|
||||
assert "Usage:" in result.output
|
||||
|
||||
|
||||
def test_banner_prints_to_a_legacy_code_page_stream(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
buffer = io.BytesIO()
|
||||
monkeypatch.setattr(sys, "stdout", io.TextIOWrapper(buffer, encoding="cp1252"))
|
||||
|
||||
@@ -51,11 +51,6 @@ class NeedsNetwork(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def test_index_lists_every_known_failure() -> None:
|
||||
assert INDEX
|
||||
assert set(KNOWN_FAILURES) <= {e["file"] for e in INDEX}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("entry", cases(INDEX))
|
||||
def test_manifest_parses_to_tracks(entry: dict[str, Any], caplog: pytest.LogCaptureFixture) -> None:
|
||||
tracks = parse(entry)
|
||||
|
||||
@@ -129,12 +129,6 @@ def test_service_filter_drops_every_ad_period_after_the_first_content_period():
|
||||
assert stitched(service_tracks().videos[0]) == ["main-1", "main-2", "main-3"]
|
||||
|
||||
|
||||
def test_whole_manifest_restore_keeps_the_service_filter():
|
||||
video = round_trip(service_tracks()).videos[0]
|
||||
assert video.data["dash"]["period"].get("id") == "main-1"
|
||||
assert stitched(video) == ["main-1", "main-2", "main-3"]
|
||||
|
||||
|
||||
def test_one_track_fragment_keeps_every_period_and_the_service_filter():
|
||||
tracks = service_tracks()
|
||||
detach_video(tracks)
|
||||
@@ -144,11 +138,6 @@ def test_one_track_fragment_keeps_every_period_and_the_service_filter():
|
||||
assert stitched(video) == ["main-1", "main-2", "main-3"]
|
||||
|
||||
|
||||
def test_import_restores_the_service_filter_from_the_export_without_a_fetch(tmp_path):
|
||||
video = export_and_import(tmp_path, service_tracks()).videos[0]
|
||||
assert stitched(video) == ["main-1", "main-2", "main-3"]
|
||||
|
||||
|
||||
def test_capture_on_a_remote_client_saves_the_whole_manifest_not_a_fragment():
|
||||
tracks = service_tracks()
|
||||
detach_video(tracks)
|
||||
@@ -180,10 +169,6 @@ def test_a_malformed_snapshot_restores_nothing(snapshot):
|
||||
assert parse(snapshot, URL, "en") is None
|
||||
|
||||
|
||||
def test_a_saved_manifest_that_does_not_parse_gives_none():
|
||||
assert parse({"manifests": [{"type": "dash", "url": URL, "data": "bm90IHpsaWI="}]}, URL, "en") is None
|
||||
|
||||
|
||||
def test_the_inflate_budget_covers_every_entry_of_one_restore(monkeypatch, caplog):
|
||||
saved = capture(service_tracks())
|
||||
entry = saved["manifests"][0]
|
||||
@@ -212,11 +197,6 @@ def test_the_fragments_and_the_whole_manifests_share_one_budget(monkeypatch):
|
||||
assert not client.audio[0].data.get("dash")
|
||||
|
||||
|
||||
def test_compression_level_zero_restores():
|
||||
video = round_trip(service_tracks(), level=0).videos[0]
|
||||
assert stitched(video) == ["main-1", "main-2", "main-3"]
|
||||
|
||||
|
||||
def test_an_export_from_a_remote_client_imports_every_track(tmp_path):
|
||||
tracks = service_tracks()
|
||||
detach_video(tracks)
|
||||
|
||||
@@ -29,10 +29,6 @@ def test_two_ids_are_refused(tmdb: int | None, imdb: str | None, tvdb: int | Non
|
||||
assert "cannot be used together" in str(exc.value)
|
||||
|
||||
|
||||
def test_no_ids_is_fine() -> None:
|
||||
assert validate_metadata_ids(None, None, None) is None
|
||||
|
||||
|
||||
def test_imdb_alone_passes_on_the_keyless_provider(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
with_keys(monkeypatch)
|
||||
assert validate_metadata_ids(None, "tt1375666", None) is None
|
||||
@@ -45,13 +41,6 @@ def test_tmdb_without_its_key_names_the_key(monkeypatch: pytest.MonkeyPatch) ->
|
||||
assert "--tmdb" in str(exc.value) and "tmdb_api_key" in str(exc.value)
|
||||
|
||||
|
||||
def test_tvdb_without_its_key_names_the_key(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
with_keys(monkeypatch)
|
||||
with pytest.raises(PlanError) as exc:
|
||||
validate_metadata_ids(None, None, 73871)
|
||||
assert "--tvdb" in str(exc.value) and "tvdb_api_key" in str(exc.value)
|
||||
|
||||
|
||||
def test_tmdb_with_its_key_passes(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
with_keys(monkeypatch, tmdb_api_key="k")
|
||||
assert validate_metadata_ids(27205, None, None) is None
|
||||
@@ -105,12 +94,6 @@ def test_api_still_reports_a_malformed_id_first() -> None:
|
||||
assert err and "positive integer" in err
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [21, "21", "mal:21"])
|
||||
def test_anilist_alone_passes_without_any_key(monkeypatch: pytest.MonkeyPatch, value: object) -> None:
|
||||
with_keys(monkeypatch)
|
||||
assert validate_metadata_ids(None, None, None, value) is None
|
||||
|
||||
|
||||
def test_anilist_pairs_with_one_other_id(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
with_keys(monkeypatch)
|
||||
assert validate_metadata_ids(None, "tt1375666", None, 21) is None
|
||||
@@ -151,14 +134,6 @@ def test_api_refuses_a_malformed_anilist_id(value: object) -> None:
|
||||
assert err and "anilist" in err
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["0", "mal:0", "²", "21.5"])
|
||||
def test_a_non_positive_or_non_decimal_anilist_value_is_refused(monkeypatch: pytest.MonkeyPatch, value: str) -> None:
|
||||
with_keys(monkeypatch)
|
||||
with pytest.raises(PlanError) as exc:
|
||||
validate_metadata_ids(None, None, None, value)
|
||||
assert "--anilist" in str(exc.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [{"anilist_id": "MAL:21"}, {"anilist_id": "007"}, {"anilist_id": " 21 "}])
|
||||
def test_api_accepts_what_the_cli_accepts(payload: dict) -> None:
|
||||
"""Both surfaces share parse_anilist_ref, so their accept sets cannot drift."""
|
||||
|
||||
@@ -51,12 +51,6 @@ def test_other_dts_profiles_stay_in_matroska(tmp_path: Path, fourcc: bytes) -> N
|
||||
assert has_mp4_only_audio_entry(write_mp4(tmp_path / "a.mp4", fourcc)) is False
|
||||
|
||||
|
||||
def test_a_file_with_no_moov_is_not_detected(tmp_path: Path) -> None:
|
||||
path = tmp_path / "a.mp4"
|
||||
path.write_bytes(box(b"ftyp", b"isom") + box(b"mdat", b"dtsx" * 8))
|
||||
assert has_mp4_only_audio_entry(path) is False, "a 4CC in mdat is not a sample entry"
|
||||
|
||||
|
||||
def build_tracks(tmp_path: Path, audio_entry: bytes) -> Tracks:
|
||||
video = Video(id_="v1", url="https://x/v", codec=Video.Codec.AVC, language="en", width=1920, height=1080, fps=24)
|
||||
audio = Audio(id_="a1", url="https://x/a", codec=Audio.Codec.DTSX, language="en", bitrate=448000)
|
||||
@@ -253,14 +247,6 @@ def test_a_changed_stsd_is_never_dropped(tmp_path: Path) -> None:
|
||||
assert not dst.exists(), "the caller must keep the original when the format changes"
|
||||
|
||||
|
||||
def test_a_single_init_is_left_alone(tmp_path: Path) -> None:
|
||||
src = tmp_path / "a.mp4"
|
||||
src.write_bytes(init_pair(b"dtsx") + fragment(b"one"))
|
||||
dst = tmp_path / "clean.mp4"
|
||||
assert strip_duplicate_init_boxes(src, dst) == 0
|
||||
assert not dst.exists()
|
||||
|
||||
|
||||
def test_an_unreadable_input_aborts_instead_of_shipping_a_placeholder(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
|
||||
@@ -20,7 +20,7 @@ from unshackle.core.config import config
|
||||
from unshackle.core.drm import ClearKeyCENC
|
||||
from unshackle.core.drm import decrypters as decrypters_module
|
||||
from unshackle.core.drm.decrypters import mp4decrypt_or_shaka
|
||||
from unshackle.core.drm.key_args import shaka_noise, track_key_args
|
||||
from unshackle.core.drm.key_args import track_key_args
|
||||
from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use
|
||||
from unshackle.core.drm.verify import kidless_track_kids
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
@@ -355,21 +355,6 @@ def test_shaka_error_line_with_exit_0_is_a_decrypt(
|
||||
assert path.read_bytes() == b"decrypted"
|
||||
|
||||
|
||||
@POSIX_STUBS
|
||||
@pytest.mark.parametrize("make", DRMS)
|
||||
def test_shaka_non_zero_exit_raises(
|
||||
tmp_path: Path, stub_packager: Callable[[int], None], make: Callable[[], Any]
|
||||
) -> None:
|
||||
stub_packager(2)
|
||||
path = tmp_path / "track.mp4"
|
||||
path.write_bytes(b"encrypted")
|
||||
drm = make()
|
||||
drm.content_keys[A] = KEY
|
||||
|
||||
with pytest.raises(subprocess.CalledProcessError):
|
||||
drm.decrypt_with_shaka_packager(path)
|
||||
|
||||
|
||||
class FakePackager:
|
||||
"""A shaka-packager Popen that records its argv, prints ``log`` and exits with ``code``."""
|
||||
|
||||
@@ -407,13 +392,6 @@ def shaka_run(tmp_path: Path, make: Callable[[], Any], raises: type[BaseExceptio
|
||||
return caught.value
|
||||
|
||||
|
||||
@pytest.mark.parametrize("make", DRMS)
|
||||
@pytest.mark.usefixtures("fake_packager")
|
||||
def test_every_drm_passes_the_fake_clock(tmp_path: Path, make: Callable[[], Any]) -> None:
|
||||
shaka_run(tmp_path, make, FileNotFoundError)
|
||||
assert "--use_fake_clock_for_muxer" in FakePackager.argv
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("fake_packager")
|
||||
def test_clearkey_gives_no_zero_kid_fallback(tmp_path: Path) -> None:
|
||||
shaka_run(tmp_path, lambda: ClearKeyCENC(kids=[A]), FileNotFoundError)
|
||||
@@ -456,24 +434,3 @@ def test_a_skipped_shaka_stream_keeps_the_input(tmp_path: Path, make: Callable[[
|
||||
def test_a_shaka_ctrl_c_exit_is_a_keyboard_interrupt(tmp_path: Path) -> None:
|
||||
FakePackager.code = 0xC000013A
|
||||
shaka_run(tmp_path, lambda: _widevine(A), KeyboardInterrupt)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("line", "noise"),
|
||||
[
|
||||
pytest.param(
|
||||
"I1103 21:41:56.557273 16212 packager_main.cc:591] Excluding 'pssh' boxes", True, id="glog-info"
|
||||
),
|
||||
pytest.param("I0503 01:02:03.000000 1 demuxer.cc:105] Demuxer::Run()", True, id="glog-info-early-month"),
|
||||
pytest.param("W1103 21:41:56.000000 1 x.cc:1] warning", True, id="glog-warning"),
|
||||
pytest.param(
|
||||
"[1103/214121:WARNING:track_run_iterator.cc(699)] Seeing non-zero composition offset", True, id="warning"
|
||||
),
|
||||
pytest.param("[1103/153402:INFO:demuxer.cc(170)] Initialize Demuxer", True, id="info"),
|
||||
pytest.param("[1103/153402:ERROR:box_definitions.cc(641)] Not implemented reached", False, id="error"),
|
||||
pytest.param("E1103 21:41:56.000000 1 x.cc:1] failed", False, id="glog-error"),
|
||||
pytest.param("Packaging completed successfully.", False, id="plain"),
|
||||
],
|
||||
)
|
||||
def test_shaka_noise(line: str, noise: bool) -> None:
|
||||
assert shaka_noise(line) is noise
|
||||
|
||||
@@ -152,31 +152,6 @@ def make_track(path: Path, codec: Audio.Codec | None) -> Audio:
|
||||
return track
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("encoder", "fmt", "declared", "extension", "probed"),
|
||||
[
|
||||
("libopus", "webm", None, ".opus", Audio.Codec.OPUS),
|
||||
("libvorbis", "webm", Audio.Codec.AAC, ".ogg", Audio.Codec.OGG),
|
||||
("flac", "flac", Audio.Codec.AAC, ".flac", Audio.Codec.FLAC),
|
||||
("libmp3lame", "mp3", None, ".mp3", Audio.Codec.MP3),
|
||||
("pcm_s16le", "wav", None, ".flac", Audio.Codec.PCM),
|
||||
("pcm_s24le", "wav", None, ".flac", Audio.Codec.PCM),
|
||||
("pcm_f32le", "wav", None, ".wav", Audio.Codec.PCM),
|
||||
],
|
||||
)
|
||||
def test_the_file_codec_decides_the_container(
|
||||
tmp_path: Path, encoder: str, fmt: str, declared: Audio.Codec | None, extension: str, probed: Audio.Codec
|
||||
) -> None:
|
||||
"""Every track downloads under a .mp4 name, and a service can declare no codec or the wrong one."""
|
||||
track = make_track(encode(tmp_path / "track.mp4", encoder, "-f", fmt), declared)
|
||||
|
||||
track.to_music_container()
|
||||
assert track.path.suffix == extension
|
||||
assert track.codec == probed
|
||||
assert header_length(track.path) == pytest.approx(6.0, abs=0.5)
|
||||
assert write_music_metadata(track.path, make_song()).written
|
||||
|
||||
|
||||
def test_24_bit_pcm_stays_24_bit_in_flac(tmp_path: Path) -> None:
|
||||
track = make_track(encode(tmp_path / "track.mp4", "pcm_s24le", "-f", "wav"), Audio.Codec.PCM)
|
||||
track.to_music_container()
|
||||
@@ -210,13 +185,6 @@ def test_a_sample_window_is_cut_in_the_remux(tmp_path: Path, encoder: str, extra
|
||||
assert header_length(track.path) == pytest.approx(2.0, abs=0.3)
|
||||
|
||||
|
||||
def test_the_remux_writes_no_encoder_tag(tmp_path: Path) -> None:
|
||||
track = make_track(encode(tmp_path / "track.mp4", "libmp3lame", "-f", "mp3"), Audio.Codec.MP3)
|
||||
track.to_music_container()
|
||||
tags = mutagen.File(track.path).tags
|
||||
assert not tags or "TSSE" not in tags
|
||||
|
||||
|
||||
def test_float_pcm_goes_to_wav_whatever_its_bit_depth(tmp_path: Path) -> None:
|
||||
"""16- and 24-bit float PCM report a bit depth FLAC can hold, but FLAC has no float samples."""
|
||||
track = make_track(encode(tmp_path / "track.mp4", "pcm_f32le", "-f", "wav"), Audio.Codec.PCM)
|
||||
|
||||
@@ -12,9 +12,6 @@ from unshackle.core.music.extract import (
|
||||
duration_seconds,
|
||||
first_number,
|
||||
first_text,
|
||||
format_duration,
|
||||
format_names,
|
||||
year_from_value,
|
||||
)
|
||||
from unshackle.core.titles.music import Music, Song
|
||||
|
||||
@@ -86,21 +83,6 @@ def test_first_number(values: tuple[Any, ...], expected: float | None) -> None:
|
||||
assert first_number(*values) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("value", "expected"),
|
||||
[
|
||||
("2021-05-04", 2021),
|
||||
("released 1999 remaster", 1999),
|
||||
(2018, 2018),
|
||||
("no year here", 1900),
|
||||
(None, 1900),
|
||||
("", 1900),
|
||||
],
|
||||
)
|
||||
def test_year_from_value(value: Any, expected: int) -> None:
|
||||
assert year_from_value(value) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("value", "expected"),
|
||||
[
|
||||
@@ -115,39 +97,6 @@ def test_duration_seconds(value: Any, expected: float | None) -> None:
|
||||
assert duration_seconds(value) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("value", "expected"),
|
||||
[
|
||||
(0, "0:00"),
|
||||
(5, "0:05"),
|
||||
(65, "1:05"),
|
||||
(599, "9:59"),
|
||||
(3600, "1:00:00"),
|
||||
(3725, "1:02:05"),
|
||||
(-5, "0:00"),
|
||||
(None, ""),
|
||||
("bad", ""),
|
||||
(float("inf"), ""),
|
||||
],
|
||||
)
|
||||
def test_format_duration(value: Any, expected: str) -> None:
|
||||
assert format_duration(value) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("value", "sep", "expected"),
|
||||
[
|
||||
(["Alice", "Bob"], ", ", "Alice, Bob"),
|
||||
(["Alice", "Alice"], ", ", "Alice"), # de-dupes
|
||||
([{"profile": {"name": "DJ"}}], ", ", "DJ"),
|
||||
({"items": [{"name": "X"}, {"name": "Y"}]}, " & ", "X & Y"),
|
||||
("Solo", ", ", "Solo"),
|
||||
],
|
||||
)
|
||||
def test_format_names(value: Any, sep: str, expected: str) -> None:
|
||||
assert format_names(value, sep=sep) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("raw_kind", "count", "expected"),
|
||||
[
|
||||
@@ -211,22 +160,6 @@ def test_build_music_from_songs() -> None:
|
||||
assert music.artwork_url == "http://art/1.jpg"
|
||||
|
||||
|
||||
def test_build_music_from_songs_overrides() -> None:
|
||||
songs = [make_song(data={"duration": 60})]
|
||||
music = build_music_from_songs(
|
||||
songs,
|
||||
kind="playlist",
|
||||
title="My Mix",
|
||||
artist="Various",
|
||||
owner="george",
|
||||
description="best of",
|
||||
)
|
||||
assert music.title == "My Mix"
|
||||
assert music.artist == "Various"
|
||||
assert music.owner == "george"
|
||||
assert music.description == "best of"
|
||||
|
||||
|
||||
def test_build_music_from_songs_of_different_releases_takes_no_fact_from_a_song() -> None:
|
||||
songs = [
|
||||
make_song(album="A", album_artist="Band A", total_tracks=30, artwork_url="http://art/a.jpg"),
|
||||
@@ -238,8 +171,3 @@ def test_build_music_from_songs_of_different_releases_takes_no_fact_from_a_song(
|
||||
|
||||
named = build_music_from_songs(songs, kind="playlist", title="My Mix", artist="Various")
|
||||
assert str(named) == "Various - My Mix"
|
||||
|
||||
|
||||
def test_build_music_from_songs_empty_raises() -> None:
|
||||
with pytest.raises(ValueError, match="nothing here"):
|
||||
build_music_from_songs([], kind="album", empty_error="nothing here")
|
||||
|
||||
@@ -115,12 +115,6 @@ def test_undated_single_degrades_cleanly(reset_folder_config):
|
||||
assert context["track_number"] == "01"
|
||||
|
||||
|
||||
def test_undated_album_template_omits_the_year_group(reset_folder_config):
|
||||
reset_folder_config.folder_templates = {"albums": "{album_artist} - {album} ({year?})"}
|
||||
result = make_song(year=None).get_filename(StubMediaInfo(), folder=True)
|
||||
assert result == "Example Artist - Example Album"
|
||||
|
||||
|
||||
def test_songs_separator_survives_a_config_without_a_songs_template(reset_folder_config):
|
||||
"""A user config with output_template but no `songs` key used to raise a KeyError."""
|
||||
reset_folder_config.output_template = {"movies": "{title}.{year}"}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user