diff --git a/tests/commands/test_cdm_cache.py b/tests/commands/test_cdm_cache.py
index 13ae69860..25bcb82c5 100644
--- a/tests/commands/test_cdm_cache.py
+++ b/tests/commands/test_cdm_cache.py
@@ -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")]
diff --git a/tests/commands/test_cfg.py b/tests/commands/test_cfg.py
index d1dc03550..c6ce64d5c 100644
--- a/tests/commands/test_cfg.py
+++ b/tests/commands/test_cfg.py
@@ -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")):
diff --git a/tests/commands/test_device_commands.py b/tests/commands/test_device_commands.py
index 2bd327a90..7e454d35e 100644
--- a/tests/commands/test_device_commands.py
+++ b/tests/commands/test_device_commands.py
@@ -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)]
diff --git a/tests/commands/test_disk_preflight.py b/tests/commands/test_disk_preflight.py
index 3d60fc40c..ba434686e 100644
--- a/tests/commands/test_disk_preflight.py
+++ b/tests/commands/test_disk_preflight.py
@@ -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)
diff --git a/tests/commands/test_dl_cli_reference.py b/tests/commands/test_dl_cli_reference.py
deleted file mode 100644
index 21e4747a3..000000000
--- a/tests/commands/test_dl_cli_reference.py
+++ /dev/null
@@ -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()
diff --git a/tests/commands/test_dl_proxy.py b/tests/commands/test_dl_proxy.py
index 4ae4ce3bd..41b482165 100644
--- a/tests/commands/test_dl_proxy.py
+++ b/tests/commands/test_dl_proxy.py
@@ -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:
diff --git a/tests/commands/test_failure_lines.py b/tests/commands/test_failure_lines.py
index f4c99cca9..553224586 100644
--- a/tests/commands/test_failure_lines.py
+++ b/tests/commands/test_failure_lines.py
@@ -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)
diff --git a/tests/commands/test_fairplay_selection_gate.py b/tests/commands/test_fairplay_selection_gate.py
index fc180fab7..1c7f0df31 100644
--- a/tests/commands/test_fairplay_selection_gate.py
+++ b/tests/commands/test_fairplay_selection_gate.py
@@ -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:
diff --git a/tests/commands/test_key_resolution_wiring.py b/tests/commands/test_key_resolution_wiring.py
deleted file mode 100644
index 1987cbc82..000000000
--- a/tests/commands/test_key_resolution_wiring.py
+++ /dev/null
@@ -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
diff --git a/tests/commands/test_kv_vault_path.py b/tests/commands/test_kv_vault_path.py
index e116e6609..97c787b4c 100644
--- a/tests/commands/test_kv_vault_path.py
+++ b/tests/commands/test_kv_vault_path.py
@@ -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
diff --git a/tests/commands/test_search_proxy.py b/tests/commands/test_search_proxy.py
deleted file mode 100644
index 338e5f726..000000000
--- a/tests/commands/test_search_proxy.py
+++ /dev/null
@@ -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")
diff --git a/tests/core/test_ac4_atmos.py b/tests/core/test_ac4_atmos.py
index 347c5ae48..06a60d606 100644
--- a/tests/core/test_ac4_atmos.py
+++ b/tests/core/test_ac4_atmos.py
@@ -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 = ''
@@ -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
diff --git a/tests/core/test_adaptive_workers.py b/tests/core/test_adaptive_workers.py
index 6a2bf799f..87b2e694a 100644
--- a/tests/core/test_adaptive_workers.py
+++ b/tests/core/test_adaptive_workers.py
@@ -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
diff --git a/tests/core/test_all_drm.py b/tests/core/test_all_drm.py
index 4d2be3e3b..e93b53178 100644
--- a/tests/core/test_all_drm.py
+++ b/tests/core/test_all_drm.py
@@ -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")
diff --git a/tests/core/test_anilist_provider.py b/tests/core/test_anilist_provider.py
index b239af770..7cc5c5818 100644
--- a/tests/core/test_anilist_provider.py
+++ b/tests/core/test_anilist_provider.py
@@ -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
diff --git a/tests/core/test_audio_channel_naming.py b/tests/core/test_audio_channel_naming.py
index f29aaba28..01a51c318 100644
--- a/tests/core/test_audio_channel_naming.py
+++ b/tests/core/test_audio_channel_naming.py
@@ -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]
diff --git a/tests/core/test_audio_resolution.py b/tests/core/test_audio_resolution.py
index c3bc1a968..1b9ad924a 100644
--- a/tests/core/test_audio_resolution.py
+++ b/tests/core/test_audio_resolution.py
@@ -142,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)
diff --git a/tests/core/test_binary_version.py b/tests/core/test_binary_version.py
index 95cd80262..707a079c5 100644
--- a/tests/core/test_binary_version.py
+++ b/tests/core/test_binary_version.py
@@ -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
diff --git a/tests/core/test_bridged_licence_key_check.py b/tests/core/test_bridged_licence_key_check.py
index 15684bf33..09e1697ac 100644
--- a/tests/core/test_bridged_licence_key_check.py
+++ b/tests/core/test_bridged_licence_key_check.py
@@ -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"]
diff --git a/tests/core/test_cacher.py b/tests/core/test_cacher.py
index 70e222d32..cf73256c5 100644
--- a/tests/core/test_cacher.py
+++ b/tests/core/test_cacher.py
@@ -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"))
diff --git a/tests/core/test_cdm_choice.py b/tests/core/test_cdm_choice.py
index e514f7b1a..9dee38f3f 100644
--- a/tests/core/test_cdm_choice.py
+++ b/tests/core/test_cdm_choice.py
@@ -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
diff --git a/tests/core/test_cdm_detect.py b/tests/core/test_cdm_detect.py
index 4d9c3218f..c35fcde9a 100644
--- a/tests/core/test_cdm_detect.py
+++ b/tests/core/test_cdm_detect.py
@@ -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"]
diff --git a/tests/core/test_clearkey.py b/tests/core/test_clearkey.py
index 8f842462b..a2b965035 100644
--- a/tests/core/test_clearkey.py
+++ b/tests/core/test_clearkey.py
@@ -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")
diff --git a/tests/core/test_clearkey_ctr.py b/tests/core/test_clearkey_ctr.py
index 3949333bc..5d5d27d03 100644
--- a/tests/core/test_clearkey_ctr.py
+++ b/tests/core/test_clearkey_ctr.py
@@ -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
diff --git a/tests/core/test_click_types.py b/tests/core/test_click_types.py
index 276a01673..15a86c340 100644
--- a/tests/core/test_click_types.py
+++ b/tests/core/test_click_types.py
@@ -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") == []
diff --git a/tests/core/test_client_cookies_flag.py b/tests/core/test_client_cookies_flag.py
index 1310afc12..416c86d4e 100644
--- a/tests/core/test_client_cookies_flag.py
+++ b/tests/core/test_client_cookies_flag.py
@@ -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:
diff --git a/tests/core/test_code_hash.py b/tests/core/test_code_hash.py
index 759b8e6ef..f2ee6d738 100644
--- a/tests/core/test_code_hash.py
+++ b/tests/core/test_code_hash.py
@@ -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"")
diff --git a/tests/core/test_config_bool_languages.py b/tests/core/test_config_bool_languages.py
index df02f94f2..c2ec00e9f 100644
--- a/tests/core/test_config_bool_languages.py
+++ b/tests/core/test_config_bool_languages.py
@@ -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)
diff --git a/tests/core/test_config_duplicate_keys.py b/tests/core/test_config_duplicate_keys.py
index d05f4e0a5..ef278c1ce 100644
--- a/tests/core/test_config_duplicate_keys.py
+++ b/tests/core/test_config_duplicate_keys.py
@@ -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"],
diff --git a/tests/core/test_config_resolution.py b/tests/core/test_config_resolution.py
index ad73eb56f..d73bc3b84 100644
--- a/tests/core/test_config_resolution.py
+++ b/tests/core/test_config_resolution.py
@@ -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"})
diff --git a/tests/core/test_config_vaults.py b/tests/core/test_config_vaults.py
index bea5319c5..44b9eb46f 100644
--- a/tests/core/test_config_vaults.py
+++ b/tests/core/test_config_vaults.py
@@ -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"])
diff --git a/tests/core/test_console_cell_width.py b/tests/core/test_console_cell_width.py
deleted file mode 100644
index c8256253f..000000000
--- a/tests/core/test_console_cell_width.py
+++ /dev/null
@@ -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
diff --git a/tests/core/test_continuous_episodes.py b/tests/core/test_continuous_episodes.py
index 5cf37e202..6e53aa8da 100644
--- a/tests/core/test_continuous_episodes.py
+++ b/tests/core/test_continuous_episodes.py
@@ -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)]
diff --git a/tests/core/test_controld_proxy.py b/tests/core/test_controld_proxy.py
index 9c51a6db0..99a00455b 100644
--- a/tests/core/test_controld_proxy.py
+++ b/tests/core/test_controld_proxy.py
@@ -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
diff --git a/tests/core/test_dash_dv_composite.py b/tests/core/test_dash_dv_composite.py
index fc914c642..7185b7417 100644
--- a/tests/core/test_dash_dv_composite.py
+++ b/tests/core/test_dash_dv_composite.py
@@ -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)
diff --git a/tests/core/test_dash_multi_period_init.py b/tests/core/test_dash_multi_period_init.py
index fdc0c6cf2..d1ebcb006 100644
--- a/tests/core/test_dash_multi_period_init.py
+++ b/tests/core/test_dash_multi_period_init.py
@@ -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"""
-
-
-
-
-
- """
- for i in (0, 1)
- )
- return f"""
-
- {base(srv)}
-{periods}
-"""
-
-
def base_mpd(srv) -> str:
periods = "\n".join(
f"""
@@ -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
diff --git a/tests/core/test_dash_period_match.py b/tests/core/test_dash_period_match.py
index 5a4436ab5..8d3261146 100644
--- a/tests/core/test_dash_period_match.py
+++ b/tests/core/test_dash_period_match.py
@@ -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'{video("v1", "5e6")}',
)
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
diff --git a/tests/core/test_dash_period_rebase.py b/tests/core/test_dash_period_rebase.py
index b4955edf5..a9df03307 100644
--- a/tests/core/test_dash_period_rebase.py
+++ b/tests/core/test_dash_period_rebase.py
@@ -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
diff --git a/tests/core/test_debug_logging.py b/tests/core/test_debug_logging.py
index 1bf518b0d..b3f5881ac 100644
--- a/tests/core/test_debug_logging.py
+++ b/tests/core/test_debug_logging.py
@@ -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) == "/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 "/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
diff --git a/tests/core/test_dovi_info_frame.py b/tests/core/test_dovi_info_frame.py
index dc68a48c2..c6c09567b 100644
--- a/tests/core/test_dovi_info_frame.py
+++ b/tests/core/test_dovi_info_frame.py
@@ -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"))
diff --git a/tests/core/test_download_archive.py b/tests/core/test_download_archive.py
index ef880cf22..d1300aa06 100644
--- a/tests/core/test_download_archive.py
+++ b/tests/core/test_download_archive.py
@@ -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")
diff --git a/tests/core/test_download_archive_loop.py b/tests/core/test_download_archive_loop.py
index fd88acd73..16a540d41 100644
--- a/tests/core/test_download_archive_loop.py
+++ b/tests/core/test_download_archive_loop.py
@@ -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 = []
diff --git a/tests/core/test_drm_lock.py b/tests/core/test_drm_lock.py
index b3dd30777..72d7613f3 100644
--- a/tests/core/test_drm_lock.py
+++ b/tests/core/test_drm_lock.py
@@ -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"}
diff --git a/tests/core/test_drm_plugins.py b/tests/core/test_drm_plugins.py
index 1325542c7..9ec7e7765 100644
--- a/tests/core/test_drm_plugins.py
+++ b/tests/core/test_drm_plugins.py
@@ -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
diff --git a/tests/core/test_dual_multi_naming.py b/tests/core/test_dual_multi_naming.py
index e5c587801..4dc1ebbcd 100644
--- a/tests/core/test_dual_multi_naming.py
+++ b/tests/core/test_dual_multi_naming.py
@@ -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"] == ""
diff --git a/tests/core/test_enrich_language.py b/tests/core/test_enrich_language.py
index a0577f432..124dc501e 100644
--- a/tests/core/test_enrich_language.py
+++ b/tests/core/test_enrich_language.py
@@ -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",
[
diff --git a/tests/core/test_episode_absolute.py b/tests/core/test_episode_absolute.py
index 2f8067889..0d7bd8b87 100644
--- a/tests/core/test_episode_absolute.py
+++ b/tests/core/test_episode_absolute.py
@@ -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"]
diff --git a/tests/core/test_episode_air_date.py b/tests/core/test_episode_air_date.py
index fa6135dd2..cc96e9d5a 100644
--- a/tests/core/test_episode_air_date.py
+++ b/tests/core/test_episode_air_date.py
@@ -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"
diff --git a/tests/core/test_episode_part.py b/tests/core/test_episode_part.py
index 6bfc8e865..e8b947a66 100644
--- a/tests/core/test_episode_part.py
+++ b/tests/core/test_episode_part.py
@@ -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
diff --git a/tests/core/test_episode_sports.py b/tests/core/test_episode_sports.py
index 914256f88..ab433a02f 100644
--- a/tests/core/test_episode_sports.py
+++ b/tests/core/test_episode_sports.py
@@ -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()]
diff --git a/tests/core/test_export.py b/tests/core/test_export.py
index 191532d65..4246a2eaf 100644
--- a/tests/core/test_export.py
+++ b/tests/core/test_export.py
@@ -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(
diff --git a/tests/core/test_export_name.py b/tests/core/test_export_name.py
index dc1309a05..da4537beb 100644
--- a/tests/core/test_export_name.py
+++ b/tests/core/test_export_name.py
@@ -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)])
diff --git a/tests/core/test_ffmpeg_decodes.py b/tests/core/test_ffmpeg_decodes.py
index 404dbb2ef..9fd59ff72 100644
--- a/tests/core/test_ffmpeg_decodes.py
+++ b/tests/core/test_ffmpeg_decodes.py
@@ -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.
diff --git a/tests/core/test_fill_air_dates.py b/tests/core/test_fill_air_dates.py
index dda5fdb8c..19f987d8d 100644
--- a/tests/core/test_fill_air_dates.py
+++ b/tests/core/test_fill_air_dates.py
@@ -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
diff --git a/tests/core/test_fps.py b/tests/core/test_fps.py
index 5ee00c0c1..6ca70b003 100644
--- a/tests/core/test_fps.py
+++ b/tests/core/test_fps.py
@@ -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 = """
diff --git a/tests/core/test_geoblock.py b/tests/core/test_geoblock.py
index 830e7063b..921479548 100644
--- a/tests/core/test_geoblock.py
+++ b/tests/core/test_geoblock.py
@@ -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,
diff --git a/tests/core/test_get_boxes.py b/tests/core/test_get_boxes.py
index 546a41c4f..6eeef1ce5 100644
--- a/tests/core/test_get_boxes.py
+++ b/tests/core/test_get_boxes.py
@@ -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)
diff --git a/tests/core/test_hdr10plus_probe.py b/tests/core/test_hdr10plus_probe.py
index 57f2cd019..31ed433e5 100644
--- a/tests/core/test_hdr10plus_probe.py
+++ b/tests/core/test_hdr10plus_probe.py
@@ -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) == "++-++"
diff --git a/tests/core/test_hls_keys.py b/tests/core/test_hls_keys.py
index 1c4d015e9..b6ffca1f0 100644
--- a/tests/core/test_hls_keys.py
+++ b/tests/core/test_hls_keys.py
@@ -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]
diff --git a/tests/core/test_hls_licence_only_key_rotation.py b/tests/core/test_hls_licence_only_key_rotation.py
index c42e3c887..b1f3b07b7 100644
--- a/tests/core/test_hls_licence_only_key_rotation.py
+++ b/tests/core/test_hls_licence_only_key_rotation.py
@@ -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"
diff --git a/tests/core/test_hls_merge_segments.py b/tests/core/test_hls_merge_segments.py
index 688e36743..537d5a849 100644
--- a/tests/core/test_hls_merge_segments.py
+++ b/tests/core/test_hls_merge_segments.py
@@ -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]
diff --git a/tests/core/test_hls_repeated_entries.py b/tests/core/test_hls_repeated_entries.py
index 7d1a3845a..e0d002202 100644
--- a/tests/core/test_hls_repeated_entries.py
+++ b/tests/core/test_hls_repeated_entries.py
@@ -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")
diff --git a/tests/core/test_hls_segment_io.py b/tests/core/test_hls_segment_io.py
index 0b4d075e4..92c34b27a 100644
--- a/tests/core/test_hls_segment_io.py
+++ b/tests/core/test_hls_segment_io.py
@@ -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}"
diff --git a/tests/core/test_hls_service_drm_keys.py b/tests/core/test_hls_service_drm_keys.py
index d1f868d94..30651e512 100644
--- a/tests/core/test_hls_service_drm_keys.py
+++ b/tests/core/test_hls_service_drm_keys.py
@@ -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")
diff --git a/tests/core/test_hls_session_keys.py b/tests/core/test_hls_session_keys.py
index c9ff059bd..8d9bf292c 100644
--- a/tests/core/test_hls_session_keys.py
+++ b/tests/core/test_hls_session_keys.py
@@ -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"),
[
diff --git a/tests/core/test_hls_webvtt_discontinuity.py b/tests/core/test_hls_webvtt_discontinuity.py
index 7bc99e135..b1c28ea2d 100644
--- a/tests/core/test_hls_webvtt_discontinuity.py
+++ b/tests/core/test_hls_webvtt_discontinuity.py
@@ -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"]
diff --git a/tests/core/test_http_cdm.py b/tests/core/test_http_cdm.py
index 3fcfadd3a..65fd63627 100644
--- a/tests/core/test_http_cdm.py
+++ b/tests/core/test_http_cdm.py
@@ -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}
diff --git a/tests/core/test_hybrid_dv_fixup.py b/tests/core/test_hybrid_dv_fixup.py
index 0c148d52c..74690eae4 100644
--- a/tests/core/test_hybrid_dv_fixup.py
+++ b/tests/core/test_hybrid_dv_fixup.py
@@ -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"]
diff --git a/tests/core/test_hybrid_hdr10plus.py b/tests/core/test_hybrid_hdr10plus.py
index 62ee98b44..fba887116 100644
--- a/tests/core/test_hybrid_hdr10plus.py
+++ b/tests/core/test_hybrid_hdr10plus.py
@@ -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
diff --git a/tests/core/test_hybrid_l6.py b/tests/core/test_hybrid_l6.py
index 5afd887da..ad0164420 100644
--- a/tests/core/test_hybrid_l6.py
+++ b/tests/core/test_hybrid_l6.py
@@ -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": {
diff --git a/tests/core/test_imdb_provider.py b/tests/core/test_imdb_provider.py
index d93917869..32a8f62c4 100644
--- a/tests/core/test_imdb_provider.py
+++ b/tests/core/test_imdb_provider.py
@@ -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"
diff --git a/tests/core/test_import_hls_ism.py b/tests/core/test_import_hls_ism.py
index f7f61edee..a63d819a7 100644
--- a/tests/core/test_import_hls_ism.py
+++ b/tests/core/test_import_hls_ism.py
@@ -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")
diff --git a/tests/core/test_import_missing_key.py b/tests/core/test_import_missing_key.py
index 7e0876481..8c08f45cf 100644
--- a/tests/core/test_import_missing_key.py
+++ b/tests/core/test_import_missing_key.py
@@ -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"]
diff --git a/tests/core/test_import_tracks.py b/tests/core/test_import_tracks.py
index acd1fea85..6cc786cb1 100644
--- a/tests/core/test_import_tracks.py
+++ b/tests/core/test_import_tracks.py
@@ -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
diff --git a/tests/core/test_ism_init.py b/tests/core/test_ism_init.py
index a259ac10c..42437e3cf 100644
--- a/tests/core/test_ism_init.py
+++ b/tests/core/test_ism_init.py
@@ -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
diff --git a/tests/core/test_ism_merge.py b/tests/core/test_ism_merge.py
index d928fdb15..ca0e12ef2 100644
--- a/tests/core/test_ism_merge.py
+++ b/tests/core/test_ism_merge.py
@@ -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\none\n\n", b"2\n00:00:02,000 --> 00:00:03,000\ntwo\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"]
diff --git a/tests/core/test_ism_range.py b/tests/core/test_ism_range.py
index 59728409f..97b80852b 100644
--- a/tests/core/test_ism_range.py
+++ b/tests/core/test_ism_range.py
@@ -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
diff --git a/tests/core/test_lang_exclusions.py b/tests/core/test_lang_exclusions.py
index 814b83cf9..a4b1b6bf3 100644
--- a/tests/core/test_lang_exclusions.py
+++ b/tests/core/test_lang_exclusions.py
@@ -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()
diff --git a/tests/core/test_language_tag_rules.py b/tests/core/test_language_tag_rules.py
index a4bf59137..e47793498 100644
--- a/tests/core/test_language_tag_rules.py
+++ b/tests/core/test_language_tag_rules.py
@@ -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"}]
diff --git a/tests/core/test_licence_turns.py b/tests/core/test_licence_turns.py
index 90fb9c7ff..9bafe72a3 100644
--- a/tests/core/test_licence_turns.py
+++ b/tests/core/test_licence_turns.py
@@ -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",
[
diff --git a/tests/core/test_load_tracks_enrich.py b/tests/core/test_load_tracks_enrich.py
index 789a1f932..7b5c2fdd1 100644
--- a/tests/core/test_load_tracks_enrich.py
+++ b/tests/core/test_load_tracks_enrich.py
@@ -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)
diff --git a/tests/core/test_login.py b/tests/core/test_login.py
index d0dcd2e43..ca75e1ee4 100644
--- a/tests/core/test_login.py
+++ b/tests/core/test_login.py
@@ -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"
diff --git a/tests/core/test_main_banner.py b/tests/core/test_main_banner.py
index 7a995cce5..91a339230 100644
--- a/tests/core/test_main_banner.py
+++ b/tests/core/test_main_banner.py
@@ -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"))
diff --git a/tests/core/test_manifest_corpus.py b/tests/core/test_manifest_corpus.py
index 483fa8460..b75641761 100644
--- a/tests/core/test_manifest_corpus.py
+++ b/tests/core/test_manifest_corpus.py
@@ -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)
diff --git a/tests/core/test_manifest_snapshot.py b/tests/core/test_manifest_snapshot.py
index c6cff89b5..1a3f38bf3 100644
--- a/tests/core/test_manifest_snapshot.py
+++ b/tests/core/test_manifest_snapshot.py
@@ -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)
diff --git a/tests/core/test_metadata_id_validation.py b/tests/core/test_metadata_id_validation.py
index e8ccd9342..05329af67 100644
--- a/tests/core/test_metadata_id_validation.py
+++ b/tests/core/test_metadata_id_validation.py
@@ -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."""
diff --git a/tests/core/test_mp4_container_routing.py b/tests/core/test_mp4_container_routing.py
index 0b41a40aa..4cb2abee9 100644
--- a/tests/core/test_mp4_container_routing.py
+++ b/tests/core/test_mp4_container_routing.py
@@ -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:
diff --git a/tests/core/test_mp4decrypt_track_key.py b/tests/core/test_mp4decrypt_track_key.py
index b56fc7175..71af20b48 100644
--- a/tests/core/test_mp4decrypt_track_key.py
+++ b/tests/core/test_mp4decrypt_track_key.py
@@ -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
diff --git a/tests/core/test_music_container.py b/tests/core/test_music_container.py
index 8e154a54b..3c3f0ce33 100644
--- a/tests/core/test_music_container.py
+++ b/tests/core/test_music_container.py
@@ -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)
diff --git a/tests/core/test_music_extract.py b/tests/core/test_music_extract.py
index e01ed4aeb..14c489b01 100644
--- a/tests/core/test_music_extract.py
+++ b/tests/core/test_music_extract.py
@@ -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")
diff --git a/tests/core/test_music_folder_template.py b/tests/core/test_music_folder_template.py
index 52ef84b78..8dc39eb81 100644
--- a/tests/core/test_music_folder_template.py
+++ b/tests/core/test_music_folder_template.py
@@ -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}"}
diff --git a/tests/core/test_music_lyrics.py b/tests/core/test_music_lyrics.py
index b7ae8f841..816380c30 100644
--- a/tests/core/test_music_lyrics.py
+++ b/tests/core/test_music_lyrics.py
@@ -1,8 +1,6 @@
"""The shared lyric helpers; each expected value is recorded from the service copies that they replace."""
-import pytest
-
-from unshackle.core.music import cues_to_lrc, cues_to_srt, lrc_stamp, lrc_to_cues
+from unshackle.core.music import cues_to_lrc, cues_to_srt, lrc_to_cues
LRC = (
"[00:05.00]third line\r\n"
@@ -30,30 +28,6 @@ CUES = [
]
-@pytest.mark.parametrize(
- ("ms", "stamp"),
- [
- (0, "00:00.00"),
- (-1, "00:00.00"),
- (-5000, "00:00.00"),
- (5, "00:00.00"),
- (15, "00:00.02"),
- (25, "00:00.02"),
- (995, "00:01.00"),
- (59994, "00:59.99"),
- (59995, "01:00.00"),
- (59996, "01:00.00"),
- (60000, "01:00.00"),
- (3599990, "59:59.99"),
- (5999994, "99:59.99"),
- (5999996, "100:00.00"),
- (123456789, "2057:36.79"),
- ],
-)
-def test_lrc_stamp(ms: int, stamp: str) -> None:
- assert lrc_stamp(ms) == stamp
-
-
def test_cues_to_lrc() -> None:
cues = [(-20, 0, "before zero"), (0, 3000, "first"), (59996, 62000, "one minute"), (6000000, 6003000, "hundred")]
assert cues_to_lrc(cues) == "[00:00.00]before zero\n[00:00.00]first\n[01:00.00]one minute\n[100:00.00]hundred"
diff --git a/tests/core/test_music_renderer.py b/tests/core/test_music_renderer.py
index 0daeab171..d375f0e97 100644
--- a/tests/core/test_music_renderer.py
+++ b/tests/core/test_music_renderer.py
@@ -1,7 +1,6 @@
from collections.abc import Callable
from typing import Any
-import jsonpickle
import pytest
from tests.lang_selection.test_kind_only_selection import FakeService, run
@@ -57,13 +56,6 @@ def test_a_collection_of_different_releases_shows_only_its_own_facts() -> None:
assert str(mixed(**OWN_FACTS)) == "Own Artist - Own Title (1990)"
-def test_a_collection_of_different_releases_shows_the_date_and_quality_set_on_it() -> None:
- music = mixed(**OWN_FACTS)
- vars(music).update(release_date="1990-02-03", quality="MP3")
- rows = dict(header(music))
- assert (rows["Released"], rows["Quality"]) == ("February 3, 1990", "MP3")
-
-
@pytest.mark.parametrize(
("facts", "line"),
[
@@ -112,26 +104,6 @@ def test_a_collection_of_one_release_shows_the_facts_of_its_first_song(album_art
assert str(Album([song(1, "Album 1", album_artist, year=None)])) == f"{artist} - Album 1 (?)"
-def test_a_collection_of_one_release_shows_its_own_facts_before_those_of_a_song() -> None:
- facts = {**OWN_FACTS, "total_discs": 3, "total_duration": 4000}
- music = Album([song(n, "Album 1", "Album Artist", explicit=True) for n in (1, 2)], **facts)
- vars(music).update(released="1990-02-03", quality="MP3")
- assert dict(header(music)) == {
- "Title": "Own Title",
- "Artist": "Own Artist",
- "Type": "Playlist Explicit",
- "Released": "February 3, 1990",
- "Year": "1990",
- "Tracks": "9",
- "Discs": "3",
- "Length": "1h 06m 40s",
- "Quality": "MP3",
- "Genre": "Genre 1",
- "Label": "Label 1",
- }
- assert str(music) == "Own Artist - Own Title (1990)"
-
-
@pytest.mark.parametrize("nested", [False, True])
def test_the_first_song_of_one_release_gives_the_quality_flags(nested: bool) -> None:
data = {"lossless": True, "hires": True, "release_date": "2001-10-14"}
@@ -139,21 +111,6 @@ def test_the_first_song_of_one_release_gives_the_quality_flags(nested: bool) ->
assert (dict(header(music))["Quality"], dict(header(music))["Released"]) == ("Hi-Res Lossless", "October 14, 2001")
-def test_a_blank_album_of_one_release_keeps_its_row() -> None:
- music = Album([song(1, " ", "Album Artist")])
- assert str(music) == "Album Artist - (2001)"
- assert header(music)[0] == ("Title", "")
-
-
-@pytest.mark.parametrize("duration", [10**400, float("inf"), "Infinity"], ids=["huge", "infinite", "text"])
-def test_a_song_duration_too_large_to_convert_does_not_count(duration: Any) -> None:
- music = Album([song(1, "Album 1", None), song(2, "Album 1", None, data={"duration": duration})])
- assert dict(header(music))["Length"] == "1m 00s"
- with console.capture() as out:
- console.print(music.tree())
- assert "Name 2" in out.get()
-
-
@pytest.mark.parametrize("field", ["title", "artist", "kind"])
def test_a_fact_is_text_and_not_markup(field: str) -> None:
with console.capture() as out:
@@ -161,55 +118,9 @@ def test_a_fact_is_text_and_not_markup(field: str) -> None:
assert "[red]x[/y] :cd:" in out.get().lower()
-def test_a_collection_from_the_title_cache_shows_only_its_own_facts() -> None:
- restored = jsonpickle.loads(jsonpickle.dumps(mixed(**OWN_FACTS)))
- assert header(restored) == OWN_ROWS
- assert str(restored) == "Own Artist - Own Title (1990)"
-
-
-@pytest.mark.parametrize("field", ["year", "total_tracks", "total_discs", "total_duration"])
-def test_a_collection_number_is_never_a_bool(field: str) -> None:
- with pytest.raises(TypeError, match=f"Expected {field} to be an int, not True"):
- Album([], **{field: True})
-
-
-def test_a_total_duration_too_large_to_convert_is_shown_as_given() -> None:
- assert MusicRenderer.format_total_duration(10**400) == str(10**400)
-
-
NOT_MARKUP = pytest.mark.parametrize("name", ["Live [red]set[/red]", "Live [/x]", "Live :cd:", "Live \\"])
-@NOT_MARKUP
-def test_the_title_line_shows_the_collection_as_given(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, name: str
-) -> None:
- service = FakeService({})
- service.get_titles = lambda: mixed(artist="Own Artist", title=name) # type: ignore[assignment]
-
- with console.capture() as out:
- run(monkeypatch, caplog, {}, service=service, list_titles=True)
-
- assert f" Album: Own Artist - {name} " in out.get()
-
-
-@NOT_MARKUP
-def test_the_track_line_shows_the_song_as_given(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, name: str
-) -> None:
- music = mixed()
- music[0].name = name
- service = FakeService({1: {}})
- tracks = service.get_tracks(service.get_titles()[0])
- service.get_titles = lambda: music # type: ignore[assignment]
- service.get_tracks = lambda title: tracks # type: ignore[method-assign]
-
- with console.capture() as out:
- run(monkeypatch, caplog, {}, service=service)
-
- assert f" Track 01: {name} " in out.get()
-
-
@pytest.mark.parametrize(
("label", "hires"),
[
@@ -301,21 +212,6 @@ def test_a_collection_of_different_releases_is_not_drawn_again(
assert "Quality" not in out
-def test_the_header_is_drawn_again_once_per_release(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- music, tracks = flac_release()
- higher = Tracks()
- higher.add(
- Audio(id_="b", url="https://x/b", language="en", codec=Audio.Codec.FLAC, bit_depth=24, sample_rate=192000)
- )
-
- out = run_release(monkeypatch, caplog, music, lambda title: tracks if title is music[0] else higher, to_end=True)
-
- assert out.count("Length") == 2
- assert music[0].data["sample_rate"] == 96000
-
-
def test_a_later_first_song_fills_the_release_song(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
diff --git a/tests/core/test_music_tagger_roundtrip.py b/tests/core/test_music_tagger_roundtrip.py
index db417754a..ca2b42dd0 100644
--- a/tests/core/test_music_tagger_roundtrip.py
+++ b/tests/core/test_music_tagger_roundtrip.py
@@ -165,12 +165,6 @@ def test_lyrics_land_in_the_container_field_players_read(tmp_path: Path) -> None
assert not [key for key in audio if "LYRICS" in key]
-def test_a_song_without_lyrics_writes_no_lyrics_field(flac_path: Path) -> None:
- write_music_metadata(flac_path, make_song())
-
- assert "LYRICS" not in FLAC(flac_path)
-
-
def test_cover_art_is_fetched_with_the_session_and_embedded(flac_path: Path) -> None:
session = FakeSession(PNG_STUB)
@@ -234,14 +228,6 @@ def test_a_webp_cover_is_embedded_as_jpeg(tmp_path: Path) -> None:
assert bytes(cover).startswith(b"\xff\xd8\xff")
-def test_a_cover_over_16_mib_is_skipped(flac_path: Path, caplog: pytest.LogCaptureFixture) -> None:
- result = write_music_metadata(flac_path, make_song(), session=FakeSession(PNG_STUB + b"\x00" * 2**24))
-
- assert not result.artwork_embedded
- assert not FLAC(flac_path).pictures
- assert "16 MiB" in caplog.text
-
-
def test_artists_and_replaygain_read_back(flac_path: Path) -> None:
song = make_song()
song.data = {"artists": ["Example Artist", "Guest Artist"], "replaygain_track_gain": -7.25, "quality": "Hi-Res"}
@@ -254,17 +240,6 @@ def test_artists_and_replaygain_read_back(flac_path: Path) -> None:
assert "COMMENT" not in audio, "a quality label is display text, not a comment"
-def test_a_replaygain_value_that_is_not_a_number_is_skipped(flac_path: Path) -> None:
- song = make_song()
- song.data = {"replaygain_track_gain": "nan", "replaygain_track_peak": "inf", "replaygain_album_gain": -3}
-
- write_music_metadata(flac_path, song)
-
- audio = FLAC(flac_path)
- assert "REPLAYGAIN_TRACK_GAIN" not in audio and "REPLAYGAIN_TRACK_PEAK" not in audio
- assert audio["REPLAYGAIN_ALBUM_GAIN"] == ["-3.00 dB"]
-
-
def test_opus_gets_no_replaygain(tmp_path: Path) -> None:
"""RFC 7845 section 5.2.1: an Opus file should not carry REPLAYGAIN_* tags."""
path = tmp_path / "04. Example Track.opus"
diff --git a/tests/core/test_music_wanted.py b/tests/core/test_music_wanted.py
index 9c317a8df..190367993 100644
--- a/tests/core/test_music_wanted.py
+++ b/tests/core/test_music_wanted.py
@@ -60,10 +60,6 @@ def multi_disc(per_disc: int = 4) -> list[Song]:
return [make_song(track=n, disc=d) for d in (1, 2) for n in range(1, per_disc + 1)]
-def test_a_bare_number_takes_one_track():
- assert select("3", single_disc()) == [3]
-
-
def test_a_range_takes_the_tracks_inside_it():
assert select("2-5", single_disc()) == [2, 3, 4, 5]
@@ -82,12 +78,6 @@ def test_the_disc_form_takes_one_track_of_that_disc():
assert kept == [(2, 3)]
-def test_the_disc_form_ranges_inside_one_disc():
- songs = multi_disc()
- kept = [(s.disc, s.track) for s in songs if title_wanted(s, SeasonRange().convert("2x1-2x3"))]
- assert kept == [(2, 1), (2, 2), (2, 3)]
-
-
def test_a_bare_number_on_a_multi_disc_release_is_disc_one():
"""An omitted disc is disc 1, the number the tracklist shows for a one-disc release."""
songs = multi_disc()
@@ -128,12 +118,6 @@ def test_bad_music_tokens_fail(token):
SeasonRange().parse_tokens(token)
-def test_song_matches_only_its_own_key():
- song = make_song(track=3, disc=2)
- assert song.matches_wanted(["2x3"]) is True
- assert song.matches_wanted(["1x3", "2x4"]) is False
-
-
def test_a_playlist_lists_and_selects_by_position_but_tags_by_album_track():
songs = [make_song(1, position=1, album="Z"), make_song(6, 2, 2, "B"), make_song(1, position=3, album="A")]
playlist = Album(reversed(songs), kind="playlist")
@@ -146,12 +130,6 @@ def test_a_playlist_lists_and_selects_by_position_but_tags_by_album_track():
assert (tags["TRACKNUMBER"], tags["DISCNUMBER"]) == ("6", "2")
-def test_a_playlist_shows_no_disc_count():
- playlist = Album([make_song(6, 2, position=1), make_song(1, 3, position=2)], kind="playlist")
- assert "Discs" not in list(MusicRenderer().render_header(playlist).columns[0].cells)
- assert "Discs" in list(MusicRenderer().render_header(Album([make_song(6, 2)])).columns[0].cells)
-
-
@pytest.mark.parametrize(("position", "key", "rule"), [(9, "1x9", "Track 09"), (None, "2x6", "Track 06")])
def test_the_download_loop_names_the_number_that_selected_the_song(monkeypatch, caplog, position, key, rule):
service = FakeService({1: {}})
diff --git a/tests/core/test_no_plugin_names.py b/tests/core/test_no_plugin_names.py
deleted file mode 100644
index 70507ab57..000000000
--- a/tests/core/test_no_plugin_names.py
+++ /dev/null
@@ -1,38 +0,0 @@
-"""Core names no plugin DRM: a plugin brings its own names, and its docs live in its own README."""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-ROOT = Path(__file__).resolve().parents[2]
-NAMES = re.compile("|".join(["mona" + "lisa", "bb" + "ts", "blow" + "fish", "stripe " + "cipher", r"\.ml" + "d"]), re.I)
-PLACES = ["unshackle", "tests", "docs", "mkdocs.yml", "README.md", "pyproject.toml"]
-SKIP = {"plugins", "_repos", "__pycache__"}
-
-
-def files() -> list[Path]:
- found = []
- for place in PLACES:
- path = ROOT / place
- if path.is_file():
- found.append(path)
- elif path.is_dir():
- found += [
- p
- for p in path.rglob("*")
- if p.is_file()
- and not SKIP & set(p.relative_to(path).parts)
- and p.suffix in {".py", ".md", ".yml", ".yaml", ".toml", ".json", ".txt"}
- ]
- return found
-
-
-def test_core_tests_and_docs_name_no_plugin_drm() -> None:
- hits = [
- f"{path.relative_to(ROOT)}:{n}"
- for path in files()
- for n, line in enumerate(path.read_text(encoding="utf-8", errors="replace").splitlines(), 1)
- if NAMES.search(line)
- ]
- assert hits == []
diff --git a/tests/core/test_paged_aac.py b/tests/core/test_paged_aac.py
index 46645ea2a..f45c2573e 100644
--- a/tests/core/test_paged_aac.py
+++ b/tests/core/test_paged_aac.py
@@ -8,12 +8,10 @@ import pytest
from unshackle.core.drm.paged_aac import (
PAGED_AAC,
- adts_header,
audio_config,
checksum,
cut,
first_frame,
- frame_sizes,
pages,
to_adts,
)
@@ -81,15 +79,6 @@ def adts_frames(stream: bytes) -> list[bytes]:
return frames
-def fletcher_32(data: bytes) -> int:
- """The page checksum by its definition, one word at a time."""
- total = running = 0xFFFF
- for word in (int.from_bytes(data[pos : pos + 2], "little") for pos in range(0, len(data), 2)):
- total = (total + word) % 0xFFFF or 0xFFFF
- running = (running + total) % 0xFFFF or 0xFFFF
- return running << 16 | total
-
-
FIRST = page(0, [b"\x01abc", b"\x00de"], number=b"\x00\x01")
LATER = page(0, [b"\x01xy"], number=b"\x00\x04")
@@ -99,11 +88,6 @@ def test_the_header_page_of_a_real_file_passes_its_checksum() -> None:
assert checksum(b"") == 0xFFFFFFFF
-@pytest.mark.parametrize("data", [b"\x01", b"\x01\x02\x03", bytes(6), b"\xff\xff" * 300, bytes(range(256))])
-def test_the_checksum_matches_its_definition(data: bytes) -> None:
- assert checksum(data) == fletcher_32(data)
-
-
def test_the_header_page_of_a_real_file_names_the_rate_and_the_channels() -> None:
flags, number, records = next(pages(HEADER_PAGE))
@@ -136,12 +120,6 @@ def test_the_cut_needs_he_aacv2_and_a_sample_count_that_fits(
assert cut(header(FIRST, total=total, first_record=config_record(config, true=true)) + FIRST) == expected
-def test_the_cut_reads_the_rate_of_the_header_page() -> None:
- data = header(FIRST, total=7081, first_record=config_record(true=1000, rate=48000)) + FIRST
-
- assert cut(data) == (6081, 1000, 48000)
-
-
def test_no_cut_comes_from_a_header_page_without_the_sample_counts() -> None:
assert cut(page(HEADER, [config_record(), b"\x02" + bytes(7)]) + FIRST) is None
@@ -163,10 +141,6 @@ def test_a_stored_frame_of_255_bytes_laces_as_255_then_0() -> None:
assert adts_frames(to_adts(file(shared))) == [b"\xff" + bytes(255)]
-def test_a_lacing_entry_of_255_continues_the_frame() -> None:
- assert frame_sizes(bytes([255, 3, 7])) == [258, 7]
-
-
@pytest.mark.parametrize(
("field", "expected"),
[
@@ -180,15 +154,6 @@ def test_the_number_of_the_first_frame_grows_with_its_value(field: bytes, expect
assert first_frame(field, 0) == expected
-def test_a_frame_too_long_for_adts_raises() -> None:
- with pytest.raises(ValueError, match="too long for ADTS"):
- adts_header(0x1FFF, 7, 1)
-
-
-def test_an_empty_file_has_no_page() -> None:
- assert list(pages(b"")) == []
-
-
@pytest.mark.parametrize("padding", [1, 2, 3, 4, 4096])
def test_zero_bytes_after_the_last_page_are_dropped(padding: int) -> None:
assert to_adts(file(FIRST) + bytes(padding)) == to_adts(file(FIRST))
diff --git a/tests/core/test_placement.py b/tests/core/test_placement.py
index 5c70e1281..71acf3bad 100644
--- a/tests/core/test_placement.py
+++ b/tests/core/test_placement.py
@@ -54,15 +54,6 @@ def audio(path: Path, track_id: str, *, descriptive: bool = False) -> Audio:
return track
-def test_two_same_language_aac_tracks_get_two_paths_without_mux(tmp_path: Path) -> None:
- place = placement(tmp_path / "out")
- folder = place.folder(MediaInfo(AAC_MP4))
- main = audio(tmp_path / "Audio_a1.mp4", "a1")
- described = audio(tmp_path / "Audio_a2.mp4", "a2", descriptive=True)
- paths = [place.track_file(folder, t, MediaInfo(AAC_MP4)) for t in (main, described)]
- assert [p.name for p in paths] == ["Some.Movie.2026.en.AAC.m4a", "Some.Movie.2026.en.AAC.2.m4a"]
-
-
def test_two_kept_tracks_beside_one_output_get_two_paths(tmp_path: Path) -> None:
place = placement(tmp_path)
output = place.claim(tmp_path, "Some.Movie.2026", ".mkv")
diff --git a/tests/core/test_playlist_encoding.py b/tests/core/test_playlist_encoding.py
index 8bda6d522..6a08094c7 100644
--- a/tests/core/test_playlist_encoding.py
+++ b/tests/core/test_playlist_encoding.py
@@ -76,13 +76,6 @@ def test_load_drm_from_playlist_sets_utf8_when_server_sent_no_charset() -> None:
assert res.encoding == "utf-8"
-def test_load_drm_from_playlist_keeps_a_charset_the_server_sent() -> None:
- res = make_response(MEDIA, "https://example.com/video/720.m3u8", "iso-8859-1")
-
- make_track(res).load_drm_from_playlist()
- assert res.encoding == "iso-8859-1"
-
-
MPD_LATIN1 = 'café'.encode("iso-8859-1")
diff --git a/tests/core/test_playready_errors.py b/tests/core/test_playready_errors.py
index 360ad497a..67895f009 100644
--- a/tests/core/test_playready_errors.py
+++ b/tests/core/test_playready_errors.py
@@ -1,19 +1,7 @@
-from collections import Counter
-
import pytest
-from pyplayready.misc.drmresults import DrmResult
from unshackle.core.drm.playready import PlayReady
-from unshackle.core.drm.playready_errors import REVOCATION_CODES, describe, is_revocation
-
-
-def test_only_oem_code_repeats_upstream() -> None:
- counts = Counter(m.value[0] for m in DrmResult)
- assert [code for code, n in counts.items() if n > 1] == [0x8004DFF]
-
-
-def test_revocation_codes() -> None:
- assert REVOCATION_CODES == {0x8004C065, 0x8004C053, 0x8004C07D}
+from unshackle.core.drm.playready_errors import describe, is_revocation
@pytest.mark.parametrize("code", [0x8004C065, -2147172251, 0x8004C053, 0x8004C07D])
@@ -31,23 +19,6 @@ def test_describe_signed_and_unsigned() -> None:
assert describe(0x8004C065) == describe(-2147172251) == text
-def test_describe_uses_upstream_name() -> None:
- assert describe(0x8004C006) == "DRM_E_INVALID_LICENSE (0x8004C006): The license is invalid"
-
-
-@pytest.mark.parametrize(
- ("code", "text"),
- [
- (0x80041100, "DRM_E_CH_BASECODE (0x80041100)"),
- (0x80048000, "DRM_E_LEGACY_BASECODE (0x80048000)"),
- (0x8004DFFC, "DRM_E_OEM_CONSTRAINT_1_FAIL (0x8004DFFC): Failed while OEM CONSTRAINT-1 check"),
- (0x8004DFFF, "DRM_E_HDCP_NON_SECURE (0x8004DFFF): Attempt to play back through insecure HDMI output path"),
- ],
-)
-def test_describe_local_codes(code: int, text: str) -> None:
- assert describe(code) == text
-
-
@pytest.mark.parametrize("code", [-1021, 0x08004DFF])
def test_describe_unknown(code: int) -> None:
assert describe(code) is None
diff --git a/tests/core/test_playready_multi_header.py b/tests/core/test_playready_multi_header.py
index ebbeb3ced..63202a71f 100644
--- a/tests/core/test_playready_multi_header.py
+++ b/tests/core/test_playready_multi_header.py
@@ -105,13 +105,6 @@ def _cert(**_: Any) -> None:
return None
-def test_kids_are_collected_from_every_header() -> None:
- drm = _drm(_wrm_header(KID_A), _wrm_header(KID_B))
-
- assert len(drm.pssh.wrm_headers) == 2
- assert drm.kids == [KID_A, KID_B]
-
-
def test_single_header_sends_one_challenge_with_the_original_pssh() -> None:
drm = _drm(_wrm_header(KID_A, KID_B))
cdm = FakeCdm({KID_A: KEY_A, KID_B: KEY_B})
@@ -335,21 +328,6 @@ def test_kids_are_read_from_every_header_version(version: str, body: str, expect
assert PlayReady(pssh=PSSH(_pro(_xml_header(version, body)))).kids == expected
-def test_customattributes_kids_follow_the_header_kids() -> None:
- kid_c = UUID("11111111-2222-3333-4444-555555555555")
- header = _xml_header(
- "4.1.0.0",
- f''
- f'',
- )
-
- drm = PlayReady(pssh=PSSH(_pro(header)))
-
- # the header KID leads (it is what the licence server acts on); CUSTOMATTRIBUTES KIDs stay reachable
- assert drm.kids == [KID_A, KID_B, kid_c]
- assert drm.kid == KID_A
-
-
def test_kids_of_every_header_lead_then_customattributes_then_the_given_kid() -> None:
kid_c = UUID("11111111-2222-3333-4444-555555555555")
kid_d = UUID("66666666-7777-8888-9999-000000000000")
diff --git a/tests/core/test_plugin_devices.py b/tests/core/test_plugin_devices.py
index a79ea9400..672e90248 100644
--- a/tests/core/test_plugin_devices.py
+++ b/tests/core/test_plugin_devices.py
@@ -10,7 +10,7 @@ from typing import Any
import pytest
-from tests.drm_plugins import EXAMPLE, OTHER, ExampleDevice
+from tests.drm_plugins import EXAMPLE, ExampleDevice
from tests.remote.sessions import launch_session
from unshackle.commands.dl import dl
from unshackle.core import plugins
@@ -86,11 +86,6 @@ def test_an_operator_device_file_comes_before_the_bundled_one(monkeypatch: pytes
assert device is not None and device.source == app_config.directories.prds / "EXAMPLE_DEFAULT.exd"
-def test_devices_need_a_device_suffix() -> None:
- with pytest.raises(ValueError, match="has devices but no device_suffix"):
- dataclasses.replace(OTHER, default_device="EXAMPLE_DEFAULT")
-
-
@pytest.fixture
def bundled(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
"""EXAMPLE with its own devices EXAMPLE_DEFAULT (its default) and EXAMPLE_V3, and no operator device files."""
diff --git a/tests/core/test_plugin_licence.py b/tests/core/test_plugin_licence.py
index 0b110278c..5bbbf2a4b 100644
--- a/tests/core/test_plugin_licence.py
+++ b/tests/core/test_plugin_licence.py
@@ -55,10 +55,6 @@ def run_licence(track: Video, vault: MemoryVault, device: Any, loads: list, **fl
return drm
-def test_the_drm_reads_its_kids_from_the_plugin_data_before_any_licence(example_plugins: None) -> None:
- assert plugin_track().drm[0].kids == [KID]
-
-
def test_a_vault_key_stands_in_for_the_licence_and_loads_no_device(example_plugins: None, device: Any) -> None:
loads: list = []
drm = run_licence(plugin_track(), MemoryVault({KID: KEY}), device, loads)
diff --git a/tests/core/test_print_listing.py b/tests/core/test_print_listing.py
deleted file mode 100644
index 61b99dfb1..000000000
--- a/tests/core/test_print_listing.py
+++ /dev/null
@@ -1,31 +0,0 @@
-import os
-
-import pytest
-
-from unshackle.core import console as console_module
-from unshackle.core.config import config
-from unshackle.core.console import console, print_listing
-
-
-@pytest.mark.parametrize("wide, lines", [(True, 1), (False, 2)])
-def test_wide_output_prints_a_listing_at_the_terminal_width(
- monkeypatch: pytest.MonkeyPatch, wide: bool, lines: int
-) -> None:
- monkeypatch.setattr(config, "wide_output", wide)
- monkeypatch.setattr(console_module.shutil, "get_terminal_size", lambda: os.terminal_size((140, 40)))
- monkeypatch.setattr(console, "width", 80)
- with console.capture() as capture:
- print_listing("x" * 100)
- assert len(capture.get().strip("\n").splitlines()) == lines
- assert console.width == 80
-
-
-def test_print_wide_keeps_a_legacy_windows_console_at_its_width(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(console_module.shutil, "get_terminal_size", lambda: os.terminal_size((140, 40)))
- monkeypatch.setattr(console, "legacy_windows", True)
- monkeypatch.setattr(console, "_width", 80)
- monkeypatch.setattr(console, "_height", 25)
- with console.capture():
- for _ in range(3):
- console_module.print_wide("x")
- assert console._width == 80
diff --git a/tests/core/test_provider_title_match.py b/tests/core/test_provider_title_match.py
index ff04dd8f0..afda1d9bb 100644
--- a/tests/core/test_provider_title_match.py
+++ b/tests/core/test_provider_title_match.py
@@ -47,11 +47,6 @@ def test_clean_keeps_letters_and_digits_of_every_script(title: str, expected: st
assert clean(title) == expected
-@pytest.mark.parametrize("title", ["เป็นต่อ", "हिंदी", "进击的巨人", "Война и мир", "The Matrix"])
-def test_fuzzy_match_a_title_with_itself(title: str) -> None:
- assert fuzzy_match(title, title)
-
-
@pytest.mark.parametrize(
("a", "b"),
[
@@ -181,11 +176,6 @@ def tmdb_search(monkeypatch: pytest.MonkeyPatch, results: list[dict], year: int
return (result.external_ids.tmdb_id if result else None), sent
-def test_tmdb_tv_search_matches_the_year_on_any_air_date(monkeypatch: pytest.MonkeyPatch) -> None:
- _, sent = tmdb_search(monkeypatch, [{"id": 1, "name": "EXAMPLE", "first_air_date": "2016-04-04"}], 2020)
- assert sent["year"] == 2020 and "first_air_date_year" not in sent
-
-
@pytest.mark.parametrize(("year", "expected"), [(2023, 2), (1999, 1), (2024, 1), (None, 1)])
def test_tmdb_prefers_the_series_that_first_aired_in_the_year_on_a_title_tie(
monkeypatch: pytest.MonkeyPatch, year: int | None, expected: int
diff --git a/tests/core/test_proxy_dispatch.py b/tests/core/test_proxy_dispatch.py
index de3ca5cad..46688cddc 100644
--- a/tests/core/test_proxy_dispatch.py
+++ b/tests/core/test_proxy_dispatch.py
@@ -3,10 +3,8 @@ provider:query split, the named or bare provider lookup, and the line that repor
from __future__ import annotations
-import json
import logging
from collections.abc import Iterator
-from contextlib import contextmanager
import pytest
@@ -96,11 +94,6 @@ def test_a_city_query_without_a_provider_prefix_fails_with_a_hint(providers: lis
resolve_proxy(value, providers)
-def test_a_prefix_naming_a_failed_provider_reports_why(providers: list) -> None:
- with pytest.raises(ValueError, match="Gamma could not load: no route"):
- split_proxy_query("gamma:us", providers)
-
-
def test_named_query_asks_only_that_provider(providers: list) -> None:
provider, uri = pick_proxy(providers, "ca", "beta")
assert isinstance(provider, Beta) and uri == "http://c:d@beta-ca.example:80"
@@ -133,20 +126,12 @@ def test_describe_masks_the_host_of_a_basic_proxy() -> None:
assert line == "Using Basic Proxy: http://xxxxx:xxxxx@xxxxx:3128"
-def test_describe_prefers_the_provider_display() -> None:
- assert describe_proxy(Beta(), "http://c:d@beta.example:80", "us") == "Using Beta Proxy via Dallas (server 12)"
-
-
def test_describe_reports_a_vpn_connection() -> None:
tunnel = Tunnel({"public_ip": "203.0.113.9", "city": "Toronto", "country": "Canada"})
assert describe_proxy(tunnel, "http://127.0.0.1:8888", "alpha:ca") == "VPN Connected: 203.0.113.9 (Toronto, Canada)"
assert tunnel.asked == ["alpha:ca"]
-def test_describe_falls_back_when_the_vpn_has_no_connection_info() -> None:
- assert describe_proxy(Tunnel(None), "http://127.0.0.1:8888", "ca") == "Using Tunnel Proxy: http://127.0.0.1:8888"
-
-
def test_describe_shows_the_full_uri_in_debug_only_when_allowed() -> None:
logging.getLogger().setLevel(logging.DEBUG)
uri = "http://user:pass@alpha.example:80"
@@ -154,13 +139,6 @@ def test_describe_shows_the_full_uri_in_debug_only_when_allowed() -> None:
assert "user:pass" not in describe_proxy(Alpha(), uri, "us", allow_debug=False)
-@pytest.mark.parametrize(
- "uri", ["http://user:pass@proxy.example:8080", "https://proxy.example:443", "socks5h://proxy.example:1080"]
-)
-def test_resolve_proxy_passes_a_uri_through(providers: list, uri: str) -> None:
- assert resolve_proxy(uri, providers) == uri
-
-
def test_resolve_proxy_logs_the_provider_without_credentials(providers: list, caplog: pytest.LogCaptureFixture) -> None:
logging.getLogger().setLevel(logging.DEBUG)
with caplog.at_level(logging.INFO, logger="proxies"):
@@ -170,11 +148,6 @@ def test_resolve_proxy_logs_the_provider_without_credentials(providers: list, ca
assert "Using Alpha Proxy: http://xxxxx:xxxxx@alpha.example:80" in caplog.text
-def test_resolve_proxy_raises_when_no_provider_answers(providers: list) -> None:
- with pytest.raises(ValueError, match="No proxy provider had a proxy for de"):
- resolve_proxy("de", providers)
-
-
def test_bare_query_skips_a_provider_that_raises(caplog: pytest.LogCaptureFixture) -> None:
class Broken:
def get_proxy(self, query: str) -> str:
@@ -202,15 +175,6 @@ def test_named_query_passes_the_provider_error_on_as_a_value_error() -> None:
assert isinstance(raised.value.__cause__, ConnectionError)
-def test_named_query_names_the_provider_for_a_bad_catalogue_response() -> None:
- class Broken:
- def get_proxy(self, query: str) -> str:
- raise json.JSONDecodeError("Expecting value", "", 0)
-
- with pytest.raises(ValueError, match="The proxy provider broken failed for us: Expecting value"):
- pick_proxy([Broken()], "us", "broken")
-
-
def test_named_query_passes_a_query_error_on_unchanged() -> None:
class Strict:
def get_proxy(self, query: str) -> str:
@@ -263,35 +227,6 @@ def test_resolve_proxy_value_reads_each_form(providers: list, value: str, expect
assert resolve_proxy_value(value, providers) == expected
-def test_resolve_proxy_value_starts_a_forwarder_for_a_control_d_resolver(monkeypatch: pytest.MonkeyPatch) -> None:
- from unshackle.core.proxies import controld
-
- monkeypatch.setattr(controld, "local_proxy", lambda uri: "http://127.0.0.1:4000")
- resolved = resolve_proxy_value("controld://efgh456@dns.controld.com", [])
- assert resolved == ResolvedProxy("http://127.0.0.1:4000", None, "Using a local proxy on port 4000")
-
-
-@pytest.mark.parametrize(
- ("value", "message"), [("us", "Getting a Proxy to us..."), ("gluetun:ca", "Connecting to VPN (ca)...")]
-)
-def test_the_status_wraps_only_the_provider_lookup(providers: list, value: str, message: str) -> None:
- shown: list[str] = []
-
- @contextmanager
- def status(text: str) -> Iterator[None]:
- shown.append(text)
- yield
-
- resolve_proxy_value(value, [*providers, Gluetun(ca="http://g.example:8888")], status=status)
- resolve_proxy_value("http://proxy.example:8080", providers, status=status)
- assert shown == [message]
-
-
-@pytest.mark.parametrize("value", ["localhost:8080", "1.2.3.4:3128"])
-def test_resolve_proxy_passes_a_host_and_port_through(providers: list, value: str) -> None:
- assert resolve_proxy(value, providers) == value
-
-
class Recorder(Alpha):
def __init__(self, **answers: str) -> None:
super().__init__(**answers)
diff --git a/tests/core/test_proxy_loading.py b/tests/core/test_proxy_loading.py
index 13eca9574..c9d23c798 100644
--- a/tests/core/test_proxy_loading.py
+++ b/tests/core/test_proxy_loading.py
@@ -40,11 +40,6 @@ def test_bare_query_skips_the_failed_provider() -> None:
assert uri.endswith("@us-dal.prod.surfshark.com:443")
-def test_query_naming_another_provider_still_works() -> None:
- uri = resolve_proxy("surfsharkvpn:us", load_proxy_providers(OTHERS))
- assert uri.endswith("@us-dal.prod.surfshark.com:443")
-
-
@pytest.mark.parametrize("name", ["nordvpn", "NordVPN"])
def test_query_naming_the_failed_provider_reports_why(name: str) -> None:
with pytest.raises(ValueError, match="NordVPN could not load: NordVPN needs its Service Credentials"):
@@ -156,20 +151,3 @@ def test_construction_makes_no_request_and_the_first_read_fetches_once(
assert getattr(provider, attr) == [{"country": "US"}]
getattr(provider, attr)
assert calls == [1]
-
-
-def test_health_probe_reads_each_proxy_catalogue(monkeypatch: pytest.MonkeyPatch) -> None:
- from unshackle.core.api.handlers import run_health_checks
-
- calls: list[int] = []
-
- def countries() -> list[dict]:
- calls.append(1)
- return [{"serverCount": 3}]
-
- monkeypatch.setattr(config, "key_vaults", [])
- monkeypatch.setattr(config, "proxy_providers", {"nordvpn": CREDENTIALS})
- monkeypatch.setattr(NordVPN, "get_countries", staticmethod(countries))
- detail = {c["id"]: c for c in run_health_checks()}["proxies"]["detail"]
- assert calls == [1]
- assert "NordVPN (1 Country (3 Servers))" in detail
diff --git a/tests/core/test_proxy_network_selector.py b/tests/core/test_proxy_network_selector.py
index 6e0e4c32d..856efa3a8 100644
--- a/tests/core/test_proxy_network_selector.py
+++ b/tests/core/test_proxy_network_selector.py
@@ -79,14 +79,6 @@ def test_remote_sends_a_surfshark_selector_unresolved() -> None:
assert resolve_remote_proxy_arg("surfsharkvpn:fr-bod@datacamp", []) == "surfsharkvpn:fr-bod@datacamp"
-@pytest.mark.parametrize(
- ("query", "expected"),
- [("fr", ("fr", None)), ("fr:paris@-datacamp", ("fr:paris", "-datacamp")), ("fr@", ("fr", None))],
-)
-def test_split_selector(query: str, expected: tuple) -> None:
- assert asn.split_selector(query) == expected
-
-
@pytest.mark.parametrize(
("selector", "expected"),
[("datacamp", ["a"]), ("Data-Camp", ["a"]), ("host royale", ["b", "c"]), ("-datacamp", ["b", "c"])],
@@ -109,11 +101,6 @@ def test_select_drops_a_server_whose_network_is_unknown_even_when_excluding(monk
assert asn.select({"a": "10.0.0.1", "x": "10.9.9.9"}, "-hostroyale") == ["a"]
-def test_select_needs_a_name() -> None:
- with pytest.raises(ValueError, match="needs a network name"):
- asn.select({"a": "10.0.0.1"}, "-")
-
-
def test_lookup_parses_cymru_bulk_whois(monkeypatch: pytest.MonkeyPatch) -> None:
answer = (
b"Bulk mode; whois.cymru.com [2026-10-22 18:57:29 +0000]\n"
@@ -146,10 +133,6 @@ def test_lookup_failure_raises_connection_error(monkeypatch: pytest.MonkeyPatch)
assert asn.lookup(["10.0.0.1"]) == {"10.0.0.1": DATACAMP}
-def test_describe_names_the_network() -> None:
- assert asn.describe("fr-028.example", "10.0.0.1") == "fr-028.example (10.0.0.1, Datacamp Limited)"
-
-
def test_describe_never_raises(monkeypatch: pytest.MonkeyPatch) -> None:
def unresolvable(host: str) -> str:
raise socket.gaierror("no such host")
@@ -182,13 +165,6 @@ def test_nordvpn_network_selector_skips_the_server_map(nordvpn: NordVPN, query:
assert nordvpn.last_hostname == f"{host}.proxy.nordvpn.com"
-@pytest.mark.parametrize(("value", "host"), [("-datacamp", "ca2"), ("ca@10.0.0.9", "ca3")])
-def test_nordvpn_server_map_takes_a_selector(nordvpn: NordVPN, value: str, host: str) -> None:
- nordvpn.server_map = {"ca": value}
- uri = nordvpn.get_proxy("ca")
- assert uri is not None and uri.endswith(f"@{host}.proxy.nordvpn.com:89")
-
-
def test_nordvpn_selector_with_no_match_raises(nordvpn: NordVPN) -> None:
with pytest.raises(ValueError, match="No NordVPN server in ca"):
nordvpn.get_proxy("ca@m247")
diff --git a/tests/core/test_qr_text.py b/tests/core/test_qr_text.py
index 58dcbb589..ff78e8b25 100644
--- a/tests/core/test_qr_text.py
+++ b/tests/core/test_qr_text.py
@@ -1,7 +1,6 @@
import segno
-from unshackle.core import console
-from unshackle.core.console import qr_text, show_qr
+from unshackle.core.console import qr_text
TOP = {"\u2588": True, "\u2580": True, "\u2584": False, " ": False}
BOTTOM = {"\u2588": True, "\u2580": False, "\u2584": True, " ": False}
@@ -15,14 +14,3 @@ def test_each_line_holds_two_module_rows_of_the_code() -> None:
unpacked += [[TOP[c] for c in line], [BOTTOM[c] for c in line]]
assert unpacked[: len(rows)] == rows
assert not any(cell for row in unpacked[len(rows) :] for cell in row)
-
-
-def test_short_text_is_a_full_qr_code_not_a_micro_one() -> None:
- assert len(qr_text("12345", indent=0).plain.splitlines()) * 2 >= 21 + 4
-
-
-def test_text_longer_than_a_qr_code_holds_draws_nothing(monkeypatch) -> None:
- printed: list = []
- monkeypatch.setattr(console.console, "print", lambda *a, **k: printed.extend(a))
- show_qr("\u20ac" * 1500)
- assert printed == []
diff --git a/tests/core/test_read_qr_image.py b/tests/core/test_read_qr_image.py
index cee96672f..215daef19 100644
--- a/tests/core/test_read_qr_image.py
+++ b/tests/core/test_read_qr_image.py
@@ -103,17 +103,6 @@ def test_each_mask_gives_its_text(mask: int) -> None:
assert read_qr_image(segno_png(mask=mask)) == URL
-@pytest.mark.parametrize("scale", [1, 3, 8])
-@pytest.mark.parametrize("border", [0, 4])
-def test_each_scale_and_border_gives_its_text(scale: int, border: int) -> None:
- assert read_qr_image(segno_png(scale=scale, border=border)) == URL
-
-
-@pytest.mark.parametrize("scale", [1.37, 2.6, 4.5])
-def test_a_resize_by_a_fraction_gives_its_text(scale: float) -> None:
- assert read_qr_image(encode_png((0,), (255,), colour=0, scale=scale)) == URL
-
-
@pytest.mark.parametrize(
"png",
[
diff --git a/tests/core/test_remote_cdm_no_probe.py b/tests/core/test_remote_cdm_no_probe.py
index 530a01927..eeb0a49d4 100644
--- a/tests/core/test_remote_cdm_no_probe.py
+++ b/tests/core/test_remote_cdm_no_probe.py
@@ -63,11 +63,6 @@ def test_missing_connection_field_raises(make: Any, field: str) -> None:
make(**{field: ""})
-def test_playready_rejects_quoted_security_level() -> None:
- with pytest.raises(TypeError):
- playready(security_level="3000")
-
-
@pytest.fixture
def redirecting_host() -> Iterator[tuple[int, list[tuple[str, Any]]]]:
"""Redirect `/dev/open` to the `Location` in the `to` query, and answer the target like a serve API."""
diff --git a/tests/core/test_remote_cdm_pssh_reuse.py b/tests/core/test_remote_cdm_pssh_reuse.py
index 6689e9bac..4ce64e60b 100644
--- a/tests/core/test_remote_cdm_pssh_reuse.py
+++ b/tests/core/test_remote_cdm_pssh_reuse.py
@@ -67,21 +67,6 @@ def test_a_later_session_does_not_inherit_the_earlier_pssh_or_kids(make_cdm: Cal
assert sent == [("FIRST_TITLE_PSSH", ["00" * 16]), (base64.b64encode(b"second").decode(), None)]
-@pytest.mark.parametrize("make_cdm", ADAPTERS)
-def test_two_open_sessions_keep_their_own_pssh(make_cdm: Callable[[], Any]) -> None:
- cdm = make_cdm()
- sent = recording(cdm)
-
- one = cdm.open()
- two = cdm.open()
- cdm.set_pssh_b64("PSSH_ONE", session_id=one)
- cdm.set_pssh_b64("PSSH_TWO", session_id=two)
- cdm.get_license_challenge(one, FakePssh(b"x"))
- cdm.get_license_challenge(two, FakePssh(b"x"))
-
- assert [init_data for init_data, _ in sent] == ["PSSH_ONE", "PSSH_TWO"]
-
-
@pytest.mark.parametrize("make_cdm", ADAPTERS)
@pytest.mark.parametrize("header", [WRMHeader(HEADER), HEADER])
def test_a_bare_wrm_header_goes_out_as_a_playready_object(make_cdm: Callable[[], Any], header: Any) -> None:
diff --git a/tests/core/test_repackage_aac.py b/tests/core/test_repackage_aac.py
deleted file mode 100644
index 2a055d559..000000000
--- a/tests/core/test_repackage_aac.py
+++ /dev/null
@@ -1,64 +0,0 @@
-"""Repackaging an MPEG-TS with ADTS AAC into MP4 runs one clean FFmpeg pass."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-from collections.abc import Callable, Iterator
-from pathlib import Path
-
-import pytest
-from langcodes import Language
-
-from unshackle.core import binaries
-from unshackle.core.tracks import Video
-from unshackle.core.utilities import close_debug_logger, init_debug_logger
-
-pytestmark = pytest.mark.skipif(binaries.FFMPEG is None, reason="requires ffmpeg")
-
-
-@pytest.fixture
-def tool_run_levels(tmp_path: Path) -> Iterator[Callable[[], list[str]]]:
- """Enable the debug log; the fixture value reads the levels of its tool_run records."""
- log = tmp_path / "debug.jsonl"
- init_debug_logger(log_path=log, enabled=True)
-
- def levels() -> list[str]:
- close_debug_logger()
- entries = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()]
- return [e["level"] for e in entries if e["operation"] == "tool_run"]
-
- yield levels
- close_debug_logger()
-
-
-def video_at(path: Path) -> Video:
- video = Video(url="https://cdn.example/v.mp4", language=Language.get("en"))
- video.path = path
- return video
-
-
-def test_adts_aac_repackages_in_one_pass_with_no_error_record(
- tmp_path: Path, tool_run_levels: Callable[[], list[str]]
-) -> None:
- source = tmp_path / "v.mp4"
- subprocess.run(
- [str(binaries.FFMPEG), "-nostdin", "-v", "error", "-y"]
- + ["-f", "lavfi", "-i", "testsrc2=size=160x90:rate=24:duration=1", "-f", "lavfi", "-i", "sine=duration=1"]
- + ["-c:v", "mpeg4", "-c:a", "aac", "-f", "mpegts", str(source)],
- check=True,
- )
- video = video_at(source)
- video.repackage()
-
- assert video.path and video.path.stat().st_size > 0
- assert tool_run_levels() == ["DEBUG"]
-
-
-def test_a_real_repackage_failure_still_logs_an_error(tmp_path: Path, tool_run_levels: Callable[[], list[str]]) -> None:
- source = tmp_path / "v.mp4"
- source.write_bytes(b"not media")
- with pytest.raises(subprocess.CalledProcessError):
- video_at(source).repackage()
-
- assert tool_run_levels() == ["ERROR"]
diff --git a/tests/core/test_request_record.py b/tests/core/test_request_record.py
index 69e28a025..47ce0845c 100644
--- a/tests/core/test_request_record.py
+++ b/tests/core/test_request_record.py
@@ -2,10 +2,8 @@
from __future__ import annotations
-import copy
import importlib
import json
-import logging
import re
import threading
from collections.abc import Iterator
@@ -14,7 +12,6 @@ from pathlib import Path
from types import SimpleNamespace
from typing import Any
-import m3u8
import pytest
import requests as rq
from requests.adapters import HTTPAdapter
@@ -22,13 +19,12 @@ from urllib3.util.retry import Retry
from unshackle.core import service as service_module
from unshackle.core import session as http_session
-from unshackle.core.config import Config, config
-from unshackle.core.manifests import DASH, HLS
+from unshackle.core.config import config
+from unshackle.core.manifests import DASH
from unshackle.core.service import Service
from unshackle.core.session import MaxRetriesError, RecordedSession, RnetSession, record_requests, unrecorded
from unshackle.core.tracks.track import Track
from unshackle.core.utilities import close_debug_logger, init_debug_logger
-from unshackle.core.utils import bitrate
from unshackle.core.utils.xml import load_xml
dl = importlib.import_module("unshackle.core.downloaders.requests")
@@ -190,13 +186,6 @@ def test_a_retried_request_writes_one_entry_per_attempt(server, debug_log, make_
assert [(e["request"]["attempt"], e["response"]["status"]) for e in entries] == [(1, 503), (2, 200)]
-def test_each_rnet_attempt_with_a_cut_body_names_its_failure(server, debug_log):
- with pytest.raises(MaxRetriesError):
- rnet_session().get(f"{server.url}/cut", max_retries=1)
-
- assert [(e["request"]["attempt"], bool(e["failure"])) for e in records(debug_log)] == [(1, True), (2, True)]
-
-
@pytest.mark.parametrize(
("make_session", "kwargs", "error"),
[
@@ -262,22 +251,6 @@ def test_a_debug_run_without_debug_requests_records_nothing(
assert "session_start" in debug_log.read_text(encoding="utf-8")
-def test_record_requests_leaves_the_session_alone_without_debug_requests(monkeypatch):
- monkeypatch.setattr(config, "debug_requests", False)
- session = rq.Session()
- record_requests(session)
-
- assert type(session) is rq.Session
-
-
-def test_a_recorded_adapter_reads_through_and_copies(debug_log):
- session = requests_session()
- adapter = session.get_adapter("http://h")
-
- assert adapter.max_retries.total == 2
- assert copy.copy(adapter).max_retries.total == 2
-
-
def test_the_service_session_records_only_with_debug_requests(monkeypatch):
class Stop(Exception):
pass
@@ -298,14 +271,6 @@ def test_the_service_session_records_only_with_debug_requests(monkeypatch):
JWT = "eyJhbGciOi.eyJzdWIi.c2ln"
-def test_the_rnet_console_line_keeps_the_query(server, debug_log, caplog):
- with caplog.at_level("DEBUG"):
- rnet_session().get(f"{server.url}/{JWT}/pts_0.mp4?sig=S2")
-
- (line,) = [r.getMessage() for r in caplog.records if " 200 " in r.getMessage()]
- assert f'"GET /{JWT}/pts_0.mp4?sig=S2 ' in line
-
-
def body_of(
server: Server, debug_log: Path, make_session: Any, path: str, kind: str | None, doc: str | bytes, **kw: Any
) -> tuple[str, bytes] | None:
@@ -425,15 +390,6 @@ def test_a_hostile_path_stays_inside_the_folder(server, debug_log, tmp_path, mak
assert sorted(e["response"]["body_file"] for e in records(debug_log)) == sorted(names)
-@pytest.mark.parametrize("make_session", SESSIONS)
-def test_the_size_comes_from_the_body_without_a_content_length(server, debug_log, make_session):
- server.docs["/chunked"] = '{"a": 1}'
- server.types["/chunked"] = "application/json"
- make_session().get(f"{server.url}/chunked")
-
- assert records(debug_log)[-1]["response"]["size"] == len(server.docs["/chunked"])
-
-
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_recorded_body_stays_readable_by_the_caller(server, debug_log, make_session):
server.docs["/api/read"] = '{"a": 1}'
@@ -472,11 +428,6 @@ def test_a_failed_body_read_is_recorded_and_raised_again(debug_log):
assert entry["response"]["body_error"].startswith("ChunkedEncodingError")
-@pytest.mark.parametrize(("value", "limit"), [(None, 0), ("5", 5), (-5, 0)])
-def test_the_body_limit_is_a_byte_count(value, limit):
- assert Config(debug_requests_body_limit=value).debug_requests_body_limit == limit
-
-
def serve_starts(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
from aiohttp import web
from click.testing import CliRunner
@@ -511,41 +462,10 @@ def test_a_server_process_records_no_body(server, debug_log, monkeypatch, tmp_pa
assert not folder(debug_log).exists()
-def test_serve_keeps_request_lines_out_of_the_dashboard_log(monkeypatch, tmp_path, caplog):
- from unshackle.core.api.stats import ring
-
- serve_starts(monkeypatch, tmp_path)
- with caplog.at_level(logging.DEBUG):
- for name in ("RnetSession", "urllib3.connectionpool", "EXAMPLE"):
- logging.getLogger(name).debug(f"EXAMPLE {name} line ?sig=S1")
- logging.getLogger("RnetSession").warning("EXAMPLE retry warning")
-
- lines = [r["msg"] for r in ring.since(0) if r["msg"].startswith("EXAMPLE")]
- assert lines == ["EXAMPLE EXAMPLE line ?sig=S1", "EXAMPLE retry warning"]
-
-
def paths(path: Path) -> list[str]:
return [e["request"]["path"] for e in records(path)]
-@pytest.mark.parametrize("make_session", SESSIONS)
-def test_hls_media_probes_are_not_recorded_but_the_playlist_is(server, debug_log, make_session):
- session = make_session()
- server.docs["/v.m3u8"] = '#EXTM3U\n#EXT-X-MAP:URI="init.mp4",BYTERANGE="1@0"\n#EXTINF:4,\nseg.ts\n#EXT-X-ENDLIST\n'
- HLS.probe_ts_info(f"{server.url}/v.m3u8", session)
- playlist = m3u8.loads(server.docs["/v.m3u8"], uri=f"{server.url}/v.m3u8")
- HLS.fetch_init_section(session, playlist.segments[0].init_section, 0)
- HLS.get_track_kid_from_init(
- SimpleNamespace(get_key_id=lambda _: None), # type: ignore[arg-type]
- HLS.init_reader(playlist, session),
- playlist.segments[0].init_section,
- )
-
- assert (server.hits.count("/seg.ts"), server.hits.count("/init.mp4")) == (1, 2)
- assert paths(debug_log) == ["/v.m3u8"]
- assert len(list(folder(debug_log).iterdir())) == 1
-
-
@pytest.mark.parametrize("make_session", SESSIONS)
def test_dash_init_reads_are_not_recorded_but_the_manifest_is(server, debug_log, monkeypatch, make_session):
monkeypatch.setattr(Track, "get_key_id", lambda *_: None)
@@ -582,28 +502,6 @@ def test_dash_init_reads_are_not_recorded_but_the_manifest_is(server, debug_log,
assert [p.suffix for p in folder(debug_log).iterdir()] == [".mpd"]
-@pytest.mark.parametrize("make_session", SESSIONS)
-def test_bitrate_probes_are_not_recorded(server, debug_log, make_session):
- session = make_session()
- bitrate.ranged_get(f"{server.url}/a.mp4", session, "bytes=0-0")
- bitrate.probe_size(bitrate.Segment(f"{server.url}/plain-b.mp4", None, None, 0.0), session)
-
- assert server.hits == ["/a.mp4", "/plain-b.mp4", "/plain-b.mp4"]
- assert records(debug_log) == []
-
-
-@pytest.mark.parametrize("make_session", SESSIONS)
-def test_track_init_and_sample_probes_are_not_recorded(server, debug_log, make_session):
- session = make_session()
- track = Track(url=f"{server.url}/c.mp4", language="en")
- track.get_init_segment(session=session)
- track.sample_byte_range(session)
- Track(url=f"{server.url}/plain-c.mp4", language="en").get_init_segment(session=session)
-
- assert (server.hits.count("/c.mp4"), server.hits.count("/plain-c.mp4")) == (4, 3)
- assert records(debug_log) == []
-
-
def test_an_unrecorded_probe_keeps_the_session_attributes(server, debug_log):
class Own(rq.Session):
def __init__(self) -> None:
diff --git a/tests/core/test_resolution_naming.py b/tests/core/test_resolution_naming.py
index 8a057be74..26b9d0839 100644
--- a/tests/core/test_resolution_naming.py
+++ b/tests/core/test_resolution_naming.py
@@ -79,14 +79,6 @@ def test_standard_resolution(width: int, height: int, expected: int) -> None:
assert standard_resolution(width, height) == expected
-def test_a_picture_with_one_side_uses_it() -> None:
- assert standard_resolution(None, 1088) == 1080
-
-
-def test_a_picture_with_no_size_has_no_resolution() -> None:
- assert standard_resolution(None, None) is None
-
-
def test_the_filename_quality_uses_the_standard_resolution() -> None:
assert quality(1920, 1088) == "1080p"
assert quality(1920, 800) == "1080p"
@@ -96,10 +88,6 @@ def test_an_interlaced_picture_keeps_the_i_suffix() -> None:
assert quality(1920, 1088, scan_type="Interlaced") == "1080i"
-def test_a_video_track_with_no_size_gives_an_empty_quality() -> None:
- assert quality(None, None) == ""
-
-
def video(width: int, height: int) -> Video:
return Video(url="https://example.test/v.mpd", language="en", codec=Video.Codec.AVC, width=width, height=height)
diff --git a/tests/core/test_resolve_by_ids.py b/tests/core/test_resolve_by_ids.py
index a01d88670..505931aff 100644
--- a/tests/core/test_resolve_by_ids.py
+++ b/tests/core/test_resolve_by_ids.py
@@ -114,11 +114,6 @@ def test_no_ids_searches(monkeypatch: pytest.MonkeyPatch) -> None:
assert calls and calls[0][:3] == ("Futurama", 1999, "tv")
-def test_no_ids_and_no_title_returns_none(monkeypatch: pytest.MonkeyPatch) -> None:
- patch_providers(monkeypatch, {})
- assert providers.resolve_by_ids(kind="tv") is None
-
-
def test_per_kind_order_puts_tvdb_first_for_tv(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "metadata_providers", {"tv": ["tvdb", "tmdb", "imdb", "omdb"]})
tvdb = FakeProvider("tvdb", MetadataResult(title="Futurama", year=1999, kind="tv"))
@@ -158,15 +153,6 @@ def test_an_anilist_id_reaches_the_anilist_provider(monkeypatch: pytest.MonkeyPa
assert tmdb.asked == []
-def test_a_supplied_anilist_id_survives_a_provider_miss(monkeypatch: pytest.MonkeyPatch) -> None:
- patch_providers(monkeypatch, {})
-
- result = providers.resolve_by_ids(anilist_id="21", title="One Piece", kind="tv")
-
- assert result is not None
- assert result.external_ids.anilist_id == 21
-
-
def test_a_mal_reference_carries_only_what_the_lookup_answered(monkeypatch: pytest.MonkeyPatch) -> None:
anilist = FakeProvider("anilist", MetadataResult(title="One Piece", external_ids=ExternalIds(anilist_id=21)))
patch_providers(monkeypatch, {"anilist": anilist})
@@ -178,15 +164,6 @@ def test_a_mal_reference_carries_only_what_the_lookup_answered(monkeypatch: pyte
assert result.external_ids.anilist_id == 21
-def test_a_mal_reference_that_misses_leaves_no_anilist_id(monkeypatch: pytest.MonkeyPatch) -> None:
- patch_providers(monkeypatch, {})
-
- result = providers.resolve_by_ids(anilist_id="mal:21", title="One Piece", kind="tv")
-
- assert result is not None
- assert result.external_ids.anilist_id is None
-
-
def test_anilist_combines_with_a_western_id(monkeypatch: pytest.MonkeyPatch) -> None:
tmdb = FakeProvider("tmdb", MetadataResult(title="One Piece", year=1999, kind="tv"))
anilist = FakeProvider("anilist", MetadataResult(title="One Piece", external_ids=ExternalIds(anilist_id=21)))
@@ -205,11 +182,6 @@ def test_anime_puts_anilist_first_with_the_rest_behind_it() -> None:
assert ordered[1:] == [name for name in providers.DEFAULT_ORDER if name != "anilist"]
-def test_without_the_hint_anilist_stays_last() -> None:
- assert [cls.NAME for cls in providers.provider_order("tv")] == list(providers.DEFAULT_ORDER)
- assert providers.DEFAULT_ORDER[-1] == "anilist"
-
-
def test_the_hint_cannot_add_a_provider_the_config_left_out(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "metadata_providers", ["tmdb", "tvdb"])
assert [cls.NAME for cls in providers.provider_order("tv", anime=True)] == ["tmdb", "tvdb"]
@@ -230,26 +202,11 @@ def test_an_anime_hint_falls_through_to_the_normal_order_on_a_miss(monkeypatch:
assert imdb.asked == ["tt0388629"]
-def test_the_anime_hint_reaches_search(monkeypatch: pytest.MonkeyPatch) -> None:
- calls: list[dict] = []
- monkeypatch.setattr(providers, "search_metadata", lambda *a, **kw: calls.append({"args": a}) or None)
- patch_providers(monkeypatch, {})
-
- providers.resolve_by_ids(title="One Piece", year=1999, kind="tv", anime=True)
-
- assert calls and calls[0]["args"][-1] is True
-
-
def test_the_service_provider_goes_first_with_the_rest_behind_it() -> None:
ordered = [cls.NAME for cls in providers.provider_order("movie", prefer="tmdb")]
assert ordered == ["tmdb", *(name for name in providers.DEFAULT_ORDER if name != "tmdb")]
-def test_the_service_provider_cannot_add_one_the_config_left_out(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(config, "metadata_providers", ["imdb"])
- assert [cls.NAME for cls in providers.provider_order("movie", prefer="tmdb")] == ["imdb"]
-
-
def test_the_service_provider_goes_before_anilist_on_an_anime_title() -> None:
ordered = [cls.NAME for cls in providers.provider_order("tv", anime=True, prefer="tmdb")]
assert ordered[:2] == ["tmdb", "anilist"]
@@ -373,19 +330,6 @@ def test_an_anilist_match_takes_the_mapped_western_ids(
assert hit.external_ids == expected
-@pytest.mark.parametrize(
- "ids",
- [ExternalIds("tt1", 5, "tv", 7, 21), ExternalIds(imdb_id="tt1"), ExternalIds()],
- ids=["all-western-ids", "not-anilist", "no-ids"],
-)
-def test_the_map_is_not_read_without_need(anime_map: list[bool], ids: ExternalIds) -> None:
- before = ExternalIds(**vars(ids))
-
- providers.fill_anime_ids(MetadataResult(kind="tv", external_ids=ids), "tv")
-
- assert (anime_map, ids) == ([], before)
-
-
def test_a_supplied_anilist_id_takes_the_mapped_western_ids(
monkeypatch: pytest.MonkeyPatch, anime_map: list[bool]
) -> None:
@@ -397,43 +341,11 @@ def test_a_supplied_anilist_id_takes_the_mapped_western_ids(
assert result.external_ids == ExternalIds("tt0388629", 37854, "tv", 81797, 21)
-def test_the_tagging_lookup_fills_the_rest_without_a_tmdb_key(
- monkeypatch: pytest.MonkeyPatch, anime_map: list[bool]
-) -> None:
- patch_providers(monkeypatch, {"anilist": FakeProvider("anilist", anilist_hit())})
-
- result = providers.resolve_by_ids(37854, anilist_id=21, kind="tv")
-
- assert result is not None
- assert result.external_ids == ExternalIds("tt0388629", 37854, "tv", 81797, 21)
-
-
-def test_a_supplied_western_id_wins_over_the_map(monkeypatch: pytest.MonkeyPatch, anime_map: list[bool]) -> None:
- patch_providers(monkeypatch, {"anilist": FakeProvider("anilist", anilist_hit())})
-
- result = providers.resolve_by_ids(tvdb_id=1, anilist_id=21, kind="tv")
-
- assert result is not None
- assert result.external_ids == ExternalIds(tvdb_id=1, anilist_id=21)
-
-
class SearchHit(FakeProvider):
def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
return self._result
-def test_a_search_hit_on_anilist_takes_the_mapped_western_ids(
- monkeypatch: pytest.MonkeyPatch, anime_map: list[bool]
-) -> None:
- monkeypatch.setattr(config, "disable_metadata", False)
- monkeypatch.setattr(providers, "provider_order", lambda *a: [lambda: SearchHit("anilist", anilist_hit())])
-
- result = search_metadata("One Piece", None, "tv")
-
- assert result is not None
- assert result.external_ids == ExternalIds("tt0388629", 37854, "tv", 81797, 21)
-
-
def western_hit(language: str | None = "ja", kind: str = "tv", **ids: Any) -> MetadataResult:
ids = {"tmdb_id": 37854, "tmdb_kind": kind, **ids}
return MetadataResult(title="One Piece", kind=kind, original_language=language, external_ids=ExternalIds(**ids))
@@ -520,14 +432,3 @@ def test_a_search_hit_on_tmdb_takes_the_mapped_anilist_id(
assert result is not None
assert result.external_ids == ExternalIds(None, 37854, "tv", None, 21)
-
-
-def test_the_tagging_search_picks_the_anilist_entry_of_the_season(
- monkeypatch: pytest.MonkeyPatch, anime_map: list[bool]
-) -> None:
- monkeypatch.setattr(providers, "search_metadata", lambda *a, **kw: western_hit(tmdb_id=1429))
-
- result = providers.resolve_by_ids(title="EXAMPLE", kind="tv", season=2)
-
- assert result is not None
- assert result.external_ids.anilist_id == 20958
diff --git a/tests/core/test_resume_across_runs.py b/tests/core/test_resume_across_runs.py
index 56ea5a1d6..d18d1d599 100644
--- a/tests/core/test_resume_across_runs.py
+++ b/tests/core/test_resume_across_runs.py
@@ -194,17 +194,6 @@ def test_flag_off_stashes_nothing(temp_root, monkeypatch):
assert not (temp_root / RESUME_STASH).exists()
-def test_partials_are_not_stashed(temp_root, monkeypatch):
- monkeypatch.setattr(config, "continue_downloads", True)
-
- with task_temp_dir():
- with pytest.raises(RuntimeError):
- run_download(monkeypatch, failing_parser)
-
- assert (temp_root / RESUME_STASH / SEG_NAME / "0.mp4").exists()
- assert not list((temp_root / RESUME_STASH).rglob("*.!dev"))
-
-
def test_a_checkpointed_output_is_stashed_beside_its_segments(temp_root, monkeypatch):
monkeypatch.setattr(config, "continue_downloads", True)
with task_temp_dir() as task_dir:
diff --git a/tests/core/test_retry_after.py b/tests/core/test_retry_after.py
index d082f7f66..fae517a55 100644
--- a/tests/core/test_retry_after.py
+++ b/tests/core/test_retry_after.py
@@ -25,10 +25,6 @@ def test_numeric_retry_after_passes_through(session):
assert session.get_sleep_time(response("3"), 1) == 3.0
-def test_huge_numeric_retry_after_is_clamped(session):
- assert session.get_sleep_time(response("86400"), 1) == session.max_backoff
-
-
def test_huge_numeric_retry_after_respects_session_cap():
session = RnetSession(max_backoff=5.0)
assert session.get_sleep_time(response("86400"), 1) == 5.0
@@ -55,11 +51,6 @@ def test_malformed_retry_after_falls_back_to_backoff(session):
assert 0 < value <= session.max_backoff
-def test_empty_retry_after_falls_back_to_backoff(session):
- value = session.get_sleep_time(response(""), 1)
- assert 0 < value <= session.max_backoff
-
-
def test_exponential_backoff_without_retry_after(session):
assert session.get_sleep_time(response(), 0) == 0.0
base = session.backoff_factor * 4
@@ -67,10 +58,6 @@ def test_exponential_backoff_without_retry_after(session):
assert session.get_sleep_time(response(), 30) == session.max_backoff
-def test_no_response_still_backs_off(session):
- assert session.get_sleep_time(None, 30) == session.max_backoff
-
-
def test_service_session_caps_retry_after():
retry = Service.get_session().get_adapter("https://example.invalid/").max_retries
assert retry.respect_retry_after_header
diff --git a/tests/core/test_rolling_merge_hls_ism.py b/tests/core/test_rolling_merge_hls_ism.py
index 149ce57ea..f2c6f43cd 100644
--- a/tests/core/test_rolling_merge_hls_ism.py
+++ b/tests/core/test_rolling_merge_hls_ism.py
@@ -194,13 +194,6 @@ def test_hls_discontinuity_keeps_post_merge(server, tmp_path, monkeypatch):
assert INIT in rolling[len(INIT) :]
-def test_ism_rolling_matches_post_merge(server, tmp_path, monkeypatch):
- plain, rolling = download_both_ways(ISM, lambda: ism_track(server), tmp_path, monkeypatch, True)
- assert rolling == plain
- assert rolling.endswith(b"".join(PARTS))
- assert len(rolling) > len(b"".join(PARTS))
-
-
@pytest.mark.parametrize(
"parser, make",
[(HLS, lambda srv: hls_track(srv, False)), (ISM, ism_track), (DASH, dash_track)],
diff --git a/tests/core/test_run_plan.py b/tests/core/test_run_plan.py
index 050364b1d..7c77123ee 100644
--- a/tests/core/test_run_plan.py
+++ b/tests/core/test_run_plan.py
@@ -4,7 +4,6 @@ from __future__ import annotations
from typing import Any
-import click
import pytest
from click.core import ParameterSource
@@ -71,11 +70,6 @@ def test_hybrid_needs_dovi_tool(monkeypatch: pytest.MonkeyPatch) -> None:
check_options({"range_": [Video.Range.HDR10]})
-def test_a_plan_error_exits_1_without_a_usage_block() -> None:
- assert PlanError("x").exit_code == 1
- assert not isinstance(PlanError("x"), click.UsageError)
-
-
def test_a_plan_error_is_an_invalid_parameters_api_error() -> None:
error = categorize_exception(PlanError("--sample and --include-sample cannot be used together."))
assert error.error_code is APIErrorCode.INVALID_PARAMETERS
diff --git a/tests/core/test_run_proxy.py b/tests/core/test_run_proxy.py
index ee1d6ae3f..4d059e2ed 100644
--- a/tests/core/test_run_proxy.py
+++ b/tests/core/test_run_proxy.py
@@ -114,13 +114,6 @@ def test_remote_cdm_host_does_not_warn(caplog, monkeypatch):
assert leaks(caplog) == []
-@pytest.mark.parametrize("host", ["8.8.8.8", "2606:4700:4700::1111", "api.example"])
-def test_public_hosts_warn(caplog, host):
- with caplog.at_level(logging.WARNING):
- lookup(host)
- assert len(leaks(caplog)) == 1
-
-
@pytest.mark.parametrize(("address", "warns"), [(("ws.example", 443), True), (("203.0.113.9", 443), False)])
def test_raw_socket_connect_to_a_host_name_warns(caplog, address, warns):
"""A connect to a host name looks it up in C, with no getaddrinfo event; an IP address had its lookup."""
@@ -181,13 +174,6 @@ def test_a_reloaded_service_class_uses_the_proxy_of_its_own_run(caplog):
assert "leak.example" in leaks(caplog)[0]
-def test_a_subclass_of_the_service_uses_the_proxy_of_its_own_run(caplog):
- sub = type("Sub", (Svc,), {})
- with caplog.at_level(logging.WARNING):
- sub().lookup("direct.example")
- assert leaks(caplog) == []
-
-
def test_a_helper_session_without_proxy_does_not_hide_a_leak(caplog):
"""A helper class of the service is not the service instance, so the proxy of the run still decides."""
with caplog.at_level(logging.WARNING):
@@ -260,17 +246,6 @@ def test_rnet_session_without_proxy_warns(caplog, kwargs, exempt, warns):
assert bool(leaks(caplog)) is warns
-def test_a_failing_check_never_fails_the_request(monkeypatch):
- def broken(*args):
- raise RuntimeError("dictionary changed size during iteration")
-
- monkeypatch.setattr(run_proxy, "check", broken)
- session = RnetSession()
- session.ensure_client = NoNetwork # type: ignore[method-assign]
- with pytest.raises(Sent):
- session.get("https://api.example/x", max_retries=0)
-
-
def test_core_parser_without_a_session_uses_the_run_proxy(monkeypatch):
from unshackle.core.manifests import DASH
diff --git a/tests/core/test_sanitize.py b/tests/core/test_sanitize.py
index 3b370de61..f5dc3b1f6 100644
--- a/tests/core/test_sanitize.py
+++ b/tests/core/test_sanitize.py
@@ -33,10 +33,6 @@ def test_safe_cache_key_rejects_absolute_paths_and_drives():
assert safe_cache_key("a\x00b") is None
-def test_safe_cache_key_accepts_plain_filename():
- assert safe_cache_key("valid-key_123") == "valid-key_123"
-
-
def test_safe_cache_key_accepts_nested_key_and_normalises_separators():
# A Cacher key with a subdirectory ("session_web/") keeps its
# posix form; a backslash from a Windows peer names the same nested file.
diff --git a/tests/core/test_sanitize_filename.py b/tests/core/test_sanitize_filename.py
index f06ad0076..e7ab2dd46 100644
--- a/tests/core/test_sanitize_filename.py
+++ b/tests/core/test_sanitize_filename.py
@@ -61,13 +61,6 @@ def test_ascii_filenames_transliterate_both_spellings(name: str, expected: str)
assert sanitize_filename(name, unicode=False) == expected
-def test_config_option_decides_when_unicode_is_not_passed(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(config, "unicode_filenames", True)
- assert sanitize_filename(THAI) == THAI
- monkeypatch.setattr(config, "unicode_filenames", False)
- assert sanitize_filename(THAI).isascii()
-
-
def test_sanitising_a_name_again_does_not_change_it() -> None:
# The removed "?" sits between the letter and its mark.
once = sanitize_filename("e?\u0301", unicode=True)
@@ -111,12 +104,6 @@ def test_episode_folder_from_the_series_template_keeps_the_multi_episode_separat
assert episode.get_filename(StubMediaInfo()) == "A.&.B.and.C.S01E02"
-@pytest.mark.parametrize("value", [["&"], [], "", False, {"&": None}, {"": "and"}, {1: "one"}, {"&": True}])
-def test_a_bad_filename_replacements_value_is_an_error(value) -> None:
- with pytest.raises(SystemExit, match="filename_replacements"):
- Config(filename_replacements=value)
-
-
def test_filename_replacements_default_to_empty_and_use_nfc_keys(monkeypatch) -> None:
assert Config().filename_replacements == {}
monkeypatch.setattr(
diff --git a/tests/core/test_segment_store.py b/tests/core/test_segment_store.py
index 79f208c4f..87bb60de5 100644
--- a/tests/core/test_segment_store.py
+++ b/tests/core/test_segment_store.py
@@ -53,10 +53,6 @@ def keep(monkeypatch):
monkeypatch.setattr(config, "continue_downloads", True)
-def test_identical_inputs_identical_digest():
- assert fingerprint(MPD, SEGMENTS) == fingerprint(MPD, SEGMENTS)
-
-
def test_rotating_query_token_ignored():
tokenised = [(f"{url}?token=abc123&expires=999", rng) for url, rng in SEGMENTS]
assert fingerprint(f"{MPD}?auth=xyz", tokenised) == fingerprint(MPD, SEGMENTS)
@@ -67,15 +63,6 @@ def test_changed_byte_range_changes_digest():
assert fingerprint(MPD, changed) != fingerprint(MPD, SEGMENTS)
-def test_changed_segment_count_changes_digest():
- assert fingerprint(MPD, SEGMENTS[:2]) != fingerprint(MPD, SEGMENTS)
-
-
-def test_changed_url_path_changes_digest():
- moved = [("https://cdn/other.mp4", rng) for _, rng in SEGMENTS]
- assert fingerprint(MPD, moved) != fingerprint(MPD, SEGMENTS)
-
-
def test_query_carried_identity_is_not_collapsed():
a = [("https://cdn/seg?t=0", None), ("https://cdn/seg?t=100", None)]
b = [("https://cdn/seg?t=0", None), ("https://cdn/seg?t=200", None)]
@@ -219,11 +206,6 @@ def test_complete_removes_the_directory_and_sidecar(tmp_path, keep):
store.complete()
-def test_sidecar_is_never_inside_save_dir(tmp_path):
- store = make_store(tmp_path)
- assert store.sidecar.parent == store.save_dir.parent
-
-
def test_open_keeps_decrypted_segments_only_for_the_same_keys(tmp_path, keep):
keys = DownloadMode(segment_keys=KEY_ARGS)
store = make_store(tmp_path)
diff --git a/tests/core/test_service_alias_case.py b/tests/core/test_service_alias_case.py
index 1bc31727e..c80e29a8c 100644
--- a/tests/core/test_service_alias_case.py
+++ b/tests/core/test_service_alias_case.py
@@ -26,9 +26,3 @@ def test_real_tag_beats_another_services_alias(two_services: None, value: str) -
from unshackle.core.services import Services
assert Services.get_tag(value) == "SVCB"
-
-
-def test_unknown_value_is_returned_unchanged(two_services: None) -> None:
- from unshackle.core.services import Services
-
- assert Services.get_tag("NOPE") == "NOPE"
diff --git a/tests/core/test_service_compiled_import_hint.py b/tests/core/test_service_compiled_import_hint.py
index a686a4776..a24b0af3f 100644
--- a/tests/core/test_service_compiled_import_hint.py
+++ b/tests/core/test_service_compiled_import_hint.py
@@ -23,8 +23,3 @@ def test_hint_names_the_file_this_python_needs(tmp_path: Path) -> None:
def test_no_hint_when_this_python_can_load_it(tmp_path: Path) -> None:
init = _service(tmp_path, f"example{EXTENSION_SUFFIXES[0]}")
assert compiled_import_hint("EXAMPLE.example", init) == ""
-
-
-def test_no_hint_for_a_pure_python_service(tmp_path: Path) -> None:
- init = _service(tmp_path)
- assert compiled_import_hint("EXAMPLE.example", init) == ""
diff --git a/tests/core/test_service_config.py b/tests/core/test_service_config.py
index 8a0a557a0..df6ed5a0f 100644
--- a/tests/core/test_service_config.py
+++ b/tests/core/test_service_config.py
@@ -23,12 +23,6 @@ def service_dir(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
return tmp_path
-def test_an_empty_config_yaml_takes_the_user_block(monkeypatch: pytest.MonkeyPatch, service_dir: Path) -> None:
- (service_dir / config.filenames.config).write_text("")
- monkeypatch.setattr(config, "services", {"EXAMPLE": {"region": "us"}})
- assert launch.load_service_config("EXAMPLE") == {"region": "us"}
-
-
def test_a_user_block_matches_the_tag_in_any_case(monkeypatch: pytest.MonkeyPatch, service_dir: Path) -> None:
(service_dir / config.filenames.config).write_text("region: gb\nendpoints:\n api: a\n")
monkeypatch.setattr(config, "services", {"example": {"region": "us"}})
diff --git a/tests/core/test_service_dl_overrides.py b/tests/core/test_service_dl_overrides.py
index b397b616c..d0d112b4f 100644
--- a/tests/core/test_service_dl_overrides.py
+++ b/tests/core/test_service_dl_overrides.py
@@ -46,13 +46,6 @@ def test_cli_value_beats_service_config():
assert ctx.params["v_lang"] == ["fr"]
-def test_env_value_beats_service_config(monkeypatch):
- monkeypatch.setenv("TEST_DL_WORKERS", "5")
- ctx = make_ctx()
- apply_service_dl_overrides(ctx, {"workers": 9}, log)
- assert ctx.params["workers"] == 5
-
-
def test_service_config_beats_global_default_map():
ctx = make_ctx(default_map={"v_lang": "de"})
assert ctx.params["v_lang"] == ["de"]
@@ -60,26 +53,12 @@ def test_service_config_beats_global_default_map():
assert ctx.params["v_lang"] == ["en"]
-def test_flag_global_true_service_false():
- ctx = make_ctx(default_map={"repack": True})
- assert ctx.params["repack"] is True
- apply_service_dl_overrides(ctx, {"repack": False}, log)
- assert ctx.params["repack"] is False
-
-
def test_range_scalar_converts_to_enum_list():
ctx = make_ctx()
apply_service_dl_overrides(ctx, {"range_": "HDR10"}, log)
assert ctx.params["range_"] == [Video.Range.HDR10]
-def test_range_alias_applies():
- """`range` in config is an accepted alias for the `range_` parameter."""
- ctx = make_ctx()
- apply_service_dl_overrides(ctx, {"range": "HDR10"}, log)
- assert ctx.params["range_"] == [Video.Range.HDR10]
-
-
def test_normalize_dl_config_maps_aliases():
assert normalize_dl_config({"range": "SDR", "list": True, "v_lang": ["en"]}) == {
"range_": "SDR",
@@ -140,27 +119,6 @@ def test_hand_built_ctx_skips_routing_params(caplog):
assert not caplog.records
-def test_hand_built_ctx_missing_param_is_skipped():
- """Known dl option absent from a hand-built context must not raise or be injected."""
- ctx = hand_built_ctx({})
- apply_service_dl_overrides(ctx, {"v_lang": ["en"]}, log)
- assert "v_lang" not in ctx.params
-
-
-@pytest.mark.parametrize(
- "value,expected",
- [
- (["en", "de"], ["en", "de"]),
- ("en,de", ["en", "de"]),
- ("en", ["en"]),
- ],
-)
-def test_language_range_yaml_shapes(value, expected):
- ctx = make_ctx()
- apply_service_dl_overrides(ctx, {"v_lang": value}, log)
- assert ctx.params["v_lang"] == expected
-
-
@pytest.mark.parametrize(
"value,expected",
[
@@ -174,9 +132,3 @@ def test_language_exclusion_tokens_survive_the_override_convert(value, expected)
ctx = make_ctx()
apply_service_dl_overrides(ctx, {"v_lang": value}, log)
assert ctx.params["v_lang"] == expected
-
-
-def test_cli_exclusion_beats_service_config():
- ctx = make_ctx(["-vl", "-es"])
- apply_service_dl_overrides(ctx, {"v_lang": ["en"]}, log)
- assert ctx.params["v_lang"] == ["-es"]
diff --git a/tests/core/test_service_remote_config.py b/tests/core/test_service_remote_config.py
index 34d5d7a5b..d69384337 100644
--- a/tests/core/test_service_remote_config.py
+++ b/tests/core/test_service_remote_config.py
@@ -89,16 +89,6 @@ def test_invalid_value_names_the_config_key(monkeypatch: pytest.MonkeyPatch, rou
group(ctx).get_command(ctx, "EXAMPLE")
-def test_resolved_service_does_not_route_the_next(monkeypatch: pytest.MonkeyPatch, routed: list) -> None:
- """Help and shell completion call get_command for every service on the context that resolved one."""
- monkeypatch.setattr(config, "services", {"EXAMPLE": {"dl": {"remote": True}}})
- ctx = make_ctx(dl.cli)
- group(ctx).resolve_command(ctx, ["EXAMPLE", "title"])
- assert ctx.params["remote"] is True
- group(ctx).get_command(ctx, "OTHER")
- assert routed == [("remote", None), ("local", None)]
-
-
def test_import_ignores_service_remote(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "services", {"EXAMPLE": {"dl": {"remote": True}}})
monkeypatch.setattr(Services, "make_import_command", staticmethod(lambda tag, ctx: click.Command(tag)))
diff --git a/tests/core/test_service_repo.py b/tests/core/test_service_repo.py
index fa1f5f275..6f1e80cf3 100644
--- a/tests/core/test_service_repo.py
+++ b/tests/core/test_service_repo.py
@@ -50,29 +50,6 @@ def test_parse_spec(spec, url, branch, dest):
assert service_repo.parse_spec(spec) == (url, branch, dest)
-def test_slug_distinguishes_hosts():
- # same owner/repo on different hosts must not share a clone dir
- a = service_repo.parse_spec("https://github.com/owner/repo")[2]
- b = service_repo.parse_spec("https://gitlab.com/owner/repo")[2]
- assert a != b
-
-
-def test_repos_base_uses_configured_local_dir(monkeypatch, tmp_path):
- from unshackle.core.config import config
-
- monkeypatch.setattr(config.directories, "services", ["owner/repo", str(tmp_path / "svc")], raising=False)
- assert service_repo.repos_base() == (tmp_path / "svc" / "_repos")
-
-
-def test_is_stale(tmp_path):
- stamp = tmp_path / "stamp"
- assert service_repo.is_stale(stamp, ttl=10) is True # missing → stale
- stamp.write_text(str(time.time()))
- assert service_repo.is_stale(stamp, ttl=10) is False # fresh
- stamp.write_text(str(time.time() - 100))
- assert service_repo.is_stale(stamp, ttl=10) is True # old
-
-
def test_clone_invokes_git(monkeypatch, tmp_path):
monkeypatch.setattr(service_repo.binaries, "Git", "git")
monkeypatch.setattr(service_repo, "repos_base", lambda: tmp_path)
@@ -142,22 +119,6 @@ def test_is_dirty_clean(monkeypatch):
assert service_repo.is_dirty(Path("/x")) is False
-def test_is_dirty_ignores_untracked_files(monkeypatch):
- # status must ask git to skip untracked files so importing services (__pycache__) isn't "dirty"
- seen = []
- monkeypatch.setattr(service_repo.binaries, "Git", "git")
-
- def run(args, **kw):
- seen.append(args)
- out = b"0" if args[3] == "rev-list" else b""
- return subprocess.CompletedProcess(args, 0, out, b"")
-
- monkeypatch.setattr(service_repo.subprocess, "run", run)
- service_repo.is_dirty(Path("/x"))
- status_args = next(a for a in seen if a[3] == "status")
- assert "--untracked-files=no" in status_args
-
-
def test_auto_refresh_refuses_dirty_clone(monkeypatch, tmp_path):
"""Auto path (force=False): a stale clone with local edits raises instead of clobbering."""
dest = tmp_path / "github.com__a__b"
@@ -238,13 +199,6 @@ def test_refresh_reports_discarded_local_edits(monkeypatch, tmp_path):
assert changes == ["!EXAMPLE"]
-def test_changed_services_up_to_date(monkeypatch):
- monkeypatch.setattr(service_repo.binaries, "Git", "git")
- # same HEAD before/after → no diff computed at all
- monkeypatch.setattr(service_repo.subprocess, "run", lambda *a, **k: pytest.fail("no git diff when HEAD unchanged"))
- assert service_repo.changed_services(Path("/x"), "same", "same") == []
-
-
@pytest.fixture
def bytecode_clone(tmp_path):
"""A clone of a repo that commits a ``.pyc``, with that ``.pyc`` rewritten as an import does."""
@@ -303,29 +257,3 @@ def test_untracked_bytecode_does_not_block_pull(bytecode_clone, tmp_path):
service_repo.pull(dest, tmp_path / "stamp")
assert (dest / "EXAMPLE" / "__init__.py").read_text() == "X = 2\n"
assert (dest / "OTHER" / "__init__.cpython-314-x86_64-linux-gnu.so").read_bytes() == b"compiled"
-
-
-@pytest.mark.parametrize("order", [["a", "b"], ["b", "a"]])
-def test_collision_first_source_wins(tmp_path, order):
- """Discovery dedupes by tag honoring list order: the FIRST source to define a tag wins,
- whether it's a local dir or a repo clone; later duplicates are shadowed."""
- dirs = {}
- for name in ("a", "b"):
- svc = tmp_path / name / "EXAMPLE"
- svc.mkdir(parents=True)
- (svc / "__init__.py").touch()
- dirs[name] = tmp_path / name
-
- seen: dict = {}
- shadowed: list = []
- for name in order: # services.py preserves config order
- for path in dirs[name].glob("*/__init__.py"):
- tag = path.parent.stem
- if tag in seen:
- shadowed.append((tag, path, seen[tag]))
- else:
- seen[tag] = path
-
- winner, loser = order[0], order[1]
- assert seen["EXAMPLE"] == dirs[winner] / "EXAMPLE" / "__init__.py"
- assert shadowed and shadowed[0][1] == dirs[loser] / "EXAMPLE" / "__init__.py"
diff --git a/tests/core/test_service_wait_for_approval.py b/tests/core/test_service_wait_for_approval.py
index c08573ce2..fad5227cd 100644
--- a/tests/core/test_service_wait_for_approval.py
+++ b/tests/core/test_service_wait_for_approval.py
@@ -1,10 +1,8 @@
import logging
-from contextlib import nullcontext
from types import SimpleNamespace
import pytest
-from unshackle.core import console
from unshackle.core.api.input_bridge import NO_USER_MESSAGE, InputBridge, NoUserBridge
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.service import Service
@@ -19,12 +17,6 @@ def test_returns_the_first_value_check_gives():
assert Service.wait_for_approval(_service(), "enter code", lambda: next(answers), timeout=5, interval=0) == "token"
-def test_times_out_when_check_never_gives_a_value():
- with pytest.raises(TimeoutError) as caught:
- Service.wait_for_approval(_service(), "enter code", lambda: None, timeout=0.05, interval=0.01)
- assert caught.value.error_code is APIErrorCode.AUTH_FAILED
-
-
def test_stops_when_the_remote_session_is_cancelled():
bridge = InputBridge()
calls = []
@@ -38,10 +30,6 @@ def test_stops_when_the_remote_session_is_cancelled():
assert len(calls) == 1
-def _raise_value_error():
- raise ValueError("denied")
-
-
def test_logs_the_message_for_a_remote_session(caplog):
"""A remote session reads the message only from the service log."""
with caplog.at_level(logging.INFO, logger="test"):
@@ -74,19 +62,3 @@ def test_no_user_message_is_an_authentication_error():
from unshackle.core.api.errors import categorize_exception
assert categorize_exception(RuntimeError(NO_USER_MESSAGE)).error_code == APIErrorCode.AUTH_FAILED
-
-
-@pytest.mark.parametrize(
- "check, expectation",
- [
- (lambda: "token", nullcontext()),
- (lambda: None, pytest.raises(TimeoutError)),
- (_raise_value_error, pytest.raises(ValueError)),
- ],
-)
-def test_shows_the_message_as_a_notice_and_clears_it(monkeypatch, check, expectation):
- notices = []
- monkeypatch.setattr(console, "_notice_handler", lambda message, qr: notices.append(message))
- with expectation:
- Service.wait_for_approval(_service(), "enter code", check, timeout=0.05, interval=0.01)
- assert notices == ["enter code", None]
diff --git a/tests/core/test_services_lazy.py b/tests/core/test_services_lazy.py
index 921944c7f..7fa80d241 100644
--- a/tests/core/test_services_lazy.py
+++ b/tests/core/test_services_lazy.py
@@ -2,17 +2,13 @@
from __future__ import annotations
-import logging
import sys
-import threading
from pathlib import Path
import click
import pytest
-from aiohttp import web
from unshackle.core import binaries, services
-from unshackle.core.config import config
pytestmark = pytest.mark.unit
@@ -87,57 +83,8 @@ def test_get_command_runs_a_good_service_beside_a_broken_one(two_services: None)
assert group.get_command(ctx, "EXAMPLE").name == "EXAMPLE"
-def test_get_tag_does_not_wait_for_a_reload_on_a_failed_tag(two_services: None) -> None:
- services.ensure_loaded("EXAMPLE")
- services.ensure_loaded("OTHER")
- held, release = threading.Event(), threading.Event()
-
- def reload() -> None:
- with services.RELOAD_LOCK:
- held.set()
- release.wait()
-
- holder = threading.Thread(target=reload)
- holder.start()
- try:
- assert held.wait(5)
- result: list[str] = []
- lookup = threading.Thread(target=lambda: result.append(services.Services.get_tag("nosuch")))
- lookup.start()
- lookup.join(5)
- assert result == ["nosuch"]
- finally:
- release.set()
- holder.join()
-
-
def test_load_all_imports_every_service(two_services: None) -> None:
services.load_all()
assert list(services.MODULES) == ["EXAMPLE"]
assert services.ALIASES == {"EXAMPLE": ("ex",)}
assert services.failed_tags(services.LOAD_ERRORS) == {"OTHER"}
-
-
-def test_env_dependencies_list_every_service_binary(two_services: None) -> None:
- from unshackle.commands.env import get_dependencies
-
- assert "ExampleTool" in {dep["name"] for dep in get_dependencies()}
-
-
-def test_serve_startup_imports_every_service(two_services: None, monkeypatch: pytest.MonkeyPatch) -> None:
- from unshackle.commands.serve import _install_service_refresh
-
- monkeypatch.setattr(config, "serve", {})
- _install_service_refresh(web.Application())
- assert list(services.MODULES) == ["EXAMPLE"]
-
-
-def test_a_run_of_one_tag_names_its_duplicate(two_services: None, caplog: pytest.LogCaptureFixture) -> None:
- services.SHADOWED[:] = [
- "EXAMPLE: using /a/EXAMPLE, ignoring /b/EXAMPLE",
- "OTHER: using /a/OTHER, ignoring /b/OTHER",
- ]
- with caplog.at_level(logging.INFO, logger="services"):
- services.check_load_errors("EXAMPLE")
- assert "EXAMPLE: 1 duplicate(s) ignored" in caplog.text
- assert "OTHER" not in caplog.text
diff --git a/tests/core/test_session_error_codes.py b/tests/core/test_session_error_codes.py
index d21916fbf..666263a06 100644
--- a/tests/core/test_session_error_codes.py
+++ b/tests/core/test_session_error_codes.py
@@ -1,7 +1,6 @@
"""An exhausted RnetSession request names its API error code and a short cause."""
import gzip
-import logging
import socket
import threading
from collections.abc import Callable, Iterator
@@ -11,7 +10,7 @@ import rnet
from unshackle.core.api.errors import categorize_exception
from unshackle.core.remote_protocol import APIErrorCode
-from unshackle.core.session import MaxRetriesError, RnetSession, failure_reason
+from unshackle.core.session import MaxRetriesError, RnetSession
pytestmark = pytest.mark.unit
@@ -41,24 +40,6 @@ class DecodingError(Exception):
"""Stands in for an rnet error, which carries its debug text."""
-@pytest.mark.parametrize(
- "text, reason",
- [
- (QUOTED, "DecodingError (stream closed because of a broken pipe)"),
- (UNQUOTED, "DecodingError (IncompleteBody)"),
- (REFUSED, "DecodingError (refused)"),
- (
- 'is_timeout error: wreq::Error { kind: Request, url: "http://x/", source: TimedOut }',
- "DecodingError (TimedOut)",
- ),
- ("is_decode error: wreq::Error { kind: Decode, source: wreq::Error { kind: Body } }", "DecodingError"),
- ],
- ids=["quoted", "unquoted", "message", "bare-source", "no-inner-error"],
-)
-def test_failure_reason_names_the_innermost_rnet_error(text: str, reason: str) -> None:
- assert failure_reason(DecodingError(text)) == reason
-
-
@pytest.fixture
def reply() -> Iterator[Callable[[bytes], str]]:
"""Start a loopback server that answers each connection with the given bytes, and give its URL."""
@@ -114,12 +95,6 @@ def test_an_exhausted_request_names_its_code(reply, answer: bytes, code: APIErro
assert err.message.endswith(f"GET 127.0.0.1 failed after 2 attempts: {cause}")
-def test_a_cut_body_retry_warning_names_the_short_cause(reply, caplog) -> None:
- with caplog.at_level(logging.WARNING):
- exhausted(reply(CUT))
- assert "DecodingError (IncompleteBody)(/x). Retrying... (1/1)" in caplog.text
-
-
@pytest.mark.parametrize("answer", [BAD_DEFLATE, CUT_GZIP, SERVER_ERROR], ids=["bad-deflate", "cut-gzip", "500"])
def test_an_exhausted_request_without_a_known_code_names_none(reply, answer: bytes) -> None:
assert getattr(exhausted(reply(answer)), "error_code", None) is None
diff --git a/tests/core/test_session_headers.py b/tests/core/test_session_headers.py
index 57554d53e..c4acd20e3 100644
--- a/tests/core/test_session_headers.py
+++ b/tests/core/test_session_headers.py
@@ -95,18 +95,6 @@ def test_popped_header_stops_being_sent(server: str) -> None:
assert Recorder.received[-1]["x-keep"] == "yes"
-def test_deleted_header_stops_being_sent(server: str) -> None:
- session = RnetSession()
- session.headers["X-Auth"] = "secret"
-
- session.get(f"{server}/one")
- assert "x-auth" in Recorder.received[-1]
-
- del session.headers["X-Auth"]
- session.get(f"{server}/two")
- assert "x-auth" not in Recorder.received[-1]
-
-
def test_clear_removes_every_header(server: str) -> None:
session = RnetSession()
session.headers.update({"X-Auth": "secret", "X-Trace": "on"})
@@ -308,37 +296,6 @@ def test_a_request_during_the_rebuild_still_carries_headers_and_cookies(server:
assert Recorder.cookies_sent[-1] == "sid=abc123"
-def test_the_rebuilt_client_is_published_only_when_it_is_ready(server: str, monkeypatch) -> None:
- """The new client must go on ``_client`` last, after the headers, the flush and the copy."""
- session = RnetSession()
- session.headers["X-Auth"] = "secret"
- session.get(f"{server}/set/sid=abc123")
-
- old = session._client
- seen: list[object] = []
- rebuilding: list[bool] = []
-
- original_flush = RnetCookieAdapter.flush_to_client
- original_copy = RnetSession.__dict__["copy_cookies"].__func__
-
- def recording_flush(self) -> None:
- if rebuilding:
- seen.append(session._client)
- original_flush(self)
-
- def recording_copy(source, target, origin: str) -> None:
- seen.append(session._client)
- original_copy(source, target, origin)
-
- monkeypatch.setattr(RnetCookieAdapter, "flush_to_client", recording_flush)
- monkeypatch.setattr(RnetSession, "copy_cookies", staticmethod(recording_copy))
- rebuilding.append(True)
- session.headers.pop("X-Auth", None)
-
- assert seen and all(client is old for client in seen)
- assert session._client is not old
-
-
def path_session(*cookies: Cookie) -> RnetSession:
session = RnetSession()
session.cookies.update(list(cookies))
diff --git a/tests/core/test_session_pool.py b/tests/core/test_session_pool.py
index 65fecdf29..fbc9f2d1a 100644
--- a/tests/core/test_session_pool.py
+++ b/tests/core/test_session_pool.py
@@ -11,7 +11,6 @@ from unittest.mock import patch
import pytest
import requests
from requests.adapters import HTTPAdapter
-from urllib3.util.retry import Retry
from unshackle.core.service import DEFAULT_TIMEOUT, TimeoutHTTPAdapter, grow_session_pool
from unshackle.core.utils.sslciphers import SSLCiphers
@@ -88,28 +87,6 @@ def test_a_distinct_http_adapter_is_grown_not_overwritten() -> None:
assert adapter._pool_connections == 64
-def test_shared_adapter_is_grown_in_place_on_both_schemes() -> None:
- session = requests.Session()
- adapter = TimeoutHTTPAdapter(pool_connections=10, pool_maxsize=10, max_retries=Retry(total=5))
- session.mount("https://", adapter)
- session.mount("http://", adapter)
- retries = adapter.max_retries
- timeout = adapter.default_timeout
-
- grow_session_pool(session, 64)
-
- https = session.get_adapter("https://x")
- assert https is adapter
- assert session.get_adapter("http://x") is adapter
- assert type(https) is TimeoutHTTPAdapter
- assert https.max_retries is retries
- assert https.default_timeout == timeout
- assert https._pool_maxsize == 64
- assert https._pool_connections == 64
- assert https._pool_block is True
- assert https.poolmanager.connection_pool_kw["maxsize"] == 64
-
-
def test_cached_proxy_manager_is_rebuilt_at_the_new_size() -> None:
"""proxy_manager_for caches one manager per proxy URL, sized when it was first built.
@@ -130,30 +107,6 @@ def test_cached_proxy_manager_is_rebuilt_at_the_new_size() -> None:
assert fresh is not stale
-def test_large_enough_pool_is_left_alone() -> None:
- session = requests.Session()
- session.mount("https://", HTTPAdapter(pool_connections=64, pool_maxsize=64))
- old = session.get_adapter("https://x")
- pool = old.poolmanager
-
- grow_session_pool(session, 64)
-
- assert session.get_adapter("https://x") is old
- assert old.poolmanager is pool, "an adapter that needs no growth must keep its warm connections"
-
-
-def test_equal_size_pool_is_left_alone() -> None:
- session = requests.Session()
- session.mount("https://", HTTPAdapter(pool_maxsize=32))
- old = session.get_adapter("https://x")
- pool = old.poolmanager
-
- grow_session_pool(session, 32)
-
- assert session.get_adapter("https://x") is old
- assert old.poolmanager is pool
-
-
@pytest.mark.parametrize("session", [object(), FakeRnetSession()])
def test_non_requests_session_is_ignored(session: object) -> None:
grow_session_pool(session, 64)
diff --git a/tests/core/test_session_response_context.py b/tests/core/test_session_response_context.py
index 079514a4a..660111bfc 100644
--- a/tests/core/test_session_response_context.py
+++ b/tests/core/test_session_response_context.py
@@ -46,14 +46,6 @@ def cover_url() -> Iterator[str]:
httpd.server_close()
-def test_a_with_block_gives_the_response_itself_and_its_content(cover_url: str) -> None:
- response = RnetSession().get(cover_url)
-
- with response as entered:
- assert entered is response
- assert entered.content == COVER
-
-
def test_the_end_of_the_with_block_closes_the_response(cover_url: str) -> None:
with RnetSession().get(cover_url, stream=True) as response:
pass
@@ -62,16 +54,5 @@ def test_the_end_of_the_with_block_closes_the_response(cover_url: str) -> None:
_ = response.content
-def test_an_exception_in_the_with_block_propagates_and_the_response_still_closes(cover_url: str) -> None:
- with (
- pytest.raises(ValueError, match="raised inside the with block"),
- RnetSession().get(cover_url, stream=True) as response,
- ):
- raise ValueError("raised inside the with block")
-
- with pytest.raises(RuntimeError):
- _ = response.content
-
-
def test_download_cover_returns_the_image_and_its_content_type(cover_url: str) -> None:
assert download_cover(RnetSession(), cover_url) == (COVER, "image/png")
diff --git a/tests/core/test_session_retry_log.py b/tests/core/test_session_retry_log.py
index 292c58629..dcaf019a7 100644
--- a/tests/core/test_session_retry_log.py
+++ b/tests/core/test_session_retry_log.py
@@ -1,6 +1,5 @@
"""RnetSession.request logs "Retrying" only when a retry follows."""
-import logging
from types import SimpleNamespace
import pytest
@@ -22,15 +21,6 @@ def rate_limited(monkeypatch):
return s
-@pytest.mark.parametrize("max_retries", [0, 2])
-def test_retry_log_counts_only_real_retries(rate_limited, caplog, max_retries):
- with caplog.at_level(logging.WARNING), pytest.raises(MaxRetriesError):
- rate_limited.get("https://example.invalid/x", max_retries=max_retries)
-
- retries = [r.getMessage() for r in caplog.records if "Retrying" in r.getMessage()]
- assert retries == [f"429 Too Many Requests(/x). Retrying... ({n}/{max_retries})" for n in range(1, max_retries + 1)]
-
-
@pytest.mark.parametrize(("max_retries", "attempts"), [(0, ""), (2, " after 3 attempts")])
def test_spent_budget_names_the_attempts_and_host_not_the_url(rate_limited, max_retries, attempts):
with pytest.raises(MaxRetriesError) as raised:
diff --git a/tests/core/test_stereo_video.py b/tests/core/test_stereo_video.py
index 02cc297b7..6d710d25d 100644
--- a/tests/core/test_stereo_video.py
+++ b/tests/core/test_stereo_video.py
@@ -2,8 +2,6 @@ from __future__ import annotations
import io
import itertools
-import logging
-import subprocess
from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -11,7 +9,6 @@ from typing import Any
import pytest
from langcodes import Language
-from unshackle.commands.dl import dl
from unshackle.core import binaries
from unshackle.core.config import config
from unshackle.core.drm.verify import decrypter_for
@@ -104,13 +101,6 @@ def test_a_track_with_a_second_video_layer_decrypts_with_mp4decrypt(
assert decrypter_for(flat) == "mp4decrypt"
-def test_a_3d_title_muxes_with_mp4box(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- calls: list[str] = []
- monkeypatch.setattr(Tracks, "_mux_mp4", lambda self, **kwargs: calls.append(kwargs["title"]) or (Path("x"), 0, []))
- assert Tracks(stereo_video(tmp_path)).mux("Film")[1] == 0
- assert calls == ["Film"]
-
-
@pytest.fixture
def mp4box_commands(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> list[list[str]]:
commands: list[list[str]] = []
@@ -147,14 +137,6 @@ def test_a_3d_mp4_mux_keeps_the_sample_whole(
assert "-for-test" in mp4box_commands[0]
-def test_a_2d_mp4_sample_cut_keeps_no_date(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mp4box_commands: list[list[str]]
-) -> None:
- monkeypatch.setattr(config, "sample", (120.0, 180.0))
- Tracks(stereo_video(tmp_path, stereo=False))._mux_mp4(title="Film", output_path=tmp_path / "out.mkv")
- assert mp4box_commands[1][1:3] == ["-for-test", "-splitx"]
-
-
def test_a_3d_mp4_mux_writes_quicktime_chapters(tmp_path: Path, mp4box_commands: list[list[str]]) -> None:
for stereo, flag in ((True, "-chapqt"), (False, "-chap")):
tracks = Tracks(stereo_video(tmp_path, stereo=stereo))
@@ -163,12 +145,6 @@ def test_a_3d_mp4_mux_writes_quicktime_chapters(tmp_path: Path, mp4box_commands:
assert flag in mp4box_commands[-1] and ({"-chap", "-chapqt"} - {flag}).isdisjoint(mp4box_commands[-1])
-def test_a_3d_track_is_never_a_hybrid_ingredient(tmp_path: Path) -> None:
- flat, layered = (stereo_video(tmp_path, stereo=s, range_=Video.Range.DV) for s in (False, True))
- candidates, standalone = Tracks.partition_hybrid_videos([flat, layered], [])
- assert candidates == [flat] and standalone == []
-
-
def test_2d_ranks_over_3d_at_one_resolution_and_the_signatures_differ(tmp_path: Path) -> None:
flat = stereo_video(tmp_path, stereo=False, height=1080, bitrate=5_000_000)
layered = stereo_video(tmp_path, stereo=True, height=1080, bitrate=9_000_000)
@@ -215,19 +191,6 @@ def test_the_filename_context_marks_a_3d_title(monkeypatch: pytest.MonkeyPatch)
assert (context(True), context(False)) == ("3D", "")
-def test_worst_prefers_the_2d_track_at_one_height(tmp_path: Path) -> None:
- videos = [
- stereo_video(tmp_path, stereo=s, height=2160, bitrate=b)
- for s, b in ((False, 9_000_000), (False, 5_000_000), (True, 40_000_000), (True, 30_000_000))
- ]
- ranked = Tracks(videos)
- ranked.sort_videos()
- assert pick_video(ranked.videos, worst=True) is videos[1]
- assert pick_video(ranked.videos, worst=False) is videos[0]
- assert pick_video([videos[2], videos[3]], worst=True) is videos[3]
- assert pick_video([], worst=True) is None
-
-
def test_worst_ranks_unknown_bitrates_and_sizes_highest(tmp_path: Path) -> None:
def ranked(*specs: tuple[bool, int, Any]) -> list[Video]:
tracks = Tracks([stereo_video(tmp_path, stereo=s, width=h * 16 // 9, height=h, bitrate=b) for s, h, b in specs])
@@ -275,17 +238,6 @@ def test_hybrid_never_pairs_a_3d_dv_track(tmp_path: Path) -> None:
assert hybrid_plan([base, layered], generate_dv=False) == ([], None)
-def test_mp4_names_skip_the_extra_tracks_of_a_3d_video_file(tmp_path: Path, mp4box_commands: list[list[str]]) -> None:
- video = stereo_video(tmp_path)
- video.path.write_bytes(box(b"moov", box(b"trak") + box(b"trak")))
- audio = Audio(url="https://x/a.mp4", language="en", codec=Audio.Codec.EC3, name="English")
- audio.path = tmp_path / "a.mp4"
- audio.path.write_bytes(b"\x00" * 16)
- Tracks([video, audio])._mux_mp4(title="Film", output_path=tmp_path / "out.mkv")
- command = mp4box_commands[0]
- assert command[command.index("-name") + 1] == "3=English"
-
-
def test_an_mp4_mux_adds_only_the_own_stream_of_each_file(tmp_path: Path, mp4box_commands: list[list[str]]) -> None:
video = stereo_video(tmp_path, stereo=False)
video.data["own_stream_only"] = True
@@ -303,13 +255,6 @@ def test_an_mp4_mux_adds_only_the_own_stream_of_each_file(tmp_path: Path, mp4box
assert command[command.index("-name") + 1] == "2=English"
-def test_a_3d_mux_that_loses_its_second_view_warns(
- tmp_path: Path, mp4box_commands: list[list[str]], caplog: pytest.LogCaptureFixture
-) -> None:
- Tracks(stereo_video(tmp_path))._mux_mp4(title="Film", output_path=tmp_path / "out.mkv")
- assert "lost its second view" in caplog.text
-
-
def test_a_downloaded_file_with_a_second_view_marks_the_video_3d(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
@@ -340,11 +285,3 @@ shared.m3u8
"""
tracks = HLS.from_text(master, url="https://cdn.example/master.m3u8").to_tracks(Language.get("en"))
assert any(v.stereo for v in tracks.videos)
-
-
-def test_a_sample_is_cut_only_from_a_matroska_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- runner = dl.__new__(dl)
- runner.log = logging.getLogger("download")
- monkeypatch.setattr(subprocess, "run", lambda *a, **k: pytest.fail("mkvmerge ran on an MP4"))
- runner.write_sample(tmp_path / "Film.mp4", SimpleNamespace(), SimpleNamespace())
- assert not (tmp_path / "Sample").exists()
diff --git a/tests/core/test_surfsharkvpn_proxy.py b/tests/core/test_surfsharkvpn_proxy.py
index 6769e6870..afa37b107 100644
--- a/tests/core/test_surfsharkvpn_proxy.py
+++ b/tests/core/test_surfsharkvpn_proxy.py
@@ -109,10 +109,3 @@ def test_unusable_server_map_entry_is_ignored_with_a_warning(server: object, cap
proxy = SurfsharkVPN(USERNAME, PASSWORD, server_map={"us": server}) # type: ignore[dict-item]
assert "ignoring server_map entry" in caplog.text
assert host(proxy.get_proxy("us")) in US_HOSTS
-
-
-@pytest.mark.parametrize("key", ["gb", "uk", "GB"])
-@pytest.mark.parametrize("query", ["gb", "uk"])
-def test_server_map_uk_and_gb_are_the_same_region(key: str, query: str) -> None:
- proxy = SurfsharkVPN(USERNAME, PASSWORD, server_map={key: "uk-lon"})
- assert host(proxy.get_proxy(query)) == "uk-lon.prod.surfshark.com:443"
diff --git a/tests/core/test_tag_file_dispatch.py b/tests/core/test_tag_file_dispatch.py
index f368b511f..aaa530a61 100644
--- a/tests/core/test_tag_file_dispatch.py
+++ b/tests/core/test_tag_file_dispatch.py
@@ -129,31 +129,6 @@ def test_a_dts_song_in_matroska_takes_mkvpropedit(calls: Calls) -> None:
assert calls.mkv and calls.mkv[0][1]["TITLE"] == "Example Track"
-def test_a_matroska_tagger_fault_warns_and_never_raises(
- calls: Calls, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- def broken_apply_tags(path: Path, tags: dict[str, str]) -> None:
- raise OSError("mkvpropedit not found")
-
- monkeypatch.setattr(tags_module, "apply_tags", broken_apply_tags)
- with caplog.at_level("WARNING", logger="TAGS"):
- tags_module.tag_file(Path("04. Example Track.mka"), make_song(), session=SESSION)
- assert "mkvpropedit not found" in caplog.text
-
-
-def test_the_tag_lookup_passes_the_service_provider(calls: Calls, monkeypatch: pytest.MonkeyPatch) -> None:
- seen: list[dict[str, Any]] = []
- monkeypatch.setattr(config, "tag_imdb_tmdb", True)
- monkeypatch.setattr(tags_module, "get_available_providers", lambda: [object()])
- monkeypatch.setattr(tags_module, "resolve_by_ids", lambda *a, **kw: seen.append(kw) or None)
-
- tags_module.tag_file(
- Path("Some Movie.mkv"), Movie(id_="movie-0001", service=DummyService, name="Some Movie"), prefer="tmdb"
- )
-
- assert seen and seen[0]["prefer"] == "tmdb"
-
-
@pytest.mark.parametrize(
("title", "season"),
[
diff --git a/tests/core/test_tag_rules.py b/tests/core/test_tag_rules.py
index 7b8549b1e..edfee711f 100644
--- a/tests/core/test_tag_rules.py
+++ b/tests/core/test_tag_rules.py
@@ -32,11 +32,6 @@ def test_list_matches_any_entry() -> None:
assert evaluate_tag_rules(rules, CONTEXT) == "UHDGROUP"
-def test_list_with_no_matching_entry() -> None:
- rules = [{"when": {"hdr": ["HDR10P", "HLG"]}, "tag": "UHDGROUP"}]
- assert evaluate_tag_rules(rules, CONTEXT) is None
-
-
def test_case_insensitive() -> None:
rules = [{"when": {"lang_tag": "subbed", "quality": "2160P"}, "tag": "SUBMOVIES"}]
assert evaluate_tag_rules(rules, CONTEXT) == "SUBMOVIES"
@@ -68,11 +63,6 @@ def test_malformed_rule_skipped(rule: dict[str, Any]) -> None:
assert evaluate_tag_rules([rule], CONTEXT) is None
-def test_no_rules_and_no_match() -> None:
- assert evaluate_tag_rules([], CONTEXT) is None
- assert evaluate_tag_rules([{"when": {"quality": "720p"}, "tag": "SD"}], CONTEXT) is None
-
-
def test_empty_context_value_matches_empty_condition() -> None:
rules = [{"when": {"edition": ""}, "tag": "PLAIN"}]
assert evaluate_tag_rules(rules, CONTEXT) == "PLAIN"
@@ -99,31 +89,11 @@ def test_numeric_operators_extract_first_number(condition: str, expected: bool)
assert (evaluate_tag_rules(rules, CONTEXT) == "MATCHED") is expected
-def test_string_inequality() -> None:
- assert evaluate_tag_rules([{"when": {"hdr": "!=DV"}, "tag": "NODV"}], CONTEXT) is None
- assert evaluate_tag_rules([{"when": {"hdr": "!=HDR10P"}, "tag": "NOHDR10P"}], CONTEXT) == "NOHDR10P"
-
-
-def test_string_equality_operator_is_case_insensitive() -> None:
- assert evaluate_tag_rules([{"when": {"lang_tag": "==subbed"}, "tag": "SUBGRP"}], CONTEXT) == "SUBGRP"
-
-
def test_plain_equality_unchanged() -> None:
assert evaluate_tag_rules([{"when": {"quality": "2160p"}, "tag": "UHD"}], CONTEXT) == "UHD"
assert evaluate_tag_rules([{"when": {"quality": "2160"}, "tag": "UHD"}], CONTEXT) is None
-def test_numeric_operator_against_value_without_a_number() -> None:
- rules = [{"when": {"hdr": ">=1080"}, "tag": "NOPE"}]
- assert evaluate_tag_rules(rules, CONTEXT) is None
-
-
-def test_ordering_operator_with_non_numeric_operand(caplog: pytest.LogCaptureFixture) -> None:
- rules = [{"when": {"hdr": ">DV"}, "tag": "NOPE"}]
- assert evaluate_tag_rules(rules, CONTEXT) is None
- assert "numeric operand" in caplog.text
-
-
def test_operators_inside_lists() -> None:
rules = [{"when": {"quality": ["<720", ">=2160"]}, "tag": "MATCHED"}]
assert evaluate_tag_rules(rules, CONTEXT) == "MATCHED"
@@ -143,11 +113,6 @@ def test_rule_entry_that_is_not_a_mapping_skipped(rule: Any) -> None:
assert evaluate_tag_rules([rule, {"when": {"title_type": "movie"}, "tag": "MATCHED"}], CONTEXT) == "MATCHED"
-@pytest.mark.parametrize("when", [["title_type", "movie"], "title_type", 42])
-def test_when_that_is_not_a_mapping_skipped(when: Any) -> None:
- assert evaluate_tag_rules([{"when": when, "tag": "NOPE"}], CONTEXT) is None
-
-
@pytest.mark.parametrize(
"rule",
[
@@ -167,10 +132,6 @@ def test_numbers_stay_valid() -> None:
assert evaluate_tag_rules([{"when": {"resolution": 1080}, "tag": "NOPE"}], CONTEXT) is None
-def test_numeric_tag_becomes_text() -> None:
- assert evaluate_tag_rules([{"when": {"title_type": "movie"}, "tag": 123}], CONTEXT) == "123"
-
-
@pytest.mark.parametrize("tag", [["A", "B"], {"x": 1}, ("A",), {"A"}])
def test_non_scalar_tag_skipped(tag: Any, caplog: pytest.LogCaptureFixture) -> None:
"""A list or dict here used to reach the filename as its repr."""
@@ -178,31 +139,12 @@ def test_non_scalar_tag_skipped(tag: Any, caplog: pytest.LogCaptureFixture) -> N
assert "must be text or a number" in caplog.text
-@pytest.mark.parametrize("tag", ["", 0])
-def test_empty_tag_skipped(tag: Any) -> None:
- assert evaluate_tag_rules([{"when": {"title_type": "movie"}, "tag": tag}], CONTEXT) is None
-
-
-def test_skipped_rule_falls_through_to_a_later_one() -> None:
- rules = [
- {"when": {"atmos": True}, "tag": "SKIPPED"},
- {"when": {"title_type": "movie"}, "tag": "MATCHED"},
- ]
- assert evaluate_tag_rules(rules, CONTEXT) == "MATCHED"
-
-
def test_several_negations_in_a_list_always_match() -> None:
"""Any-entry matching makes a list of negations useless, which the docs warn about."""
rules = [{"when": {"hdr": ["!=DV", "!=HLG"]}, "tag": "ALWAYS"}]
assert evaluate_tag_rules(rules, CONTEXT) == "ALWAYS"
-def test_leading_space_before_an_operator_is_literal() -> None:
- """Current behaviour: the operator is only found at the very start of the value."""
- rules = [{"when": {"quality": " >=2160"}, "tag": "NOPE"}]
- assert evaluate_tag_rules(rules, CONTEXT) is None
-
-
def test_inequality_holds_for_a_value_with_no_number() -> None:
""" "DV" really is not equal to 2160, so != holds while the others fail."""
assert evaluate_tag_rules([{"when": {"hdr": "!=2160"}, "tag": "MATCHED"}], CONTEXT) == "MATCHED"
@@ -210,12 +152,6 @@ def test_inequality_holds_for_a_value_with_no_number() -> None:
assert evaluate_tag_rules([{"when": {"hdr": "==2160"}, "tag": "NOPE"}], CONTEXT) is None
-@pytest.mark.parametrize("condition", ["!=", ">=", "<", "=", "=="])
-def test_bare_operator_fails(condition: str, caplog: pytest.LogCaptureFixture) -> None:
- assert evaluate_tag_rules([{"when": {"hdr": condition}, "tag": "NOPE"}], CONTEXT) is None
- assert "no value to compare against" in caplog.text
-
-
def test_composite_hdr_does_not_match_plain_dv() -> None:
"""DV titles carry a base-layer suffix, which the docs tell users to list explicitly."""
context = {**CONTEXT, "hdr": "DV.HDR10P"}
diff --git a/tests/core/test_tag_rules_integration.py b/tests/core/test_tag_rules_integration.py
index b3a7f52f5..37ad89d7a 100644
--- a/tests/core/test_tag_rules_integration.py
+++ b/tests/core/test_tag_rules_integration.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import inspect
import types
from collections.abc import Iterator
from typing import Any
@@ -65,25 +64,11 @@ def context_for(rules: list[dict[str, Any]], monkeypatch: pytest.MonkeyPatch) ->
return make_movie().build_base_template_context(make_media_info(["en"]))
-def test_matching_rule_replaces_the_tag(monkeypatch: pytest.MonkeyPatch) -> None:
- context = context_for([{"when": {"title_type": "movie"}, "tag": "MOVIEGRP"}], monkeypatch)
- assert context["tag"] == "MOVIEGRP"
-
-
def test_no_matching_rule_keeps_the_config_tag(monkeypatch: pytest.MonkeyPatch) -> None:
context = context_for([{"when": {"title_type": "series"}, "tag": "TVGRP"}], monkeypatch)
assert context["tag"] == "NOGRP"
-def test_no_rules_keeps_the_config_tag(monkeypatch: pytest.MonkeyPatch) -> None:
- context = context_for([], monkeypatch)
- assert context["tag"] == "NOGRP"
-
-
-def test_title_type_is_in_the_context(monkeypatch: pytest.MonkeyPatch) -> None:
- assert context_for([], monkeypatch)["title_type"] == "movie"
-
-
def test_rules_run_after_lang_tag(monkeypatch: pytest.MonkeyPatch) -> None:
"""A rule matching on lang_tag only works if lang_tag is resolved first."""
monkeypatch.setattr(config, "language_tags", {"rules": [{"audio": "ja", "tag": "SUBBED"}]})
@@ -120,14 +105,3 @@ def test_a_quality_rule_matches_the_built_context(monkeypatch: pytest.MonkeyPatc
assert context["quality"] == "2160p"
assert context["video"] == "H.265"
assert context["tag"] == "UHDGROUP"
-
-
-def test_dl_clears_tag_rules_when_tag_is_given() -> None:
- """Source-level pin: the block lives inside the click-driven dl.__init__."""
- from unshackle.commands.dl import dl
-
- source = inspect.getsource(dl.__init__)
- block = source.split("if tag:")[1].split("\n\n")[0]
-
- assert "config.tag = tag" in block
- assert "config.tag_rules = []" in block
diff --git a/tests/core/test_task_temp.py b/tests/core/test_task_temp.py
index 11a25132d..88cf936e2 100644
--- a/tests/core/test_task_temp.py
+++ b/tests/core/test_task_temp.py
@@ -60,14 +60,6 @@ def test_task_dir_removed_on_exception(temp_root: Path) -> None:
assert config.directories.temp == temp_root
-def test_task_dir_removed_on_keyboard_interrupt(temp_root: Path) -> None:
- with pytest.raises(KeyboardInterrupt):
- with task_temp_dir() as task_dir:
- raise KeyboardInterrupt
- assert not task_dir.exists()
- assert config.directories.temp == temp_root
-
-
def test_sweep_removes_unlocked_stale_dir(temp_root: Path) -> None:
task_dir = make_task_dir(temp_root)
(task_dir / "leftover.mp4").write_bytes(b"x")
diff --git a/tests/core/test_template_formatter.py b/tests/core/test_template_formatter.py
index fa639be98..4c626c4d8 100644
--- a/tests/core/test_template_formatter.py
+++ b/tests/core/test_template_formatter.py
@@ -15,7 +15,7 @@ from unshackle.core.titles.episode import Episode
from unshackle.core.titles.movie import Movie
from unshackle.core.titles.music import Song
from unshackle.core.utilities import sanitize_filename
-from unshackle.core.utils.template_formatter import TemplateFormatter, detect_spacer
+from unshackle.core.utils.template_formatter import TemplateFormatter
@pytest.mark.parametrize(
@@ -49,25 +49,6 @@ def test_omitted_conditional_leaves_no_separator_debris(template, context, expec
assert TemplateFormatter(template).format(context) == expected
-@pytest.mark.parametrize(
- ("template", "context"),
- [
- ("{title} ({year?})", {"title": "Some Movie", "year": ""}),
- ("{title} [{quality?}]", {"title": "Some Movie", "quality": ""}),
- ("{title}.{quality?}", {"title": "Some Movie", "quality": ""}),
- ("{title} - {tag?}", {"title": "Some Movie", "tag": ""}),
- ],
-)
-def test_result_is_safe_as_a_windows_path_segment(template, context):
- """Windows strips these when creating a directory but not when looking one up."""
- result = TemplateFormatter(template).format(context)
- assert result == result.strip(" ."), f"unsafe path segment: {result!r}"
-
-
-def test_empty_result_falls_back():
- assert TemplateFormatter("{title?}").format({"title": ""}) == "untitled"
-
-
def test_missing_required_variable_raises():
with pytest.raises(ValueError, match="Missing required template variables"):
TemplateFormatter("{title}.{year}").format({"title": "T"})
@@ -87,10 +68,6 @@ def test_sanitize_filename_strips_unsafe_edges(raw, spacer, expected):
assert sanitize_filename(raw, spacer) == expected
-def test_sanitize_filename_keeps_interior_dots():
- assert sanitize_filename("Mr. Robot", ".") == "Mr.Robot"
-
-
@pytest.mark.parametrize(
("template", "context", "expected"),
[
@@ -209,34 +186,6 @@ def test_folder_templates_keep_path_separators(folder_config, kind, make_title,
assert_safe_path(result)
-@pytest.mark.parametrize(
- ("kind", "make_title", "template"),
- [
- ("movies", make_movie, "{title} ({year?})"),
- ("series", make_episode, "{title} ({year?})"),
- ("songs", make_song, "{artist} - {album} [{genre?}]"),
- ("albums", make_album_song, "{album_artist} - {album} [{genre?}]"),
- ],
-)
-def test_folder_names_are_safe_when_conditionals_are_omitted(folder_config, kind, make_title, template):
- folder_config.folder_templates = {kind: template}
- assert_safe_path(make_title().get_filename(StubMediaInfo(), folder=True))
-
-
-@pytest.mark.parametrize(
- ("template", "expected"),
- [
- ("Shows/{title}.{year?}/Season.{season}", "Shows/Some.Show/Season.S01"),
- ("Shows/{title} {year?}/Season {season}", "Shows/Some Show/Season S01"),
- ],
-)
-def test_series_folder_handles_both_separator_styles(folder_config, template, expected):
- folder_config.folder_templates = {"series": template}
- result = make_episode().get_filename(StubMediaInfo(), folder=True)
- assert result == expected
- assert_safe_path(result)
-
-
@pytest.mark.parametrize(
("template", "expected"),
[
@@ -254,21 +203,6 @@ def test_single_variable_segments_follow_the_whole_path(folder_config, template,
assert_safe_path(result)
-@pytest.mark.parametrize(
- ("template", "expected"),
- [
- ("{title}.{year}.{quality}", "."),
- ("{title} {year} {quality}", " "),
- ("{title} ({year})", " "),
- ("Movies/{title} ({year?})", " "),
- ("Shows/{title}.{year?}/Season.{season}", "."),
- ("{title}", "."), # nothing between two variables, so scene style wins
- ],
-)
-def test_detect_spacer(template, expected):
- assert detect_spacer(template) == expected
-
-
@pytest.mark.parametrize(
("series_template", "expected"),
[
diff --git a/tests/core/test_title_metadata.py b/tests/core/test_title_metadata.py
index 786ea30d8..cd4b06220 100644
--- a/tests/core/test_title_metadata.py
+++ b/tests/core/test_title_metadata.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import logging
from datetime import date
from typing import Any
@@ -193,36 +192,6 @@ def test_the_hints_take_the_title_before_the_source() -> None:
assert TitleMetadata(force_daily=True).daily_hint(daily_title) is True
-@pytest.mark.parametrize(
- ("result", "level", "message"),
- [
- (None, logging.WARNING, "--enrich found no metadata"),
- (
- found(title="Real Name"),
- logging.WARNING,
- "--enrich source gave no year, language, kept the service's values",
- ),
- (
- found(title="Real", year=1999, original_language="ko"),
- logging.INFO,
- "Original language from metadata: ko",
- ),
- ],
- ids=["nothing", "missing", "language"],
-)
-def test_enrich_reports_what_the_source_gave(
- monkeypatch: pytest.MonkeyPatch,
- caplog: pytest.LogCaptureFixture,
- result: MetadataResult | None,
- level: int,
- message: str,
-) -> None:
- Providers(monkeypatch, result)
- caplog.set_level(logging.INFO, logger="download")
- TitleMetadata(tmdb_id=5).prepare(Movies([movie()]), enrich=True, tvdb_order="", continuous=False)
- assert (level, message) in [(r.levelno, r.getMessage()) for r in caplog.records]
-
-
def test_enrich_fills_the_air_dates_of_a_daily_series(monkeypatch: pytest.MonkeyPatch) -> None:
tvdb = FakeTvdb({}, [{"seasonNumber": 1, "number": 1, "aired": "2026-08-10"}])
Providers(monkeypatch, found(tvdb_id=73871), tvdb)
@@ -231,14 +200,6 @@ def test_enrich_fills_the_air_dates_of_a_daily_series(monkeypatch: pytest.Monkey
assert [t.air_date for t in titles] == [date(2026, 8, 10)]
-def test_a_listing_prints_the_search_match(monkeypatch: pytest.MonkeyPatch) -> None:
- Providers(monkeypatch, found(title="The Show"))
- monkeypatch.setattr(providers, "result_matches", lambda result, title: result.title == title)
- with console.capture() as captured:
- TitleMetadata().search(episode(1, 1), listing=True)
- assert "Search -> The Show (ID 1396)" in captured.get()
-
-
def test_an_anilist_search_hit_keeps_its_anilist_id_for_the_tags(monkeypatch: pytest.MonkeyPatch) -> None:
hit = MetadataResult(
title="The Show", external_ids=ExternalIds(tmdb_id=37854, tmdb_kind="tv", anilist_id=21), source="anilist"
@@ -252,19 +213,6 @@ def test_an_anilist_search_hit_keeps_its_anilist_id_for_the_tags(monkeypatch: py
assert "Search -> The Show (ID 37854)" in captured.get()
-def test_a_listing_with_no_movie_match_says_so(monkeypatch: pytest.MonkeyPatch) -> None:
- Providers(monkeypatch, None)
- with console.capture() as captured:
- TitleMetadata().search(movie(), listing=True)
- assert "Search -> No match found" in captured.get()
-
-
-def test_a_movie_fetches_the_movie_external_ids(monkeypatch: pytest.MonkeyPatch) -> None:
- calls = Providers(monkeypatch, None)
- TitleMetadata(tmdb_id=5, cache=CACHE).search(movie())
- assert calls.fetched == [(5, "movie", *CACHE)]
-
-
def test_the_service_provider_reaches_every_lookup(monkeypatch: pytest.MonkeyPatch) -> None:
calls = Providers(monkeypatch, found(tvdb_id=73871), FakeTvdb({(1, 1): (1, 1, None)}))
TitleMetadata(metadata_provider="tmdb").prepare(
@@ -286,12 +234,6 @@ def test_a_title_overrides_the_service_provider(monkeypatch: pytest.MonkeyPatch)
assert calls.resolved[0][1]["prefer"] == "tvdb"
-def test_an_empty_title_provider_keeps_the_configured_order() -> None:
- ep = episode(1, 1)
- ep.metadata_provider = ""
- assert TitleMetadata(metadata_provider="tmdb").provider_hint(ep) == ""
-
-
def test_a_per_title_anime_flag_keeps_the_service_provider(monkeypatch: pytest.MonkeyPatch) -> None:
calls = Providers(monkeypatch, None)
ep = episode(1, 1)
diff --git a/tests/core/test_title_source.py b/tests/core/test_title_source.py
index 388b0e958..17ff423fa 100644
--- a/tests/core/test_title_source.py
+++ b/tests/core/test_title_source.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import logging
from pathlib import Path
from typing import Any
from uuid import UUID
@@ -17,7 +16,7 @@ from tests.remote.key_source import MemoryKeySource, remote_keys
from unshackle.commands import dl as dl_module
from unshackle.core.config import config
from unshackle.core.credential import Credential
-from unshackle.core.drm import ClearKeyCTR, CustomDRM, PlayReady, Widevine
+from unshackle.core.drm import ClearKeyCTR, PlayReady, Widevine
from unshackle.core.drm.cenc import drm_stub
from unshackle.core.import_service import ImportService
from unshackle.core.service import Service
@@ -46,11 +45,6 @@ def an_import(tmp_path: Path) -> ImportService:
return ImportService(import_ctx(), "EXAMPLE", "movie-1", str(crit_export(tmp_path / "export.json")))
-def test_a_service_licenses_through_its_callbacks_and_has_no_key_source() -> None:
- svc = service()
- assert (svc.key_arrival, svc.key_source) == (KeyArrival.CALLBACK, None)
-
-
@pytest.mark.parametrize(("server_cdm", "arrival"), [(True, KeyArrival.SERVER), (False, KeyArrival.CALLBACK)])
def test_a_remote_session_follows_the_server_cdm_and_is_its_own_key_source(
server_cdm: bool, arrival: KeyArrival
@@ -71,10 +65,6 @@ def test_a_service_is_cached_under_the_title_id_it_keeps(attr: str) -> None:
assert svc.cache_identity() == CacheIdentity("cacher", "show-1", "gb", get_account_hash(None))
-def test_a_service_with_no_title_id_has_none_to_cache_under() -> None:
- assert service().cache_identity().title_id is None
-
-
def test_a_remote_session_and_an_import_have_no_title_cache(tmp_path: Path) -> None:
remote = remote_keys()
remote.title_id = "show-1"
@@ -152,18 +142,6 @@ def test_only_a_service_saves_its_login_cookies(tmp_path: Path) -> None:
assert an_import(tmp_path).login_cookies is None
-def test_the_source_defaults_leave_a_track_alone() -> None:
- """A source that defines no hooks, sample decrypter or licence callback gets the no-op base."""
- svc = service(log=logging.getLogger("test"))
- assert not svc.decrypts_samples(None) # type: ignore[arg-type]
- assert svc.get_widevine_license(challenge=b"", title=None, track=None) is None # type: ignore[arg-type]
- assert svc.get_playready_license(challenge=b"", title=None, track=None) is None # type: ignore[arg-type]
- with pytest.raises(NotImplementedError):
- svc.get_sample_decrypter(None, 1) # type: ignore[arg-type]
- assert svc.sample_decrypter(None) is None # type: ignore[arg-type]
- svc.close()
-
-
def test_a_source_that_decrypts_samples_hands_its_decrypter_for_the_track() -> None:
class Decrypting(ExampleService):
def decrypts_samples(self, track: Any) -> bool:
@@ -218,83 +196,10 @@ class KeyedSource(FakeService):
self.closed += 1
-@pytest.mark.parametrize(
- ("arrival", "line"),
- [
- (KeyArrival.EXPORT, "Using keys from the export; no CDM required"),
- (KeyArrival.SERVER, "Using server CDM (Widevine); no local CDM required"),
- ],
-)
-def test_dl_licenses_with_no_cdm_of_its_own_when_the_keys_arrive_from_the_source(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, arrival: KeyArrival, line: str
-) -> None:
- lines: list[str] = []
- monkeypatch.setattr(logging.getLogger("test_kind_only"), "info", lambda msg, *a, **k: lines.append(msg))
- saved: list[Any] = []
- monkeypatch.setattr(dl_module.login, "save_cookies", lambda *a: saved.append(a))
- source = KeyedSource(arrival)
- assert harness.run(monkeypatch, caplog, {1: {}}, service=source, to_end=True, skip_dl=True) is None
- assert line in lines
- assert (source.closed, saved) == (1, [])
-
-
-class CipheredSource(KeyedSource):
- """A server-keyed source whose video and audio tracks carry the DRM of ``drm``."""
-
- def __init__(self, drm: dict[str, Any], server_cdm_type: str) -> None:
- super().__init__(KeyArrival.SERVER)
- self.drm = drm
- self.keys.server_cdm_type = server_cdm_type
-
- def get_tracks(self, title: Any) -> Any:
- tracks = super().get_tracks(title)
- for track in tracks:
- track.drm = self.drm.get(track.id)
- return tracks
-
-
def ctr() -> ClearKeyCTR:
return ClearKeyCTR(licence=None, iv=bytes(16), magic=b"EX")
-@pytest.mark.parametrize(
- ("drm", "server_cdm_type", "line"),
- [
- ({"v": [ctr()], "a": [ctr()]}, "widevine", "Using keys from the server; no local CDM required"),
- (
- {"v": ["held-plugin"], "a": [ctr()]},
- "playready",
- "Using keys from the server; no local CDM required",
- ),
- ({"a": [ctr()]}, "widevine", "Using server CDM (Widevine); no local CDM required"),
- (
- {"v": [drm_stub("widevine", KIDS)], "a": [ctr()]},
- "widevine",
- "Using server CDM (Widevine); no local CDM required",
- ),
- ({"v": [drm_stub("playready", KIDS)]}, "playready", "Using server CDM (PlayReady); no local CDM required"),
- ({"a": [ctr()]}, "example", "Using server CDM (EXAMPLE); no local CDM required"),
- ],
- ids=["whole-file", "whole-file-playready-server", "video-drm-not-loaded", "mixed", "playready", "plugin"],
-)
-def test_dl_names_the_server_cdm_only_for_a_title_that_needs_one(
- monkeypatch: pytest.MonkeyPatch,
- caplog: pytest.LogCaptureFixture,
- example_plugins: None,
- drm: dict[str, Any],
- server_cdm_type: str,
- line: str,
-) -> None:
- held = CustomDRM("other", data={"key": bytes(8).hex()})
- drm = {kind: [held if d == "held-plugin" else d for d in drms] for kind, drms in drm.items()}
- lines: list[str] = []
- monkeypatch.setattr(logging.getLogger("test_kind_only"), "info", lambda msg, *a, **k: lines.append(msg))
- monkeypatch.setattr(dl_module.login, "save_cookies", lambda *a: None)
- source = CipheredSource(drm, server_cdm_type)
- assert harness.run(monkeypatch, caplog, {1: {}}, service=source, to_end=True, skip_dl=True) is None
- assert [msg for msg in lines if "no local CDM required" in msg] == [line]
-
-
def test_dl_saves_the_login_cookies_of_a_service(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, tmp_path: Path
) -> None:
diff --git a/tests/core/test_tool_failed.py b/tests/core/test_tool_failed.py
index 207fc4563..84cc0303a 100644
--- a/tests/core/test_tool_failed.py
+++ b/tests/core/test_tool_failed.py
@@ -12,12 +12,10 @@ from unshackle.core.api.errors import categorize_exception
from unshackle.core.config import config
from unshackle.core.drm import decrypters
from unshackle.core.remote_protocol import APIErrorCode
-from unshackle.core.tracks import Audio, Hybrid, Subtitle, Video
-from unshackle.core.tracks import hybrid as hybrid_module
-from unshackle.core.tracks.subtitle_convert import SubtitleEditBackend
+from unshackle.core.tracks import Hybrid
from unshackle.core.utilities import close_debug_logger, init_debug_logger
from unshackle.core.utils import subprocess as subprocess_module
-from unshackle.core.utils.subprocess import ToolFailed, run_step, run_tool, tool_reason
+from unshackle.core.utils.subprocess import ToolFailed, run_tool, tool_reason
KEY = "b5df2ae3f63b8dda9049d6e41422e075"
POSIX_STUBS = pytest.mark.skipif(sys.platform == "win32", reason="the tool stubs are shell scripts")
@@ -34,40 +32,16 @@ def test_the_reason_is_the_last_lines_without_blank_lines_or_glog_prefixes() ->
assert tool_reason(stderr) == "second; Packaging Error: 5; last"
-def test_the_short_glog_prefix_is_removed() -> None:
- assert tool_reason("E1128 12:00:01.123456 1 packager_main.cc:612] Packaging Error: 5\n") == "Packaging Error: 5"
-
-
-def test_a_long_reason_line_keeps_its_start_and_its_end() -> None:
- line = "Cannot close file " + "x" * 300 + ", possibly running out of disk space."
- reason = tool_reason(line)
- assert reason.startswith("Cannot close file ") and reason.endswith("running out of disk space.")
- assert len(reason) == 205
-
-
@pytest.mark.parametrize("empty", [None, "", b"", "\n \n"])
def test_no_output_gives_no_reason(empty: str | bytes | None) -> None:
assert tool_reason(empty) == ""
-def test_the_message_names_tool_exit_reason_and_command() -> None:
- error = ToolFailed("FFmpeg", 1, ["ffmpeg", Path("in.mp4")], stderr=b"No space left on device\n")
- assert str(error) == "FFmpeg failed (exit 1): No space left on device; command: ffmpeg in.mp4"
-
-
def test_stdout_is_the_reason_when_stderr_is_empty() -> None:
error = ToolFailed("SubtitleEdit", 1, ["se"], output="Errors:\nAccess denied\n", stderr="")
assert str(error) == "SubtitleEdit failed (exit 1): Errors:; Access denied; command: se"
-@pytest.mark.parametrize(
- ("code", "text"),
- [(5, "exit 5"), (-9, "signal 9"), (0xC0000005, "exit 0xc0000005")],
-)
-def test_a_failure_with_no_output_names_only_the_exit(code: int, text: str) -> None:
- assert str(ToolFailed("ccextractor", code, ["cc"])) == f"ccextractor failed ({text}); command: cc"
-
-
def test_run_tool_raises_a_called_process_error_with_the_reason() -> None:
with pytest.raises(subprocess.CalledProcessError) as caught:
run_tool("tool", exits(2, stderr="Failed to write file out.mp4"), "tool step")
@@ -76,11 +50,6 @@ def test_run_tool_raises_a_called_process_error_with_the_reason() -> None:
assert str(caught.value).startswith("tool failed (exit 2): Failed to write file out.mp4; command: ")
-def test_run_tool_returns_the_completed_process_on_exit_0() -> None:
- p = run_tool("tool", exits(0, stdout="done"), "tool step")
- assert p.returncode == 0 and p.stdout == b"done"
-
-
def test_a_failed_run_logs_the_reason_without_the_command(monkeypatch: pytest.MonkeyPatch) -> None:
logged: list[dict] = []
monkeypatch.setattr(
@@ -101,29 +70,6 @@ def stub(tmp_path: Path, name: str, script: str) -> Path:
return path
-@POSIX_STUBS
-def test_a_repackage_failure_names_the_ffmpeg_reason(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(binaries, "FFMPEG", stub(tmp_path, "ffmpeg", "echo 'No space left on device' >&2; exit 1"))
- track = Audio("http://example.test/a.mp4", "en", codec=Audio.Codec.AAC)
- track.path = tmp_path / "a.mp4"
- track.path.write_bytes(b"audio")
-
- with pytest.raises(subprocess.CalledProcessError, match=r"^FFmpeg failed \(exit 1\): No space left on device; "):
- track.repackage()
-
-
-@POSIX_STUBS
-def test_a_subtitleedit_failure_names_the_reason_it_wrote_to_stdout(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- monkeypatch.setattr(binaries, "SubtitleEdit", stub(tmp_path, "SubtitleEdit", "echo 'Access is denied'; exit 1"))
- src = tmp_path / "s.srt"
- src.write_text("1\n00:00:01,000 --> 00:00:02,000\nhi\n")
-
- with pytest.raises(subprocess.CalledProcessError, match=r"^SubtitleEdit failed \(exit 1\): Access is denied; "):
- SubtitleEditBackend().convert(Subtitle.Codec.SubRip, src, Subtitle.Codec.WebVTT, tmp_path / "s.vtt")
-
-
@POSIX_STUBS
def test_an_mp4decrypt_failure_names_the_reason_and_keeps_the_key(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
@@ -168,15 +114,6 @@ def test_run_tool_logs_a_handled_exit_code_at_debug(
assert levels(debug_entries()) == [level]
-@pytest.mark.parametrize(("stderr", "level"), [("bad MAX_PQ_LUMINANCE value", "DEBUG"), ("Invalid PPS index", "ERROR")])
-def test_run_step_logs_a_handled_stderr_marker_at_debug(
- debug_entries: Callable[[], list[dict]], stderr: str, level: str
-) -> None:
- with pytest.raises(RuntimeError, match=stderr):
- run_step(exits(1, stderr=stderr), label="tool step", handled=("MAX_PQ_LUMINANCE",))
- assert levels(debug_entries()) == [level]
-
-
def dovi_stub(tmp_path: Path, mode_3_error: str) -> Path:
"""A dovi_tool that fails with mode_3_error under -m and writes the RPU without it."""
return stub(
@@ -211,38 +148,3 @@ def test_a_real_rpu_failure_still_logs_error(
entries = debug_entries()
assert levels(entries) == ["ERROR"] and levels(entries, "hybrid_extract_rpu") == ["ERROR"]
-
-
-@POSIX_STUBS
-def test_a_stream_without_hdr10plus_metadata_logs_no_error(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch, debug_entries: Callable[[], list[dict]]
-) -> None:
- monkeypatch.setattr(config.directories, "temp", tmp_path)
- tool = stub(tmp_path, "hdr10plus_tool", 'echo "File doesn\'t contain dynamic metadata, stopping." >&2; exit 1')
- monkeypatch.setattr(hybrid_module, "HDR10PlusTool", tool)
- hybrid = Hybrid.__new__(Hybrid)
- hybrid.hdr10plus_file = "HDR10Plus.json"
-
- with pytest.raises(hybrid_module.NoHDR10PlusMetadata):
- hybrid.extract_hdr10plus(None) # type: ignore[arg-type]
-
- assert "ERROR" not in levels(debug_entries(), None)
-
-
-@pytest.mark.skipif(not (binaries.CCExtractor and binaries.FFMPEG), reason="needs ccextractor and FFmpeg")
-@pytest.mark.parametrize("suffix", ["mp4", "ts"])
-def test_a_video_without_captions_gives_no_cc_track(
- tmp_path: Path, debug_entries: Callable[[], list[dict]], suffix: str
-) -> None:
- clip = tmp_path / f"v.{suffix}"
- subprocess.run(
- [binaries.FFMPEG, "-v", "error", "-f", "lavfi", "-i", "testsrc=size=320x240:rate=25", "-t", "2"]
- + ["-c:v", "mpeg4", clip],
- check=True,
- )
- video = Video(url="", codec=Video.Codec.AVC, language="en", id_="v")
- video.path = clip
-
- assert video.ccextractor(track_id="cc", out_path=tmp_path / "cc.srt", language="en") is None
- assert not (tmp_path / "cc.srt").exists()
- assert "ERROR" not in levels(debug_entries())
diff --git a/tests/core/test_trun_data_offset.py b/tests/core/test_trun_data_offset.py
index 7d25e8758..119d9c191 100644
--- a/tests/core/test_trun_data_offset.py
+++ b/tests/core/test_trun_data_offset.py
@@ -3,19 +3,14 @@
from __future__ import annotations
import struct
-import subprocess
from pathlib import Path
from uuid import UUID
import pytest
-from tests.core.test_ffmpeg_decodes import GOP, video
from tests.core.test_kid_windows import box, full
-from unshackle.core import binaries
from unshackle.core.config import config
-from unshackle.core.drm import ClearKeyCENC
from unshackle.core.drm.verify import decrypter_for, offsets_not_moof_relative
-from unshackle.core.utils.subprocess import ffmpeg_decodes
KID = UUID("11223344556677889900aabbccddeeff")
KEY = "00112233445566778899aabbccddeeff"
@@ -63,38 +58,9 @@ def test_offsets_not_moof_relative(tmp_path: Path, data: bytes, expected: bool)
assert offsets_not_moof_relative(path) is expected
-def test_a_missing_file_is_not_detected(tmp_path: Path) -> None:
- assert offsets_not_moof_relative(tmp_path / "gone.mp4") is False
-
-
def test_decrypter_for_routes_only_the_shaka_default(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
(flagged := tmp_path / "gpac.mp4").write_bytes(box(b"moov") + fragment(trun(0xA04), tfhd=ABSOLUTE))
(normal := tmp_path / "dash.mp4").write_bytes(box(b"moov") + fragment(trun(0xA05)))
monkeypatch.setattr(config, "decryption", "shaka")
assert decrypter_for(flagged) == "mp4decrypt"
assert decrypter_for(normal) == "shaka"
-
-
-@pytest.mark.skipif(
- not (binaries.FFMPEG and binaries.MP4Box and binaries.Mp4decrypt and binaries.ShakaPackager),
- reason="needs FFmpeg, MP4Box, mp4decrypt and shaka-packager",
-)
-def test_a_gpac_fragmented_track_decrypts_under_the_shaka_default(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- def run(*cmd: object) -> None:
- subprocess.run([str(part) for part in cmd], cwd=tmp_path, check=True, capture_output=True)
-
- video(tmp_path / "src.mp4", *GOP, size="640x360")
- (tmp_path / "drm.xml").write_text(GPAC_DRM)
- run(binaries.MP4Box, "-quiet", "-crypt", "drm.xml", "src.mp4", "-out", "enc.mp4")
- run(binaries.MP4Box, "-quiet", "-frag", "2000", "enc.mp4", "-out", "track.mp4")
- track = tmp_path / "track.mp4"
- monkeypatch.setattr(config, "decryption", "shaka")
- monkeypatch.setattr(config.directories, "temp", tmp_path / "temp")
-
- picked = decrypter_for(track)
- ClearKeyCENC(kids=[KID], content_keys={KID: KEY}).decrypt(track)
-
- assert ffmpeg_decodes(track, video=True)
- assert picked == "mp4decrypt"
diff --git a/tests/core/test_try_ensure_utf8.py b/tests/core/test_try_ensure_utf8.py
index 4b02d42ef..a1e1e1fab 100644
--- a/tests/core/test_try_ensure_utf8.py
+++ b/tests/core/test_try_ensure_utf8.py
@@ -11,11 +11,6 @@ from unshackle.core.utilities import try_ensure_utf8
pytestmark = pytest.mark.unit
-def test_utf8_input_is_returned_unchanged() -> None:
- data = "caf\u00e9 \u2014 \u65e5\u672c".encode("utf8")
- assert try_ensure_utf8(data) is data
-
-
def test_cp1252_input_is_converted_to_utf8() -> None:
assert try_ensure_utf8(b"caf\xe9 \x93q\x94") == "caf\u00e9 \u201cq\u201d".encode("utf8")
diff --git a/tests/core/test_tvdb.py b/tests/core/test_tvdb.py
index 404b086c9..941015b06 100644
--- a/tests/core/test_tvdb.py
+++ b/tests/core/test_tvdb.py
@@ -7,7 +7,7 @@ import pytest
from unshackle.core import providers
from unshackle.core.config import config
from unshackle.core.providers import result_matches
-from unshackle.core.providers.tvdb import TVDBProvider, ids_from_remote, pick_match, result_names
+from unshackle.core.providers.tvdb import TVDBProvider, ids_from_remote, pick_match
from unshackle.core.utils.tags import build_tags_from_ids
REMOTE_IDS = [
@@ -62,10 +62,6 @@ def test_order_map_reverses_with_source_order(monkeypatch: pytest.MonkeyPatch) -
assert mapping[(1, 10)] == (2, 1, "A Flight to Remember")
-def test_order_map_is_noop_when_orders_match() -> None:
- assert TVDBProvider().get_order_map(73871, "official") == {}
-
-
def test_order_map_empty_when_order_missing(monkeypatch: pytest.MonkeyPatch) -> None:
p = TVDBProvider()
stub(p, monkeypatch)
@@ -119,11 +115,6 @@ EXAMPLE_HIT = {
}
-def test_result_names_lists_each_name_once() -> None:
- assert result_names(EXAMPLE_HIT) == ("エグザンプル", "Eguzanpuru", "EXAMPLE Show")
- assert result_names({"name": "EXAMPLE", "aliases": [{"language": "eng", "name": "x"}, ""]}) == ("EXAMPLE",)
-
-
def test_search_matches_on_a_translated_name(monkeypatch: pytest.MonkeyPatch) -> None:
p = TVDBProvider()
monkeypatch.setattr(p, "api_get", lambda path, params=None: [EXAMPLE_HIT])
@@ -133,11 +124,6 @@ def test_search_matches_on_a_translated_name(monkeypatch: pytest.MonkeyPatch) ->
assert not result_matches(result, "OTHER Show")
-def test_cached_tvdb_result_matches_on_a_translated_name() -> None:
- result = providers.cached_to_result(EXAMPLE_HIT, "tvdb", "tv")
- assert result is not None and result_matches(result, "EXAMPLE Show")
-
-
def test_tvdb2_tag_follows_the_matroska_spec() -> None:
# TVDB2 IDs are prefixed by entity type: matroska.org/technical/tagging.html
from unshackle.core.providers import ExternalIds
@@ -146,11 +132,6 @@ def test_tvdb2_tag_follows_the_matroska_spec() -> None:
assert build_tags_from_ids(ExternalIds(tvdb_id=113), "movie")["TVDB2"] == "movies/113"
-def test_provider_order_defaults(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(config, "metadata_providers", [])
- assert [c.NAME for c in providers.provider_order()] == list(providers.DEFAULT_ORDER)
-
-
def test_provider_order_is_configurable(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "metadata_providers", ["TVDB", "tmdb", "nope", "tvdb"])
# unknown entries dropped, duplicates collapsed, case ignored, order kept
@@ -216,13 +197,6 @@ def test_get_episodes_fails_closed_on_a_truncated_listing(monkeypatch: pytest.Mo
assert p._episodes == {}
-def test_get_episodes_does_not_cache_an_empty_listing(monkeypatch: pytest.MonkeyPatch) -> None:
- p = TVDBProvider()
- monkeypatch.setattr(p, "api_get", lambda _path, params: None)
- assert p.get_episodes(73871, "official") == []
- assert p._episodes == {}
-
-
class _Svc:
pass
diff --git a/tests/core/test_vault_bad_keys.py b/tests/core/test_vault_bad_keys.py
index 75593b220..edce5dc8d 100644
--- a/tests/core/test_vault_bad_keys.py
+++ b/tests/core/test_vault_bad_keys.py
@@ -1,5 +1,4 @@
import logging
-import threading
from pathlib import Path
from types import SimpleNamespace
from uuid import UUID
@@ -10,9 +9,9 @@ from tests.core.key_resolver import MemoryVault, key_table, resolver, vaults_of
from unshackle.core.drm import key_resolution
from unshackle.core.drm.key_resolution import ContentKeyResolver
from unshackle.core.title_source import HeldKeys, KeyBatch
-from unshackle.core.vault import RateLimited, vault_session
+from unshackle.core.vault import RateLimited
from unshackle.core.vaults import Vaults
-from unshackle.vaults.API import API, Exceptions
+from unshackle.vaults.API import API
from unshackle.vaults.HTTP import HTTP
from unshackle.vaults.SQLite import SQLite
@@ -189,22 +188,6 @@ def test_segment_decrypted_track_flags_and_raises(tmp_path: Path, monkeypatch: p
assert local.is_bad_key(KID, BAD)
-def test_downloaders_route_through_the_hook(monkeypatch: pytest.MonkeyPatch) -> None:
- """Every real decrypt site calls decrypt_track, so the dl hook sees it."""
- import inspect
-
- from unshackle.core.manifests import dash, hls, ism, segment_pipeline, url
- from unshackle.core.tracks import track
-
- for module in (segment_pipeline, hls):
- assert "decrypt_track(" in inspect.getsource(module), module.__name__
- for module in (dash, hls, ism, url):
- assert "complete_track(" in inspect.getsource(module), module.__name__
- for module in (dash, hls, ism, segment_pipeline, track, url):
- src = inspect.getsource(module)
- assert "drm.decrypt(save_path)" not in src and "drm.decrypt(merged_path)" not in src, module.__name__
-
-
def test_every_poisoned_vault_is_burned_then_the_cdm_answers(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
local = SQLite("local", tmp_path / "local.db")
poisoned = [Remote(f"poisoned{i}", tmp_path / f"p{i}.db") for i in range(3)]
@@ -253,45 +236,6 @@ def test_kv_copy_never_moves_the_flag_table(tmp_path: Path) -> None:
assert list(dst.get_keys("SVC")) == [(KID.hex, GOOD)]
-def test_retry_takes_the_next_parallel_answer_without_a_new_request(tmp_path: Path) -> None:
- from tests.core.test_vaults_lookup import FakeVault
-
- started, release = threading.Event(), threading.Event()
-
- class Fast(FakeVault):
- def get_key(self, kid: UUID | str, service: str) -> str | None:
- # answer only once the slow query runs, or the pool shutdown cancels it before it starts
- started.wait(5)
- return super().get_key(kid, service)
-
- class Slow(FakeVault):
- def get_key(self, kid: UUID | str, service: str) -> str | None:
- started.set()
- release.wait(5)
- return super().get_key(kid, service)
-
- local = SQLite("local", tmp_path / "local.db")
- fast, slow = Fast("fast", BAD), Slow("slow", GOOD)
- vaults = Vaults("SVC")
- vaults.vaults = [local, fast, slow]
- landed = threading.Event()
- offer = vaults.offer
-
- def offered(kid: UUID | str, key: str, source: object) -> None:
- offer(kid, key, source) # type: ignore[arg-type]
- if source is slow:
- landed.set()
-
- vaults.offer = offered # type: ignore[method-assign]
-
- assert vaults.get_key(KID) == (BAD, fast)
- vaults.flag_bad_key(KID, BAD)
- release.set()
- assert landed.wait(5)
- assert vaults.get_key(KID) == (GOOD, slow)
- assert fast.calls == 1 and slow.calls == 1
-
-
@pytest.mark.parametrize("replace", [False, True])
def test_cdm_returning_the_flagged_key_clears_the_flag(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, replace: bool
@@ -461,16 +405,6 @@ def test_an_unkeyed_kid_the_file_uses_is_licensed_before_the_decrypt(
assert drm.decrypted_with == [{KID: GOOD}]
-def test_drm_without_content_keys_still_decrypts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- """HLS AES-128 ClearKey has no KID:KEY map; the hook must pass it straight through."""
- keys = make_resolver(monkeypatch, Vaults("SVC"))
- path = tmp_path / "video.ts"
- path.write_bytes(b"cipher")
- calls: list[Path] = []
- keys.decrypt_verified(SimpleNamespace(decrypt=calls.append), path)
- assert calls == [path]
-
-
def test_flag_on_a_read_only_vault_keeps_its_rows(tmp_path: Path) -> None:
ro = SQLite("ro", tmp_path / "ro.db", no_push=True)
ro.add_key("SVC", KID, BAD)
@@ -812,19 +746,6 @@ def test_a_clear_file_judges_and_copies_no_vault_key(tmp_path: Path, monkeypatch
assert not local.is_bad_key(KID, BAD)
-def test_flagged_pair_warns_once_per_vault(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
- local = SQLite("local", tmp_path / "local.db")
- poisoned = Remote("poisoned", tmp_path / "poisoned.db")
- poisoned.add_key("SVC", KID, BAD)
- local.flag_bad_key("SVC", KID, BAD, "poisoned")
- vaults = Vaults("SVC")
- vaults.vaults = [local, poisoned]
- with caplog.at_level(logging.WARNING, logger="unshackle.core.vaults"):
- for _ in range(3):
- assert vaults.get_key(KID) == (None, None)
- assert sum("flagged bad, skipping" in r.getMessage() for r in caplog.records) == 1
-
-
def test_add_key_refuses_a_flagged_pair_with_a_dashed_kid(tmp_path: Path) -> None:
local = SQLite("local", tmp_path / "local.db")
local.flag_bad_key("SVC", KID, BAD, "poisoned")
@@ -942,18 +863,6 @@ def test_cache_resolved_keys_skips_a_key_a_local_vault_holds(tmp_path: Path, cap
assert [r.getMessage() for r in caplog.records if r.name == "download"] == ["Cached 1 Key to 1/1 Vaults"]
-def test_api_vault_does_not_shrink_the_batch_on_429(monkeypatch: pytest.MonkeyPatch) -> None:
- api = API("vault", "https://vault.example/", "tok")
- posts: list[str] = []
- limited = SimpleNamespace(status_code=429)
- monkeypatch.setattr(api.session, "post", lambda url, **kw: posts.append(url) or limited)
-
- with pytest.raises(Exceptions.TooManyRequests):
- api.add_keys("SVC", {KID: GOOD})
-
- assert len(posts) == 1
-
-
def test_http_vault_does_not_fall_back_to_single_inserts_on_429(monkeypatch: pytest.MonkeyPatch) -> None:
vault = HTTP("vault", "https://vault.example/", password="tok", api_mode="json")
posts: list[str] = []
@@ -966,12 +875,6 @@ def test_http_vault_does_not_fall_back_to_single_inserts_on_429(monkeypatch: pyt
assert len(posts) == 1
-def test_vault_session_retries_429_but_not_a_dead_vault() -> None:
- retry = vault_session(10).get_adapter("https://vault.example").max_retries
- assert retry.status_forcelist == [429]
- assert (retry.connect, retry.read, retry.other) == (0, 0, 0)
-
-
def test_an_unreachable_vault_costs_one_attempt_per_run(monkeypatch: pytest.MonkeyPatch) -> None:
import requests
@@ -996,15 +899,3 @@ def test_an_unreachable_vault_costs_one_attempt_per_run(monkeypatch: pytest.Monk
assert vaults.get_key(SIBLING) == (None, None)
assert vaults.add_keys({KID: GOOD}) == 0
assert calls == ["https://api.example/svc/" + KID.hex]
-
-
-def test_a_vault_still_rate_limited_is_not_used_again(monkeypatch: pytest.MonkeyPatch) -> None:
- calls: list[str] = []
- api = API("api", "https://api.example/", "tok")
- monkeypatch.setattr(api.session, "get", lambda url, **kw: calls.append(url) or SimpleNamespace(status_code=429))
- vaults = Vaults("SVC")
- vaults.vaults = [api]
-
- assert vaults.get_key(KID) == (None, None)
- assert vaults.get_key(SIBLING) == (None, None)
- assert calls == ["https://api.example/svc/" + KID.hex]
diff --git a/tests/core/test_vault_failure_messages.py b/tests/core/test_vault_failure_messages.py
index 2aa926b58..08dabece5 100644
--- a/tests/core/test_vault_failure_messages.py
+++ b/tests/core/test_vault_failure_messages.py
@@ -46,37 +46,6 @@ def test_brief_keeps_the_host_and_reason_and_drops_the_url() -> None:
assert leak not in text
-def test_brief_names_a_timeout() -> None:
- error = requests.ReadTimeout(
- "HTTPConnectionPool(host='vault.example', port=8080): Read timed out. (read timeout=10)", request=request()
- )
- text = brief(error)
- assert "timed out" in text
- assert "SECRETPW" not in text
-
-
-def test_brief_gives_the_status_of_an_http_error() -> None:
- response = html(503)
- error = requests.HTTPError(f"503 Server Error: Service Unavailable for url: {URL}", response=response)
- assert brief(error) == "HTTP 503 from vault.example:8080"
-
-
-def test_brief_keeps_one_short_line_of_any_other_error() -> None:
- assert brief(ValueError("line1\nline2")) == "line1"
- assert len(brief(ValueError("x" * 5000))) <= 200
- assert brief(ValueError()) == "ValueError"
-
-
-def test_brief_keeps_the_reason_of_a_tls_failure() -> None:
- error = requests.exceptions.SSLError(
- "HTTPSConnectionPool(host='vault.example', port=8080): Max retries exceeded with url: /vault.php?password=SECRETPW "
- "(Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: "
- "self-signed certificate (_ssl.c:1010)')))",
- request=request(),
- )
- assert brief(error) == "SSLError to vault.example:8080 (certificate verify failed: self-signed certificate)"
-
-
def test_brief_keeps_the_text_of_a_requests_error_with_no_request() -> None:
assert brief(requests.JSONDecodeError("Expecting value", "", 0)).startswith("Expecting value")
text = brief(requests.exceptions.InvalidSchema(f"No connection adapters were found for 'htp{URL[4:]}'"))
@@ -120,35 +89,6 @@ def test_a_query_mode_vault_that_is_down_never_logs_its_password(
assert vault in vaults.unreachable
-def test_an_api_vault_that_answers_html_is_skipped_after_one_warning(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- calls: list[str] = []
-
- def parked(url: str, **kw: object) -> requests.Response:
- calls.append(url)
- return html()
-
- vault = API("api", "https://api.example/", "tok")
- monkeypatch.setattr(vault.session, "get", parked)
- monkeypatch.setattr(vault.session, "post", parked)
- vaults = Vaults("SVC")
- vaults.vaults = [vault]
-
- with caplog.at_level(logging.DEBUG):
- assert vaults.get_key(KID) == (None, None)
- assert vaults.get_key(SIBLING) == (None, None)
-
- assert len(calls) == 1
- assert vault in vaults.unreachable
- warnings = [m for m in records(caplog, logging.WARNING) if m.startswith("Failed to get key")]
- assert warnings == ["Failed to get key from Vault 'api': HTTP 200 text/html response is not a JSON object"]
- assert not [r for r in caplog.records if " None:
diff --git a/tests/core/test_vault_ledger.py b/tests/core/test_vault_ledger.py
index b40b3719c..de808ff67 100644
--- a/tests/core/test_vault_ledger.py
+++ b/tests/core/test_vault_ledger.py
@@ -6,7 +6,6 @@ from types import SimpleNamespace
from uuid import UUID
import pytest
-import requests
from tests.core.key_resolver import MemoryVault, vaults_of
from unshackle.vaults.SQLite import SQLite
@@ -94,73 +93,6 @@ def test_a_licence_clears_a_flag_of_this_run_without_a_local_vault(caplog: pytes
assert remote.told == []
-def test_one_source_offered_twice_at_once_is_held_once() -> None:
- """Thread A has checked an offer and not yet stored it when thread B offers the same pair."""
- a_storing, b_moved, release = threading.Event(), threading.Event(), threading.Event()
- vaults = vaults_of()
- source = server()
-
- class HeldList(list):
- def append(self, item: object) -> None:
- if threading.current_thread().name == "a":
- a_storing.set()
- release.wait(10)
- else:
- b_moved.set()
- super().append(item)
-
- class Lock:
- """The ledger lock, which tells the test when thread B waits for it."""
-
- def __init__(self) -> None:
- self.lock = threading.Lock()
-
- def __enter__(self) -> None:
- if threading.current_thread().name == "b":
- b_moved.set()
- self.lock.acquire()
-
- def __exit__(self, *exc: object) -> None:
- self.lock.release()
-
- vaults.candidates[KID] = HeldList()
- vaults.lock = Lock() # type: ignore[assignment]
- a = threading.Thread(target=vaults.offer, args=(KID, BAD, source), name="a")
- b = threading.Thread(target=vaults.offer, args=(KID, BAD, source), name="b")
- a.start()
- assert a_storing.wait(10)
- b.start()
- assert b_moved.wait(10)
- release.set()
- a.join(10)
- b.join(10)
-
- assert vaults.candidates[KID] == [(BAD, source)]
-
-
-def test_two_lookups_that_fail_at_once_warn_once(caplog: pytest.LogCaptureFixture) -> None:
- both_asking = threading.Barrier(2, timeout=10)
-
- class Down(MemoryVault):
- def get_key(self, kid: UUID | str, service: str) -> str | None:
- both_asking.wait()
- raise requests.ConnectTimeout("no answer")
-
- vaults = vaults_of(Down(local=False, name="down"))
- with caplog.at_level(logging.WARNING, logger="unshackle.core.vaults"):
- threads = [threading.Thread(target=vaults.get_key, args=(KID,)) for _ in range(2)]
- for thread in threads:
- thread.start()
- for thread in threads:
- thread.join(10)
-
- messages = [record.getMessage() for record in caplog.records]
- assert messages == [
- "Failed to get key from Vault 'down': no answer",
- "Skipping Vault 'down' for the rest of this run",
- ]
-
-
def test_a_licence_that_returns_the_dropped_key_warns_once_unflags_it_and_stores_it_again(
caplog: pytest.LogCaptureFixture,
) -> None:
@@ -248,19 +180,6 @@ def test_a_licence_key_is_stored_then_sent_to_the_server_vault_and_its_flag_wait
]
-def test_a_vault_write_that_fails_logs_one_error_line(caplog: pytest.LogCaptureFixture) -> None:
- class Failing(MemoryVault):
- def is_bad_key(self, kid: UUID | str, key: str) -> bool:
- raise RuntimeError("disk gone")
-
- vaults = vaults_of(Failing())
- vaults.licensed({KID: GOOD})
- with caplog.at_level(logging.ERROR):
- vaults.wait_writes()
-
- assert caplog.record_tuples == [("download", logging.ERROR, "Vault write failed: RuntimeError('disk gone')")]
-
-
def test_a_proven_track_sends_one_set_to_the_server_vault_and_copies_only_its_vault_keys() -> None:
remote, local = MemoryVault({KID: GOOD}, local=False), MemoryVault(name="local")
vaults = vaults_of(local, remote)
@@ -276,14 +195,3 @@ def test_a_proven_track_sends_one_set_to_the_server_vault_and_copies_only_its_va
assert local.added == {KID: GOOD}
assert remote.added == {}
assert pushed == [({KID: GOOD, SIBLING: BAD}, "track")]
-
-
-def test_building_and_dropping_many_vaults_starts_no_thread() -> None:
- """The server builds a Vaults per request; the one vault writer of the process starts only on its first write."""
- before = set(threading.enumerate())
-
- for _ in range(50):
- vaults_of(MemoryVault())
-
- assert set(threading.enumerate()) - before == set()
- assert all(vaults_of().WRITER is vaults_of().WRITER for _ in range(3))
diff --git a/tests/core/test_vault_push_retry.py b/tests/core/test_vault_push_retry.py
index 06527a1ef..e3c90175b 100644
--- a/tests/core/test_vault_push_retry.py
+++ b/tests/core/test_vault_push_retry.py
@@ -31,18 +31,6 @@ def parked_host(calls: list, status: int = 200, body: bytes = PARKED_PAGE) -> Ca
return parked
-def test_an_unreachable_json_vault_fails_the_push(monkeypatch: pytest.MonkeyPatch) -> None:
- vault = HTTP("json", "https://vault.invalid/rpc", "token", api_mode="json")
-
- def down(method: str, params: dict) -> dict:
- raise ConnectionError("vault is down")
-
- monkeypatch.setattr(vault, "request", down)
- vaults = Vaults("SVC")
- vaults.vaults = [vault]
- assert vaults.add_keys({KID: KEY}) == 0
-
-
@pytest.mark.parametrize(
"mode, status, body",
[
@@ -119,13 +107,6 @@ def test_a_json_vault_error_reply_to_a_single_push_stays_a_quiet_false(
assert not caplog.records
-def test_a_json_vault_with_a_broken_url_warns_on_a_single_push(caplog: pytest.LogCaptureFixture) -> None:
- _, vaults = one_json_vault("vault.example/rpc")
- with caplog.at_level(logging.WARNING):
- assert vaults.add_key(KID, KEY) == 0
- assert [r.getMessage().split(":")[0] for r in caplog.records] == ["Failed to add key to Vault 'EXAMPLE'"]
-
-
def test_a_json_vault_that_is_down_fails_the_service_list(monkeypatch: pytest.MonkeyPatch) -> None:
vault, _ = one_json_vault()
monkeypatch.setattr(vault.session, "post", no_answer)
@@ -156,43 +137,6 @@ def query_vault() -> HTTP:
return HTTP("EXAMPLE", "https://vault.example/", password="tok", username="user")
-@pytest.mark.parametrize(
- "vault, call",
- [
- pytest.param(query_vault(), lambda v: v.get_key(KID, "SVC"), id="query-get_key"),
- pytest.param(query_vault(), lambda v: list(v.get_keys("SVC")), id="query-get_keys"),
- pytest.param(query_vault(), lambda v: v.add_key("SVC", KID, KEY), id="query-add_key"),
- pytest.param(query_vault(), lambda v: v.add_keys("SVC", {KID: KEY}), id="query-add_keys"),
- pytest.param(query_vault(), lambda v: list(v.get_services()), id="query-get_services"),
- pytest.param(
- HTTP("EXAMPLE", "https://vault.example/", api_key="tok", api_mode="decrypt_labs"),
- lambda v: v.get_key(KID, "SVC"),
- id="decrypt_labs-get_key",
- ),
- pytest.param(API("api", "https://api.example/", "tok"), lambda v: v.add_key("SVC", KID, KEY), id="api-add_key"),
- pytest.param(
- API("api", "https://api.example/", "tok"), lambda v: list(v.get_services()), id="api-get_services"
- ),
- pytest.param(
- API("api", "https://api.example/", "tok"),
- lambda v: v.flag_bad_key("SVC", KID, KEY, "api"),
- id="api-flag_bad_key",
- ),
- pytest.param(
- API("api", "https://api.example/", "tok"), lambda v: v.unflag_bad_key(KID, KEY), id="api-unflag_bad_key"
- ),
- ],
-)
-def test_a_vault_still_rate_limited_after_the_retries_raises(
- vault: HTTP | API, call: Callable[[Any], object], monkeypatch: pytest.MonkeyPatch
-) -> None:
- monkeypatch.setattr(vault.session, "get", rate_limited)
- monkeypatch.setattr(vault.session, "post", rate_limited)
- monkeypatch.setattr(vault.session, "delete", rate_limited)
- with pytest.raises(RateLimited):
- call(vault)
-
-
def answers(*replies: bytes) -> Callable[..., requests.Response]:
queue = list(replies)
return lambda *a, **kw: fake_response(200, queue.pop(0), "application/json")
diff --git a/tests/core/test_vault_server_ops.py b/tests/core/test_vault_server_ops.py
index 0b64f9bff..736e63c53 100644
--- a/tests/core/test_vault_server_ops.py
+++ b/tests/core/test_vault_server_ops.py
@@ -66,11 +66,6 @@ def test_a_vault_type_stores_flags_only_when_it_reads_them_back() -> None:
assert module.stores_flags == (module.is_bad_key is not Vault.is_bad_key), module
-def test_a_vault_type_has_tables_only_when_it_can_make_them() -> None:
- for module in MODULES.values():
- assert module.has_tables == (module.create_table is not Vault.create_table), module
-
-
def test_flag_stores_names_the_configs_whose_vault_type_keeps_flags() -> None:
configs = [
{"type": "SQLite", "name": "local"},
diff --git a/tests/core/test_vault_table_case.py b/tests/core/test_vault_table_case.py
index 456ce1f4e..430130804 100644
--- a/tests/core/test_vault_table_case.py
+++ b/tests/core/test_vault_table_case.py
@@ -194,11 +194,6 @@ def test_copy_skips_a_service_it_cannot_read(tmp_path: Path) -> None:
assert copy_service_data(dst, UnlistableVault("unlistable"), "svca", LOG) == 0
-def test_copy_skips_a_vault_that_cannot_list_services() -> None:
- with pytest.raises(ValueError):
- list(UnlistableVault("unlistable").get_services())
-
-
def test_lookups_work_from_another_thread(vault: SQLite) -> None:
"""`kv search` probes services in a ThreadPoolExecutor; connections are thread-local."""
found: list[str | None] = []
diff --git a/tests/core/test_vaults_lookup.py b/tests/core/test_vaults_lookup.py
index 638780d01..cc9c94e5e 100644
--- a/tests/core/test_vaults_lookup.py
+++ b/tests/core/test_vaults_lookup.py
@@ -46,17 +46,5 @@ def test_local_hit_skips_remote() -> None:
assert remote.calls == 0
-def test_remote_vaults_run_together_and_first_hit_wins() -> None:
- local = FakeVault("local", None, local=True)
- slow = FakeVault("slow", "cc" * 16, delay=1.0)
- fast = FakeVault("fast", "dd" * 16, delay=0.05)
- start = time.monotonic()
- key, vault = make(local, slow, fast).get_key("kid")
- assert (key, vault) == ("dd" * 16, fast)
- assert time.monotonic() - start < 0.9 # did not wait for the slow vault
- assert slow.calls == 1 and local.calls == 1
- assert slow.threads != fast.threads
-
-
def test_miss_everywhere() -> None:
assert make(FakeVault("a", None), FakeVault("b", "0" * 32)).get_key("kid") == (None, None)
diff --git a/tests/core/test_verify_proxy_exit.py b/tests/core/test_verify_proxy_exit.py
index e29fc7c87..3f2f2d34c 100644
--- a/tests/core/test_verify_proxy_exit.py
+++ b/tests/core/test_verify_proxy_exit.py
@@ -62,13 +62,6 @@ def test_proxied_lookup_ignores_env_proxy(monkeypatch):
assert settings["proxies"]["https"] == "http://127.0.0.1:2"
-def test_local_lookup_keeps_env_proxy(monkeypatch):
- monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:1")
- sess = ip_info.lookup_session(None)
- settings = sess.merge_environment_settings("https://ipinfo.io/json", {}, None, None, None)
- assert settings["proxies"]["https"] == "http://127.0.0.1:1"
-
-
def test_get_ip_info_collects_connection_errors_only(monkeypatch):
def refused(session):
raise OSError("refused")
diff --git a/tests/core/test_vivid_hybrid.py b/tests/core/test_vivid_hybrid.py
index 4ba4704c2..0746791bf 100644
--- a/tests/core/test_vivid_hybrid.py
+++ b/tests/core/test_vivid_hybrid.py
@@ -82,10 +82,6 @@ def test_a_vivid_track_that_cannot_be_a_base_falls_back_to_the_other_range(bad:
assert isinstance(select(videos, [R.HYBRID]), Skip)
-def test_a_taller_av1_vivid_track_does_not_take_the_height_of_the_hybrid() -> None:
- assert ids(select([vid("av1", R.VIVID, 2160, C.AV1), vid("viv", R.VIVID), dv()], [R.HYBRID])) == ["viv", "dv"]
-
-
def test_the_gate_counts_a_vivid_track_only_as_a_chosen_base() -> None:
vivid = vid("viv", R.VIVID)
assert hybrid_gate_failure([vivid, dv()], False)
diff --git a/tests/core/test_widevine_get_content_keys.py b/tests/core/test_widevine_get_content_keys.py
index 3cb5a83dd..e889aa178 100644
--- a/tests/core/test_widevine_get_content_keys.py
+++ b/tests/core/test_widevine_get_content_keys.py
@@ -11,7 +11,7 @@ from pywidevine.pssh import PSSH
from unshackle.core.cdm.custom_remote_cdm import CustomRemoteCDMExceptions
from unshackle.core.cdm.decrypt_labs_remote_cdm import DecryptLabsRemoteCDMExceptions
-from unshackle.core.drm import ClearKeyCENC, PlayReady, Widevine
+from unshackle.core.drm import Widevine
from unshackle.core.utilities import declared_kwargs
KID = UUID("00112233-4455-6677-8899-aabbccddeeff")
@@ -116,9 +116,3 @@ def test_a_licence_the_cdm_cannot_parse_is_one_line(error: Exception) -> None:
with pytest.raises(click.ClickException, match=KID.hex):
_drm().get_content_keys(JunkCdm(), certificate=lambda **_: None, licence=lambda **_: b"junk licence")
-
-
-@pytest.mark.parametrize("drm", [Widevine, PlayReady, ClearKeyCENC])
-def test_a_licence_with_no_usable_key_is_one_line(drm: Any) -> None:
- assert issubclass(drm.Exceptions.EmptyLicense, click.ClickException)
- assert issubclass(drm.Exceptions.CEKNotFound, click.ClickException)
diff --git a/tests/core/test_windows_fonts.py b/tests/core/test_windows_fonts.py
index 1347e16d9..30b23221d 100644
--- a/tests/core/test_windows_fonts.py
+++ b/tests/core/test_windows_fonts.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import sys
import types
-from pathlib import Path, PureWindowsPath
+from pathlib import Path
import pytest
@@ -72,21 +72,3 @@ def test_a_font_is_found_by_the_family_name_in_its_file(registry, tmp_path, monk
fonts = utilities.get_windows_fonts()
assert fonts == {"MyFont-Bold": user, "My Font": user}
assert utilities.find_font_with_fallbacks("My Font", fonts) == user
-
-
-def test_an_absolute_registry_value_replaces_the_font_folder():
- user = r"C:\Users\x\AppData\Local\Microsoft\Windows\Fonts\MyFont-Bold.ttf"
- assert PureWindowsPath(r"C:\Windows\Fonts", user) == PureWindowsPath(user)
-
-
-def test_missing_files_bitmap_fonts_and_odd_values_are_skipped(registry, tmp_path):
- font(tmp_path / "machine/modern.fon")
- collection = font(tmp_path / "machine/msgothic.ttc")
- registry[HKLM] = [
- ("Modern (All res)", "modern.fon"),
- ("MS Gothic & MS UI Gothic (TrueType)", "msgothic.ttc"),
- ("Gone (TrueType)", "gone.ttf"),
- ("Binary (TrueType)", b"x.ttf"),
- ]
- registry[HKCU] = [("Deleted (TrueType)", str(tmp_path / "user/Deleted.ttf"))]
- assert utilities.get_windows_fonts() == {"MS Gothic & MS UI Gothic": collection}
diff --git a/tests/core/test_wire.py b/tests/core/test_wire.py
index 00a87b9a5..fdfe76af5 100644
--- a/tests/core/test_wire.py
+++ b/tests/core/test_wire.py
@@ -6,8 +6,6 @@ import inspect
import json
import logging
import re
-import subprocess
-import sys
from datetime import date
from pathlib import Path
from typing import Any
@@ -18,7 +16,6 @@ import pytest
from pywidevine.pssh import PSSH as WidevinePSSH
from tests.core.test_zero_kid_fallback import _playready_pssh
-from unshackle.core import wire
from unshackle.core.config import config
from unshackle.core.drm import ClearKeyCENC, ClearKeyCTR, CustomDRM, PlayReady, Widevine
from unshackle.core.import_service import ImportService
@@ -31,7 +28,6 @@ from unshackle.core.tracks.track import Track
from unshackle.core.wire import (
apply_title_fields,
apply_tracks_reply,
- attachment_to_dict,
build_attachment,
build_chapters,
build_title,
@@ -700,23 +696,6 @@ def test_rest_episode() -> None:
assert serialize_title(full_episode(), None) == REST_EPISODE
-def test_rest_episode_without_a_name_gets_a_placeholder_and_no_optional_keys() -> None:
- assert serialize_title(episode(name=None), None) == {
- "type": "episode",
- "name": "Episode 05",
- "id": "ep-0001",
- "language": "en",
- "description": "An example episode.",
- "date": "2024-03-09",
- "cover_url": "https://img.example/ep.jpg",
- "year": 2024,
- "series_title": "Example Show",
- "season": 2,
- "number": 5,
- "air_date": "2024-03-09",
- }
-
-
def test_rest_movie() -> None:
assert serialize_title(movie(), None) == REST_MOVIE
@@ -725,23 +704,6 @@ def test_rest_song() -> None:
assert serialize_title(song(), None) == REST_SONG
-def test_rest_title_of_no_known_kind() -> None:
- assert serialize_title(OtherTitle(), None) == {
- "type": "other",
- "name": "Other Thing",
- "id": "other-0001",
- "language": None,
- "description": None,
- "date": None,
- "cover_url": None,
- }
-
-
-def test_rest_title_key_order_is_stable() -> None:
- assert list(serialize_title(full_episode(), None)) == list(REST_EPISODE)
- assert list(serialize_title(song(), None)) == list(REST_SONG)
-
-
def test_export_episode_meta() -> None:
meta = title_to_meta(full_episode())
assert meta == META_EPISODE
@@ -758,15 +720,6 @@ def test_export_movie_meta() -> None:
}
-def test_export_meta_of_another_title_is_a_movie_named_by_str() -> None:
- assert title_to_meta(OtherTitle()) == {
- "id": "other-0001",
- "language": None,
- "type": "movie",
- "name": "Other Thing",
- }
-
-
def test_export_song_meta_rebuilds_the_song_the_rest_form_rebuilds() -> None:
rebuilt = title_fields(build_title(json_copy(title_to_meta(song())), "EXAMPLE", "fallback-id"))
assert rebuilt == title_fields(build_title(json_copy(REST_SONG), "EXAMPLE", "fallback-id"))
@@ -789,20 +742,6 @@ def test_build_title_drops_the_placeholder_name() -> None:
}
-def test_build_title_from_rest_movie() -> None:
- assert title_fields(build_title(json_copy(REST_MOVIE), "EXAMPLE", "fallback-id")) == {
- "class": "Movie",
- "service": "EXAMPLE",
- "id": "movie-0001",
- "language": "fr",
- "year": 2023,
- "data": {"cover_url": "https://img.example/film.jpg"},
- "name": "Example Film",
- "description": "An example film.",
- "anime": None,
- }
-
-
def test_build_title_from_rest_song() -> None:
fields = title_fields(build_title(json_copy(REST_SONG), "EXAMPLE", "fallback-id"))
assert fields == {
@@ -844,28 +783,6 @@ def test_build_title_from_export_meta() -> None:
assert title_fields(title) == {**EPISODE_FIELDS, "data": None, "description": None}
-def test_build_title_from_a_bare_episode_uses_the_fallbacks() -> None:
- assert title_fields(build_title({"type": "episode"}, "EXAMPLE", "fallback-id")) == {
- "class": "Episode",
- "service": "EXAMPLE",
- "id": "fallback-id",
- "language": None,
- "year": None,
- "data": None,
- "title": "Unknown",
- "season": 0,
- "number": 0,
- "name": None,
- "part": None,
- "description": None,
- "air_date": None,
- "absolute": None,
- "sport": False,
- "anime": None,
- "daily": None,
- }
-
-
def test_build_title_refuses_an_unknown_kind() -> None:
with pytest.raises(click.ClickException, match="unknown title type 'other'"):
build_title(json_copy(serialize_title(OtherTitle(), None)), "EXAMPLE", "fallback-id")
@@ -1156,12 +1073,6 @@ def test_reconstruct_rest_drm_skips_what_it_cannot_parse(caplog: pytest.LogCaptu
assert caplog.messages[0].startswith("Skipping unparseable playready DRM entry from server: InvalidPssh(")
-def test_export_drm_decode() -> None:
- rebuilt = [drm_from_dict(json_copy(d.to_dict())) for d in (widevine(VIDEO_KID), playready(VIDEO_KID, AUDIO_KID))]
- rebuilt.append(drm_from_dict(json_copy(clearkey().to_dict())))
- assert [drm_fields(d) for d in rebuilt] == [WIDEVINE_FIELDS, PLAYREADY_FIELDS, CLEARKEY_FIELDS]
-
-
def test_export_drm_decode_takes_the_stored_keys() -> None:
data = {
"system": "Widevine",
@@ -1224,11 +1135,6 @@ def test_reconstruct_rest_drm_refuses_a_bad_plugin_kid_with_one_line(example_plu
assert e.value.error_code is APIErrorCode.DRM_ERROR # type: ignore[attr-defined]
-def test_a_track_with_an_unknown_drm_type_stops_the_title() -> None:
- with pytest.raises(click.ClickException, match="futuredrm"):
- build_tracks({"video": [{**REST_VIDEO, "drm": [{"type": "futuredrm", "kids": [str(VIDEO_KID)]}]}]})
-
-
@pytest.mark.parametrize(
"data", [{"system": "FutureDRM", "kids": [VIDEO_KID.hex]}, {"system": "FutureDRM", "pssh_b64": "x"}]
)
@@ -1289,54 +1195,6 @@ def test_build_attachment_by_url_and_with_nothing() -> None:
assert build_attachment({"name": "x"}) is None
-def test_rest_titles_round_trip() -> None:
- for title in (full_episode(), movie()):
- assert title_fields(
- build_title(json_copy(serialize_title(title, None)), "EXAMPLE", "fallback-id")
- ) == title_fields(title)
- rebuilt = title_fields(build_title(json_copy(serialize_title(song(), None)), "EXAMPLE", "fallback-id"))
- assert {**rebuilt, "data": None} == {**title_fields(song()), "data": None}
-
-
-def test_export_meta_round_trips_the_fields_it_carries() -> None:
- episode_meta = title_fields(build_title(json_copy(title_to_meta(full_episode())), "EXAMPLE", "fallback-id"))
- assert episode_meta == {**title_fields(full_episode()), "data": None, "description": None}
- movie_meta = title_fields(build_title(json_copy(title_to_meta(movie())), "EXAMPLE", "fallback-id"))
- assert movie_meta == {**title_fields(movie()), "data": None, "description": None}
-
-
-def test_rest_tracks_round_trip_with_their_drm() -> None:
- track = video()
- track.drm = [widevine(VIDEO_KID), playready(VIDEO_KID, AUDIO_KID)]
- track.drm_preference = "pr"
- lists = serialize_tracks(Tracks([track, audio(), subtitle()]), movie(), include_url=True)
- rebuilt = build_tracks(json_copy(lists))
- assert [track_fields(t) for t in (*rebuilt.videos, *rebuilt.audio, *rebuilt.subtitles)] == [
- track_fields(t) for t in (track, audio(), subtitle())
- ]
-
-
-def test_export_tracks_round_trip_without_closed_captions() -> None:
- for track in (video(), audio(), subtitle()):
- expected = track_fields(track)
- if isinstance(track, Video):
- expected["closed_captions"] = []
- assert track_fields(track_from_dict(json_copy(track_to_dict(track)))) == expected
-
-
-def test_both_track_forms_decode_the_shared_fields_the_same_way() -> None:
- shared = ("id", "url", "language", "is_original_lang", "descriptor", "needs_repack", "name", "edition", "note")
- forms: list[tuple[Any, Any, Any]] = [
- (video(), serialize_video_track, deserialize_video),
- (audio(), serialize_audio_track, deserialize_audio),
- (subtitle(), serialize_subtitle_track, deserialize_subtitle),
- ]
- for track, encode, decode in forms:
- rest = track_fields(decode(json_copy(encode(track, include_url=True))))
- export = track_fields(track_from_dict(json_copy(track_to_dict(track))))
- assert {key: rest[key] for key in shared} == {key: export[key] for key in shared}
-
-
URL_SUBTITLE = {
"type": "Subtitle",
"id": "good",
@@ -1390,38 +1248,6 @@ def test_drm_round_trips_in_both_forms() -> None:
assert drm_fields(drm_from_dict(json_copy(drm_to_dict(one)))) == drm_fields(one)
-def test_attachments_round_trip_in_both_forms(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- def fields(attachment: Attachment) -> tuple[Any, ...]:
- return attachment.url, attachment.name, attachment.mime_type, attachment.description
-
- by_url = Attachment(
- url="https://img.example/poster.jpg", name="Poster", mime_type="image/jpeg", description="Cover"
- )
- for data in (serialize_attachment(by_url), attachment_to_dict(by_url)):
- rebuilt = build_attachment(json_copy(data))
- assert rebuilt is not None
- assert fields(rebuilt) == fields(by_url)
- monkeypatch.setattr(config.directories, "temp", tmp_path / "temp")
- poster = tmp_path / "poster.jpg"
- poster.write_bytes(b"jpeg-bytes")
- by_path = Attachment(path=poster, name="Poster", description="Cover")
- rebuilt = build_attachment(json_copy(serialize_attachment(by_path)))
- assert rebuilt is not None and rebuilt.path is not None
- assert (fields(rebuilt), rebuilt.path.read_bytes()) == (fields(by_path), b"jpeg-bytes")
-
-
-def test_an_attachment_over_the_inline_limit_is_skipped(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(wire, "ATTACHMENT_INLINE_LIMIT", 4)
- poster = tmp_path / "poster.jpg"
- poster.write_bytes(b"jpeg-bytes")
- assert serialize_attachment(Attachment(path=poster, name="Poster")) is None
-
-
-def test_an_export_track_of_an_unhashable_type_is_refused_as_before() -> None:
- with pytest.raises(TypeError, match="unhashable type|as a dict key"):
- track_from_dict({**EXPORT_VIDEO, "type": {"a": 1}})
-
-
RENAMED = {"range_": "range", "id_": "id", "title": "series_title"}
NOT_SENT = {"session", "downloader", "downloader_args", "from_file", "extra", "service", "data"}
NOT_EXPORTED = NOT_SENT | {"closed_captions", "drm", "description"}
@@ -1459,17 +1285,6 @@ def test_every_constructor_field_crosses_the_edge(item: Any, rest: Any, export:
assert fields - NOT_EXPORTED - set(export(obj)) == set()
-@pytest.mark.parametrize(
- "module",
- ["unshackle.core.wire", "unshackle.core.api", "unshackle.core.tracks", "unshackle.core.drm"],
-)
-def test_each_module_imports_first_in_a_new_interpreter(module: str) -> None:
- """wire imports tracks, drm and titles, and they import wire inside their to_dict, so no order may cycle."""
- root = Path(__file__).resolve().parents[2]
- result = subprocess.run([sys.executable, "-c", f"import {module}"], cwd=root, capture_output=True, check=False)
- assert result.returncode == 0, result.stderr.decode("utf-8", errors="replace")
-
-
class FLAGGED:
ANIME = True
METADATA_PROVIDER = "tmdb"
diff --git a/tests/downloaders/test_bounded_requests.py b/tests/downloaders/test_bounded_requests.py
index 208220d02..9b49e7255 100644
--- a/tests/downloaders/test_bounded_requests.py
+++ b/tests/downloaders/test_bounded_requests.py
@@ -1,14 +1,9 @@
-import itertools
-import math
import sys
import threading
-import time
-import types
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
import requests as rq
-from rich import filesize
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.downloaders.requests import download
@@ -96,13 +91,3 @@ def test_a_cut_body_bounds_the_following_requests(tmp_path, server):
assert spans and all(int(end) - int(start) + 1 <= CHUNK for start, end in spans)
# the bounded requests are cheap because they share one pooled connection
assert server.connections < len(server.ranges)
-
-
-def test_each_speed_line_is_the_window_rate_rounded_up(tmp_path, server, monkeypatch):
- clock = itertools.count(step=11.0)
- monkeypatch.setattr(downloader, "time", types.SimpleNamespace(**{**vars(time), "monotonic": lambda: next(clock)}))
- events = list(download(url=server.url, save_path=tmp_path / "0.mp4", session=rq.Session()))
-
- pairs = [(events[i - 1]["advance"], e["downloaded"]) for i, e in enumerate(events) if "downloaded" in e]
- assert any(n % 11 for n, _ in pairs)
- assert all(text == f"{filesize.decimal(math.ceil(n / 11))}/s" for n, text in pairs)
diff --git a/tests/downloaders/test_cancel_hardening.py b/tests/downloaders/test_cancel_hardening.py
index 69ac6f593..7809002c6 100644
--- a/tests/downloaders/test_cancel_hardening.py
+++ b/tests/downloaders/test_cancel_hardening.py
@@ -17,7 +17,6 @@ Pins three teardown-safety invariants:
import importlib
import threading
-import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
@@ -125,32 +124,6 @@ def test_dispatch_parts_does_not_finalize_on_global_cancel(server, tmp_path):
assert save_path.with_name(f"{save_path.name}.!dev").exists()
-def test_backoff_wait_exits_promptly_on_batch_abort(server, tmp_path, monkeypatch):
- server.always_status = 503
- monkeypatch.setattr(dl, "retry_sleep", lambda exc, attempts: 30.0)
- abort = threading.Event()
-
- def consume() -> None:
- for _ in dl.download(
- url=url(server),
- save_path=tmp_path / "seg.bin",
- session=Session(),
- segmented=True,
- abort=abort,
- ):
- pass
-
- worker = threading.Thread(target=consume)
- start = time.monotonic()
- worker.start()
- time.sleep(0.5) # let the first attempt fail and enter the backoff wait
- abort.set()
- worker.join(timeout=10)
- assert not worker.is_alive()
- # generous bound: far below the 30s nap, so the wait was interrupted, not slept out
- assert time.monotonic() - start < 10
-
-
@pytest.mark.parametrize("adaptive", [False, True])
def test_cancelled_batch_raises_instead_of_finishing_or_hanging(server, tmp_path, adaptive):
dl.DOWNLOAD_CANCELLED.set()
diff --git a/tests/downloaders/test_download_hardening.py b/tests/downloaders/test_download_hardening.py
index 9779fcc1b..ecfc1eb6f 100644
--- a/tests/downloaders/test_download_hardening.py
+++ b/tests/downloaders/test_download_hardening.py
@@ -116,16 +116,6 @@ def test_range_item_ignored_by_server_fails_not_corrupts(server, tmp_path, monke
assert not list(tmp_path.glob("seg_*.bin"))
-def test_range_item_spanning_whole_resource_accepts_200(server, tmp_path):
- # RFC 9110 lets a server ignore Range and answer 200 with the whole resource; when the
- # slice spans that resource the body is byte-identical to the 206 and must be kept
- server.honor_range = False
- urls = [{"url": url(server), "headers": {"Range": f"bytes=0-{len(PARENT) - 1}"}}]
- files = run(server, tmp_path, urls, max_workers=1)
- assert files[0].read_bytes() == PARENT
- assert len(server.requests) == 1
-
-
def test_range_item_retry_rewrites_slice(server, tmp_path, monkeypatch):
server.truncate_first = True
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
@@ -138,22 +128,12 @@ def test_range_item_retry_rewrites_slice(server, tmp_path, monkeypatch):
assert len(ranges) >= 2
-def test_segment_requests_ask_identity_encoding(server, tmp_path):
- run(server, tmp_path, [{"url": url(server)}], max_workers=1)
- assert all(r.get("Accept-Encoding") == "identity" for r in server.requests)
-
-
def exc_with_headers(headers):
exc = Exception("boom")
exc.response = SimpleNamespace(headers=headers)
return exc
-def test_retry_sleep_honors_numeric_retry_after():
- assert dl.retry_sleep(exc_with_headers({"Retry-After": "3"}), 1) == 3.0
- assert dl.retry_sleep(exc_with_headers({"Retry-After": "9999"}), 1) == 60.0 # session.MAX_BACKOFF cap
-
-
def test_retry_sleep_honors_http_date_retry_after():
when = format_datetime(datetime.now(UTC) + timedelta(seconds=10), usegmt=True)
assert 5 <= dl.retry_sleep(exc_with_headers({"Retry-After": when}), 1) <= 10
@@ -166,25 +146,6 @@ def test_retry_sleep_exponential_backoff_with_jitter():
assert dl.retry_sleep(Exception("reset"), 30) == 60.0 # capped
-def test_retry_sleep_invalid_retry_after_falls_back():
- v = dl.retry_sleep(exc_with_headers({"Retry-After": "soon"}), 1)
- assert dl.RETRY_WAIT <= v <= dl.RETRY_WAIT * 1.1
-
-
-def test_retry_sleep_naive_http_date_treated_as_utc():
- # "-0000" makes parsedate_to_datetime return a naive datetime; must clamp, not raise
- when = format_datetime(datetime.now(UTC).replace(tzinfo=None) + timedelta(seconds=10))
- assert when.endswith("-0000")
- v = dl.retry_sleep(exc_with_headers({"Retry-After": when}), 1)
- assert 5 <= v <= 10
-
-
-def test_retry_sleep_nan_retry_after_falls_back():
- # float("nan") parses; a non-finite wait must fall back to the exponential path
- v = dl.retry_sleep(exc_with_headers({"Retry-After": "nan"}), 1)
- assert dl.RETRY_WAIT <= v <= dl.RETRY_WAIT * 1.1
-
-
def test_retry_sleep_honors_retry_after_on_wrapped_cause():
# RnetSession raises MaxRetriesError whose __cause__ HTTPError carries the response
exc = Exception("max retries exceeded")
diff --git a/tests/downloaders/test_empty_subrange.py b/tests/downloaders/test_empty_subrange.py
deleted file mode 100644
index 1997296fe..000000000
--- a/tests/downloaders/test_empty_subrange.py
+++ /dev/null
@@ -1,110 +0,0 @@
-"""A bounded sub-range that returns no bytes must fail, not spin.
-
-After a cut, the sequential path asks for bounded sub-ranges and treats a whole
-sub-range as progress rather than a retry. A response with an empty body of
-unknown length (a chunked 206, a 204, a 304) makes no progress, so it must
-raise and spend an attempt, or the same request repeats forever.
-"""
-
-import sys
-import threading
-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-
-import pytest
-import requests as rq
-
-from unshackle.core.constants import DOWNLOAD_CANCELLED
-from unshackle.core.downloaders.requests import download
-
-# the package re-exports the `requests` function, shadowing the module of the same name
-downloader = sys.modules[download.__module__]
-
-BODY = bytes(range(256)) * 256 # 64 KiB
-CUT_AFTER = 10 * 1024
-CHUNK = 16 * 1024
-DEADLINE = 30
-
-
-class _EmptyRangeServer(ThreadingHTTPServer):
- """Cuts the first body, then answers every bounded range with an empty chunked 206."""
-
- allow_reuse_address = True
- daemon_threads = True
-
- def __init__(self):
- self.ranges: list[str] = []
- super().__init__(("127.0.0.1", 0), _EmptyRangeHandler)
- self.url = f"http://127.0.0.1:{self.server_address[1]}/seg.mp4"
-
- def handle_error(self, request, client_address): # the client hanging up is expected here
- pass
-
-
-class _EmptyRangeHandler(BaseHTTPRequestHandler):
- protocol_version = "HTTP/1.1"
-
- def log_message(self, *_):
- pass
-
- def do_GET(self):
- header = self.headers.get("Range")
- self.server.ranges.append(header)
- start, end, bounded = 0, len(BODY) - 1, False
- if header:
- start_s, _, end_s = header.removeprefix("bytes=").partition("-")
- start, end = int(start_s), (int(end_s) if end_s else len(BODY) - 1)
- bounded = bool(end_s)
- if bounded:
- # a valid response: the chunked terminator closes a zero-length body, so requests raises nothing
- self.send_response(206)
- self.send_header("Content-Range", f"bytes {start}-{end}/{len(BODY)}")
- self.send_header("Transfer-Encoding", "chunked")
- self.end_headers()
- self.wfile.write(b"0\r\n\r\n")
- return
- body = BODY[start : end + 1]
- self.send_response(206 if header else 200)
- if header:
- self.send_header("Content-Range", f"bytes {start}-{end}/{len(BODY)}")
- self.send_header("Content-Length", str(len(body)))
- self.end_headers()
- # the cut teaches the downloader to bound the requests that follow
- self.wfile.write(body[:CUT_AFTER])
- self.close_connection = True
-
-
-@pytest.fixture
-def server(monkeypatch):
- DOWNLOAD_CANCELLED.clear()
- monkeypatch.setattr(downloader, "RETRY_WAIT", 0)
- monkeypatch.setattr(downloader, "REQUEST_CHUNK_SIZE", CHUNK)
- monkeypatch.setattr(downloader, "MIN_REQUEST_CHUNK", 4 * 1024)
- monkeypatch.setattr(downloader, "MIN_RESUME_PROGRESS", 1024)
- server = _EmptyRangeServer()
- threading.Thread(target=server.serve_forever, daemon=True).start()
- yield server
- server.shutdown()
- server.server_close()
- DOWNLOAD_CANCELLED.clear()
-
-
-def test_empty_sub_range_fails_instead_of_looping(tmp_path, server):
- save_path = tmp_path / "0.mp4"
- result: list[BaseException] = []
-
- def run() -> None:
- try:
- list(download(url=server.url, save_path=save_path, session=rq.Session()))
- except BaseException as exc:
- result.append(exc)
-
- # a hard deadline: a regression hangs this thread, and the suite must fail, not stall
- worker = threading.Thread(target=run, daemon=True)
- worker.start()
- worker.join(timeout=DEADLINE)
-
- assert not worker.is_alive(), f"download still running after {DEADLINE}s ({len(server.ranges)} requests)"
- assert result and isinstance(result[0], IOError), f"expected an IOError, got {result!r}"
- assert "no bytes" in str(result[0])
- assert len(server.ranges) <= downloader.MAX_ATTEMPTS + 1
- assert not save_path.exists()
diff --git a/tests/downloaders/test_failure_surfacing.py b/tests/downloaders/test_failure_surfacing.py
index a868c0694..d5a52ad3c 100644
--- a/tests/downloaders/test_failure_surfacing.py
+++ b/tests/downloaders/test_failure_surfacing.py
@@ -208,21 +208,6 @@ def test_slice_segment_rejects_a_206_for_the_wrong_range(tmp_path, server):
assert len(server.requests) == downloader.MAX_ATTEMPTS
-@pytest.mark.parametrize("server", ["range_clamped_206"], indirect=True)
-def test_slice_segment_accepts_a_206_clamped_to_the_last_byte(tmp_path, server):
- # some manifests author a range end past the resource; the clamped 206 is the whole slice
- save_path = tmp_path / "0.mp4"
- list(
- download(
- url=server.url,
- save_path=save_path,
- session=rq.Session(),
- headers={"Range": f"bytes=0-{len(BODY)}"},
- )
- )
- assert save_path.read_bytes() == BODY
-
-
@pytest.mark.parametrize("server", ["range_capped_206"], indirect=True)
def test_slice_segment_rejects_a_206_capped_short_of_the_requested_end(tmp_path, server):
# the body is a valid prefix of the slice, so only the Content-Range end catches it;
@@ -276,26 +261,3 @@ def test_failed_segment_fails_the_batch(tmp_path, server):
)
)
assert sorted(p.name for p in tmp_path.iterdir() if p.suffix == ".mp4") == []
-
-
-@pytest.mark.parametrize("server", ["ok"], indirect=True)
-def test_batch_larger_than_the_queue_window_downloads_every_segment(tmp_path, server):
- # a broken top-up livelocks the drain loop instead of erroring, so consume on a thread and
- # let the timeout fail the test
- urls = [server.url] * 6
- advanced = 0
-
- def consume():
- nonlocal advanced
- advanced = sum(
- event["advance"]
- for event in requests_downloader(urls=urls, output_dir=tmp_path, filename="{i:02}.mp4", max_workers=1)
- if "advance" in event
- )
-
- consumer = threading.Thread(target=consume, daemon=True)
- consumer.start()
- consumer.join(timeout=30)
- assert not consumer.is_alive(), "downloader never finished the batch"
- assert advanced == len(urls)
- assert sorted(p.name for p in tmp_path.iterdir() if p.suffix == ".mp4") == [f"{i:02}.mp4" for i in range(6)]
diff --git a/tests/downloaders/test_hedge_handles.py b/tests/downloaders/test_hedge_handles.py
deleted file mode 100644
index 96dd8cfe7..000000000
--- a/tests/downloaders/test_hedge_handles.py
+++ /dev/null
@@ -1,111 +0,0 @@
-"""Hedged segment racers must release their file handles before the batch completes.
-
-A superseded loser that keeps its .!dev handle open makes the manifest merge's
-stray sweep raise PermissionError (WinError 32) on Windows. This test forces a
-hedge with a trickling first response and checks the invariant at the exact
-moment merge would run.
-"""
-
-import importlib
-import os
-import threading
-import time
-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-from pathlib import Path
-
-import pytest
-
-from unshackle.core.constants import DOWNLOAD_CANCELLED
-
-# the downloaders package re-exports the requests() function, shadowing the submodule
-dl = importlib.import_module("unshackle.core.downloaders.requests")
-
-SEGMENTS = 10
-SLOW_INDEX = 4
-FAST_BODY = b"F" * 4096
-SLOW_BODY = b"S" * 40960
-TRICKLE_CHUNK = 2048
-TRICKLE_DELAY = 0.5
-
-
-class _Handler(BaseHTTPRequestHandler):
- def do_GET(self):
- with self.server.count_lock:
- self.server.counts[self.path] = self.server.counts.get(self.path, 0) + 1
- nth = self.server.counts[self.path]
- slow_path = self.path == f"/seg/{SLOW_INDEX}"
- body = SLOW_BODY if slow_path else FAST_BODY
- self.send_response(200)
- self.send_header("Content-Length", str(len(body)))
- self.end_headers()
- if slow_path and nth == 1:
- # trickle only the first attempt so the hedge retry wins instantly
- for i in range(0, len(body), TRICKLE_CHUNK):
- try:
- self.wfile.write(body[i : i + TRICKLE_CHUNK])
- self.wfile.flush()
- except (BrokenPipeError, ConnectionResetError):
- return
- time.sleep(TRICKLE_DELAY)
- else:
- self.wfile.write(body)
-
- def log_message(self, *args):
- pass
-
-
-@pytest.fixture
-def trickle_server():
- server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
- server.counts = {}
- server.count_lock = threading.Lock()
- threading.Thread(target=server.serve_forever, daemon=True).start()
- yield server
- server.shutdown()
-
-
-@pytest.mark.unit
-def test_hedge_loser_releases_handles_before_merge(tmp_path, trickle_server, monkeypatch):
- monkeypatch.setattr(dl, "HEDGE_MIN_WAIT", 0.3)
- monkeypatch.setattr(dl, "RETRY_WAIT", 0.1)
- DOWNLOAD_CANCELLED.clear()
- threads_before = {t.ident for t in threading.enumerate()}
-
- port = trickle_server.server_address[1]
- urls = [f"http://127.0.0.1:{port}/seg/{i}" for i in range(SEGMENTS)]
- start = time.monotonic()
- for _event in dl.requests(urls=urls, output_dir=tmp_path, filename="{i:02}.mp4", max_workers=4):
- pass
- wall = time.monotonic() - start
-
- with trickle_server.count_lock:
- slow_hits = trickle_server.counts[f"/seg/{SLOW_INDEX}"]
- assert slow_hits == 2, "hedge never fired; the race under test was not exercised"
-
- # the batch must not stall draining the loser's stream (trickle alone takes ~10s)
- assert wall < 5
-
- for i in range(SEGMENTS):
- expected = SLOW_BODY if i == SLOW_INDEX else FAST_BODY
- assert (tmp_path / f"{i:02}.mp4").read_bytes() == expected
-
- strays = list(tmp_path.glob("*.!dev"))
- fd_dir = Path("/proc/self/fd")
- if fd_dir.exists():
- open_targets = set()
- for fd in fd_dir.iterdir():
- try:
- open_targets.add(os.readlink(fd))
- except OSError:
- continue
- held = [s.name for s in strays if str(s) in open_targets]
- assert not held, f"racer still holds open handles at completion: {held}"
- for stray in strays:
- stray.unlink() # raises PermissionError (WinError 32) on Windows if a handle is open
-
- leaked = [
- t.name
- for t in threading.enumerate()
- if t.ident not in threads_before and t.name.startswith("ThreadPoolExecutor")
- ]
- assert not leaked, f"racer threads still alive at completion: {leaked}"
diff --git a/tests/downloaders/test_multiprocess.py b/tests/downloaders/test_multiprocess.py
index 0d173b5a6..c1bd61b8c 100644
--- a/tests/downloaders/test_multiprocess.py
+++ b/tests/downloaders/test_multiprocess.py
@@ -19,8 +19,6 @@ real spawns stay fast.
"""
import importlib
-import multiprocessing
-import os
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -30,9 +28,7 @@ from requests import Session
from tests.downloaders.test_outage_budget import _FullDisk
from unshackle.core.api.errors import categorize_exception
-from unshackle.core.constants import DownloadCancelled
from unshackle.core.remote_protocol import APIErrorCode
-from unshackle.core.utils.sslciphers import SSLCiphers
dl = importlib.import_module("unshackle.core.downloaders.requests")
@@ -102,10 +98,6 @@ def clear_cancel():
dl.DOWNLOAD_CANCELLED.clear()
-def die_without_result(queue, kwargs):
- os._exit(3)
-
-
def full_disk_worker(queue, kwargs):
dl.open = _FullDisk
dl.mp_worker(queue, kwargs)
@@ -150,18 +142,6 @@ def test_multiprocess_stride_downloads_all_segments_correctly(server, tmp_path):
assert total_advance == n
-def test_multiprocess_child_crash_raises(server, tmp_path):
- # download_multiprocess has no MP_MIN_SEGMENTS gate, so drive it directly with 2 urls.
- # a dict url without "url" raises KeyError while requests() builds the save path (before
- # any retry loop), so the child sends __mp_error__ fast; the sibling downloads normally.
- good = {"url": url(server, "/seg/0.bin")}
- bad = {"nourl": True}
- with pytest.raises(RuntimeError) as raised:
- run_mp([good, bad], tmp_path)
-
- assert not hasattr(raised.value, "error_code")
-
-
def test_a_full_disk_in_a_child_keeps_its_download_error_code(server, tmp_path, monkeypatch):
monkeypatch.setattr(dl, "mp_worker", full_disk_worker)
with pytest.raises(RuntimeError) as raised:
@@ -171,51 +151,6 @@ def test_a_full_disk_in_a_child_keeps_its_download_error_code(server, tmp_path,
assert categorize_exception(raised.value).error_code == APIErrorCode.DOWNLOAD_ERROR
-def test_multiprocess_child_death_raises(tmp_path, monkeypatch):
- monkeypatch.setattr(dl, "mp_worker", die_without_result)
- raised: list[BaseException] = []
-
- def drive():
- try:
- run_mp([{"url": "http://127.0.0.1:1/a"}, {"url": "http://127.0.0.1:1/b"}], tmp_path)
- except BaseException as exc:
- raised.append(exc)
-
- thread = threading.Thread(target=drive, daemon=True)
- thread.start()
- thread.join(timeout=30)
-
- assert not thread.is_alive()
- assert len(raised) == 1 and isinstance(raised[0], RuntimeError)
- assert "died without result" in str(raised[0])
-
-
-def test_multiprocess_cancel_terminates_children(server, tmp_path):
- server.delay = 0.5 # slow segments so cancel lands well before the batch could finish
- n = dl.MP_MIN_SEGMENTS
- urls = [{"url": url(server, f"/seg/{i}.bin")} for i in range(n)]
-
- baseline = len(multiprocessing.active_children())
- start = time.time()
- progressed = 0
- with pytest.raises(DownloadCancelled):
- for event in dl.requests(urls, output_dir=tmp_path, filename="seg_{i:04}.bin", max_workers=4, processes=2):
- if event.get("advance") or event.get("written"):
- progressed += 1
- if progressed >= 2:
- dl.DOWNLOAD_CANCELLED.set() # sibling-track cancel: parent must tear the children down
- elapsed = time.time() - start
-
- # cancel stopped the work: nowhere near all segments finished, and no hang
- assert len(list(tmp_path.glob("seg_*.bin"))) < n
- assert elapsed < 15
- # the finally-block join reaps the spawned children promptly
- deadline = time.time() + 5
- while time.time() < deadline and len(multiprocessing.active_children()) > baseline:
- time.sleep(0.05)
- assert len(multiprocessing.active_children()) <= baseline
-
-
def test_speed_limit_forces_single_process(server, tmp_path, monkeypatch):
"""A set speed limit must keep the batch in-process: spawned children re-import the
module and would run with no TokenBucket, silently ignoring the configured cap."""
@@ -253,36 +188,3 @@ def test_children_carry_session_params(server, tmp_path):
assert len(files) == n
for f in files:
assert f.read_bytes() == seg_body(int(f.stem.split("_")[1]))
-
-
-def test_service_mounted_adapter_forces_single_process(server, tmp_path, monkeypatch):
- """A child mounts a plain adapter, so a session carrying SSLCiphers has to stay in this process."""
-
- def no_mp(**kwargs):
- raise AssertionError("multiprocess fan-out engaged for a session with a service-mounted adapter")
-
- monkeypatch.setattr(dl, "download_multiprocess", no_mp)
- session = Session()
- session.mount("https://", SSLCiphers(security_level=2))
- n = dl.MP_MIN_SEGMENTS
- urls = [{"url": url(server, f"/seg/{i}.bin")} for i in range(n)]
-
- for _ in dl.requests(
- urls, output_dir=tmp_path, filename="seg_{i:04}.bin", session=session, max_workers=4, processes=2
- ):
- pass
-
- assert len(list(tmp_path.glob("seg_*.bin"))) == n
-
-
-def test_multiprocess_skips_the_held_indices_and_counts_them_done(server, tmp_path):
- n = dl.MP_MIN_SEGMENTS
- urls = [{"url": url(server, f"/seg/{i}.bin")} for i in range(n)]
- skip = frozenset(range(0, n, 3))
-
- events = list(
- dl.requests(urls, tmp_path, "seg_{i:04}.bin", session=Session(), max_workers=4, processes=2, skip=skip)
- )
-
- assert sum(e.get("advance", 0) for e in events) == n
- assert sorted(p.name for p in tmp_path.iterdir()) == [f"seg_{i:04}.bin" for i in range(n) if i not in skip]
diff --git a/tests/downloaders/test_no_retry_session.py b/tests/downloaders/test_no_retry_session.py
index b54056dd5..95f072997 100644
--- a/tests/downloaders/test_no_retry_session.py
+++ b/tests/downloaders/test_no_retry_session.py
@@ -36,20 +36,3 @@ def test_view_shares_the_pools_it_was_copied_from() -> None:
assert twin is not adapter, "the view must be its own adapter, or Retry(0) lands on the caller"
assert twin.poolmanager is adapter.poolmanager
assert twin.proxy_manager is adapter.proxy_manager
-
-
-def test_view_never_retries_and_leaves_the_caller_retrying() -> None:
- session = pooled_session(total=5)
- view = no_retry_session(session)
-
- assert view.adapters["https://"].max_retries.total == 0
- assert session.adapters["https://"].max_retries.total == 5, "the caller's retry policy must survive"
-
-
-def test_repeated_views_keep_reusing_one_pool() -> None:
- """``download()`` rebuilds the view per segment; every rebuild must land on the same pool."""
- session = pooled_session()
- origin = session.adapters["https://"].poolmanager
-
- for _ in range(3):
- assert no_retry_session(session).adapters["https://"].poolmanager is origin
diff --git a/tests/downloaders/test_outage_budget.py b/tests/downloaders/test_outage_budget.py
index 6969b5ee2..d082259fc 100644
--- a/tests/downloaders/test_outage_budget.py
+++ b/tests/downloaders/test_outage_budget.py
@@ -10,13 +10,10 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
import requests as rq
-import rnet
-from tests.downloaders.test_content_encoding import _FakeRnetResponse
from tests.downloaders.test_rnet_session_paths import SESSIONS
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.remote_protocol import APIErrorCode
-from unshackle.core.session import MaxRetriesError
from unshackle.core.utilities import get_free_port
dl = importlib.import_module("unshackle.core.downloaders.requests")
@@ -128,53 +125,3 @@ def test_status_failure_keeps_the_normal_budget(tmp_path, serve):
assert server.requests == dl.MAX_ATTEMPTS
assert not hasattr(raised.value, "error_code")
-
-
-@pytest.mark.parametrize("make_session", SESSIONS)
-def test_malformed_url_keeps_the_normal_budget(tmp_path, make_session):
- retried: list[Exception] = []
-
- with pytest.raises(Exception) as raised:
- list(
- dl.download(
- url="htp://127.0.0.1/a",
- save_path=tmp_path / "a.bin",
- session=make_session(),
- on_retry=retried.append,
- )
- )
-
- assert len(retried) == dl.MAX_ATTEMPTS - 1
- assert any(f"gave up after {dl.MAX_ATTEMPTS} failed attempts" in note for note in raised.value.__notes__)
-
-
-class _StatusError(Exception):
- def __init__(self, response):
- super().__init__(f"HTTP {response.status_code}")
- self.response = response
-
-
-class _RecoveringSession:
- """Refuses six connections, answers one 503, then serves the body."""
-
- def __init__(self):
- self.calls = 0
-
- def get(self, url, stream=True, **kwargs):
- self.calls += 1
- if self.calls <= 6:
- raise MaxRetriesError("GET 127.0.0.1 failed", cause=rnet.ConnectionError("connection refused"))
- if self.calls == 7:
- raise _StatusError(_FakeRnetResponse(503, {}, b""))
- return _FakeRnetResponse(200, {}, b"body-bytes")
-
-
-def test_outage_does_not_spend_the_status_budget(tmp_path, monkeypatch):
- monkeypatch.setattr(dl, "retry_sleep", lambda exc, attempts: 0)
- session = _RecoveringSession()
- save_path = tmp_path / "a.bin"
-
- list(dl.download(url="http://127.0.0.1:1/a", save_path=save_path, session=dl.RnetTransport(session)))
-
- assert save_path.read_bytes() == b"body-bytes"
- assert session.calls == 8
diff --git a/tests/downloaders/test_probe_ranged.py b/tests/downloaders/test_probe_ranged.py
index e1ef87146..837979981 100644
--- a/tests/downloaders/test_probe_ranged.py
+++ b/tests/downloaders/test_probe_ranged.py
@@ -22,7 +22,6 @@ only to decide not to use it.
import importlib
import threading
-import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
@@ -155,33 +154,6 @@ def test_probe_reuses_the_pooled_connection(server):
assert server.connections == 1
-def test_probe_does_not_drain_a_200_body(server):
- server.mode = "ignores_range"
- session = Session()
-
- assert dl.probe_ranged(url(server), session) == (0, False)
-
- for _ in range(50):
- with server.lock:
- if server.broke or server.written >= len(BIG):
- break
- time.sleep(0.1)
- with server.lock:
- assert server.written < len(BIG)
-
-
-def test_probe_asks_for_identity_encoding(server):
- server.mode = "encode_unless_identity"
- session = Session()
-
- assert dl.probe_ranged(url(server), session) == (len(PAYLOAD), True)
- assert server.requests[-1][1] == "identity"
-
- # a caller that names its own encoding still wins
- assert dl.probe_ranged(url(server), session, headers={"Accept-Encoding": "gzip"}) == (0, False)
- assert server.requests[-1][1] == "gzip"
-
-
def test_probe_uses_the_url_items_headers(server, tmp_path, monkeypatch):
server.mode = "needs_auth"
monkeypatch.setattr(dl, "RANGE_PARALLEL_MIN_SIZE", 8 * 1024)
@@ -196,19 +168,3 @@ def test_probe_uses_the_url_items_headers(server, tmp_path, monkeypatch):
assert probes and all(r[2] == AUTH for r in probes)
# the probe was answered, so the ranged path ran instead of one sequential connection
assert [r for r in server.requests if r[0] and r[0] != "bytes=0-0"]
-
-
-def test_probe_does_not_drain_a_fat_206_body(server):
- """A 206 carrying the whole resource must not be read to decide whether to use ranges."""
- server.mode = "fat_206"
- session = Session()
-
- assert dl.probe_ranged(url(server), session) == (len(BIG), True)
-
- for _ in range(50):
- with server.lock:
- if server.broke or server.written >= len(BIG):
- break
- time.sleep(0.1)
- with server.lock:
- assert server.written < len(BIG)
diff --git a/tests/downloaders/test_ranged_parallel.py b/tests/downloaders/test_ranged_parallel.py
index 04c0f4148..bdb823c84 100644
--- a/tests/downloaders/test_ranged_parallel.py
+++ b/tests/downloaders/test_ranged_parallel.py
@@ -221,46 +221,6 @@ def test_permanent_status_unwraps_causes():
BIG = bytes((i * 13 + 7) % 256 for i in range(8 * 1024 * 1024))
-class _BigHandler(BaseHTTPRequestHandler):
- protocol_version = "HTTP/1.1"
-
- def do_GET(self):
- srv = self.server
- rng = self.headers.get("Range")
- with srv.lock:
- srv.requests.append(rng)
- if not rng:
- self.send_response(200)
- self.send_header("Content-Length", str(len(BIG)))
- self.end_headers()
- self.wfile.write(BIG)
- return
- start_s, _, end_s = rng.removeprefix("bytes=").partition("-")
- start = int(start_s)
- end = int(end_s) if end_s else len(BIG) - 1
- body = BIG[start : end + 1]
- self.send_response(206)
- self.send_header("Content-Range", f"bytes {start}-{end}/{len(BIG)}")
- self.send_header("Content-Length", str(len(body)))
- self.end_headers()
- self.wfile.write(body)
-
- def log_message(self, *args):
- pass
-
-
-@pytest.fixture
-def big_server():
- srv = ThreadingHTTPServer(("127.0.0.1", 0), _BigHandler)
- srv.lock = threading.Lock()
- srv.requests = []
- thread = threading.Thread(target=srv.serve_forever, daemon=True)
- thread.start()
- yield srv
- srv.shutdown()
- thread.join(timeout=5)
-
-
_REAL_SPLIT = dl.split_ranges
@@ -291,32 +251,8 @@ def plan_split(monkeypatch, tmp_path, total_size, max_workers):
return record[0]
-def test_part_count_matches_worker_count(tmp_path, monkeypatch):
- _, _, _, parts = plan_split(monkeypatch, tmp_path, 64 * 1024 * 1024, 16)
- assert len(parts) == 16
-
- _, _, _, parts = plan_split(monkeypatch, tmp_path, 16 * 1024 * 1024, 4)
- assert len(parts) == 4
-
-
def test_part_floor_caps_sliver_count(tmp_path, monkeypatch):
# below the 4 MiB floor a part's handshake costs more than its transfer
_, _, target, parts = plan_split(monkeypatch, tmp_path, 16 * 1024 * 1024, 64)
assert target == 4 * 1024 * 1024
assert len(parts) == 4
-
-
-def test_worker_driven_parts_merge_byte_identical(big_server, tmp_path):
- save_path = tmp_path / "big.bin"
- for _ in dl.dispatch_parts(
- url=url(big_server, "/big.bin"),
- save_path=save_path,
- session=Session(),
- total_size=len(BIG),
- max_workers=2,
- ):
- pass
-
- assert save_path.read_bytes() == BIG
- assert len({r for r in big_server.requests if r}) == 2
- assert not save_path.with_name(save_path.name + ".!dev").exists()
diff --git a/tests/downloaders/test_ranged_part_queue.py b/tests/downloaders/test_ranged_part_queue.py
deleted file mode 100644
index da85a6904..000000000
--- a/tests/downloaders/test_ranged_part_queue.py
+++ /dev/null
@@ -1,88 +0,0 @@
-"""The workers of a ranged single-file download share fixed-size parts from one queue.
-
-A connection that the host holds keeps one part, and the other worker completes the rest.
-"""
-
-import importlib
-import threading
-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-
-from requests import Session
-
-from unshackle.core.constants import DOWNLOAD_CANCELLED
-
-dl = importlib.import_module("unshackle.core.downloaders.requests")
-
-BODY = bytes(range(256)) * 256
-
-
-class _Server(ThreadingHTTPServer):
- daemon_threads = True
-
- def __init__(self):
- self.lock = threading.Lock()
- self.served: list[str] = []
- self.held: str | None = None
- self.release = threading.Event()
- self.others_done_at_release = -1
- super().__init__(("127.0.0.1", 0), _Handler)
- self.url = f"http://127.0.0.1:{self.server_address[1]}/big.bin"
-
- def handle_error(self, request, client_address):
- pass
-
-
-class _Handler(BaseHTTPRequestHandler):
- protocol_version = "HTTP/1.1"
-
- def log_message(self, *_):
- pass
-
- def do_GET(self):
- server = self.server
- header = self.headers.get("Range")
- start, end = 0, len(BODY) - 1
- if header:
- start_s, _, end_s = header.removeprefix("bytes=").partition("-")
- start, end = int(start_s), (int(end_s) if end_s else len(BODY) - 1)
- body = BODY[start : end + 1]
- with server.lock:
- held = server.held is None
- if held:
- server.held = header
- if held:
- server.release.wait(5)
- with server.lock:
- server.others_done_at_release = len(server.served)
- with server.lock:
- server.served.append(header)
- if not held and len(server.served) == 7:
- server.release.set()
- self.send_response(206)
- self.send_header("Content-Range", f"bytes {start}-{end}/{len(BODY)}")
- self.send_header("Content-Length", str(len(body)))
- self.end_headers()
- self.wfile.write(body)
-
-
-def test_fast_connection_takes_the_parts_a_held_connection_cannot(tmp_path, monkeypatch):
- monkeypatch.setattr(dl, "RANGE_PARALLEL_PART_SIZE", 8 * 1024)
- monkeypatch.setattr(dl, "RANGE_PARALLEL_MIN_PART_SIZE", 2 * 1024)
- DOWNLOAD_CANCELLED.clear()
- server = _Server()
- threading.Thread(target=server.serve_forever, daemon=True).start()
- save_path = tmp_path / "big.bin"
- try:
- for _ in dl.dispatch_parts(
- url=server.url, save_path=save_path, session=Session(), total_size=len(BODY), max_workers=2
- ):
- pass
- finally:
- server.release.set()
- server.shutdown()
- server.server_close()
- DOWNLOAD_CANCELLED.clear()
-
- assert save_path.read_bytes() == BODY
- assert len(set(server.served)) == 8
- assert server.others_done_at_release == 7
diff --git a/tests/downloaders/test_ranges.py b/tests/downloaders/test_ranges.py
index 981c79fdd..82d3f481e 100644
--- a/tests/downloaders/test_ranges.py
+++ b/tests/downloaders/test_ranges.py
@@ -2,7 +2,7 @@
import pytest
-from unshackle.core.downloaders.ranges import Answer, Mode, Verdict, has_range_header, range_answer
+from unshackle.core.downloaders.ranges import Answer, Mode, Verdict, range_answer
pytestmark = pytest.mark.unit
@@ -13,21 +13,6 @@ def rng(value: str | None) -> dict[str, str]:
return {} if value is None else {"Range": value}
-@pytest.mark.parametrize(
- ("item", "expected"),
- [
- ({}, False),
- ({"headers": None}, False),
- ({"headers": {}}, False),
- ({"headers": {"Accept": "*/*"}}, False),
- ({"headers": {"Range": "bytes=0-127"}}, True),
- ({"headers": {"range": "bytes=0-127"}}, True),
- ],
-)
-def test_has_range_header(item, expected):
- assert has_range_header(item) is expected
-
-
@pytest.mark.parametrize(
("requested", "status", "content_range", "known", "kwargs", "expected"),
[
diff --git a/tests/downloaders/test_read_timeout_config.py b/tests/downloaders/test_read_timeout_config.py
deleted file mode 100644
index bb9b431e0..000000000
--- a/tests/downloaders/test_read_timeout_config.py
+++ /dev/null
@@ -1,51 +0,0 @@
-"""Segment requests on rnet carry network.read_timeout from the config, or READ_TIMEOUT when it is unset.
-
-A per-request read_timeout overrides the one on the rnet client, so the downloader must pass the configured value.
-"""
-
-import importlib
-
-import pytest
-
-from tests.downloaders.test_content_encoding import _FakeRnetResponse
-from unshackle.core.config import config
-
-dl = importlib.import_module("unshackle.core.downloaders.requests")
-
-
-class FakeSession:
- def __init__(self):
- self.calls: list[dict] = []
-
- def get(self, url, stream=True, **kwargs):
- self.calls.append(kwargs)
- return _FakeRnetResponse(200, {}, b"body-bytes")
-
-
-@pytest.fixture
-def session():
- return FakeSession()
-
-
-@pytest.mark.parametrize(
- "network, module_default, kwargs, expected",
- [
- pytest.param({"read_timeout": 7}, None, {}, 7, id="configured"),
- pytest.param({}, None, {}, dl.READ_TIMEOUT, id="unset"),
- pytest.param({}, 2, {}, 2, id="patched-default"),
- pytest.param({"read_timeout": 7}, None, {"read_timeout": 3}, 3, id="caller-wins"),
- ],
-)
-def test_segment_request_read_timeout(tmp_path, session, monkeypatch, network, module_default, kwargs, expected):
- monkeypatch.setattr(config, "network", network)
- if module_default is not None:
- monkeypatch.setattr(dl, "READ_TIMEOUT", module_default)
- transport = dl.RnetTransport(session)
- list(dl.download(url="http://127.0.0.1:1/a", save_path=tmp_path / "a.bin", session=transport, **kwargs))
- assert session.calls[0]["read_timeout"] == expected
-
-
-def test_probe_uses_the_configured_read_timeout(session, monkeypatch):
- monkeypatch.setattr(config, "network", {"read_timeout": 7})
- dl.probe_ranged("http://127.0.0.1:1/a", dl.RnetTransport(session))
- assert session.calls[0]["read_timeout"] == 7
diff --git a/tests/downloaders/test_rnet_session_paths.py b/tests/downloaders/test_rnet_session_paths.py
index 6f25c180c..0774f4faf 100644
--- a/tests/downloaders/test_rnet_session_paths.py
+++ b/tests/downloaders/test_rnet_session_paths.py
@@ -96,15 +96,6 @@ def server(monkeypatch):
DOWNLOAD_CANCELLED.clear()
-@pytest.mark.parametrize("make_session", SESSIONS)
-def test_plain_body_arrives_whole(tmp_path, server, make_session):
- save_path = tmp_path / "0.mp4"
- list(dl.download(url=f"{server.url}/plain", save_path=save_path, session=make_session()))
-
- assert save_path.read_bytes() == BODY
- assert len(server.hits) == 1
-
-
@pytest.mark.parametrize("make_session", SESSIONS)
def test_cut_body_resumes_with_range(tmp_path, server, make_session):
save_path = tmp_path / "0.mp4"
@@ -134,17 +125,6 @@ def test_retry_after_header_sets_the_wait(tmp_path, server, make_session, monkey
assert waits == [1.0]
-@pytest.mark.parametrize("make_session", SESSIONS)
-def test_stalled_body_times_out_and_retries(tmp_path, server, make_session, monkeypatch):
- monkeypatch.setattr(dl, "READ_TIMEOUT", 1)
- monkeypatch.setattr("unshackle.core.config.config.network", {})
- save_path = tmp_path / "0.mp4"
- list(dl.download(url=f"{server.url}/stall", save_path=save_path, session=make_session()))
-
- assert save_path.read_bytes() == BODY
- assert len(server.hits) == 2
-
-
@pytest.mark.parametrize("make_session", SESSIONS)
def test_transport_body_reads_headers_in_any_case(server, make_session):
body = dl.transport_for(make_session()).get(f"{server.url}/plain", headers={"Range": "bytes=0-9"})
diff --git a/tests/downloaders/test_session_spec.py b/tests/downloaders/test_session_spec.py
index 521a169d0..a67a44cc3 100644
--- a/tests/downloaders/test_session_spec.py
+++ b/tests/downloaders/test_session_spec.py
@@ -16,7 +16,6 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
from requests import Session
-from requests.adapters import HTTPAdapter
from requests.auth import HTTPBasicAuth
from tests.core.test_session_verify import self_signed_url as self_signed_url
@@ -55,30 +54,6 @@ def test_rnet_spec_round_trips_cookie_domains() -> None:
assert rebuilt.cookies.get_dict(domain="localhost") == {}
-def test_rnet_spec_keeps_dict_set_cookies() -> None:
- ns = rnet_session_with_cookies()
-
- spec = build_session_spec(ns)
- assert spec is not None
- rebuilt = rebuild_session(spec, 1)
- assert rebuilt is not None
-
- assert rebuilt.cookies["loose"] == "ghi"
-
-
-def test_rnet_spec_cookies_carry_domain_information() -> None:
- ns = rnet_session_with_cookies()
-
- spec = build_session_spec(ns)
- assert spec is not None
-
- assert {(c.domain, c.path, c.name, c.value) for c in spec["cookies"]} == {
- ("cdn.example.com", "/", "cdn_token", "abc"),
- ("api.example.com", "/", "api_token", "def"),
- ("", "/", "loose", "ghi"),
- }
-
-
def test_rnet_spec_keeps_same_name_cookies_on_their_paths() -> None:
"""Same-name cookies on two paths must reach a child apart, or a stale one goes to every path."""
ns = make_session("Chrome131")
@@ -94,20 +69,6 @@ def test_rnet_spec_keeps_same_name_cookies_on_their_paths() -> None:
assert rebuilt.cookies.get("hdntl", path="/t/2") == "two"
-def test_rnet_spec_is_picklable() -> None:
- spec = build_session_spec(rnet_session_with_cookies())
- assert spec is not None
-
- loaded = pickle.loads(pickle.dumps(spec))
- # stdlib Cookie has no __eq__, so compare the cookies by their fields
- assert [vars(c) for c in loaded.pop("cookies")] == [vars(c) for c in spec.pop("cookies")]
- assert loaded == spec
-
-
-def test_rnet_spec_without_impersonate_is_not_rebuildable() -> None:
- assert build_session_spec(RnetSession()) is None
-
-
class _CookieHandler(BaseHTTPRequestHandler):
"""Sets one cookie on /set and echoes the Cookie header it receives on /echo."""
@@ -168,22 +129,6 @@ def test_rebuilt_requests_session_pool_is_sized_to_worker_count() -> None:
assert adapter.poolmanager.connection_pool_kw["maxsize"] == 24
-def test_rebuilt_rnet_session_has_no_adapters() -> None:
- """rnet pools internally; the sizing fix must not reach into that path."""
- spec = build_session_spec(rnet_session_with_cookies())
- assert spec is not None
-
- rebuilt = rebuild_session(spec, 24)
- assert rebuilt is not None
-
- assert not isinstance(rebuilt, Session)
- assert not hasattr(rebuilt, "adapters")
-
-
-def test_unrebuildable_spec_stays_none() -> None:
- assert rebuild_session({"kind": "none"}, 24) is None
-
-
def test_requests_spec_round_trips_cookie_domains() -> None:
rs = Session()
rs.cookies.set("cdn_token", "abc", domain="cdn.example.com")
@@ -270,18 +215,6 @@ def test_requests_spec_carries_cert_and_auth() -> None:
assert rebuilt.auth == HTTPBasicAuth("user", "pass")
-def test_requests_spec_is_picklable() -> None:
- rs = Session()
- rs.verify = False
- rs.params = {"at": "auth-token"}
- rs.cookies.set("cdn_token", "abc", domain="cdn.example.com")
-
- spec = build_session_spec(rs)
- assert spec is not None
-
- assert pickle.loads(pickle.dumps(spec))["params"] == {"at": "auth-token"}
-
-
def test_requests_spec_with_unpicklable_auth_is_not_rebuildable() -> None:
"""auth takes any callable. One that spawn cannot pickle has to fall back, not kill the child."""
rs = Session()
@@ -303,13 +236,3 @@ def test_mounted_ssl_ciphers_is_not_rebuildable() -> None:
rs.mount("https://cdn.example.com", SSLCiphers(security_level=2))
assert build_session_spec(rs) is None
-
-
-def test_rebuilt_requests_session_mounts_a_plain_adapter() -> None:
- """The spec only ever describes a plain adapter, so the child must not appear to hold more than that."""
- spec = build_session_spec(Session())
- assert spec is not None
- rebuilt = rebuild_session(spec, 4)
- assert rebuilt is not None
-
- assert type(rebuilt.get_adapter("https://example.com")) is HTTPAdapter
diff --git a/tests/downloaders/test_speed_limit.py b/tests/downloaders/test_speed_limit.py
index 0e61851a3..9c846ac37 100644
--- a/tests/downloaders/test_speed_limit.py
+++ b/tests/downloaders/test_speed_limit.py
@@ -1,13 +1,10 @@
import importlib
-import inspect
-import threading
-import time
from types import SimpleNamespace
import pytest
from unshackle.core.constants import DOWNLOAD_CANCELLED
-from unshackle.core.downloaders.requests import TokenBucket, format_speed, parse_speed_limit
+from unshackle.core.downloaders.requests import TokenBucket, parse_speed_limit
requests_downloader = importlib.import_module("unshackle.core.downloaders.requests")
@@ -69,50 +66,6 @@ def test_parse_speed_limit_rejects(value):
parse_speed_limit(value)
-@pytest.mark.parametrize(
- ("rate", "expected"),
- [
- (500, "500 bytes/s"),
- (999.2, "1.0 kB/s"),
- (512_000, "512.0 kB/s"),
- (39 * 1024**2, "40.9 MB/s"),
- (1.5 * 1024**3, "1.6 GB/s"),
- ],
-)
-def test_format_speed(rate, expected):
- assert format_speed(rate) == expected
-
-
-def test_result_accepts_a_missing_speed_limit():
- """The API/serve path calls dl.result() by keyword without speed_limit."""
- from unshackle.commands.dl import dl
-
- assert inspect.signature(dl.result).parameters["speed_limit"].default is None
-
-
-def test_bucket_holds_aggregate_rate_across_threads():
- rate = 10_000_000
- bucket = TokenBucket(rate)
- chunk = 100_000
- totals = [0, 0, 0, 0]
- start = time.monotonic()
- stop = start + 1.0
-
- def worker(i: int) -> None:
- while time.monotonic() < stop:
- bucket.consume(chunk)
- totals[i] += chunk
-
- threads = [threading.Thread(target=worker, args=(i,)) for i in range(4)]
- for t in threads:
- t.start()
- for t in threads:
- t.join()
- achieved = sum(totals) / (time.monotonic() - start)
- # exceeding the limit is a real failure; undershoot is scheduler noise on a loaded box, so no lower bound
- assert achieved <= rate * 1.1
-
-
def test_bucket_refills_at_the_rate(monkeypatch):
"""On a simulated clock the throughput is exact, so a slow refill fails like a fast one."""
clock = [0.0]
@@ -135,15 +88,3 @@ def test_bucket_chunk_larger_than_capacity_does_not_deadlock(monkeypatch):
bucket.consume(1_100_000)
assert len(waits) == 1
assert 1.0 < waits[0] < 2.0
-
-
-def test_bucket_wait_aborts_on_cancellation():
- """Debt sleeps grow with thread count; cancelling must not wait them out."""
- bucket = TokenBucket(1_000)
- DOWNLOAD_CANCELLED.set()
- try:
- start = time.monotonic()
- bucket.consume(1_000_000)
- assert time.monotonic() - start < 1.0
- finally:
- DOWNLOAD_CANCELLED.clear()
diff --git a/tests/downloaders/test_speed_window.py b/tests/downloaders/test_speed_window.py
index 46d555b2c..57a53684d 100644
--- a/tests/downloaders/test_speed_window.py
+++ b/tests/downloaders/test_speed_window.py
@@ -22,22 +22,9 @@ def test_first_report_is_the_since_start_average():
assert win.rate(2.5, 25_000_000) == pytest.approx(10_000_000)
-def test_zero_span_returns_none():
- win = SpeedWindow(0.0)
- assert win.rate(0.0, 1_000_000) is None
-
-
def test_stall_returns_none():
"""Once the seed ages out, a total that stops growing has no delta to report."""
win = SpeedWindow(0.0)
for t in range(0, SPEED_ROLLING_WINDOW + 6):
rate = win.rate(float(t), 1_000_000)
assert rate is None
-
-
-def test_window_drops_old_samples():
- win = SpeedWindow(0.0)
- for t in range(0, 3 * SPEED_ROLLING_WINDOW):
- win.rate(float(t), t * 1_000_000)
- assert win.samples[0][0] >= 2 * SPEED_ROLLING_WINDOW - 1
- assert len(win.samples) == SPEED_ROLLING_WINDOW + 1
diff --git a/tests/downloaders/test_submission_window.py b/tests/downloaders/test_submission_window.py
deleted file mode 100644
index 0723e7d84..000000000
--- a/tests/downloaders/test_submission_window.py
+++ /dev/null
@@ -1,105 +0,0 @@
-"""Submission-window invariants for the segmented drain loop.
-
-Segments are not all submitted up front: that convoys on the pool's global lock and starves
-the event drain. The loop meters submission through a window it tops up. The window must hold
-two segments for every worker, so a worker that finishes one finds the next already staged
-instead of idling until the next drain cycle. Fixed and adaptive mode must agree on that
-ratio; adaptive sizes it from its live target instead of from ``max_workers``.
-
-The test stalls every response, so no future can complete and the queue settles at exactly
-the window. Counting ``pool.submit`` calls makes the queue depth observable: a blocked
-server only ever sees ``max_workers`` requests, whatever is staged behind them.
-"""
-
-import importlib
-import threading
-import time
-from concurrent.futures.thread import ThreadPoolExecutor
-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-
-import pytest
-
-dl = importlib.import_module("unshackle.core.downloaders.requests")
-
-BODY = b"segment-body" * 64
-MAX_WORKERS = 4
-SEG_COUNT = 20 # more than the window, so queue depth is the only bound
-
-pytestmark = pytest.mark.unit
-
-
-class _Handler(BaseHTTPRequestHandler):
- def do_GET(self):
- self.server.release.wait(timeout=10)
- self.send_response(200)
- self.send_header("Content-Length", str(len(BODY)))
- self.end_headers()
- self.wfile.write(BODY)
-
- def log_message(self, *args):
- pass
-
-
-@pytest.fixture
-def server():
- srv = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
- srv.release = threading.Event()
- thread = threading.Thread(target=srv.serve_forever, daemon=True)
- thread.start()
- yield srv
- srv.release.set()
- srv.shutdown()
- thread.join(timeout=5)
-
-
-@pytest.fixture(autouse=True)
-def clean_cancel():
- dl.DOWNLOAD_CANCELLED.clear()
- yield
- dl.DOWNLOAD_CANCELLED.clear()
-
-
-@pytest.fixture
-def submissions(monkeypatch):
- counter: list[int] = []
-
- class _CountingPool(ThreadPoolExecutor):
- def submit(self, fn, /, *args, **kwargs):
- counter.append(1) # list.append is atomic, so no lock is needed here
- return super().submit(fn, *args, **kwargs)
-
- monkeypatch.setattr(dl, "ThreadPoolExecutor", _CountingPool)
- return counter
-
-
-@pytest.mark.parametrize("adaptive", [False, True])
-def test_queue_holds_two_segments_per_worker(server, submissions, tmp_path, adaptive):
- urls = [{"url": f"http://127.0.0.1:{server.server_address[1]}/seg{i}.bin"} for i in range(SEG_COUNT)]
- events: list[dict] = []
-
- def run():
- events.extend(
- dl.requests(
- urls,
- output_dir=tmp_path,
- filename="seg_{i:04}.bin",
- max_workers=MAX_WORKERS,
- adaptive=adaptive,
- )
- )
-
- worker = threading.Thread(target=run, daemon=True)
- worker.start()
- try:
- deadline = time.time() + 3.0
- while time.time() < deadline and len(submissions) < 2 * MAX_WORKERS:
- time.sleep(0.02)
- time.sleep(0.2) # settle, so an over-filled window is caught as well as an under-filled one
- assert len(submissions) == 2 * MAX_WORKERS
- finally:
- server.release.set()
- worker.join(timeout=30)
-
- assert not worker.is_alive()
- assert sum(event.get("advance", 0) for event in events) == SEG_COUNT
- assert len(sorted(tmp_path.glob("seg_*.bin"))) == SEG_COUNT
diff --git a/tests/downloaders/test_tail_boost.py b/tests/downloaders/test_tail_boost.py
index e2b6970dc..7abc4f2ce 100644
--- a/tests/downloaders/test_tail_boost.py
+++ b/tests/downloaders/test_tail_boost.py
@@ -156,20 +156,6 @@ def test_tail_boost_split_produces_byte_identical_segment(server, tmp_path):
assert not list(tmp_path.glob("*.tp.!dev"))
-def test_tail_boost_finalize_last_part_wins(server, tmp_path):
- files, _ = run(server, tmp_path, seg_urls(server))
-
- assert boost_engaged(server), "tail boost never engaged; finalize path untested"
- assert len(files) == SEG_COUNT
- # last part wins: the pre-truncated .tp.!dev is os.replace'd into save_path, leaving no target
- assert not list(tmp_path.glob("*.tp.!dev"))
- for path in ranged_counts(server):
- i = int(path.removeprefix("/seg").removesuffix(".bin"))
- save_path = tmp_path / f"seg_{i:04}.bin"
- assert save_path.exists()
- assert not save_path.with_name(f"{save_path.name}.tp.!dev").exists()
-
-
def test_tail_boost_part_failure_falls_back_to_normal_path(server, tmp_path, monkeypatch):
server.break_offset_ranges = True # every part window past the first fails, but not for good
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
@@ -187,25 +173,6 @@ def test_tail_boost_part_failure_falls_back_to_normal_path(server, tmp_path, mon
assert not list(tmp_path.glob("*.tp.!dev"))
-def test_tail_boost_failure_does_not_abort_sibling_segments(server, tmp_path, monkeypatch):
- server.break_offset_ranges = True
- monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
-
- files, _ = run(server, tmp_path, seg_urls(server))
-
- assert boost_engaged(server), "tail boost never engaged; the fallback path is untested"
- # the parts of one segment share an abort of their own: setting the batch-wide one would
- # strand every other in-flight worker and end the batch with segments missing
- assert len(files) == SEG_COUNT
- with server.lock:
- reqs = list(server.requests)
- boosted_paths = {path for path, rng in reqs if rng and rng != "bytes=0-0"}
- assert boosted_paths
- # each boosted segment went back on the normal path: a plain unranged GET for it
- plain = {path for path, rng in reqs if rng is None}
- assert boosted_paths <= plain
-
-
def test_tail_boost_permanent_part_failure_still_fails_the_batch(server, tmp_path, monkeypatch):
server.deny_offset_ranges = True # every part window past the first is a 403
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
diff --git a/tests/downloaders/test_transport.py b/tests/downloaders/test_transport.py
index 45b6c077f..7c65ba698 100644
--- a/tests/downloaders/test_transport.py
+++ b/tests/downloaders/test_transport.py
@@ -3,7 +3,6 @@
import importlib
import io
-import pytest
import requests as rq
from unshackle.core.session import RnetSession
@@ -60,57 +59,6 @@ def test_each_session_kind_gets_its_transport():
assert dl.transport_for(transport) is transport
-def test_requests_transport_has_no_retries_and_no_record():
- session = rq.Session()
- view = dl.transport_for(session).session
- assert view is not session
- assert view.record_request is False
- assert all(adapter.max_retries.total == 0 for adapter in view.adapters.values())
-
-
-class _RnetSession(RnetSession):
- def __init__(self):
- super().__init__()
- self.calls: list[dict] = []
-
- def get(self, url, **kwargs):
- self.calls.append(kwargs)
- return _Response()
-
-
-def test_rnet_transport_turns_retries_and_record_off():
- session = _RnetSession()
- dl.transport_for(session).get("http://127.0.0.1:1/a")
- assert session.calls[0]["max_retries"] == 0
- assert session.calls[0]["record_request"] is False
- assert session.calls[0]["stream"] is True
-
-
-def test_requests_body_reads_raw_and_read1_only_while_racing():
- response = _Response({"Content-Length": "6"})
- body = dl.RequestsBody(response, raw=True)
- racing = iter([True, False, False])
- assert b"".join(body.chunks(2, lambda: next(racing))) == b"abcdef"
- assert response.raw.calls == ["read1", "read", "read"]
-
-
-class _Transport(dl.Transport):
- def __init__(self):
- self.response = _Response({"Content-Length": "6"})
-
- def get(self, url, **kwargs):
- return dl.RequestsBody(self.response, raw=True)
-
-
-@pytest.mark.parametrize("claimed, expected", [(None, {"read"}), (lambda: False, {"read1"})])
-def test_download_reads_read1_only_for_a_claimable_segment(tmp_path, claimed, expected):
- transport = _Transport()
- events = dl.download("http://127.0.0.1:1/a", tmp_path / "a.bin", transport, claimed=claimed, racing=lambda: True)
- list(events)
- assert (tmp_path / "a.bin").read_bytes() == b"abcdef"
- assert set(transport.response.raw.calls) == expected
-
-
def test_an_encoded_body_goes_through_iter_content():
response = _Response({"content-encoding": "gzip", "Content-Length": "6"})
body = dl.RequestsBody(response, raw=True)
@@ -118,11 +66,3 @@ def test_an_encoded_body_goes_through_iter_content():
assert body.content_length == 0
assert list(body.chunks(2, None)) == [b"abcdef"]
assert response.raw.calls == []
-
-
-def test_another_session_kind_is_read_with_iter_content_and_a_timeout():
- session = _Session()
- transport = dl.transport_for(session)
- assert transport.session is session
- assert list(transport.get("http://127.0.0.1:1/a").chunks(2, None)) == [b"abcdef"]
- assert session.calls[0]["timeout"] == (dl.CONNECT_TIMEOUT, dl.READ_TIMEOUT)
diff --git a/tests/lang_selection/test_apply_original_language.py b/tests/lang_selection/test_apply_original_language.py
index f2e566c5a..c783bb9c6 100644
--- a/tests/lang_selection/test_apply_original_language.py
+++ b/tests/lang_selection/test_apply_original_language.py
@@ -45,9 +45,3 @@ def test_original_flag_moves_to_the_enrich_language():
t = title("es", audio=[track("es-419", original=True), track("it-IT")])
apply_original_language(t, Language.get("it"))
assert [a.is_original_lang for a in t.tracks.audio] == [False, True]
-
-
-def test_same_language_leaves_flags_alone():
- t = title("it", videos=[track(None, original=True)])
- apply_original_language(t, Language.get("it"))
- assert t.tracks.videos[0].is_original_lang is True
diff --git a/tests/lang_selection/test_as_requested.py b/tests/lang_selection/test_as_requested.py
deleted file mode 100644
index ae802ac8c..000000000
--- a/tests/lang_selection/test_as_requested.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from __future__ import annotations
-
-import pytest
-
-from unshackle.core.utilities import as_requested
-
-
-@pytest.mark.parametrize(
- "tokens,orig_token,expected",
- [
- # the user passed no -l, so orig resolved to en behind their back; report orig
- (["en"], "en", "orig"),
- (["en", "ja"], "en", "orig, ja"),
- # the user named en, so report en
- (["en"], None, "en"),
- (["ja"], "en", "ja"),
- (["en", "ja"], None, "en, ja"),
- ([], "en", ""),
- ],
-)
-def test_as_requested(tokens: list[str], orig_token: str | None, expected: str) -> None:
- assert as_requested(tokens, orig_token) == expected
diff --git a/tests/lang_selection/test_embedded_audio_langs.py b/tests/lang_selection/test_embedded_audio_langs.py
index 5148f70f8..abb79cd66 100644
--- a/tests/lang_selection/test_embedded_audio_langs.py
+++ b/tests/lang_selection/test_embedded_audio_langs.py
@@ -9,18 +9,6 @@ def video(**data):
return SimpleNamespace(data=data)
-def test_no_videos():
- assert embedded_audio_langs([], True) == []
-
-
-def test_video_without_a_declaration():
- assert embedded_audio_langs([video(), video(audio_language="")], True) == []
-
-
-def test_declared_language_is_returned():
- assert embedded_audio_langs([video(audio_language="zh-CN")], True) == ["zh-CN"]
-
-
def test_every_declaring_video_counts():
videos = [video(audio_language="zh-CN"), video(), video(audio_language="th")]
assert embedded_audio_langs(videos, True) == ["zh-CN", "th"]
diff --git a/tests/lang_selection/test_find_missing_langs.py b/tests/lang_selection/test_find_missing_langs.py
deleted file mode 100644
index ef693a6b8..000000000
--- a/tests/lang_selection/test_find_missing_langs.py
+++ /dev/null
@@ -1,105 +0,0 @@
-from __future__ import annotations
-
-import pytest
-
-from unshackle.core.utilities import find_missing_langs
-
-
-@pytest.mark.parametrize(
- "requested,available,expected",
- [
- (["en"], ["en"], []),
- (["en", "ja"], ["en", "ja", "fr"], []),
- (["en", "fil"], ["en"], ["fil"]),
- (["en", "ko", "ja"], ["en"], ["ko", "ja"]),
- (["fil"], ["en", "ja"], ["fil"]),
- (["fil", "ko"], ["en"], ["fil", "ko"]),
- (["es"], ["es-419"], []),
- (["es-419"], ["es"], ["es-419"]),
- (["es-419"], ["es-MX", "es-ES"], ["es-419"]),
- (["en-US"], ["en-GB"], ["en-US"]),
- (["en"], ["en-US"], []),
- (["all"], [], []),
- (["best"], [], []),
- (["orig"], [], []),
- (["all", "en"], ["en"], []),
- (["best", "fil"], ["en"], ["fil"]),
- ([], ["en"], []),
- (["en"], [], ["en"]),
- (["en"], [None, "en"], []),
- (["en"], [None], ["en"]),
- (["zh"], ["zh-Hans"], []),
- (["zh-CN"], ["zh-Hans"], []),
- (["zh-Hans"], ["zh-CN"], []),
- (["zh-TW"], ["zh-Hant"], []),
- (["zh-Hant"], ["zh-TW"], []),
- (["zh"], ["zh-Hant"], ["zh"]),
- (["zh-Hans"], ["zh-Hant"], ["zh-Hans"]),
- (["zh-CN"], ["zh-TW"], ["zh-CN"]),
- (["zh-HK"], ["zh-Hant"], ["zh-HK"]),
- (["zh"], ["cmn"], []),
- (["cmn"], ["zh"], []),
- (["zh"], ["yue"], ["zh"]),
- (["yue"], ["zh-HK"], ["yue"]),
- (["fil"], ["tl"], []),
- (["tl"], ["fil"], []),
- (["fil"], ["tgl"], []),
- (["tgl"], ["fil"], []),
- (["fil"], ["fil-PH"], []),
- (["tl"], ["fil-PH"], []),
- ],
-)
-def test_close_match(requested, available, expected):
- assert find_missing_langs(requested, available, exact=False) == expected
-
-
-@pytest.mark.parametrize(
- "requested,available,expected",
- [
- (["es"], ["es-419"], ["es"]),
- (["es-419"], ["es"], ["es-419"]),
- (["en"], ["en-US"], []),
- (["en-US"], ["en"], []),
- (["en"], ["en-GB"], ["en"]),
- (["en-US"], ["en-GB"], ["en-US"]),
- (["en-US"], ["en-US"], []),
- (["en-US", "en-GB"], ["en-US"], ["en-GB"]),
- (["en"], ["en"], []),
- (["all", "es-419"], ["es"], ["es-419"]),
- (["zh"], ["zh-Hans"], []),
- (["zh-CN"], ["zh-Hans"], []),
- (["zh-TW"], ["zh-Hant"], []),
- (["zh"], ["cmn"], []),
- (["zh-HK"], ["zh-Hant"], ["zh-HK"]),
- (["zh-Hans"], ["zh-Hant"], ["zh-Hans"]),
- (["zh-CN"], ["zh-TW"], ["zh-CN"]),
- (["fil"], ["tl"], []),
- (["tl"], ["fil"], []),
- (["fil"], ["tgl"], []),
- (["fil"], ["fil-PH"], []),
- (["tl"], ["fil-PH"], []),
- ],
-)
-def test_exact_match(requested, available, expected):
- assert find_missing_langs(requested, available, exact=True) == expected
-
-
-def test_order_preserved():
- assert find_missing_langs(["ja", "ko", "fr"], ["en"], exact=False) == ["ja", "ko", "fr"]
-
-
-def test_duplicates_in_request():
- assert find_missing_langs(["fil", "fil", "en"], ["en"], exact=False) == ["fil", "fil"]
-
-
-def test_zh_catalogue_simplified_only_misses_traditional():
- assert find_missing_langs(["zh-Hant", "zh-TW"], ["en", "zh-Hans"], exact=False) == ["zh-Hant", "zh-TW"]
-
-
-def test_mixed_zh_fil_request():
- assert find_missing_langs(["en", "zh-Hans", "fil"], ["en", "tl"], exact=False) == ["zh-Hans"]
-
-
-def test_zh_cn_request_with_tw_catalogue():
- assert find_missing_langs(["zh-CN"], ["zh-TW"], exact=False) == ["zh-CN"]
- assert find_missing_langs(["zh-CN"], ["zh-TW"], exact=True) == ["zh-CN"]
diff --git a/tests/lang_selection/test_kind_only_selection.py b/tests/lang_selection/test_kind_only_selection.py
index d37d668a5..7e70f8ced 100644
--- a/tests/lang_selection/test_kind_only_selection.py
+++ b/tests/lang_selection/test_kind_only_selection.py
@@ -151,15 +151,6 @@ def test_a_single_title_with_no_such_track_exits(
assert "Skipping" not in caplog.text
-def test_subs_only_with_no_matching_subtitle_exits_a_single_title_and_skips_in_a_season(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- assert run(monkeypatch, caplog, {1: {}}, subs_only=True, s_lang=["fr"]) == 1
- assert run(monkeypatch, caplog, {1: {}, 2: {}}, subs_only=True, s_lang=["fr"]) == 1
- assert caplog.text.count("Skipping Show S01E") == 2
- assert "Skipping Show S01E02: There's no track left for the selected options." in caplog.text
-
-
def test_a_multi_title_run_skips_the_title_and_continues(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
@@ -168,13 +159,6 @@ def test_a_multi_title_run_skips_the_title_and_continues(
assert "Skipping Show S01E01" in caplog.text
-def test_a_multi_title_run_with_every_title_skipped_fails(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- assert run(monkeypatch, caplog, {1: {}, 2: {}}, forced_subs_only=True) == 1
- assert caplog.text.count("Skipping Show S01E") == 2
-
-
def test_a_required_language_miss_stops_the_run_by_default(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
@@ -206,14 +190,6 @@ def test_skip_missing_skips_the_title_and_reports_it(
assert state.title == "Show"
-def test_skip_missing_skips_a_filter_miss_and_continues(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- ids = run(monkeypatch, caplog, {1: {}, 2: {"ko": True}}, a_lang=["ko"], skip_missing=True)
- assert ids == {"video": ["v"], "audio": ["ko"], "subs": ["s"]}
- assert "Skipping Show S01E01" in caplog.text
-
-
def test_skip_missing_still_fails_a_run_that_skips_every_title(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
@@ -222,72 +198,12 @@ def test_skip_missing_still_fails_a_run_that_skips_every_title(
assert run(monkeypatch, caplog, {1: {}}, require_audio=["ko"], skip_missing=True) == 1
-class LangService(FakeService):
- """Each episode names its original language and its audio languages; the video is in the original language."""
-
- def get_titles_cached(self) -> Series:
- return Series(
- Episode(id_=f"show-s01-e{n:03}", service=FakeService, title="Show", season=1, number=n, language=ep["orig"])
- for n, ep in self.episodes.items()
- )
-
- def get_tracks(self, title: Episode) -> Tracks:
- ep = self.episodes[title.number]
- tracks = Tracks()
- tracks.add(Video(id_="v", url="https://x/v", language=ep["orig"] or "en", codec=Video.Codec.AVC))
- for lang in ep["audio"]:
- tracks.add(Audio(id_=lang, url=f"https://x/{lang}", language=lang, codec=Audio.Codec.AAC, bitrate=128_000))
- return tracks
-
-
JA_EN = {"orig": "ja", "audio": ["ja", "en"]}
FR = {"orig": "ja", "audio": ["fr"]}
EVERY = {"orig": "ja", "audio": ["ja", "ko", "en"]}
ORIG_KO_EN = ["orig", "ko", "en"]
-@pytest.mark.parametrize(
- "first,flags,outcome,logged",
- [
- (JA_EN, {}, 1, "Show S01E01: ko not found in audio tracks"),
- (JA_EN, {"skip_missing": True}, ["ja", "ko", "en"], "Skipping Show S01E01: ko not found in audio tracks"),
- ({"orig": "ja", "audio": ["ko", "en"]}, {"skip_missing": True}, ["ja", "ko", "en"], "S01E01: orig not found"),
- (JA_EN, {"best_available": True}, ["ja", "en"], "ko not found in audio tracks, continuing with: orig, en"),
- (FR, {"best_available": True}, 1, "orig, ko, en not found in audio tracks and no fallback available"),
- (FR, {"best_available": True, "skip_missing": True}, ["ja", "ko", "en"], "Skipping Show S01E01: orig, ko, en"),
- (JA_EN, {"best_available": True, "require_audio": ["ko"]}, 1, "Required audio language(s) not found: ko"),
- (
- JA_EN,
- {"best_available": True, "require_audio": ["ko"], "skip_missing": True},
- ["ja", "ko", "en"],
- "Skipping Show S01E01: Required audio language(s) not found: ko",
- ),
- ],
-)
-def test_several_audio_languages_skip_an_episode_that_misses_one(
- monkeypatch: pytest.MonkeyPatch,
- caplog: pytest.LogCaptureFixture,
- first: dict,
- flags: dict[str, Any],
- outcome: Any,
- logged: str,
-) -> None:
- """-al orig,ko,en on a season where only the second episode has all three."""
- episodes = {1: first, 2: EVERY}
- result = run(monkeypatch, caplog, episodes, service=LangService(episodes), a_lang=ORIG_KO_EN, **flags)
- assert (result if outcome == 1 else result["audio"]) == outcome
- assert logged in caplog.text
-
-
-def test_several_audio_languages_fail_a_season_that_misses_one_everywhere(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- episodes = {1: JA_EN, 2: JA_EN}
- assert run(monkeypatch, caplog, episodes, service=LangService(episodes), a_lang=ORIG_KO_EN, skip_missing=True) == 1
- assert caplog.text.count("ko not found in audio tracks") == 2
- assert "Skipped all 2 titles" in caplog.text
-
-
def test_a_partly_skipped_run_completes_and_lists_the_skips(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
@@ -296,37 +212,6 @@ def test_a_partly_skipped_run_completes_and_lists_the_skips(
assert "Skipped 1 of 2 titles: Show S01E01" in caplog.text
-@pytest.mark.parametrize("no_mux,settled", [(False, 2), (True, 1)])
-def test_a_skipped_title_settles_its_post_script_group(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, no_mux: bool, settled: int
-) -> None:
- """The season event waits on every title of a group; a skipped title counts as settled, once at count time."""
- import unshackle.commands.dl as dl_module
-
- seen: list[str] = []
- group = dl_module.post_script_group
- monkeypatch.setattr(dl_module, "post_script_group", lambda t: seen.append(str(t)) or group(t))
- run(monkeypatch, caplog, {1: {}, 2: {"ko": True}}, a_lang=["ko"], skip_missing=True, no_mux=no_mux)
- assert seen.count("Show S01E01") == settled
-
-
-class CaptionlessService(FakeService):
- """A service that finds out in get_tracks that the title has no subtitles, and turns them off."""
-
- def get_tracks(self, title: Episode) -> Tracks:
- tracks = super().get_tracks(title)
- tracks.subtitles = []
- self.NO_SUBTITLES = True
- return tracks
-
-
-def test_no_subtitles_set_in_get_tracks_turns_the_subtitle_requirement_off(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- ids = run(monkeypatch, caplog, {1: {}}, service=CaptionlessService({1: {}}), require_subs=["en"])
- assert ids == {"video": ["v"], "audio": ["a"], "subs": []}
-
-
class Muxed(BaseException):
"""Stops the run at the first mux."""
diff --git a/tests/lang_selection/test_overlapping_audio_dedup.py b/tests/lang_selection/test_overlapping_audio_dedup.py
index d22cf41af..528ddb579 100644
--- a/tests/lang_selection/test_overlapping_audio_dedup.py
+++ b/tests/lang_selection/test_overlapping_audio_dedup.py
@@ -19,7 +19,6 @@ import pytest
from unshackle.core.tracks import Audio
from unshackle.core.tracks.tracks import Tracks
-from unshackle.core.utilities import is_exact_match
# Base language vs regional variant that CLDR rates at distance 0 (paradigm locales). These are
# the pairs that collapse under naive exact matching.
@@ -108,29 +107,12 @@ def select(tags, pool, exact=True):
return [(t.id, str(t.language)) for t in Tracks.by_language(pool, tags, per_language=1, exact_match=exact)]
-@pytest.mark.parametrize("base,reg", COLLAPSING_PAIRS)
-def test_collapsing_pairs_are_distance_zero(base, reg):
- # Root cause: the regional variant exact-matches the base request (CLDR paradigm data).
- assert is_exact_match(base, [reg]) is True
-
-
-@pytest.mark.parametrize("base,reg", DISTINCT_PAIRS)
-def test_distinct_pairs_are_not_distance_zero(base, reg):
- # Contrast: these never collapse, which is why the bug was language-specific.
- assert is_exact_match(base, [reg]) is False
-
-
@pytest.mark.parametrize("base,reg", COLLAPSING_PAIRS)
def test_exact_lang_selects_distinct_collapsing_variants(base, reg):
# Both tracks present + both tags requested: each tag must route to its own track.
assert select([base, reg], mk(base, reg)) == [(base, base), (reg, reg)]
-@pytest.mark.parametrize("base,reg", DISTINCT_PAIRS)
-def test_exact_lang_distinct_regionals_still_work(base, reg):
- assert select([base, reg], mk(base, reg)) == [(base, base), (reg, reg)]
-
-
def test_exact_lang_lenient_base_to_regional_fallback():
# Only the regional present; a base request must still find it when CLDR rates them equal.
assert select(["en"], mk("en-US")) == [("en-US", "en-US")]
@@ -138,12 +120,6 @@ def test_exact_lang_lenient_base_to_regional_fallback():
assert select(["zh"], mk("cmn")) == [("cmn", "cmn")]
-def test_exact_lang_stays_strict_for_nonzero_distance():
- # `es` does NOT accept `es-419` in exact mode (distance 5), but fuzzy mode does.
- assert select(["es"], mk("es-419")) == []
- assert select(["es"], mk("es-419"), exact=False) == [("es-419", "es-419")]
-
-
@pytest.mark.parametrize("base,reg", COLLAPSING_PAIRS)
def test_overlapping_tags_never_duplicate_in_fuzzy_mode(base, reg):
# Non-exact still collapses base/regional, but must dedupe rather than return a track twice.
@@ -163,14 +139,6 @@ def test_exact_lang_three_way_base_and_two_regionals():
assert select(["fr", "fr-CA"], mk("fr-FR", "fr-CA")) == [("fr-FR", "fr-FR"), ("fr-CA", "fr-CA")]
-@pytest.mark.parametrize("tag", REAL_WORLD_AUDIO_LANGS)
-def test_full_language_set_each_tag_resolves_to_itself(tag):
- # Against a full real-world language pool, every exact request must return its own track, so
- # that no tag captures another's: ar-EG must resolve to ar-EG, never to ar.
- pool = mk(*REAL_WORLD_AUDIO_LANGS)
- assert select([tag], pool) == [(tag, tag)]
-
-
def test_full_language_set_selects_every_track_once():
pool = mk(*REAL_WORLD_AUDIO_LANGS)
selected = Tracks.by_language(pool, REAL_WORLD_AUDIO_LANGS, per_language=1, exact_match=True)
diff --git a/tests/lang_selection/test_regional_selection_loop.py b/tests/lang_selection/test_regional_selection_loop.py
index a26b02e3b..89c75be89 100644
--- a/tests/lang_selection/test_regional_selection_loop.py
+++ b/tests/lang_selection/test_regional_selection_loop.py
@@ -69,20 +69,6 @@ def test_orig_takes_another_region_of_the_title_language(
assert ids["video"] == ["v"]
-def test_orig_keeps_the_script_the_title_region_implies(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- ids = run(monkeypatch, caplog, RegionalService("zh-TW", ["zh-HK", "zh-CN"], []))
- assert ids["audio"] == ["zh-HK"]
-
-
-def test_a_regional_audio_request_misses_rather_than_take_a_sibling(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- assert run(monkeypatch, caplog, RegionalService("fr-FR", ["fr-CA"], []), a_lang=["fr-FR"]) == 1
- assert "fr-FR not found in audio tracks" in caplog.text
-
-
def test_a_regional_sdh_track_is_stripped_when_only_a_sibling_is_plain(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
@@ -98,26 +84,6 @@ def test_a_forced_track_does_not_hide_the_plain_track_a_region_means(
assert run(monkeypatch, caplog, service, s_lang=["es-ES"])["subs"] == ["es"]
-def test_a_bare_sdh_track_is_stripped_when_only_another_variant_is_plain(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- service = RegionalService("en", ["en"], [("en", "sdh"), ("en-GB", "")])
- assert sorted(run(monkeypatch, caplog, service, s_lang=["en"])["subs"]) == ["en-sdh", "en-sdh_stripped"]
-
-
-def test_a_bare_audio_request_takes_the_variant_it_means(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- service = RegionalService("en", ["en", "pt-PT", "pt-BR"], [])
- assert run(monkeypatch, caplog, service, a_lang=["pt"])["audio"] == ["pt-BR"]
-
-
-def test_orig_takes_the_title_variant_over_the_one_a_bare_tag_means(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- assert run(monkeypatch, caplog, RegionalService("fr-CA", ["fr-FR", "fr-CA", "en"], []))["audio"] == ["fr-CA"]
-
-
@pytest.mark.parametrize(
("subs", "flags", "expected"),
[
@@ -373,10 +339,3 @@ def test_a_standalone_range_beside_hybrid_does_not_add_a_hybrid_base(
with pytest.raises(Planned) as planned:
run_hdr(monkeypatch, caplog, videos, ["HYBRID", "HDR10"], to_end=True, video_only=True)
assert planned.value.base_ids == expected
-
-
-def test_the_fallback_from_a_failed_hybrid_ranks_regional_tags_as_one_language(
- monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- videos = [("sdr-au", "en-AU", "SDR", 3840, 2160, 3000), ("sdr-gb", "en-GB", "SDR", 3840, 2160, 9000)]
- assert run_hdr(monkeypatch, caplog, videos, ["HYBRID", "SDR"], best_available=True)["video"] == ["sdr-gb"]
diff --git a/tests/lang_selection/test_required_langs.py b/tests/lang_selection/test_required_langs.py
index 913421439..b0bf75511 100644
--- a/tests/lang_selection/test_required_langs.py
+++ b/tests/lang_selection/test_required_langs.py
@@ -1,11 +1,8 @@
from __future__ import annotations
-import inspect
-
import pytest
from unshackle.commands.dl import dl
-from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS, cast_dl_params
from unshackle.core.utilities import missing_required_langs
@@ -32,12 +29,6 @@ def test_missing_required_langs(required, available, expected):
assert missing_required_langs(required, available) == expected
-def test_exclusion_token_is_not_a_required_language():
- # '-fr' must not be read as a language named "-fr", which could never match
- assert missing_required_langs(["en", "-fr"], ["en", "ja"]) == []
- assert missing_required_langs(["en", "-fr"], ["ja"]) == ["en"]
-
-
def test_orig_resolves_to_the_title_language():
assert missing_required_langs(["orig"], ["ja"], "ja") == []
assert missing_required_langs(["orig"], ["en"], "ja") == ["ja"]
@@ -59,25 +50,6 @@ def test_all_and_best_tokens_require_nothing():
assert missing_required_langs(["best"], []) == []
-@pytest.mark.parametrize("flag", ["--require-audio", "--require-video", "--best-available", "--warn-only"])
-def test_flag_is_registered_on_the_dl_command(flag):
- assert any(flag in param.opts for param in dl.cli.params)
-
-
-@pytest.mark.parametrize(
- "flag,expected_param",
- [
- ("--require-audio", "require_audio"),
- ("--require-video", "require_video"),
- ("--warn-only", "best_available"),
- ("--best-available", "best_available"),
- ],
-)
-def test_flag_maps_to_its_param_name(flag, expected_param):
- param = next(p for p in dl.cli.params if flag in p.opts)
- assert param.name == expected_param
-
-
@pytest.mark.parametrize("flag", ["--require-audio", "--require-video"])
def test_require_flags_parse_a_comma_list(flag):
param = next(p for p in dl.cli.params if flag in p.opts)
@@ -85,13 +57,6 @@ def test_require_flags_parse_a_comma_list(flag):
assert param.type.convert("en,ja", param, None) == ["en", "ja"]
-@pytest.mark.parametrize("key", ["require_audio", "require_video"])
-def test_api_passes_the_flags_through(key):
- # the REST API bypasses click, so the default and the dl.result param must both exist
- assert DEFAULT_DOWNLOAD_PARAMS[key] == []
- assert key in inspect.signature(dl.result).parameters
-
-
def test_api_accepts_the_require_flags():
from tests.admission import refusal
@@ -104,16 +69,6 @@ def test_api_accepts_the_require_flags():
)
-@pytest.mark.parametrize(
- "key,default",
- [("require_audio", []), ("require_video", []), ("audio_description_only", False), ("forced_subs_only", False)],
-)
-def test_api_reaches_dl_result(key, default):
- assert DEFAULT_DOWNLOAD_PARAMS[key] == default
- assert key in inspect.signature(dl.result).parameters
- assert cast_dl_params(dl.cli, {})[key] == default
-
-
@pytest.mark.parametrize(
"value",
["en,fr", "en", {"lang": "en"}, [1], ["en", None]],
diff --git a/tests/lang_selection/test_required_langs_gate.py b/tests/lang_selection/test_required_langs_gate.py
index 28907843c..f7789c04b 100644
--- a/tests/lang_selection/test_required_langs_gate.py
+++ b/tests/lang_selection/test_required_langs_gate.py
@@ -26,12 +26,6 @@ def test_language_objects_satisfy_a_requirement():
assert missing_required_langs(["en"], [Language.get("fr")]) == ["en"]
-def test_orig_accepts_a_language_object_title_language():
- # title.language is a langcodes.Language at the call site, never a str
- assert missing_required_langs(["orig"], ["ja"], Language.get("ja")) == []
- assert missing_required_langs(["orig"], ["en"], Language.get("ja")) == ["ja"]
-
-
def test_requirement_checks_the_catalogue_not_the_selection():
# -l best,-fr --require-audio en: the gate answers "does en exist", so the
# exclusion of fr from the *selection* must not make en count as missing
@@ -55,17 +49,6 @@ def test_the_gate_counts_audio_embedded_in_a_kept_video() -> None:
assert selection(require_audio=["ko"], audio_only=True).select(title(), False) == missing
-def test_ado_does_not_count_audio_embedded_in_the_video_at_the_gate() -> None:
- title = episode(video(data={"audio_language": "ko"}), audio("ad", bitrate=1, descriptive=True))
- sel = selection(require_audio=["ko"], audio_description=True, audio_description_only=True)
- assert sel.select(title, False) == Skip("Required audio language(s) not found: ko")
-
-
-def test_a_run_with_every_required_language_present_keeps_the_title() -> None:
- sel = selection(require_audio=["en"], require_video=["en"], require_subs=["en"])
- assert isinstance(sel.select(standard(), False), Kept)
-
-
def test_the_gate_honours_exact_lang() -> None:
def title() -> Any:
return episode(video(), audio(language="en-GB"))
diff --git a/tests/lang_selection/test_track_selection.py b/tests/lang_selection/test_track_selection.py
index 0de5ed9cd..2bfcd061f 100644
--- a/tests/lang_selection/test_track_selection.py
+++ b/tests/lang_selection/test_track_selection.py
@@ -74,11 +74,6 @@ def test_ado_keeps_the_descriptive_track_and_the_other_types() -> None:
assert kept(sel.select(standard(ad=True, forced=True), False)) == {"video": ["v"], "audio": ["ad"], "subs": ["s"]}
-def test_fso_keeps_the_forced_track_and_the_other_types() -> None:
- sel = selection(forced_subs=True, forced_subs_only=True)
- assert kept(sel.select(standard(ad=True, forced=True), False)) == {"video": ["v"], "audio": ["a"], "subs": ["sf"]}
-
-
def test_only_flags_with_their_type_flags_give_a_single_kind() -> None:
sel = selection(audio_description=True, audio_description_only=True, audio_only=True)
assert kept(sel.select(standard(ad=True, forced=True), False)) == {"video": [], "audio": ["ad"], "subs": []}
@@ -101,12 +96,6 @@ def test_a_kind_only_miss_is_a_kind_only_skip(flags: dict[str, Any], reason: str
assert selection(**flags).select(standard(), False) == Skip(reason, kind_only=True)
-def test_ado_runs_when_the_title_has_no_separate_audio() -> None:
- title = episode(video(data={"audio_language": "en"}))
- sel = selection(audio_description=True, audio_description_only=True)
- assert sel.select(title, False) == Skip("There's no audio description track.", kind_only=True)
-
-
def test_ado_does_not_count_audio_embedded_in_the_video() -> None:
def title() -> Episode:
return episode(video(data={"audio_language": "ko"}), audio("ad", bitrate=1, descriptive=True))
diff --git a/tests/orchestration/test_merge_video.py b/tests/orchestration/test_merge_video.py
index 41dc34f29..d9a0beb81 100644
--- a/tests/orchestration/test_merge_video.py
+++ b/tests/orchestration/test_merge_video.py
@@ -73,32 +73,6 @@ def test_merge_splits_on_range() -> None:
assert len(groups) == 2
-def test_merge_splits_on_resolution() -> None:
- """1080p vs 2160p of the same range+codec → separate groups."""
- videos = [
- make_video("1080", range_=SDR, height=1080, codec=HEVC),
- make_video("2160", range_=SDR, height=2160, codec=HEVC),
- ]
- groups = group_videos_by_variant(videos, merge=True)
- assert len(groups) == 2
-
-
-def test_merge_multi_range_yields_one_group_per_range() -> None:
- """Regression guard: -r HYBRID,DV,HDR10,SDR must never collapse into one file.
-
- HYBRID is resolved upstream into a DV deliverable plus the requested standalone
- ranges; here the four selected single-range tracks must stay in four groups.
- """
- videos = [
- make_video("sdr", range_=SDR, height=2160, codec=HEVC),
- make_video("hdr10", range_=HDR10, height=2160, codec=HEVC),
- make_video("dv", range_=DV, height=2160, codec=HEVC),
- make_video("dv-hybrid", range_=DV, height=1080, codec=HEVC), # different height
- ]
- groups = group_videos_by_variant(videos, merge=True)
- assert len(groups) == 4
-
-
def test_no_merge_yields_one_group_per_track() -> None:
"""merge=False reproduces today's per-track behaviour exactly."""
videos = [
@@ -122,8 +96,3 @@ def test_merge_preserves_first_seen_order() -> None:
# HEVC group seen first (and gathers both languages), AVC group second.
assert [v.id for v in groups[0]] == ["hevc-en", "hevc-fr"]
assert [v.id for v in groups[1]] == ["avc-en"]
-
-
-def test_empty_input_returns_empty() -> None:
- assert group_videos_by_variant([], merge=True) == []
- assert group_videos_by_variant([], merge=False) == []
diff --git a/tests/orchestration/test_music_remux_flow.py b/tests/orchestration/test_music_remux_flow.py
index 299c57b15..dc3ce62c4 100644
--- a/tests/orchestration/test_music_remux_flow.py
+++ b/tests/orchestration/test_music_remux_flow.py
@@ -50,53 +50,6 @@ def make_audio(path: Path, codec: Audio.Codec, track_id: str) -> Audio:
return track
-def test_the_hook_remuxes_every_audio_track_of_a_song(tmp_path: Path) -> None:
- song = make_song()
- song.tracks = Tracks(
- [
- make_audio(fragmented_mp4(tmp_path / "Audio_a1.mp4", "flac"), Audio.Codec.FLAC, "a1"),
- make_audio(fragmented_mp4(tmp_path / "Audio_a2.mp4", "aac"), Audio.Codec.AAC, "a2"),
- ]
- )
-
- remux_music_tracks(song, log)
-
- assert [t.path.suffix for t in song.tracks.audio] == [".flac", ".m4a"]
- for track in song.tracks.audio:
- assert header_length(track.path) == pytest.approx(6.0, abs=0.5)
-
-
-def test_one_broken_track_warns_and_does_not_stop_the_rest(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
- broken = tmp_path / "Audio_a1.mp4"
- broken.write_bytes(b"") # ffmpeg cannot read this, so its remux must fail
- song = make_song()
- song.tracks = Tracks(
- [
- make_audio(broken, Audio.Codec.AAC, "a1"),
- make_audio(fragmented_mp4(tmp_path / "Audio_a2.mp4", "aac"), Audio.Codec.AAC, "a2"),
- ]
- )
-
- with caplog.at_level(logging.WARNING, logger=log.name):
- remux_music_tracks(song, log)
-
- assert "Could not remux audio track a1" in caplog.text
- assert song.tracks.audio[0].path == broken, "a failed remux must keep the downloaded file"
- assert song.tracks.audio[1].path.suffix == ".m4a", "the failure must not stop the other tracks"
-
-
-def test_a_non_song_title_is_left_alone(tmp_path: Path) -> None:
- source = fragmented_mp4(tmp_path / "Audio_a1.mp4", "aac")
- track = make_audio(source, Audio.Codec.AAC, "a1")
-
- class NotASong:
- tracks = Tracks([track])
-
- remux_music_tracks(NotASong(), log)
-
- assert track.path == source
-
-
def test_a_fragmented_flac_song_ends_playable_named_and_tagged(tmp_path: Path, default_templates: None) -> None:
"""The full post-download flow: hook, MediaInfo naming, final move, music tagging."""
song = make_song()
diff --git a/tests/remote/e2e/test_live_health.py b/tests/remote/e2e/test_live_health.py
index e64588c64..e5e0478dc 100644
--- a/tests/remote/e2e/test_live_health.py
+++ b/tests/remote/e2e/test_live_health.py
@@ -30,8 +30,3 @@ def test_health_requires_secret_key(server_url: str, secret_key: str) -> None:
r = requests.get(f"{server_url}/api/health", timeout=10)
assert r.status_code == (401 if secret_key else 200)
-
-
-def test_unknown_route_returns_404(http_session, server_url: str) -> None:
- r = http_session.get(f"{server_url}/api/this-does-not-exist", timeout=10)
- assert r.status_code in (404, 405)
diff --git a/tests/remote/e2e/test_live_remote_client.py b/tests/remote/e2e/test_live_remote_client.py
index fa7b968b5..24d9e42a6 100644
--- a/tests/remote/e2e/test_live_remote_client.py
+++ b/tests/remote/e2e/test_live_remote_client.py
@@ -7,18 +7,6 @@ import pytest
pytestmark = [pytest.mark.live]
-def test_remote_client_get_health(remote_client) -> None:
- body = remote_client.get("/api/health")
- assert body["status"] == "ok"
- assert "version" in body
-
-
-def test_remote_client_get_services(remote_client) -> None:
- body = remote_client.get("/api/services")
- assert "services" in body
- assert isinstance(body["services"], list)
-
-
def test_remote_client_get_404_raises_systemexit(remote_client) -> None:
with pytest.raises(SystemExit):
remote_client.get("/api/session/this-does-not-exist")
diff --git a/tests/remote/e2e/test_live_session_lifecycle.py b/tests/remote/e2e/test_live_session_lifecycle.py
index 0d2321f93..7cdda3c30 100644
--- a/tests/remote/e2e/test_live_session_lifecycle.py
+++ b/tests/remote/e2e/test_live_session_lifecycle.py
@@ -50,22 +50,6 @@ def delete_session(http_session, server_url: str, sid: str) -> None:
http_session.delete(f"{server_url}/api/session/{sid}", timeout=30)
-def test_session_create_then_delete(http_session, server_url: str, service_case) -> None:
- service, conf = service_case
- sid = create_session(http_session, server_url, service, conf)
- try:
- r = http_session.get(f"{server_url}/api/session/{sid}", timeout=30)
- assert r.status_code == 200
- info = r.json()
- assert info.get("session", {}).get("service_tag", service) == service or service in str(info)
- finally:
- delete_session(http_session, server_url, sid)
-
- # After delete, info should 404
- r2 = http_session.get(f"{server_url}/api/session/{sid}", timeout=30)
- assert r2.status_code == 404
-
-
def test_session_titles_returns_list(http_session, server_url: str, service_case) -> None:
service, conf = service_case
sid = create_session(http_session, server_url, service, conf)
@@ -107,12 +91,3 @@ def test_session_tracks_for_first_title(http_session, server_url: str, service_c
assert body.get("video") or body.get("audio"), body
finally:
delete_session(http_session, server_url, sid)
-
-
-def test_session_delete_idempotent_returns_404_after(http_session, server_url: str, service_case) -> None:
- service, conf = service_case
- sid = create_session(http_session, server_url, service, conf)
- delete_session(http_session, server_url, sid)
-
- r = http_session.delete(f"{server_url}/api/session/{sid}", timeout=30)
- assert r.status_code in (404, 200) # tolerate both depending on server semantics
diff --git a/tests/remote/process.py b/tests/remote/process.py
new file mode 100644
index 000000000..9b1b827c0
--- /dev/null
+++ b/tests/remote/process.py
@@ -0,0 +1,69 @@
+"""Helpers for the tests that start a client process and stop it with a signal."""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+from collections.abc import Callable, Iterator
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from tests.remote.unit.test_remote_loopback import KEY
+from tests.remote.unit.test_session_lifetime import ROOT
+from unshackle.core.config import config
+
+posix = pytest.mark.skipif(sys.platform == "win32", reason="POSIX signals")
+BOUND = 8.0
+
+
+@pytest.fixture
+def run(tmp_path: Path) -> Iterator[Callable[..., subprocess.Popen[str]]]:
+ """Start a process in a session or a console group of its own; a fixture so that no process outlives its test."""
+ started: list[subprocess.Popen[str]] = []
+
+ def begin(*argv: str, **options: Any) -> subprocess.Popen[str]:
+ defaults: dict[str, Any] = {"stdin": subprocess.DEVNULL, "stdout": subprocess.PIPE, "stderr": subprocess.STDOUT}
+ if sys.platform == "win32":
+ defaults["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
+ else:
+ defaults["start_new_session"] = True
+ argv = (sys.executable, *argv)
+ options = {**defaults, **options}
+ started.append(subprocess.Popen(argv, cwd=ROOT, text=True, encoding="utf-8", errors="replace", **options))
+ return started[-1]
+
+ yield begin
+ for process in started:
+ process.kill()
+ process.wait()
+ if process.stdout:
+ process.stdout.close()
+
+
+def wait_line(process: subprocess.Popen[str], text: str) -> str:
+ assert process.stdout is not None
+ for line in process.stdout:
+ if text in line:
+ return line
+ pytest.fail(f"the client did not print {text!r}")
+
+
+def settings(url: str, path: Path) -> dict[str, Any]:
+ """The config of a client process that reaches the test server and nothing else."""
+ folders = ("cache", "cookies", "downloads", "temp", "logs", "services", "wvds", "prds")
+ return {
+ "remote_services": {"test": {"url": url, "api_key": KEY}},
+ "directories": {name: str(path / name) for name in folders},
+ "update_checks": False,
+ "title_cache_enabled": False,
+ "output_template": {"movies": "{title}", "series": "{title}", "songs": "{title}"},
+ }
+
+
+@pytest.fixture(autouse=True)
+def lasting_sessions(server: SimpleNamespace) -> None: # noqa: F811
+ """A session must not expire on the server while a test holds the DELETE back."""
+ config.serve["session_ttl"] = 300
diff --git a/tests/remote/unit/test_api_availability.py b/tests/remote/unit/test_api_availability.py
index dfabd7c83..c3a600c47 100644
--- a/tests/remote/unit/test_api_availability.py
+++ b/tests/remote/unit/test_api_availability.py
@@ -39,23 +39,8 @@ def test_private_data_and_unknown_fields_never_leak():
assert data["availability"]["token"] == "secret"
-def test_missing_metadata_keeps_response_unchanged():
- assert "availability" not in serialize_title(episode(), None)
-
-
def test_remote_input_is_also_allowlisted():
info = serialize_title(episode(), None)
info["availability"] = {"paid": True, "access": "denied", "cookies": "secret"}
rebuilt = build_title(info, "EXAMPLE", "fallback")
assert rebuilt.data["availability"] == {"paid": True, "access": "denied"}
-
-
-def test_availability_appends_without_reordering_existing_fields():
- title = episode()
- title.part = 2
- title.anime = True
- original = serialize_title(title, None)
- title.data = {"availability": {"paid": True, "access": "granted"}}
- serialized = serialize_title(title, None)
- assert list(serialized) == [*original, "availability"]
- assert {key: serialized[key] for key in original} == original
diff --git a/tests/remote/unit/test_api_dl_options.py b/tests/remote/unit/test_api_dl_options.py
index a29599040..e40ea20f3 100644
--- a/tests/remote/unit/test_api_dl_options.py
+++ b/tests/remote/unit/test_api_dl_options.py
@@ -36,48 +36,11 @@ download_fields = importlib.util.module_from_spec(HOOK_SPEC)
HOOK_SPEC.loader.exec_module(download_fields)
-def test_the_openapi_yaml_documents_each_api_dl_option_with_its_default():
- """The download request body documents every dl option the API takes, with its API default, beside its own
- request keys. A missing default reads as null."""
- properties = download_fields.request_schema()["properties"]
- assert DEFAULT_DOWNLOAD_PARAMS.keys() <= properties.keys()
- assert properties.keys() - DEFAULT_DOWNLOAD_PARAMS.keys() == {"service", "title_id", "remote", "client_name", "cdm"}
- assert {key: properties[key].get("default") for key in DEFAULT_DOWNLOAD_PARAMS} == DEFAULT_DOWNLOAD_PARAMS
-
-
-def test_the_docs_hook_renders_a_row_for_each_request_field():
- """mkdocs.yml loads the hook, which renders one row for each request body field."""
- assert "docs/hooks/download_fields.py" in (ROOT / "mkdocs.yml").read_text(encoding="utf-8")
- schema = download_fields.request_schema()
- rows = download_fields.render(schema).splitlines()[2:]
- assert [row.split("`")[1] for row in rows] == list(schema["properties"])
-
-
-def test_api_defaults_cast_to_the_dl_defaults():
- """``wanted`` keeps its API default of no keys, which dl reads as every title, like the CLI's None."""
- ctx = click.Context(dl.cli)
- expected = {p.name: p.type_cast_value(ctx, p.get_default(ctx)) for p in dl.cli.params if p.name not in CLI_ONLY}
- assert cast_dl_params(dl.cli, {}) == {**expected, "wanted": []}
-
-
def test_cli_only_options_never_reach_dl():
cast = cast_dl_params(dl.cli, {"postscript": ["rm -rf /"], "speed_limit": "1M", "list_": True})
assert not CLI_ONLY & cast.keys()
-@pytest.mark.parametrize(
- "value,expected",
- [
- ("HDR10+", [Video.Range.HDR10P]),
- (["dv", "HDR10+"], [Video.Range.DV, Video.Range.HDR10P]),
- ([], [Video.Range.SDR]),
- (None, [Video.Range.SDR]),
- ],
-)
-def test_range_takes_the_api_spellings(value, expected):
- assert cast_dl_params(dl.cli, {"range": value})["range_"] == expected
-
-
def test_values_are_cast_by_the_dl_click_types():
cast = cast_dl_params(
dl.cli,
@@ -108,20 +71,6 @@ def test_values_are_cast_by_the_dl_click_types():
assert (cast["output_dir"], cast["cdm_only"], cast["s_lang"]) == (None, False, ["all"])
-def test_every_dl_option_reaches_dl_result():
- """An option outside the dl.__init__ and dl.result signatures is read from ctx.params elsewhere."""
- named = set(inspect.signature(dl.__init__).parameters) | set(inspect.signature(dl.result).parameters)
- assert {p.name for p in dl.cli.params} - named == {
- "server",
- "remote",
- "local_proxy",
- "reset_cache",
- "no_cache",
- "cdm_name",
- "import_file",
- }
-
-
@pytest.mark.parametrize(
"parent_params,sent",
[
@@ -200,3 +149,26 @@ def test_the_worker_keeps_the_code_of_an_api_error(tmp_path, monkeypatch):
payload.write_text(json.dumps({"job_id": "j", "service": "EXAMPLE", "title_id": "t", "parameters": {}}))
download_worker.main(["download_worker", str(payload), str(result)])
assert json.loads(result.read_text())["error_code"] == "INVALID_PARAMETERS"
+
+
+def test_the_openapi_yaml_documents_each_api_dl_option_with_its_default():
+ """The download request body documents every dl option the API takes, with its API default, beside its own
+ request keys. A missing default reads as null."""
+ properties = download_fields.request_schema()["properties"]
+ assert DEFAULT_DOWNLOAD_PARAMS.keys() <= properties.keys()
+ assert properties.keys() - DEFAULT_DOWNLOAD_PARAMS.keys() == {"service", "title_id", "remote", "client_name", "cdm"}
+ assert {key: properties[key].get("default") for key in DEFAULT_DOWNLOAD_PARAMS} == DEFAULT_DOWNLOAD_PARAMS
+
+
+def test_every_dl_option_reaches_dl_result():
+ """An option outside the dl.__init__ and dl.result signatures is read from ctx.params elsewhere."""
+ named = set(inspect.signature(dl.__init__).parameters) | set(inspect.signature(dl.result).parameters)
+ assert {p.name for p in dl.cli.params} - named == {
+ "server",
+ "remote",
+ "local_proxy",
+ "reset_cache",
+ "no_cache",
+ "cdm_name",
+ "import_file",
+ }
diff --git a/tests/remote/unit/test_api_episode_part.py b/tests/remote/unit/test_api_episode_part.py
index a281ca2f6..5af9909be 100644
--- a/tests/remote/unit/test_api_episode_part.py
+++ b/tests/remote/unit/test_api_episode_part.py
@@ -9,7 +9,6 @@ from __future__ import annotations
import asyncio
import json
-import re
from typing import Any
import pytest
@@ -102,14 +101,6 @@ def test_partless_episode_json_has_no_part_key() -> None:
assert d["name"] == "Pilot"
-def test_partful_episode_json_carries_part_last() -> None:
- d = serialize_title(ep(part=2), None)
- assert d["part"] == 2
- # additive: `part` is appended, every pre-existing key keeps its position
- assert list(d.keys())[:11] == list(serialize_title(ep(part=None), None).keys())
- assert list(d.keys())[11] == "part"
-
-
def test_part_stays_out_of_the_name_field() -> None:
"""`name` is a reconstruction input for build_title, not a display string."""
assert serialize_title(ep(part=2), None)["name"] == "Pilot"
@@ -124,17 +115,6 @@ def test_remote_build_title_round_trip() -> None:
assert partless.part is None
-def test_movie_json_unaffected() -> None:
- from langcodes import Language
-
- from unshackle.core.titles.movie import Movie
-
- d = serialize_title(
- Movie(id_="movie-0001", service=_FakeSvc, name="Film", year=2024, language=Language.get("en")), None
- )
- assert "part" not in d
-
-
@pytest.fixture
def split_titles() -> list[Episode]:
"""E1 split into three parts, E2 unsplit."""
@@ -177,11 +157,6 @@ def test_discrete_fields_with_part_select_one(monkeypatch, split_titles) -> None
assert selected(result) == ["1x1.3"]
-def test_discrete_part_accepts_string(monkeypatch, split_titles) -> None:
- result = run_list_tracks(monkeypatch, split_titles, season=1, episode=1, part="3")
- assert selected(result) == ["1x1.3"]
-
-
def test_discrete_no_match_error_reports_the_part_qualified_key(monkeypatch, split_titles) -> None:
result = run_list_tracks(monkeypatch, split_titles, season=1, episode=1, part=9)
assert result["status"] == 404
@@ -193,60 +168,17 @@ def test_discrete_partless_error_key_unchanged(monkeypatch, split_titles) -> Non
assert result["details"]["wanted"] == "9x9"
-def test_part_is_a_transport_key_not_a_service_option() -> None:
- """`part` addresses the title, so it must never reach a service's own --part option."""
- assert "part" in handlers.LIST_HANDLER_TRANSPORT_KEYS
- assert "part" in handlers.SESSION_TRANSPORT_KEYS
-
-
def test_rest_multi_episode_order_is_stable_across_parts(monkeypatch) -> None:
titles = [ep(1, 2, None), ep(1, 1, 3), ep(1, 1, 1), ep(1, 1, 2)]
result = run_list_tracks(monkeypatch, titles, wanted="S01")
assert selected(result) == ["1x1.1", "1x1.2", "1x1.3", "1x2"]
-@pytest.mark.parametrize(
- ("wanted", "parsed"),
- [
- (["1x1"], ["1x1"]),
- (["1x1.2"], ["1x1.2"]),
- (["!1x1.2"], ["!1x1.2"]),
- (["1x1", "!1x1.2"], ["1x1", "!1x1.2"]),
- ("1x1, 1x2", ["1x1", "1x2"]),
- (["1x01"], ["1x1"]),
- ],
-)
-def test_parsed_keys_pass_unchanged(wanted: Any, parsed: list[str]) -> None:
- """A pre-parsed part or negative key never reaches parse_tokens, which cannot read it."""
- assert SEASON_RANGE.convert(wanted) == parsed
-
-
@pytest.mark.parametrize("wanted", [["S01E01"], "S01E01", ["s1e1"], "s1e1; S01E01"])
def test_tokens_parse_from_a_list_or_a_separated_string(wanted: Any) -> None:
assert SEASON_RANGE.convert(wanted) == ["1x1"]
-def test_a_mixed_list_parses_every_token() -> None:
- assert sorted(SEASON_RANGE.convert(["1x1", "S01E02"])) == ["1x1", "1x2"]
-
-
-def test_dl_and_handlers_share_the_one_match_helper() -> None:
- """Both filters must route through Episode.matches_wanted, or they drift."""
- from pathlib import Path
-
- import unshackle.commands.dl as dl_module
-
- dl_source = Path(dl_module.__file__).read_text(encoding="utf8")
- handlers_source = Path(handlers.__file__).read_text(encoding="utf8")
-
- assert "matches_wanted(wanted)" in dl_source
- assert "matches_wanted(wanted)" in handlers_source
- # no inline key compare left behind on either side
- inline = re.compile(r"f\"\{title\.season\}x\{title\.number\}\"\s*\n?\s*(?:in|not in)\s+wanted")
- assert not inline.search(dl_source)
- assert not inline.search(handlers_source)
-
-
@pytest.mark.parametrize(
"wanted_tokens",
[
diff --git a/tests/remote/unit/test_api_proxy.py b/tests/remote/unit/test_api_proxy.py
index a809e74ea..9d25e2164 100644
--- a/tests/remote/unit/test_api_proxy.py
+++ b/tests/remote/unit/test_api_proxy.py
@@ -104,12 +104,6 @@ def test_no_proxy_skips_the_checks_and_loads_no_providers(no_providers):
assert decide(PLAIN, "EXAMPLE", "http://127.0.0.1:8080", no_proxy=True) == ("http://127.0.0.1:8080", [])
-def test_server_proxy_resolves_a_country_code(server_region, providers):
- server_region("IN")
- provider = providers("http://us.proxy:8080")
- assert decide(SERVER_PROXY, "EXAMPLE", "us") == ("http://us.proxy:8080", [provider])
-
-
def test_server_proxy_auto_proxies_a_client_in_another_region(server_region, providers):
server_region("IN")
provider = providers("http://ca.proxy:8080")
@@ -213,13 +207,6 @@ def test_a_server_account_service_refuses_a_proxy_uri(proxy):
assert exc_info.value.error_code == APIErrorCode.FORBIDDEN
-def test_the_server_account_is_asked_only_for_a_proxy_uri(providers):
- providers("http://us.proxy:8080")
- assert decide(SERVER_PROXY, "EXAMPLE", "us", server_account=lambda: pytest.fail("asked")).proxy == (
- "http://us.proxy:8080"
- )
-
-
class TestAdmit:
"""A download job: the same checks for the proxy and the download proxy, tunnel: refused."""
@@ -279,11 +266,6 @@ def test_only_the_server_proxy_stamp_gives_a_job_the_server_providers(monkeypatc
assert job_providers({"server_proxy": stamp}) == expected
-def test_the_job_stamps_carry_the_grant():
- assert SERVER_PROXY.stamps() == {"server_proxy": True, "local_proxy": True}
- assert PLAIN.stamps() == {"server_proxy": False, "local_proxy": False}
-
-
def test_a_geofenced_remote_service_gets_its_first_allowed_region_as_proxy():
fenced = {"tag": "EXAMPLE", "geofence": ["US", "ca"], "geoblock": ["us"]}
assert geofence_proxy(SERVER_PROXY, {}, {"tag": "EXAMPLE", "geofence": ["US", "ca"]}) == {"proxy": "us"}
diff --git a/tests/remote/unit/test_api_service_dl_overrides.py b/tests/remote/unit/test_api_service_dl_overrides.py
index 471944ec3..c52f67f47 100644
--- a/tests/remote/unit/test_api_service_dl_overrides.py
+++ b/tests/remote/unit/test_api_service_dl_overrides.py
@@ -52,12 +52,6 @@ def env(monkeypatch):
return run
-def test_service_dl_sets_defaults(env):
- params = env(dl={"workers": 7, "range": ["HDR10"]})
- assert params["workers"] == 7
- assert params["range"] == ["HDR10"]
-
-
def test_request_value_beats_service_dl(env):
assert env(body={"workers": 3}, dl={"workers": 7})["workers"] == 3
@@ -74,10 +68,6 @@ def test_routing_and_unknown_keys_are_ignored(env):
assert "speed_limit" not in params
-def test_click_spelling_of_range_lands_as_range(env):
- assert env(dl={"range_": ["HLG"]})["range"] == ["HLG"]
-
-
def test_gate_sees_service_dl(env):
env(dl={"quality": [2160]})
assert env.gate["quality"] == [2160]
@@ -106,10 +96,6 @@ def test_client_sent_keys_uses_the_stamp():
assert "client_keys" not in params
-def test_client_sent_keys_without_stamp_counts_all_keys():
- assert dm.client_sent_keys({"workers": 1, "quality": None}) == {"workers", "quality"}
-
-
def test_service_options_travel_nested_without_their_defaults(env, monkeypatch):
@click.command()
@click.option("--profile", type=int, default=1)
diff --git a/tests/remote/unit/test_api_title_fields.py b/tests/remote/unit/test_api_title_fields.py
index 23f2a6d7a..b6e010244 100644
--- a/tests/remote/unit/test_api_title_fields.py
+++ b/tests/remote/unit/test_api_title_fields.py
@@ -57,23 +57,6 @@ def test_a_plain_episode_gains_no_new_keys() -> None:
assert not [k for k in NEW_KEYS if k in d]
-def test_a_plain_movie_gains_no_new_keys() -> None:
- d = serialize_title(_movie(), None)
- assert not [k for k in NEW_KEYS if k in d]
-
-
-def test_air_date_is_serialized_as_an_iso_string() -> None:
- assert serialize_title(ep(air_date=date(2026, 8, 11)), None)["air_date"] == "2026-08-11"
-
-
-def test_an_unparseable_air_date_is_serialized_as_text() -> None:
- assert serialize_title(ep(air_date="soon"), None)["air_date"] == "soon"
-
-
-def test_absolute_is_serialized() -> None:
- assert serialize_title(ep(absolute=57), None)["absolute"] == 57
-
-
@pytest.mark.parametrize("value", [True, False])
def test_per_title_daily_and_anime_are_serialized_both_ways(value: bool) -> None:
episode = ep()
@@ -96,10 +79,6 @@ class _AnimeDailySvc:
DAILY = True
-class _PlainSvc:
- pass
-
-
def test_the_stamp_fills_both_flags_from_the_service_class() -> None:
d = serialize_title(ep(), _AnimeDailySvc())
assert (d["anime"], d["daily"]) == (True, True)
@@ -113,11 +92,6 @@ def test_the_stamp_never_overrides_a_per_title_false() -> None:
assert (d["anime"], d["daily"]) == (False, False)
-def test_a_plain_service_stamps_nothing() -> None:
- d = serialize_title(ep(), _PlainSvc())
- assert not [k for k in NEW_KEYS if k in d]
-
-
class _ProviderSvc:
METADATA_PROVIDER = "tmdb"
@@ -138,18 +112,6 @@ def test_the_metadata_provider_survives_the_round_trip() -> None:
assert round_trip(ep()).metadata_provider is None
-def test_title_to_meta_round_trip_keeps_the_metadata_provider() -> None:
- movie = _movie()
- movie.metadata_provider = "tmdb"
- assert build_title(title_to_meta(movie), "FAKE", "fallback-id").metadata_provider == "tmdb"
-
-
-def test_a_movie_is_never_stamped_daily() -> None:
- d = serialize_title(_movie(), _AnimeDailySvc())
- assert d["anime"] is True
- assert "daily" not in d
-
-
class _FakeService:
ANIME = True
DAILY = True
@@ -191,14 +153,6 @@ def test_list_tracks_selects_a_playlist_song_by_position(monkeypatch: pytest.Mon
assert (title["id"], title["position"], title["track"]) == ("song-B", 2, 6)
-def test_list_titles_stamps_the_service_flags(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "FAKE")
- monkeypatch.setattr(handlers, "launch_served", lambda *a, **kw: handlers.Launched(_FakeService([ep()]), None, None))
- response = asyncio.run(handlers.list_titles_handler({"service": "FAKE", "title_id": "t1"}))
- title = json.loads(response.body)["titles"][0]
- assert (title["anime"], title["daily"]) == (True, True)
-
-
def round_trip(episode: Episode, stamp: Any | None = None) -> Episode:
return build_title(serialize_title(episode, stamp), "FAKE", "fallback-id")
@@ -232,19 +186,6 @@ def test_a_per_title_false_survives_the_round_trip() -> None:
assert rebuilt.daily is False
-def test_a_movie_round_trip_keeps_the_anime_flag() -> None:
- movie = _movie()
- movie.anime = True
- rebuilt = build_title(serialize_title(movie, None), "FAKE", "fallback-id")
- assert isinstance(rebuilt, Movie)
- assert rebuilt.anime is True
-
-
-def test_title_to_meta_omits_the_new_keys_for_a_plain_episode() -> None:
- meta = title_to_meta(ep())
- assert not [k for k in ("absolute", "daily", "anime") if k in meta]
-
-
def test_title_to_meta_round_trip_keeps_the_new_fields() -> None:
episode = ep(air_date=date(2026, 8, 11), absolute=57)
episode.daily = True
@@ -255,19 +196,6 @@ def test_title_to_meta_round_trip_keeps_the_new_fields() -> None:
assert (rebuilt.daily, rebuilt.anime) == (True, True)
-def test_title_to_meta_round_trip_leaves_unset_flags_inheriting() -> None:
- rebuilt = build_title(title_to_meta(ep()), "FAKE", "fallback-id")
- assert rebuilt.absolute is None
- assert (rebuilt.daily, rebuilt.anime) == (None, None)
-
-
-def test_title_to_meta_round_trip_keeps_the_movie_anime_flag() -> None:
- movie = _movie()
- movie.anime = True
- rebuilt = build_title(title_to_meta(movie), "FAKE", "fallback-id")
- assert rebuilt.anime is True
-
-
def test_song_tag_data_survives_the_remote_round_trip() -> None:
song = Song(
id_="song-0001",
diff --git a/tests/remote/unit/test_cdm_call_log.py b/tests/remote/unit/test_cdm_call_log.py
index 88e774576..a0ab76f1f 100644
--- a/tests/remote/unit/test_cdm_call_log.py
+++ b/tests/remote/unit/test_cdm_call_log.py
@@ -12,7 +12,7 @@ from aiohttp import web
from click.testing import CliRunner
from unshackle.commands.serve import serve
-from unshackle.core.api.stats import SeqRing, cdm_calls, cdm_log_middleware, cdm_sessions, key_id
+from unshackle.core.api.stats import SeqRing, cdm_calls, cdm_log_middleware, key_id
from unshackle.core.config import config
pytestmark = pytest.mark.unit
@@ -202,30 +202,6 @@ async def test_refusals_are_recorded_with_their_message(aiohttp_client, serve_ap
assert page["sessions"] == [] and "wrong-key" not in json.dumps(page)
-async def test_gzipped_refusal_is_read_and_capped(aiohttp_client, serve_app) -> None:
- """compression_middleware runs inside the log middleware, so a long refusal arrives as gzip."""
- client = await aiohttp_client(serve_app)
- device = "d" * 400
- resp = await client.get(f"/{device}/open", headers={**USER, "Accept-Encoding": "gzip"})
- assert resp.status == 403 and resp.headers["Content-Encoding"] == "gzip"
- (record,) = (await cdm_log(client))["records"]
- assert record["device"] == device[:255] and len(record["error"]) == 300
- assert record["error"].startswith("Device 'ddd")
-
-
-async def test_refused_call_leaves_the_request_body_unread(aiohttp_client, serve_app) -> None:
- """A 401 is decided before the handler, so the body stays unread: no cost, and no session id, for an unknown key."""
- client = await aiohttp_client(serve_app)
- body = {"session_id": "ab" * 16, "license_message": LICENCE}
- assert (
- await client.post("/chrome_l3/parse_license", headers={"X-Secret-Key": "wrong-key"}, json=body)
- ).status == 401
- assert (await client.post("/chrome_l3/parse_license", headers=USER, json=body)).status == 400
- refused, unopened = (await cdm_log(client))["records"]
- assert refused["status"] == 401 and refused["session_id"] is None
- assert unopened["status"] == 400 and unopened["session_id"] == "ab" * 16
-
-
async def test_raised_http_exception_is_recorded_with_its_status(aiohttp_client) -> None:
"""aiohttp answers a raised ``HTTPException`` itself, so the record carries that status, not 500."""
@@ -295,7 +271,3 @@ def test_call_log_keeps_the_newest_and_counts_on() -> None:
log.append({"op": op})
assert [(r["seq"], r["op"]) for r in log.since()] == [(2, "get_keys"), (3, "close")]
assert log.since(2) == [{"seq": 3, "op": "close"}] and log.seq == 3
-
-
-def test_sessions_snapshot_is_empty_without_a_cdm() -> None:
- assert cdm_sessions(web.Application()) == []
diff --git a/tests/remote/unit/test_cdm_patch_leaves_no_shadow.py b/tests/remote/unit/test_cdm_patch_leaves_no_shadow.py
deleted file mode 100644
index 97ba77752..000000000
--- a/tests/remote/unit/test_cdm_patch_leaves_no_shadow.py
+++ /dev/null
@@ -1,39 +0,0 @@
-"""No test may patch ``load_cdm`` on the CDM package with ``setattr``.
-
-``unshackle.core.cdm`` resolves ``load_cdm`` through a lazy ``__getattr__`` (PEP 562), so the
-name never sits in the package dict. ``monkeypatch.setattr`` on the package reads the old value
-through ``__getattr__`` and, on undo, writes the real function into the package dict. That key
-shadows ``__getattr__`` for the rest of the process, and every later test that patches
-``unshackle.core.cdm.loader`` loses its stub. ``tests/commands/test_cdm_cache.py`` ran the real
-loader and raised ``ValueError: device_b does not exist``.
-
-``monkeypatch.setitem(cdm_mod.__dict__, "load_cdm", ...)`` leaves no residue: it deletes the key
-it added. This guard names the file at fault instead of leaving the damage to surface in an
-unrelated test.
-"""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-import pytest
-
-pytestmark = pytest.mark.unit
-
-TESTS_ROOT = Path(__file__).resolve().parents[2]
-
-# A setattr of load_cdm on anything but the loader module, which holds the name for real.
-PACKAGE_SETATTR = re.compile(r"""setattr\(\s*(?!loader\b)[\w.]+\s*,\s*["']load_cdm["']""")
-
-
-def test_no_test_patches_load_cdm_on_the_package() -> None:
- offenders: list[str] = []
- for path in sorted(TESTS_ROOT.rglob("test_*.py")):
- if path == Path(__file__).resolve():
- continue
- for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
- if PACKAGE_SETATTR.search(line):
- offenders.append(f"{path.relative_to(TESTS_ROOT)}:{number}: {line.strip()}")
-
- assert not offenders, "patch the package dict with monkeypatch.setitem instead:\n" + "\n".join(offenders)
diff --git a/tests/remote/unit/test_client_device_cdm.py b/tests/remote/unit/test_client_device_cdm.py
index b1f0c8c6b..b6ab34110 100644
--- a/tests/remote/unit/test_client_device_cdm.py
+++ b/tests/remote/unit/test_client_device_cdm.py
@@ -3,8 +3,6 @@
from __future__ import annotations
import json
-import threading
-import time
from types import SimpleNamespace
from typing import Any
from uuid import UUID
@@ -15,15 +13,11 @@ from pywidevine import DeviceTypes
from pywidevine.pssh import PSSH
from tests.remote.sessions import hold_session, launch_session, session_entry
-from tests.remote.unit.test_tunnel import wait_until
from unshackle.core.api import handlers, key_policy, server_keys
from unshackle.core.api.errors import APIError
from unshackle.core.api.input_bridge import InputBridge
from unshackle.core.cdm.client_relay import ClientDeviceCdm, answer_cdm_call
-from unshackle.core.launch import served_context
-from unshackle.core.remote_protocol import APIErrorCode, AuthStatus, LicensingMode, Licensor
-from unshackle.core.run_plan import served_plan
-from unshackle.core.utils.click_types import ContextData
+from unshackle.core.remote_protocol import APIErrorCode, LicensingMode, Licensor
pytestmark = pytest.mark.unit
@@ -107,47 +101,6 @@ def test_the_client_refuses_a_challenge_for_the_other_drm_system() -> None:
assert "not a playready device" in answer["error"]
-def attached_channel(bridge: InputBridge) -> list[Any]:
- """Attach a session channel that takes every ask; the asks it took."""
- offered: list[Any] = []
- bridge.channel = SimpleNamespace(attached=True, offer=lambda ask: offered.append(ask) or True) # type: ignore[assignment]
- return offered
-
-
-def wait_offered(offered: list[Any]) -> Any:
- assert wait_until(lambda: offered, 5), "the bridge offered no ask to the channel"
- return offered[0]
-
-
-def test_a_cdm_call_after_authentication_leaves_the_status_alone() -> None:
- bridge = InputBridge()
- bridge.login_status = AuthStatus.AUTHENTICATED
- offered = attached_channel(bridge)
- result: list[dict] = []
- worker = threading.Thread(target=lambda: result.append(bridge.request_cdm({"op": "challenge"}, timeout=5)))
- worker.start()
- ask = wait_offered(offered)
- assert ask.cdm_call == {"op": "challenge"}
-
- assert bridge.answer(ask.id, json.dumps({"session": "s", "challenge": "Yw=="}))
- worker.join(timeout=2)
-
- assert result == [{"session": "s", "challenge": "Yw=="}]
- assert bridge.login_status is AuthStatus.AUTHENTICATED
- assert bridge.get_pending_ask() is None
-
-
-@pytest.mark.parametrize(
- ("answer", "message"),
- [("not json", "update unshackle"), (json.dumps({"error": "no local CDM is loaded"}), "no local CDM")],
-)
-def test_a_bad_or_refused_answer_stops_the_service(answer: str, message: str) -> None:
- bridge = InputBridge()
- threading.Timer(0.1, lambda: bridge.submit_response(answer)).start()
- with pytest.raises(RuntimeError, match=message):
- bridge.request_cdm({"op": "keys"}, timeout=5)
-
-
def test_the_overlay_keeps_only_the_client_identity() -> None:
server = {"esn": "SERVER", "Kpe": "server-kpe", "esn_map": {7000: "server-template"}, "endpoints": {"a": "b"}}
merged, identity = handlers.client_config_overlay(
@@ -214,45 +167,6 @@ def test_a_relaying_client_gets_a_stand_in_with_its_device_facts(monkeypatch: py
assert built["params"]["client_identity"] is True
-def test_an_answered_call_is_no_longer_pending_before_the_service_wakes(monkeypatch: pytest.MonkeyPatch) -> None:
- bridge = InputBridge()
- release = threading.Event()
- real_open = bridge._open
-
- def open_slowly(prompt: str, cdm_call: Any = None) -> Any:
- ask = real_open(prompt, cdm_call)
- real_wait = ask.answered.wait
-
- def slow_wait(timeout: float) -> bool:
- release.wait(5) # hold the service thread asleep after the answer arrives
- return real_wait(timeout)
-
- ask.answered.wait = slow_wait # type: ignore[method-assign]
- return ask
-
- monkeypatch.setattr(bridge, "_open", open_slowly)
- worker = threading.Thread(target=lambda: bridge.request_cdm({"op": "challenge"}, timeout=5))
- worker.start()
- for _ in range(100):
- if bridge.get_pending_ask():
- break
- time.sleep(0.01)
-
- assert bridge.submit_response(json.dumps({"session": "s", "challenge": "Yw=="}))
- assert bridge.get_pending_ask() is None
- assert bridge.submit_response("{}") is False
- release.set()
- worker.join(timeout=2)
-
-
-def test_a_lent_server_device_marks_the_stand_in() -> None:
- server = object()
- cdm = ClientDeviceCdm(DirectBridge(FakeWidevineCdm()), is_playready=True, server_device=lambda: server)
- assert cdm.lent is False
- assert cdm.lend_server_device() is server
- assert cdm.lent is True
-
-
def test_a_lent_device_session_never_licenses_live() -> None:
refusal = server_keys.live_licence_refusal(session_entry(licensing=LicensingMode(Licensor.LENT_DEVICE)), object())
assert refusal is not None
@@ -399,13 +313,6 @@ def test_a_server_device_option_takes_the_first_listed_device_of_a_dual_entry(
assert devices == [loaded]
-@pytest.mark.parametrize(
- ("value", "requested"), [(True, True), ("false", False), ("0", False), ("yes", True), (False, False)]
-)
-def test_a_server_device_option_counts_as_the_service_casts_it(value: Any, requested: bool) -> None:
- assert handlers.server_device_requested(ServerSideService, {"service_params": {"server_side": value}}) is requested
-
-
@pytest.mark.parametrize(("server_side", "cdm_type"), [(True, None), (False, "widevine")])
def test_a_track_listing_with_a_server_device_option_ignores_the_client_system(
monkeypatch: pytest.MonkeyPatch, server_side: bool, cdm_type: str | None
@@ -426,13 +333,6 @@ def test_a_track_listing_with_a_server_device_option_ignores_the_client_system(
assert loaded == [cdm_type]
-def test_a_client_map_entry_replaces_the_server_entry_of_the_same_number() -> None:
- merged, _ = handlers.client_config_overlay(
- {"esn_map": {4464: "server-template", 7000: "other"}}, ("esn_map",), {"esn_map": {"4464": "client-template"}}
- )
- assert merged["esn_map"] == {7000: "other", "4464": "client-template"}
-
-
def lent_device_session() -> Any:
return session_entry(
licensing=LicensingMode(Licensor.LENT_DEVICE),
@@ -495,45 +395,6 @@ def test_a_lent_device_without_the_vault_grant_asks_the_server_for_no_key() -> N
svc.license_track(track, None)
-@pytest.mark.parametrize("params", [{}, {"quality": None}])
-def test_every_service_context_defaults_quality_to_a_list(params: Any) -> None:
- parent = served_context(ContextData(config={}, cdm=None, proxy_providers=[]), served_plan(params), {})
- assert parent.params["quality"] == []
-
-
-def test_a_call_no_client_fetches_fails_fast_and_restores_the_status() -> None:
- bridge = InputBridge()
- bridge.login_status = AuthStatus.AUTHENTICATED
- started = time.monotonic()
- with pytest.raises(TimeoutError, match="none is listening"):
- bridge.request_cdm({"op": "challenge"}, timeout=30, pickup=0.2)
- assert time.monotonic() - started < 5
- assert bridge.login_status is AuthStatus.AUTHENTICATED
- assert bridge.get_pending_ask() is None
-
-
-def test_a_call_the_channel_took_gets_the_full_answer_window() -> None:
- bridge = InputBridge()
- offered = attached_channel(bridge)
- result: list[dict] = []
- worker = threading.Thread(target=lambda: result.append(bridge.request_cdm({"op": "keys"}, timeout=5, pickup=0.3)))
- worker.start()
- ask = wait_offered(offered)
- time.sleep(0.6) # past the pickup window: a call the channel took must still wait for its answer
- assert bridge.answer(ask.id, json.dumps({"keys": []}))
- worker.join(timeout=2)
- assert result == [{"keys": []}]
-
-
-def test_cancel_wakes_a_call_waiting_for_a_client() -> None:
- bridge = InputBridge()
- threading.Timer(0.1, bridge.cancel).start()
- started = time.monotonic()
- with pytest.raises(RuntimeError, match="cancelled"):
- bridge.request_cdm({"op": "challenge"}, timeout=30, pickup=20)
- assert time.monotonic() - started < 5
-
-
@pytest.mark.parametrize(
("fields", "forbidden"),
[
diff --git a/tests/remote/unit/test_client_preferences.py b/tests/remote/unit/test_client_preferences.py
index 8736956ab..60c949001 100644
--- a/tests/remote/unit/test_client_preferences.py
+++ b/tests/remote/unit/test_client_preferences.py
@@ -74,15 +74,6 @@ def test_preferences_alone_are_no_identity(monkeypatch: pytest.MonkeyPatch) -> N
assert built["keys"]["client_identity"] is False
-def test_a_service_that_lists_preferences_as_an_identity_still_merges_them(monkeypatch: pytest.MonkeyPatch) -> None:
- class Listed:
- CLIENT_CONFIG = ("esn", "preferences")
-
- built = launched(monkeypatch, Licensor.SERVER_CDM, {"preferences": {"language": "ja-JP"}}, Listed)
-
- assert built["config"]["preferences"] == {"language": "ja-JP", "profile": 0}
-
-
def test_a_lent_device_keeps_the_client_preferences(monkeypatch: pytest.MonkeyPatch) -> None:
built = launched(monkeypatch, Licensor.CLIENT_DEVICE, {"preferences": CLIENT, "esn": "CLIENT"}, Identity)
@@ -107,14 +98,6 @@ def test_ill_formed_preferences_are_refused(monkeypatch: pytest.MonkeyPatch, sup
launched(monkeypatch, Licensor.SERVER_CDM, supplied)
-def test_the_identity_rules_stay_as_they_are() -> None:
- merged, identity = handlers.client_config_overlay({"esn": "SERVER", "Kph": "k"}, ("esn", "Kph"), {"esn": "CLIENT"})
-
- assert (merged, identity) == ({"esn": "CLIENT"}, True)
- with pytest.raises(APIError):
- handlers.client_config_overlay({}, ("esn",), {"esn": True})
-
-
def test_the_client_reads_its_own_preferences(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
diff --git a/tests/remote/unit/test_client_presence.py b/tests/remote/unit/test_client_presence.py
index 802824490..27487b258 100644
--- a/tests/remote/unit/test_client_presence.py
+++ b/tests/remote/unit/test_client_presence.py
@@ -6,27 +6,22 @@ The clients are real ones, and the silence is a moved clock: the limits are the
from __future__ import annotations
import asyncio
-import contextlib
-import math
import subprocess
import time
import uuid
-from collections.abc import Callable, Iterator
+from collections.abc import Callable
from pathlib import Path
-from threading import Event
from types import SimpleNamespace
from typing import Any
import aiohttp
import pytest
import requests
-from aiohttp import web
from tests.remote.unit.test_remote_loopback import server # noqa: F401
from tests.remote.unit.test_remote_loopback import (
KEY,
OTHER_KEY,
- StubService,
make_client,
on_loop,
)
@@ -43,28 +38,21 @@ from tests.remote.unit.test_session_lifetime import ( # noqa: F401
from tests.remote.unit.test_tunnel import wait_until
from unshackle.core.api import session_store
from unshackle.core.api.client_presence import (
- AWAY_LIMIT,
FIRST_CONTACT_LIMIT,
LEFT_LIMIT,
- ClientPresence,
ClientState,
)
-from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
-from unshackle.core.api.session_store import SessionEntry, SessionStore
+from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT
+from unshackle.core.api.session_store import SessionEntry
from unshackle.core.config import config
-from unshackle.core.remote_channel import CDM_CLOSE_TIMEOUT, RECONNECT_DELAY, RECONNECT_MAX
-from unshackle.core.remote_lifetime import END_TIMEOUT
from unshackle.core.remote_protocol import (
CHANNEL_ROUTE,
- CHANNEL_SESSION_GONE,
SESSION_CREATE_ROUTE,
SESSION_ROUTE,
TITLES_ROUTE,
APIErrorCode,
AuthStatus,
)
-from unshackle.core.remote_service import RemoteError
-from unshackle.core.tunnel import HEARTBEAT
pytestmark = pytest.mark.unit
@@ -138,100 +126,6 @@ def killed(server: SimpleNamespace, client: Start) -> Callable[[], SessionEntry]
return run
-def test_the_sweep_ends_the_session_of_a_killed_client_at_the_away_limit(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- killed: Callable[..., SessionEntry],
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- assert session_store.SWEEP_INTERVAL <= 5
- monkeypatch.setattr(session_store, "SWEEP_INTERVAL", 0.02)
- entry = killed()
- directory = store_token(entry)
- on_loop(server, session_store.get_session_store().start_cleanup_loop())
- silent_for(entry, AWAY_LIMIT - 5)
- assert not wait_until(lambda: sessions() == [], 0.5)
- silent_for(entry, AWAY_LIMIT + 1)
- assert wait_until(lambda: sessions() == [] and not directory.exists(), DEADLINE)
-
-
-def test_the_login_of_a_killed_client_stops_at_the_away_limit(
- server: SimpleNamespace, # noqa: F811
- killed: Callable[..., SessionEntry],
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- stopped = Event()
-
- def wait_for_approval(stub: StubService, cookies: Any, credential: Any) -> None:
- try:
- while not stopped.wait(0.01):
- stub._input_bridge.ensure_active()
- finally:
- stopped.set()
-
- monkeypatch.setattr(StubService, "authenticate", wait_for_approval)
- entry = killed(logs_in=False)
- assert not stopped.is_set()
- assert ends_after(server, entry, AWAY_LIMIT)
- assert stopped.wait(DEADLINE)
- assert wait_until(lambda: not session_store.get_session_store()._logins, DEADLINE)
-
-
-def test_a_request_of_a_killed_client_does_not_keep_its_session(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- killed: Callable[..., SessionEntry],
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """The request holds the lock, and its end is no sign of the client that asked for it."""
- release = Event()
- monkeypatch.setitem(StubService.hooks, "titles", lambda stub: release.wait(DEADLINE))
- events: list[str] = []
- monkeypatch.setattr(session_store, "_publish", lambda action, *a, **k: events.append(action))
- replies: list[Any] = []
-
- def ask(entry: SessionEntry) -> None:
- replies.append(in_thread(lambda: get(server, TITLES_ROUTE, entry)))
- assert wait_until(entry.lock.locked, DEADLINE)
-
- try:
- entry = killed(before=ask)
- assert entry.lock.locked()
- assert ends_after(server, entry, AWAY_LIMIT)
- with pytest.raises(RuntimeError, match="cancelled"):
- entry.input_bridge.ensure_active() # type: ignore[union-attr]
- finally:
- release.set()
- assert replies[0]().status_code == 200
- assert entry.presence.silence > AWAY_LIMIT
- assert events[-1] == "delete"
-
-
-def test_a_request_that_waits_for_the_lock_does_not_start_after_the_end(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
-) -> None:
- release = Event()
- started: list[StubService] = []
- StubService.hooks["titles"] = lambda stub: (started.append(stub), release.wait(DEADLINE)) and None
- session_id = str(uuid.uuid4())
- assert create(server.url, session_id).status_code == 200
- (entry,) = sessions()
- assert logged_in(entry)
- entry.presence.attached()
- try:
- first = in_thread(lambda: get(server, TITLES_ROUTE, entry))
- assert wait_until(lambda: len(started) == 1, DEADLINE)
- second = in_thread(lambda: get(server, TITLES_ROUTE, entry))
- assert wait_until(lambda: bool(entry.lock._waiters), DEADLINE)
- on_loop(server, session_store.get_session_store().delete(session_id))
- finally:
- release.set()
- assert first().status_code == 200
- assert second().json()["error_code"] == APIErrorCode.SESSION_NOT_FOUND
- assert len(started) == 1
-
-
def test_a_delete_after_the_close_of_the_channel_returns_the_login_cache(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
@@ -266,51 +160,6 @@ def test_a_session_ends_when_no_delete_follows_the_close_of_the_channel(
service.close()
-@contextlib.contextmanager
-def half_open_gateway(server: SimpleNamespace) -> Iterator[str]: # noqa: F811
- """A gateway that passes the channel upgrade to the server, then drops it and answers the client 502."""
-
- async def forward(request: web.Request) -> web.StreamResponse:
- async with aiohttp.ClientSession(auto_decompress=False) as http:
- headers = {k: v for k, v in request.headers.items() if k.startswith("X-") or k == "Content-Type"}
- if request.path.endswith("/channel"):
- async with http.ws_connect(server.url + request.path, headers=headers) as ws:
- await ws.receive()
- ws._response.connection.transport.abort() # type: ignore[union-attr]
- return web.Response(status=502)
- url, body = server.url + request.path_qs, await request.read()
- async with http.request(request.method, url, headers=headers, data=body) as reply:
- return web.Response(status=reply.status, body=await reply.read(), content_type="application/json")
-
- async def start() -> web.AppRunner:
- app = web.Application()
- app.router.add_route("*", "/{path:.*}", forward)
- runner = web.AppRunner(app)
- await runner.setup()
- await web.TCPSite(runner, "127.0.0.1", 0).start()
- return runner
-
- runner = on_loop(server, start())
- try:
- yield f"http://127.0.0.1:{runner.addresses[0][1]}"
- finally:
- on_loop(server, runner.cleanup())
-
-
-def test_a_refused_channel_upgrade_stops_the_client_with_one_line(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
-) -> None:
- with half_open_gateway(server) as url:
- service = make_client(url)
- try:
- with pytest.raises(RemoteError, match=r"^The remote server at \S+ refused the session channel: HTTP 502$"):
- service.authenticate()
- finally:
- service.close()
- assert wait_until(lambda: sessions() == [], DEADLINE)
-
-
Socket = aiohttp.ClientWebSocketResponse
@@ -332,92 +181,6 @@ def channel(server: SimpleNamespace, logins: list[Any]) -> Callable[..., None]:
return run
-async def close_code(socket: Socket) -> Any:
- """Read until the server closes the socket; its close code."""
- while (msg := await socket.receive()).type is aiohttp.WSMsgType.TEXT:
- pass
- return msg.data
-
-
-async def a_state_is(entry: SessionEntry, state: ClientState) -> bool:
- return await asyncio.to_thread(state_is, entry, state)
-
-
-@pytest.mark.parametrize(
- ("close", "state"),
- [
- (lambda ws: ws.close(code=1000), ClientState.LEFT),
- (lambda ws: ws.close(code=1001), ClientState.AWAY),
- (lambda ws: ws.send_frame(b"", aiohttp.WSMsgType.CLOSE), ClientState.AWAY),
- ],
- ids=["1000", "1001", "no-code"],
-)
-def test_only_a_close_with_1000_of_the_client_is_a_leave(
- channel: Callable[..., None], close: Callable[[Socket], Any], state: ClientState
-) -> None:
- async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
- socket = await connect()
- assert await a_state_is(entry, ClientState.PRESENT)
- await close(socket)
- assert await a_state_is(entry, state)
- await socket.close()
-
- channel(check)
-
-
-def test_a_replaced_socket_does_not_mark_the_new_one_away(
- server: SimpleNamespace, # noqa: F811
- channel: Callable[..., None],
-) -> None:
- async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
- first = await connect()
- assert await a_state_is(entry, ClientState.PRESENT)
- old = entry.channel.ws
- second = await connect()
- assert await close_code(first) == 1000
- await first.close()
- assert await asyncio.to_thread(wait_until, lambda: old is not None and old.close_code is not None, DEADLINE)
- assert entry.presence.state is ClientState.PRESENT
- assert await asyncio.to_thread(stays, server, entry)
- await second.close()
- assert await a_state_is(entry, ClientState.LEFT)
-
- channel(check)
-
-
-def test_the_end_of_the_session_is_no_leave(server: SimpleNamespace, channel: Callable[..., None]) -> None: # noqa: F811
- async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
- socket = await connect()
- assert await a_state_is(entry, ClientState.PRESENT)
- assert (await asyncio.to_thread(delete, server.url, entry.session_id)).ok
- assert await close_code(socket) == CHANNEL_SESSION_GONE
- assert await a_state_is(entry, ClientState.AWAY)
-
- channel(check)
-
-
-def test_a_new_channel_or_a_request_after_the_leave_is_a_client_that_still_works(
- server: SimpleNamespace, # noqa: F811
- channel: Callable[..., None],
-) -> None:
- """A client that gives up on a slow channel closes it with 1000, then opens a new one or sends a request."""
-
- async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
- await (await connect()).close()
- assert await a_state_is(entry, ClientState.LEFT)
- socket = await connect()
- assert await a_state_is(entry, ClientState.PRESENT)
- await socket.close()
- assert await a_state_is(entry, ClientState.LEFT)
- assert (await asyncio.to_thread(get, server, SESSION_ROUTE, entry, OTHER_KEY)).status_code == 403
- assert entry.presence.state is ClientState.LEFT
- assert (await asyncio.to_thread(get, server, SESSION_ROUTE, entry)).ok
- assert entry.presence.state is ClientState.AWAY
- assert await asyncio.to_thread(ends_after, server, entry, AWAY_LIMIT)
-
- channel(check)
-
-
def test_a_client_that_never_comes_back_for_its_session_loses_it(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
@@ -444,48 +207,3 @@ def test_a_client_without_the_session_channel_is_refused(
assert titles.status_code == 426 and titles.json()["error_code"] == APIErrorCode.CLIENT_OUTDATED
assert get(server, SESSION_ROUTE, entry).ok
assert entry.presence.state is ClientState.AWAITED
-
-
-@pytest.mark.parametrize("busy", [False, True], ids=["idle", "busy"])
-@pytest.mark.parametrize("ttl_seconds", [30, 100, 300, 1200, 3600])
-async def test_no_session_stays_for_longer_than_its_ttl_lets_it(
- monkeypatch: pytest.MonkeyPatch, ttl_seconds: int, busy: bool
-) -> None:
- """Work for a client keeps its session past a short TTL, as before, until the client is gone."""
- monkeypatch.setitem(config.serve, "session_ttl", ttl_seconds)
- store = SessionStore()
- entry = await store.create("EXAMPLE", None, input_bridge=InputBridge())
- entry.input_bridge.login_status = AuthStatus.AUTHENTICATED # type: ignore[union-attr]
- entry.presence.detached(left=False)
- if busy:
- await entry.lock.acquire()
- limit = max(180, ttl_seconds / 2) if busy else min(ttl_seconds, max(180, ttl_seconds / 2))
- for silence, count in ((limit - 5, 0), (limit + 1, 1)):
- silent_for(entry, silence)
- entry.idle_since = entry.presence.seen_at
- assert await store.cleanup_expired() == count
-
-
-def test_each_limit_is_longer_than_the_silence_of_a_client_that_still_works() -> None:
- """The numbers of the client: a ping is lost, the DELETE is late, or the create reply never arrives."""
- detection = HEARTBEAT * 1.5
- delete_arrives = 5 + CDM_CLOSE_TIMEOUT + 3 * END_TIMEOUT
- reconnects = sum(min(RECONNECT_DELAY * 2**n, RECONNECT_MAX) for n in range(6))
- assert 120 + END_TIMEOUT < FIRST_CONTACT_LIMIT <= 150
- assert detection + reconnects < AWAY_LIMIT <= 180
- assert max(delete_arrives, reconnects) < LEFT_LIMIT <= 90
-
-
-def test_a_client_that_is_present_has_no_limit() -> None:
- presence = ClientPresence()
- presence.attached()
- assert presence.limit(TTL) == math.inf
-
-
-@pytest.mark.parametrize("left", [True, False])
-def test_the_loss_of_the_channel_restarts_the_clock(left: bool) -> None:
- presence = ClientPresence()
- presence.attached()
- presence.seen_at -= 10 * TTL
- presence.detached(left)
- assert presence.silence < 5 and not presence.gone(TTL)
diff --git a/tests/remote/unit/test_compression.py b/tests/remote/unit/test_compression.py
index 2c494b94c..be8227945 100644
--- a/tests/remote/unit/test_compression.py
+++ b/tests/remote/unit/test_compression.py
@@ -35,22 +35,6 @@ def test_skips_when_client_does_not_accept_gzip() -> None:
assert resp.body == body_json or len(resp.body) >= len(body_json) - 8
-def test_skips_when_body_below_threshold() -> None:
- async def handler(req): # noqa: ARG001
- return web.json_response({"hi": "x"})
-
- resp = run(compression_middleware(_FakeReq(), handler))
- assert resp.headers.get("Content-Encoding") != "gzip"
-
-
-def test_skips_non_json_response() -> None:
- async def handler(req): # noqa: ARG001
- return web.Response(body=b"x" * 4096, content_type="text/plain")
-
- resp = run(compression_middleware(_FakeReq(), handler))
- assert resp.headers.get("Content-Encoding") != "gzip"
-
-
def test_compresses_large_json_when_accepted() -> None:
big = {"data": "x" * 4096}
@@ -62,25 +46,3 @@ def test_compresses_large_json_when_accepted() -> None:
decompressed = gzip.decompress(resp.body)
assert json.loads(decompressed) == big
assert resp.content_length == len(resp.body)
-
-
-def test_compresses_a_body_over_the_thread_size_on_a_worker_thread(monkeypatch) -> None:
- from unshackle.core.api import compression
-
- threaded = []
- real = asyncio.to_thread
-
- async def to_thread(fn, *args, **kwargs):
- threaded.append(fn)
- return await real(fn, *args, **kwargs)
-
- monkeypatch.setattr(compression.asyncio, "to_thread", to_thread)
- monkeypatch.setattr(compression, "GZIP_THREAD_SIZE", 1024)
- big = {"data": "x" * 4096}
-
- async def handler(req): # noqa: ARG001
- return web.json_response(big)
-
- resp = run(compression_middleware(_FakeReq(), handler))
- assert threaded == [gzip.compress]
- assert json.loads(gzip.decompress(resp.body)) == big
diff --git a/tests/remote/unit/test_dashboard.py b/tests/remote/unit/test_dashboard.py
index af4daf1eb..dc5c41e25 100644
--- a/tests/remote/unit/test_dashboard.py
+++ b/tests/remote/unit/test_dashboard.py
@@ -4,10 +4,8 @@ from __future__ import annotations
import asyncio
import logging
-import sys
import threading
import uuid
-from collections.abc import Callable
from datetime import UTC, datetime, timedelta
import pytest
@@ -75,36 +73,6 @@ def test_ring_since_and_level() -> None:
assert [r["msg"] for r in ring.since(0, "warning")] == ["m3"]
-def _hammer(write: Callable[[], object], read: Callable[[], object]) -> None:
- """Call ``read`` on this thread while four threads call ``write`` in a loop."""
- stop = threading.Event()
-
- def spin() -> None:
- while not stop.is_set():
- write()
-
- old_interval = sys.getswitchinterval()
- sys.setswitchinterval(1e-6)
- threads = [threading.Thread(target=spin, daemon=True) for _ in range(4)]
- try:
- for t in threads:
- t.start()
- for _ in range(300):
- read()
- finally:
- stop.set()
- sys.setswitchinterval(old_interval)
- for t in threads:
- t.join()
-
-
-def test_bus_since_survives_concurrent_publish() -> None:
- local = EventBus(history=5000)
- _hammer(lambda: local.publish("log", {}), lambda: local.since(0))
- seqs = [item["seq"] for item in local.history]
- assert seqs == list(range(seqs[0], seqs[0] + len(seqs)))
-
-
def test_bus_publish_reenters_its_lock() -> None:
local = EventBus()
@@ -119,12 +87,6 @@ def test_bus_publish_reenters_its_lock() -> None:
assert [item["seq"] for item in local.since(0)] == [1]
-def test_ring_since_survives_concurrent_emit() -> None:
- ring = RingLogHandler(maxlen=5000)
- record = logging.LogRecord("test.ring", logging.INFO, __file__, 0, "m", None, None)
- _hammer(lambda: ring.handle(record), lambda: ring.since(0))
-
-
def test_ring_masks_host_paths_and_secrets_in_records() -> None:
"""The ring feeds both /api/logs and the SSE stream, so it must mask on the way in."""
from pathlib import Path
@@ -362,28 +324,6 @@ async def test_dashboard_log_read_does_not_touch_the_session() -> None:
assert entry.last_accessed > stale
-async def test_dashboard_services_states(aiohttp_client, dashboard_cfg, monkeypatch) -> None:
- from unshackle.core import services as services_module
-
- tags = services_module.Services.get_tags()
- if not tags:
- pytest.skip("no services installed")
- staged, failed = tags[0], tags[-1]
- monkeypatch.setattr(services_module, "PENDING", {staged})
- monkeypatch.setattr(services_module, "PENDING_SINCE", {staged: 1756908900.0})
- monkeypatch.setattr(services_module, "LOAD_ERRORS", [f"{failed}: failed to import - ImportError: boom"])
-
- client = await aiohttp_client(make_app())
- rows = {
- r["tag"]: r
- for r in await (await client.get("/api/dashboard/services", headers={"X-Secret-Key": "dash-secret"})).json()
- }
- assert rows[failed]["state"] == "failed" and "boom" in rows[failed]["error"]
- if staged != failed:
- assert rows[staged]["state"] == "staged" and rows[staged]["staged_since"] == 1756908900.0
- assert all(r["state"] == "loaded" for t, r in rows.items() if t not in (staged, failed))
-
-
async def test_dashboard_services_lists_only_configured(aiohttp_client, dashboard_cfg, monkeypatch) -> None:
from pathlib import Path
@@ -411,26 +351,6 @@ async def test_dashboard_services_lists_only_configured(aiohttp_client, dashboar
assert {r["tag"] for r in everything} == {"AAA", "BBB", "CCC"}
-async def test_status_reports_no_session_limit(aiohttp_client, dashboard_cfg, monkeypatch) -> None:
- monkeypatch.setitem(config.serve, "max_sessions", None)
- client = await aiohttp_client(make_app())
- body = await (await client.get("/api/dashboard/status", headers={"X-Secret-Key": "dash-secret"})).json()
- assert body["max_sessions"] is None
-
-
-async def test_dashboard_health(aiohttp_client, dashboard_cfg, monkeypatch) -> None:
- from unshackle.core.api import handlers
-
- monkeypatch.setattr(config, "key_vaults", [])
- monkeypatch.setattr(config, "proxy_providers", {})
- handlers._health_cache.clear()
- client = await aiohttp_client(make_app())
- body = await (await client.get("/api/dashboard/health", headers={"X-Secret-Key": "dash-secret"})).json()
- assert body["status"] in {"ok", "degraded", "failing"}
- assert {"id", "label", "status", "detail", "ms"} <= set(body["checks"][0])
- assert all(c["status"] in {"ok", "warn", "fail"} for c in body["checks"])
-
-
async def test_unknown_key_on_open_route_does_not_grow_key_stats(aiohttp_client, monkeypatch) -> None:
"""Counters keyed by the raw header of an unknown key would grow without bound."""
monkeypatch.setitem(config.serve, "users", {"real": {}})
@@ -480,64 +400,6 @@ def test_health_check_masks_vault_secrets() -> None:
assert "hunter2" not in detail and detail.startswith("ConnectionError")
-async def test_health_vault_probe_tolerates_api_vault_rejecting_the_probe(aiohttp_server, monkeypatch) -> None:
- """An API vault answers code 3/4 to a dummy service or KID; that proves it is up, not down."""
- from unshackle.core.api.handlers import run_health_checks
-
- async def reject(request: web.Request) -> web.Response:
- return web.json_response({"code": 4, "message": "bad kid"})
-
- vault_app = web.Application()
- vault_app.router.add_get("/{tail:.*}", reject)
- server = await aiohttp_server(vault_app)
- monkeypatch.setattr(
- config, "key_vaults", [{"type": "API", "name": "t", "uri": str(server.make_url("/")), "token": "tok"}]
- )
- monkeypatch.setattr(config, "proxy_providers", {})
- checks = {c["id"]: c for c in await asyncio.to_thread(run_health_checks)}
- assert checks["vault:t"]["status"] == "ok", checks["vault:t"]
-
-
-def test_health_warns_without_a_sqlite_vault_to_store_flags(monkeypatch, tmp_path) -> None:
- from unshackle.core.api.handlers import run_health_checks
-
- monkeypatch.setattr(config, "proxy_providers", {})
- monkeypatch.setattr(
- config, "key_vaults", [{"type": "API", "name": "shared", "uri": "http://127.0.0.1:9", "token": "t"}]
- )
- checks = {c["id"]: c for c in run_health_checks()}
- assert (checks["bad_keys"]["status"], checks["vault:shared"]["status"]) == ("warn", "fail")
-
- monkeypatch.setattr(config, "key_vaults", [{"type": "SQLite", "name": "local", "path": str(tmp_path / "k.db")}])
- checks = {c["id"]: c for c in run_health_checks()}
- assert checks["bad_keys"]["status"] == "ok" and "local" in checks["bad_keys"]["detail"]
- assert checks["vault:local"]["status"] == "ok"
-
- monkeypatch.setattr(config, "key_vaults", [])
- assert {c["id"]: c for c in run_health_checks()}["bad_keys"]["status"] == "ok"
-
-
-def test_health_proxy_probe_reports_a_provider_that_fails_to_build(monkeypatch) -> None:
- from unshackle.core.api.handlers import run_health_checks
-
- monkeypatch.setattr(config, "key_vaults", [])
- monkeypatch.setattr(config, "proxy_providers", {"nordvpn": {"username": "u"}}) # missing password
- checks = {c["id"]: c for c in run_health_checks()}
- assert checks["proxies"]["status"] == "fail" and "TypeError" in checks["proxies"]["detail"]
-
-
-def test_health_proxy_probe_stays_out_of_the_log_ring(monkeypatch, caplog) -> None:
- """Rendering a provider fetches its server catalog, and the panel refreshes every 30 s."""
- from unshackle.core.api.handlers import run_health_checks
-
- monkeypatch.setattr(config, "key_vaults", [])
- monkeypatch.setattr(config, "proxy_providers", {"basic": {"us": "http://user:pass@host:8080"}})
- with caplog.at_level(logging.INFO, logger="proxies"):
- checks = {c["id"]: c for c in run_health_checks()}
- assert checks["proxies"]["status"] == "ok" and "Basic" in checks["proxies"]["detail"]
- assert [r.message for r in caplog.records if r.name == "proxies"] == []
-
-
async def test_health_vault_checks_are_told_apart_by_name(aiohttp_server, monkeypatch) -> None:
"""Two vaults of one type used to answer under the same id and the same label."""
from unshackle.core.api.handlers import run_health_checks
@@ -685,41 +547,6 @@ def test_health_proxy_probe_masks_provider_credentials(monkeypatch) -> None:
assert "nordpass1234" not in detail and "proxypass1" not in detail
-async def test_health_probe_timeout_reports_what_finished(aiohttp_client, dashboard_cfg, monkeypatch) -> None:
- """A vault that accepts the connection then stalls must not hang the panel forever."""
- from unshackle.core.api import handlers
-
- released = threading.Event()
-
- def stalling_probe(checks=None):
- checks = [] if checks is None else checks
- checks.append({"id": "ffmpeg", "label": "ffmpeg", "status": "ok", "detail": "7.1", "ms": 1.0})
- released.wait(6) # the stalled vault; the deadline fires long before this returns
- checks.append({"id": "never", "label": "never", "status": "ok", "detail": "", "ms": 0.0})
- return checks
-
- handlers._health_cache.clear()
- monkeypatch.setattr(handlers, "run_health_checks", stalling_probe)
- monkeypatch.setattr(handlers, "HEALTH_PROBE_TIMEOUT", 1.0)
-
- client = await aiohttp_client(make_app())
- try:
- body = await (await client.get("/api/dashboard/health", headers={"X-Secret-Key": "dash-secret"})).json()
- finally:
- released.set() # an interpreter exit joins the probe thread, so do not leave it asleep
-
- ids = [c["id"] for c in body["checks"]]
- assert "ffmpeg" in ids, "the probe that finished before the deadline must survive"
- assert "never" not in ids
- assert body["status"] == "failing"
- timed_out = next(c for c in body["checks"] if c["id"] == "probe")
- assert timed_out["status"] == "fail" and "timed out" in timed_out["detail"]
-
- # The timeout is cached for the full TTL, so callers cannot stack up more stalled threads.
- assert (await client.get("/api/dashboard/health", headers={"X-Secret-Key": "dash-secret"})).status == 200
- assert handlers._health_cache["payload"]["status"] == "failing"
-
-
async def test_dashboard_services_carry_the_catalogue(aiohttp_client, dashboard_cfg, monkeypatch) -> None:
import enum
from pathlib import Path
diff --git a/tests/remote/unit/test_download_archive_api.py b/tests/remote/unit/test_download_archive_api.py
index 94e4c531a..5efaa0539 100644
--- a/tests/remote/unit/test_download_archive_api.py
+++ b/tests/remote/unit/test_download_archive_api.py
@@ -12,7 +12,6 @@ from unshackle.core.api import download_manager as dm
from unshackle.core.api import download_worker
from unshackle.core.api.job_channel import WorkerResult
from unshackle.core.config import config
-from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
PRESENT = [
{
@@ -56,11 +55,6 @@ def test_worker_takes_the_payload_scope_and_reports_already_present(monkeypatch,
assert json.loads(progress.read_text())["already_present"] == PRESENT
-def test_api_options_default_off():
- assert DEFAULT_DOWNLOAD_PARAMS["skip_existing"] is False
- assert DEFAULT_DOWNLOAD_PARAMS["force"] is False
-
-
def test_manager_uses_owner_scope_and_keeps_already_present_in_history(monkeypatch, tmp_path):
payloads = []
diff --git a/tests/remote/unit/test_download_gates_redaction.py b/tests/remote/unit/test_download_gates_redaction.py
index 546aa7903..429ae4c8b 100644
--- a/tests/remote/unit/test_download_gates_redaction.py
+++ b/tests/remote/unit/test_download_gates_redaction.py
@@ -4,7 +4,6 @@ and the secret redaction applied to job parameters and error/stderr fields."""
from __future__ import annotations
from datetime import datetime
-from pathlib import Path
import pytest
from aiohttp import web
@@ -44,10 +43,6 @@ def test_redact_parameters_masks_secrets_and_proxy_userinfo():
assert params["credential"] == "user:hunter2" # original dict not mutated
-def test_redact_parameters_masks_credentials_dict():
- assert redact_parameters({"credentials": {"default": "u:p"}})["credentials"] == "***"
-
-
def test_secret_values_includes_password_half_and_dict_values():
secrets = secret_values({"credential": "user:hunter2", "credentials": {"d": "alice:wonder"}})
assert "user:hunter2" in secrets # full credential
@@ -63,11 +58,6 @@ def test_redact_text_scrubs_credential_and_proxy_from_free_text():
assert "***" in out
-def test_redact_text_passthrough_without_secrets():
- assert _redact_text("plain error", {}) == "plain error"
- assert _redact_text(None, {}) is None
-
-
def test_to_dict_full_details_redacts_error_fields_and_parameters():
job = DownloadJob(
job_id="j1",
@@ -85,29 +75,6 @@ def test_to_dict_full_details_redacts_error_fields_and_parameters():
assert d["parameters"]["credential"] == "***"
-def test_to_dict_redacts_again_only_when_an_error_field_changes(monkeypatch):
- from unshackle.core.api import download_manager
-
- calls = []
- real = download_manager._redact_text
- monkeypatch.setattr(download_manager, "_redact_text", lambda text, *rest: calls.append(text) or real(text, *rest))
- job = DownloadJob(
- job_id="j1",
- status=JobStatus.FAILED,
- created_time=datetime(2026, 1, 1),
- service="EXAMPLE",
- title_id="t",
- parameters={"credential": "user:hunter2"},
- )
- job.error_message = "login failed for user:hunter2"
- job.to_dict(include_full_details=True)
- job.to_dict(include_full_details=True)
- assert len(calls) == 4
- job.error_message = "still failing for user:hunter2"
- assert "hunter2" not in job.to_dict(include_full_details=True)["error_message"]
- assert len(calls) == 8
-
-
class _PastGate(Exception):
"""Raised by the stubbed download manager to prove a request got past the gate."""
@@ -135,13 +102,6 @@ async def test_cdm_override_forbidden_by_default(stub_handler):
assert ei.value.error_code == APIErrorCode.FORBIDDEN
-async def test_cdm_override_allowed_when_enabled(stub_handler):
- stub_handler.setattr(handlers.config, "serve", {"cdm_overrides": True})
- # passing the gate reaches the stubbed Services.load, whose error is caught and returned as a response
- resp = await handlers.download_handler({"service": "EXAMPLE", "title_id": "t", "cdm": "dev"})
- assert isinstance(resp, web.Response)
-
-
async def test_cdm_override_allowlist_permits_only_named_device(stub_handler):
stub_handler.setattr(handlers.config, "serve", {"cdm_overrides": ["good"]})
assert isinstance(
@@ -165,14 +125,6 @@ async def test_credential_allowed_when_enabled(stub_handler):
assert isinstance(resp, web.Response)
-def test_range_validation_accepts_hdr10p_and_alias(monkeypatch):
- monkeypatch.setattr("unshackle.core.binaries.DoviTool", Path("dovi_tool"))
- # canonical "HDR10P" and back-compat "HDR10+" both pass; mixed casing too
- assert refusal({"range": ["HDR10P", "DV", "SDR"]}) is None
- assert refusal({"range": ["hdr10+"]}) is None
- assert refusal({"range": "HYBRID"}) is None
-
-
def test_range_validation_rejects_unknown_and_lists_hdr10p():
err = refusal({"range": ["HDR99"]})
assert err and "hdr10p" in err.lower() and "HDR99" in err
diff --git a/tests/remote/unit/test_download_manager.py b/tests/remote/unit/test_download_manager.py
index 6653a7725..d953decaa 100644
--- a/tests/remote/unit/test_download_manager.py
+++ b/tests/remote/unit/test_download_manager.py
@@ -7,15 +7,13 @@ cleanup/serialize); they do not exercise the actual subprocess download path.
from __future__ import annotations
import asyncio
-from collections.abc import Callable
-from contextlib import suppress
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
import pytest
-from unshackle.core.api.download_manager import DownloadJob, DownloadQueueManager, JobStatus, get_download_manager
+from unshackle.core.api.download_manager import DownloadJob, DownloadQueueManager, JobStatus
pytestmark = pytest.mark.unit
@@ -26,43 +24,6 @@ def manager() -> DownloadQueueManager:
return DownloadQueueManager(max_concurrent_downloads=2, job_retention_hours=24)
-@pytest.fixture
-def fake_worker(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Callable[[str], None]:
- """Make the manager spawn a worker script with this source; it imports the unshackle under test."""
- import os
-
- def use(source: str) -> None:
- worker = tmp_path / "worker.py"
- worker.write_text(source, encoding="utf-8")
- spawn = asyncio.create_subprocess_exec
- env = {**os.environ, "PYTHONPATH": str(Path(__file__).resolve().parents[3])}
-
- async def spawn_fake_worker(executable: str, *args: str, **kwargs: Any) -> Any:
- return await spawn(executable, str(worker), *args[2:], env=env, **kwargs)
-
- monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn_fake_worker)
-
- return use
-
-
-def test_create_job_returns_queued_job(manager: DownloadQueueManager) -> None:
- job = manager.create_job("EXAMPLE", "movie-123", profile="default")
- assert isinstance(job, DownloadJob)
- assert job.status is JobStatus.QUEUED
- assert job.service == "EXAMPLE"
- assert job.title_id == "movie-123"
- assert job.parameters == {"profile": "default"}
-
-
-def test_get_and_list_jobs(manager: DownloadQueueManager) -> None:
- a = manager.create_job("EXAMPLE", "a")
- b = manager.create_job("DEMO", "b")
- assert manager.get_job(a.job_id) is a
- assert manager.get_job("missing") is None
- listed = manager.list_jobs()
- assert {j.job_id for j in listed} == {a.job_id, b.job_id}
-
-
def test_to_dict_short_vs_full(manager: DownloadQueueManager) -> None:
job = manager.create_job("EXAMPLE", "t", profile="p")
short = job.to_dict()
@@ -82,24 +43,12 @@ def test_cancel_queued_job_sets_cancelled_and_signals_event(manager: DownloadQue
assert job.cancel_event.is_set()
-def test_cancel_unknown_job_returns_false(manager: DownloadQueueManager) -> None:
- assert manager.cancel_job("never-existed") is False
-
-
def test_cancel_completed_job_returns_false(manager: DownloadQueueManager) -> None:
job = manager.create_job("EXAMPLE", "t")
job.status = JobStatus.COMPLETED
assert manager.cancel_job(job.job_id) is False
-def test_cancel_downloading_job_signals(manager: DownloadQueueManager) -> None:
- job = manager.create_job("EXAMPLE", "t")
- job.status = JobStatus.DOWNLOADING
- assert manager.cancel_job(job.job_id) is True
- assert job.status is JobStatus.CANCELLED
- assert job.cancel_event.is_set()
-
-
def test_cleanup_old_jobs_drops_old_terminal_states(manager: DownloadQueueManager) -> None:
now = datetime.now()
old = now - timedelta(hours=48)
@@ -128,12 +77,6 @@ def test_cleanup_old_jobs_drops_old_terminal_states(manager: DownloadQueueManage
assert drop_old_failed.job_id not in remaining
-def test_get_download_manager_returns_singleton() -> None:
- a = get_download_manager()
- b = get_download_manager()
- assert a is b
-
-
async def test_busy_services_counts_a_live_remote_session() -> None:
from unshackle.core.api.download_manager import busy_services
from unshackle.core.api.session_store import get_session_store
@@ -147,16 +90,6 @@ async def test_busy_services_counts_a_live_remote_session() -> None:
assert "EXAMPLE" not in busy_services()
-def test_job_status_values() -> None:
- assert {s.value for s in JobStatus} == {
- "queued",
- "downloading",
- "completed",
- "failed",
- "cancelled",
- }
-
-
def test_api_sub_format_keeps_the_original_sentinel() -> None:
"""sub_format "original" keeps the source format, so the API cast must not turn it into a codec or None."""
from unshackle.commands.dl import dl
@@ -246,36 +179,6 @@ def test_perform_download_puts_the_lang_selection_in_the_service_ctx(
assert selection == expected
-def test_perform_download_passes_latest_episodes_to_dl_result(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- import click
-
- import unshackle.commands.dl as dl_module
- from unshackle.core.api import download_manager, handlers
- from unshackle.core.services import Services
-
- class FakeDl:
- cli = dl_module.dl.cli
-
- def __init__(self, ctx: click.Context, **kwargs: object) -> None:
- pass
-
- def result(self, **kwargs: object) -> None:
- raise _CapturedCtx(kwargs)
-
- class FakeService:
- cli = click.Command("svc", callback=lambda title: object())
-
- monkeypatch.setattr(dl_module, "dl", FakeDl)
- monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path))
- monkeypatch.setattr(Services, "load", staticmethod(lambda s: FakeService))
- monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
-
- with pytest.raises(_CapturedCtx) as exc:
- download_manager.perform_download("job-1", "EXAMPLE", "t1", {"latest_episodes": 3})
-
- assert exc.value.args[0]["latest_episodes"] == 3
-
-
def test_perform_download_gives_dl_the_defaults_for_null_and_empty_values(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
@@ -437,43 +340,6 @@ def test_a_prompt_discards_an_answer_sent_before_it(tmp_path: Path, monkeypatch:
assert exc_info.value.error_code is APIErrorCode.AUTH_FAILED # type: ignore[attr-defined]
-def test_concurrent_prompts_go_out_one_at_a_time(monkeypatch: pytest.MonkeyPatch) -> None:
- import json
- import os
- import sys
- import threading
- import time
- from types import SimpleNamespace
-
- from unshackle.core.api import download_worker
- from unshackle.core.console import prompt_user, set_prompt_handler
-
- read_fd, write_fd = os.pipe()
- monkeypatch.setattr(sys, "stdin", SimpleNamespace(fileno=lambda: read_fd))
- monkeypatch.setattr(download_worker, "AUTH_INPUT_TIMEOUT", 5.0)
- updates: list[dict] = []
- download_worker.relay_prompts(updates.append)
- results: list[str] = []
- askers = [threading.Thread(target=lambda p=p: results.append(prompt_user(p)), daemon=True) for p in ("A", "B")]
- try:
- for asker in askers:
- asker.start()
- time.sleep(0.2)
- assert len(updates) == 1
- for answer, prompts_sent in (("1", 1), ("2", 3)):
- deadline = time.monotonic() + 5
- while len(updates) < prompts_sent and time.monotonic() < deadline:
- time.sleep(0.01)
- os.write(write_fd, (json.dumps(answer) + "\n").encode("utf-8"))
- for asker in askers:
- asker.join(timeout=5)
- finally:
- set_prompt_handler(None)
- os.close(write_fd)
- assert sorted(results) == ["1", "2"]
- assert [u["input_prompt"] is None for u in updates] == [False, True, False, True]
-
-
def test_submit_input_writes_one_json_line_to_the_worker(manager: DownloadQueueManager) -> None:
import io
from types import SimpleNamespace
@@ -507,63 +373,6 @@ job_channel.write_result(result_path, job_channel.WorkerResult("success", answer
"""
-async def test_a_repeated_prompt_reaches_an_event_listener(
- fake_worker: Callable[[str], None], manager: DownloadQueueManager
-) -> None:
- """A re-prompt with the same text right after an answer must still publish an event."""
- import asyncio
-
- fake_worker(FAKE_PROMPT_WORKER)
- job = manager.create_job("EXAMPLE", "t")
- events = manager.subscribe(job.job_id)
- run = asyncio.create_task(manager.run_download_async(job))
-
- async def answer_next_prompt(answer: str) -> None:
- while True:
- event = await events.get()
- if event and event["data"]["input_prompt"]:
- assert manager.submit_input(job, answer) is True
- return
-
- await asyncio.wait_for(answer_next_prompt("111111"), timeout=20)
- await asyncio.wait_for(answer_next_prompt("222222"), timeout=20)
- assert await asyncio.wait_for(run, timeout=20) == ["111111", "222222"]
- assert job.input_prompt is None
-
-
-async def test_a_notice_reaches_the_job_and_an_event_listener(
- fake_worker: Callable[[str], None], manager: DownloadQueueManager
-) -> None:
- """The job carries the worker's notice while the worker waits, and drops it at the end."""
- import asyncio
-
- # The prompt holds the worker open until the test has seen the notice.
- source = FAKE_PROMPT_WORKER.replace("import prompt_user", "import prompt_user, show_notice").replace(
- 'answers = [prompt_user("Enter OTP"), prompt_user("Enter OTP")]',
- 'show_notice("Enter pair code ABCD", "https://login.example/pair")\n'
- 'answers = [prompt_user("Continue", "https://login.example/pair")]',
- )
- assert source.count("show_notice") == 2, "FAKE_PROMPT_WORKER changed; update the replacements"
- fake_worker(source)
- job = manager.create_job("EXAMPLE", "t")
- events = manager.subscribe(job.job_id)
- run = asyncio.create_task(manager.run_download_async(job))
-
- async def answer_after_notice() -> None:
- while True:
- event = await events.get()
- if event and event["data"]["input_prompt"]:
- assert event["data"]["notice"] == "Enter pair code ABCD"
- assert job.to_dict()["notice"] == "Enter pair code ABCD"
- assert event["data"]["qr"] == job.to_dict()["qr"] == "https://login.example/pair"
- assert manager.submit_input(job, "ok") is True
- return
-
- await asyncio.wait_for(answer_after_notice(), timeout=20)
- assert await asyncio.wait_for(run, timeout=20) == ["ok"]
- assert job.notice is None and job.qr is None
-
-
async def test_input_handler_rejects_bad_requests(
monkeypatch: pytest.MonkeyPatch, manager: DownloadQueueManager
) -> None:
@@ -601,22 +410,6 @@ sys.exit(download_worker.main(["worker"] + sys.argv[1:]))
"""
-async def test_a_failed_job_keeps_the_worker_error(
- fake_worker: Callable[[str], None], manager: DownloadQueueManager
-) -> None:
- """The job records the worker's traceback and error, not the parent's "Worker exited" wrapper."""
- import asyncio
-
- fake_worker(FAKE_FAILING_WORKER)
- job = manager.create_job("EXAMPLE", "t")
- with pytest.raises(Exception, match="Worker exited"):
- await asyncio.wait_for(manager.execute_download(job), timeout=60)
-
- assert job.status is JobStatus.FAILED
- assert "{}[[1]] = 2" in (job.error_traceback or "")
- assert not (job.error_details or "").startswith("Worker exited")
-
-
def test_client_job_view_hides_debug_fields_without_debug_api() -> None:
from types import SimpleNamespace
@@ -645,19 +438,6 @@ sys.exit(download_worker.main(["worker"] + sys.argv[1:]))
"""
-async def test_a_skip_written_just_before_the_worker_exits_reaches_the_job(
- fake_worker: Callable[[str], None], manager: DownloadQueueManager
-) -> None:
- import asyncio
-
- fake_worker(FAKE_SKIPPING_WORKER)
- job = manager.create_job("EXAMPLE", "t")
- with pytest.raises(Exception, match="Skipped all 2 titles"):
- await asyncio.wait_for(manager.run_download_async(job), timeout=20)
- assert job.skipped_titles == [{"title": "Show S01E02", "reason": "missing ko"}]
- assert job.to_dict()["skipped_titles"] == job.skipped_titles
-
-
def test_a_stopped_run_names_its_reason_in_the_job_error(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
import click
@@ -746,15 +526,6 @@ def test_a_download_error_keeps_the_code_its_raiser_named(
assert exc.value.error_code == (APIErrorCode.WORKER_ERROR if carrier == "none" else APIErrorCode.DRM_ERROR)
-async def _until(condition: Callable[[], bool], timeout: float = 10.0) -> None:
- """Wait for ``condition`` with a deadline."""
- loop = asyncio.get_running_loop()
- deadline = loop.time() + timeout
- while not condition():
- assert loop.time() < deadline, "condition not met before the deadline"
- await asyncio.sleep(0.01)
-
-
@pytest.fixture
def downloading(monkeypatch: pytest.MonkeyPatch, manager: DownloadQueueManager) -> Any:
"""A manager whose jobs download until cancelled, with no history file written."""
@@ -785,23 +556,6 @@ async def test_a_cancel_of_the_worker_task_ends_it_while_a_job_downloads(
assert job.completed_time is not None
-async def test_a_cancel_of_the_job_download_keeps_the_worker_running(
- manager: DownloadQueueManager, downloading: Any
-) -> None:
- worker = asyncio.create_task(manager.download_worker("w"))
- try:
- job = manager.create_job("EXAMPLE", "t")
- await asyncio.wait_for(downloading.wait(), timeout=10)
- manager._active_downloads[job.job_id].cancel()
- await _until(lambda: job.completed_time is not None)
- assert job.status is JobStatus.CANCELLED
- assert not worker.done()
- finally:
- worker.cancel()
- with suppress(asyncio.CancelledError):
- await worker
-
-
async def test_shutdown_cancels_every_job_and_ends_each_stream_on_its_terminal_event(
manager: DownloadQueueManager, downloading: Any
) -> None:
@@ -824,11 +578,3 @@ async def test_shutdown_cancels_every_job_and_ends_each_stream_on_its_terminal_e
assert events[-1] == "cancelled"
with pytest.raises(APIError):
manager.create_job("EXAMPLE", "v")
-
-
-async def test_the_shutdown_hook_makes_no_manager(monkeypatch: pytest.MonkeyPatch) -> None:
- from unshackle.core.api import download_manager
-
- monkeypatch.setattr(download_manager, "download_manager", None)
- await download_manager.shutdown_download_manager(object())
- assert download_manager.download_manager is None
diff --git a/tests/remote/unit/test_errors.py b/tests/remote/unit/test_errors.py
index c99d7fb7f..19103ab98 100644
--- a/tests/remote/unit/test_errors.py
+++ b/tests/remote/unit/test_errors.py
@@ -59,11 +59,6 @@ def test_api_error_default_http_status_per_code() -> None:
assert all(status < 500 for status in cases.values())
-def test_api_error_explicit_http_status_overrides_default() -> None:
- err = APIError(APIErrorCode.INVALID_INPUT, "x", http_status=418)
- assert err.http_status == 418
-
-
def test_build_error_response_from_api_error() -> None:
err = APIError(
APIErrorCode.SESSION_NOT_FOUND,
@@ -83,12 +78,6 @@ def test_build_error_response_from_api_error() -> None:
assert "timestamp" in body
-def test_build_error_response_retryable_flag() -> None:
- err = APIError(APIErrorCode.NETWORK_ERROR, "boom", retryable=True)
- body = _body(build_error_response(err))
- assert body["retryable"] is True
-
-
def test_build_error_response_from_generic_exception() -> None:
resp = build_error_response(RuntimeError("oops"))
assert resp.status == 422
@@ -97,12 +86,6 @@ def test_build_error_response_from_generic_exception() -> None:
assert body["message"] == f"oops (ref {body['ref']})"
-def test_categorize_fallback_names_no_exception_class() -> None:
- err = categorize_exception(RuntimeError("oops"), context={"op": "x"})
- assert err.error_code == APIErrorCode.INTERNAL_ERROR
- assert err.details == {"op": "x"}
-
-
def test_build_error_response_debug_mode_includes_traceback() -> None:
try:
raise ValueError("kaboom")
@@ -182,34 +165,6 @@ def test_a_body_that_ended_early_is_a_retryable_network_error(make: Callable[[],
assert (resp.status, body["error_code"], body.get("retryable")) == (424, "NETWORK_ERROR", True)
-def test_a_bad_content_encoding_is_no_network_error() -> None:
- assert categorize_exception(rnet_error(BAD_DEFLATE)).error_code != APIErrorCode.NETWORK_ERROR
-
-
-def test_a_bare_rnet_error_reads_as_its_short_cause() -> None:
- err = categorize_exception(rnet_error(SHORT_BODY))
- assert err.message == "Network error occurred: DecodingError (IncompleteBody)"
-
-
-def test_categorize_preserves_context() -> None:
- api_err = categorize_exception(ValueError("bad"), context={"op": "search"})
- assert api_err.details["op"] == "search"
-
-
-def test_handle_api_exception_with_api_error_preserves_code() -> None:
- err = APIError(APIErrorCode.TRACK_NOT_FOUND, "no track")
- resp = handle_api_exception(err)
- body = _body(resp)
- assert body["error_code"] == "TRACK_NOT_FOUND"
- assert resp.status == 404
-
-
-def test_handle_api_exception_categorizes_generic() -> None:
- resp = handle_api_exception(ConnectionError("oops"))
- body = _body(resp)
- assert body["error_code"] == "NETWORK_ERROR"
-
-
# Locks the FULL observable response (http status, error_code, retryable) that
# a client sees for a generic (non-APIError) exception flowing through the
# handle_api_exception funnel that every route's `except Exception` path calls.
@@ -341,16 +296,6 @@ def test_an_error_code_that_is_no_api_code_falls_back_to_the_keywords() -> None:
assert categorize_exception(exc).error_code == APIErrorCode.NETWORK_ERROR
-def test_a_system_exit_stays_a_service_error_whatever_its_cause_names() -> None:
- try:
- try:
- raise coded(ValueError("bad"), APIErrorCode.INVALID_PROXY)
- except ValueError as e:
- raise SystemExit(1) from e
- except SystemExit as exit_:
- assert categorize_exception(exit_).error_code == APIErrorCode.SERVICE_ERROR
-
-
@pytest.mark.parametrize(
"error",
[
diff --git a/tests/remote/unit/test_handlers_serialize.py b/tests/remote/unit/test_handlers_serialize.py
index b838e8349..7aff8a5e4 100644
--- a/tests/remote/unit/test_handlers_serialize.py
+++ b/tests/remote/unit/test_handlers_serialize.py
@@ -2,10 +2,7 @@
from __future__ import annotations
-import io
-
import pytest
-import requests
from langcodes import Language
from tests.admission import refusal
@@ -14,19 +11,14 @@ from unshackle.core.api.handlers import (
listed_titles,
sanitize_log,
search_handler,
- validate_service,
)
from unshackle.core.api.server_keys import drm_preference_name
-from unshackle.core.config import config
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.titles.episode import Episode
-from unshackle.core.titles.movie import Movie
from unshackle.core.tracks import Audio, Subtitle, Video
from unshackle.core.tracks.track import Track
from unshackle.core.wire import (
- serialize_audio_track,
serialize_drm,
- serialize_subtitle_track,
serialize_title,
serialize_video_track,
)
@@ -100,16 +92,6 @@ def test_sanitize_log(raw, expected: str) -> None:
assert sanitize_log(raw) == expected
-def test_serialize_title_movie() -> None:
- movie = Movie(id_="movie-0001", service=_FakeSvc, name="Title X", year=2024, language=Language.get("en"))
- d = serialize_title(movie, None)
- assert d["type"] == "movie"
- assert d["name"] == "Title X"
- assert d["year"] == 2024
- assert d["id"] == "movie-0001"
- assert d["language"] == "en"
-
-
def test_serialize_title_episode_named() -> None:
ep = Episode(
id_="ep-00001",
@@ -129,41 +111,12 @@ def test_serialize_title_episode_named() -> None:
assert d["name"] == "Pilot"
-def test_serialize_title_episode_unnamed_falls_back_to_number() -> None:
- ep = Episode(
- id_="ep-00002",
- service=_FakeSvc,
- title="Show",
- season=1,
- number=5,
- name=None,
- year=None,
- language=Language.get("en"),
- )
- d = serialize_title(ep, None)
- assert d["name"] == "Episode 05"
-
-
def test_no_titles_is_a_service_error() -> None:
with pytest.raises(APIError) as exc:
listed_titles(None)
assert exc.value.error_code == APIErrorCode.SERVICE_ERROR
-def test_init_segment_reports_the_http_status() -> None:
- refused = requests.Response()
- refused.status_code = 403
- refused.raw = io.BytesIO()
-
- class FakeSession(requests.Session):
- def request(self, *args: object, **kwargs: object) -> requests.Response:
- return refused
-
- track = Video(url="https://cdn.example/v.mp4", language=Language.get("en"))
- with pytest.raises(ValueError, match="HTTP 403"):
- track.get_init_segment(session=FakeSession())
-
-
def test_serialize_video_track_basic() -> None:
d = serialize_video_track(video())
assert d["id"] == "video-001"
@@ -177,50 +130,6 @@ def test_serialize_video_track_basic() -> None:
assert "url" not in d
-def test_display_labels_match_the_filename_labels(monkeypatch: pytest.MonkeyPatch) -> None:
- """codec_display and range_display use the filename names, after any codec_names override."""
- hevc = video(codec=Video.Codec.HEVC, range_=Video.Range.DV)
- hevc.hdr10_base = True
- assert serialize_audio_track(audio(codec=Audio.Codec.EC3))["codec_display"] == "DDP"
- assert (serialize_video_track(hevc)["codec_display"], serialize_video_track(hevc)["range_display"]) == (
- "H.265",
- "DV+HDR",
- )
- assert serialize_video_track(video(codec=Video.Codec.VC1))["codec_display"] == "VC-1"
-
- monkeypatch.setattr(config, "codec_names", {"DDP": "EAC3", "H.265": "HEVC"})
- assert serialize_audio_track(audio(codec=Audio.Codec.EC3))["codec_display"] == "EAC3"
- assert serialize_video_track(hevc)["codec_display"] == "HEVC"
-
-
-def test_serialize_video_track_include_url() -> None:
- d = serialize_video_track(video(), include_url=True)
- assert d["url"] == "https://example.com/v.mpd"
-
-
-def test_serialize_audio_track_basic() -> None:
- d = serialize_audio_track(audio())
- assert d["id"] == "audio-001"
- assert d["codec"] == "AAC"
- assert d["bitrate"] == 128
- assert d["channels"] == 2
- assert d["descriptive"] is False
-
-
-def test_serialize_video_track_drm_preference_round_trip() -> None:
- d = serialize_video_track(video())
- assert d["drm_preference"] is None
- v = video()
- v.drm_preference = "pr"
- assert serialize_video_track(v)["drm_preference"] == "pr"
-
-
-def test_serialize_audio_track_drm_preference() -> None:
- a = audio()
- a.drm_preference = "widevine"
- assert serialize_audio_track(a)["drm_preference"] == "widevine"
-
-
def test_drm_preference_name_maps_short_forms() -> None:
v = video()
assert drm_preference_name(v) is None
@@ -232,20 +141,6 @@ def test_drm_preference_name_maps_short_forms() -> None:
assert drm_preference_name(v) == "widevine"
-def test_serialize_subtitle_track_basic() -> None:
- d = serialize_subtitle_track(subtitle(forced=True))
- assert d["id"] == "sub-001"
- assert d["codec"] == "WebVTT"
- assert d["forced"] is True
- assert d["sdh"] is False
- assert d["cc"] is False
-
-
-def test_serialize_drm_none_returns_none() -> None:
- assert serialize_drm(None) is None
- assert serialize_drm([]) is None
-
-
def test_serialize_drm_widevine_minimal() -> None:
class _PSSH:
def dumps(self) -> str:
@@ -283,14 +178,6 @@ def test_serialize_drm_playready_pssh_without_dumps_is_omitted() -> None:
assert info["kids"] == ["00112233445566778899aabbccddeeff"]
-def test_validate_service_unknown_returns_none() -> None:
- assert validate_service("NOPE_THIS_IS_NOT_REAL_") is None
-
-
-def test_validate_download_params_accepts_defaults() -> None:
- assert refusal({}) is None
-
-
@pytest.mark.parametrize(
"data, fragment",
[
diff --git a/tests/remote/unit/test_input_bridge.py b/tests/remote/unit/test_input_bridge.py
index c41194d3a..1bf055656 100644
--- a/tests/remote/unit/test_input_bridge.py
+++ b/tests/remote/unit/test_input_bridge.py
@@ -2,10 +2,6 @@
from __future__ import annotations
-import threading
-import time
-from types import SimpleNamespace
-
import pytest
from unshackle.core.api.input_bridge import InputBridge
@@ -14,68 +10,6 @@ from unshackle.core.remote_protocol import AuthStatus
pytestmark = pytest.mark.unit
-def pending_prompt(bridge: InputBridge) -> str | None:
- ask = bridge.get_pending_ask()
- return ask.prompt if ask else None
-
-
-def test_initial_status_is_authenticating() -> None:
- bridge = InputBridge()
- assert bridge.login_status is AuthStatus.AUTHENTICATING
- assert pending_prompt(bridge) is None
-
-
-def test_submit_response_returns_false_when_no_prompt_pending() -> None:
- bridge = InputBridge()
- assert bridge.submit_response("foo") is False
-
-
-def test_request_input_blocks_until_submit() -> None:
- bridge = InputBridge()
- result: list[str] = []
-
- def worker() -> None:
- result.append(bridge.request_input("OTP?", timeout=5))
-
- t = threading.Thread(target=worker)
- t.start()
- for _ in range(50):
- if pending_prompt(bridge) == "OTP?":
- break
- time.sleep(0.02)
- assert pending_prompt(bridge) == "OTP?"
-
- assert bridge.submit_response("123456") is True
- t.join(timeout=2)
- assert result == ["123456"]
- assert bridge.login_status is AuthStatus.AUTHENTICATING
- assert pending_prompt(bridge) is None
-
-
-def test_request_input_times_out() -> None:
- bridge = InputBridge()
- with pytest.raises(TimeoutError, match="No client response"):
- bridge.request_input("hello", timeout=0.6)
- assert bridge.login_status is AuthStatus.AUTHENTICATING
-
-
-def test_a_prompt_after_a_timed_out_one_takes_its_answer() -> None:
- """A login that catches the timeout and asks again gets the answer through the remote login routes."""
- bridge = InputBridge()
- with pytest.raises(TimeoutError):
- bridge.request_input("Code?", timeout=0.01)
- offered = threading.Event()
- bridge.channel = SimpleNamespace(offer=lambda ask: offered.set() or False, attached=False) # type: ignore[assignment]
- answers: list[str] = []
- worker = threading.Thread(target=lambda: answers.append(bridge.request_input("Code again?", timeout=5)))
- worker.start()
- assert offered.wait(5)
- assert pending_prompt(bridge) == "Code again?"
- assert bridge.submit_response("1234")
- worker.join(5)
- assert answers == ["1234"]
-
-
def test_cancel_before_request_raises_immediately() -> None:
bridge = InputBridge()
bridge.cancel()
@@ -84,36 +18,6 @@ def test_cancel_before_request_raises_immediately() -> None:
assert bridge.login_status is AuthStatus.AUTHENTICATING
-def test_cancel_unblocks_pending_request() -> None:
- bridge = InputBridge()
- exc: list[Exception] = []
-
- def worker() -> None:
- try:
- bridge.request_input("OTP?", timeout=5)
- except RuntimeError as e:
- exc.append(e)
-
- t = threading.Thread(target=worker)
- t.start()
- for _ in range(50):
- if pending_prompt(bridge):
- break
- time.sleep(0.02)
-
- bridge.cancel()
- t.join(timeout=2)
- assert exc and isinstance(exc[0], RuntimeError)
- assert bridge.login_status is AuthStatus.AUTHENTICATING
-
-
-def test_login_status_setter() -> None:
- bridge = InputBridge()
- bridge.login_status = AuthStatus.AUTHENTICATED
- assert bridge.login_status is AuthStatus.AUTHENTICATED
- assert pending_prompt(bridge) is None
-
-
def test_request_input_after_authentication_fails_fast() -> None:
"""After the login, a prompt with no attached session channel must not wait for an answer."""
bridge = InputBridge()
diff --git a/tests/remote/unit/test_job_admission.py b/tests/remote/unit/test_job_admission.py
index c7561910f..ba2850651 100644
--- a/tests/remote/unit/test_job_admission.py
+++ b/tests/remote/unit/test_job_admission.py
@@ -63,12 +63,6 @@ def test_the_server_proxy_stamp_comes_from_the_key_policy(server):
assert admit({"server_proxy": True}).params["server_proxy"] is False
-def test_the_parameter_check_leaves_the_request_body_as_it_is(server):
- body = {"output_dir": "shows"}
- assert job_admission.check_parameters(body)["output_dir"] == str((server / "shows").resolve())
- assert body == {"output_dir": "shows"}
-
-
def test_a_profile_that_names_a_path_is_invalid_parameters(server):
with pytest.raises(APIError) as ei:
admit({"profile": "../x"})
diff --git a/tests/remote/unit/test_job_channel.py b/tests/remote/unit/test_job_channel.py
index e38198eb5..6db11c798 100644
--- a/tests/remote/unit/test_job_channel.py
+++ b/tests/remote/unit/test_job_channel.py
@@ -40,14 +40,6 @@ def test_an_update_that_changes_nothing_reports_no_change() -> None:
assert apply_progress(state, {}) is False
-def test_number_fields_are_cast() -> None:
- state = JobProgress()
- apply_progress(state, {"progress": 5, "segments_done": 2, "completed_tracks": 1.0})
- assert state.progress == 5.0 and isinstance(state.progress, float)
- assert isinstance(state.segments_done, float)
- assert state.completed_tracks == 1 and isinstance(state.completed_tracks, int)
-
-
@pytest.mark.parametrize(
("update", "names"),
[
diff --git a/tests/remote/unit/test_key_identity.py b/tests/remote/unit/test_key_identity.py
index ef3836f66..b50ff625a 100644
--- a/tests/remote/unit/test_key_identity.py
+++ b/tests/remote/unit/test_key_identity.py
@@ -1,21 +1,16 @@
"""An API key's own cdm and service_config entries, and the identity cache a server device keeps per key."""
-import asyncio
import base64
import json
-import uuid
import zlib
from types import SimpleNamespace
import pytest
-from tests.remote.sessions import stub_service_build
from unshackle.core.api import handlers, job_admission, key_policy, server_keys
from unshackle.core.api.errors import APIError
from unshackle.core.api.key_policy import KeyPolicy
-from unshackle.core.api.session_store import get_session_store
from unshackle.core.config import config
-from unshackle.core.remote_protocol import AuthStatus, LicensingMode, Licensor
@pytest.fixture
@@ -33,11 +28,6 @@ def test_a_key_entry_replaces_the_whole_server_entry(server):
assert KeyPolicy({}).cdm_config() is config
-def test_licence_device_comes_from_the_key_entry(server):
- assert server_keys.resolve_device_name(KeyPolicy({"cdm": {"EXAMPLE": "own"}}), "playready", "EXAMPLE") == "own"
- assert server_keys.resolve_device_name(KeyPolicy({}), "playready", "EXAMPLE") == "shared_pr"
-
-
def test_a_session_keeps_the_policy_it_was_created_with(server, monkeypatch):
pinned, reloaded = KeyPolicy({"cdm": {"EXAMPLE": "pinned"}}), KeyPolicy({"cdm": {"EXAMPLE": "reloaded"}})
monkeypatch.setattr(handlers, "request_policy", lambda request: reloaded)
@@ -117,105 +107,6 @@ def test_a_known_device_passes_validation(server, monkeypatch):
assert KeyPolicy({"cdm": {"EXAMPLE": {"widevine": "dev"}}}).entry_error("u") is not None
-@pytest.mark.parametrize(
- "server_cdm, sent, own, returned",
- [
- (True, {}, True, {"tokens", "keys/planted"}),
- (False, {}, True, {"tokens", "keys/planted"}),
- (False, {"cdm_type": "playready"}, True, {"tokens", "keys/planted"}),
- (False, {"cdm_type": "playready"}, False, {"tokens", "keys/device1", "keys/planted"}),
- ],
-)
-def test_a_session_keeps_identity_keys_from_the_client_unless_the_identity_is_the_clients(
- server, monkeypatch, server_cdm, sent, own, returned
-):
- class Service(_Service):
- _input_bridge = log = cache = None
-
- def authenticate(self, cookies, credential):
- self.cache.get("keys/device1").set("identity")
- self.cache.get("tokens").set("login")
-
- user = KeyPolicy({"service_config": {"EXAMPLE": {"device_id": "key"}}} if own else {})
- text = base64.b64encode(zlib.compress(b'{"data": "x"}')).decode("ascii")
- monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: service)
- monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
- monkeypatch.setattr(handlers, "server_account_for", lambda *args: False)
- monkeypatch.setattr(handlers, "request_policy", lambda request: user)
- monkeypatch.setattr(handlers, "choose_session_cdm", lambda *args: (server_cdm, None))
- monkeypatch.setattr(handlers.Services, "load", lambda service: Service)
- stub_service_build(monkeypatch, Service)
- monkeypatch.setattr(handlers, "load_client_cookies", lambda text: text)
-
- async def run():
- data = {
- "service": "EXAMPLE",
- "title_id": "t",
- "session_id": str(uuid.uuid4()),
- "cookies": "x",
- "cache": {"keys/planted": text},
- **sent,
- }
- response = await handlers.session_create_handler(data)
- session = get_session_store().peek(json.loads(response.body)["session_id"])
- try:
- for _ in range(250):
- if session.auth_status != AuthStatus.AUTHENTICATING:
- break
- await asyncio.sleep(0.02)
- return session, set(handlers.collect_cache_files(session.cache_tag))
- finally:
- await get_session_store().delete(session.session_id)
-
- session, sent_back = asyncio.run(run())
-
- assert session.policy is user
- assert sent_back == returned
-
-
-def test_a_service_on_the_lent_device_makes_a_lent_device_session(server, monkeypatch):
- class Service(_Service):
- _input_bridge = log = cache = None
- ctx = SimpleNamespace(obj=SimpleNamespace(cdm=SimpleNamespace(lent=True)))
-
- def authenticate(self, cookies, credential):
- self.cache.get("keys/device1").set("identity")
-
- monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: service)
- monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
- monkeypatch.setattr(handlers, "server_account_for", lambda *args: False)
- monkeypatch.setattr(handlers, "request_policy", lambda request: KeyPolicy({"server_vault": True}))
- monkeypatch.setattr(handlers, "choose_session_cdm", lambda *args: (False, None))
- monkeypatch.setattr(handlers.Services, "load", lambda service: Service)
- stub_service_build(monkeypatch, Service)
- monkeypatch.setattr(handlers, "load_client_cookies", lambda text: text)
-
- async def run():
- data = {
- "service": "EXAMPLE",
- "title_id": "t",
- "session_id": str(uuid.uuid4()),
- "cookies": "x",
- "cdm_type": "widevine",
- }
- reply = json.loads((await handlers.session_create_handler(data)).body)
- session = get_session_store().peek(reply["session_id"])
- try:
- for _ in range(250):
- if session.auth_status != AuthStatus.AUTHENTICATING:
- break
- await asyncio.sleep(0.02)
- return reply, session, set(handlers.collect_cache_files(session.cache_tag))
- finally:
- await get_session_store().delete(session.session_id)
-
- reply, session, cache = asyncio.run(run())
-
- assert session.licensing == LicensingMode(Licensor.LENT_DEVICE, server_vault=True)
- assert (reply["server_cdm"], reply["server_device"], reply["server_vault"]) == (False, True, True)
- assert "keys/device1" not in cache
-
-
def test_a_reload_checks_key_devices_against_the_new_config(server, monkeypatch):
monkeypatch.setattr(handlers.Services, "get_tags", staticmethod(lambda: ["EXAMPLE"]))
fresh = SimpleNamespace(remote_cdm=[{"name": "new_remote", "device_type": "PLAYREADY"}])
@@ -224,17 +115,6 @@ def test_a_reload_checks_key_devices_against_the_new_config(server, monkeypatch)
assert user.entry_error("u") is not None
-def test_a_block_value_reaches_only_plain_values_of_other_sections(server, monkeypatch):
- base = {"p1": {"device_id": "p1", "headers": {"a": "b"}}, "device_key": "server"}
- monkeypatch.setattr(key_policy, "load_service_config", lambda service: json.loads(json.dumps(base)))
- block = {"device_id": "key", "headers": {"c": "d"}, "device_key": {"nested": 1}}
-
- merged = KeyPolicy({"service_config": {"EXAMPLE": block}}).service_yaml("EXAMPLE")
-
- assert merged["p1"] == {"device_id": "key", "headers": {"a": "b"}}
- assert merged["device_key"] == {"nested": 1}
-
-
def test_a_removed_key_loses_its_identity_cache(server):
handlers.keyed_cache("_s", _Service(), "EXAMPLE", "gone", KeyPolicy(), True).get("keys/device1").set("keys")
handlers.keyed_cache("_s", _Service(), "EXAMPLE", "kept", KeyPolicy(), True).get("keys/device1").set("keys")
diff --git a/tests/remote/unit/test_key_policy.py b/tests/remote/unit/test_key_policy.py
index 1de9b8002..ddeb88a88 100644
--- a/tests/remote/unit/test_key_policy.py
+++ b/tests/remote/unit/test_key_policy.py
@@ -108,11 +108,6 @@ def test_the_named_services_are_the_global_list_else_every_keys_list():
assert api_keys({"users": users}) == ["a", "b", "c", "d"]
-def test_the_policy_hands_over_the_cap_of_the_service():
- policy = KeyPolicy({"server_cdm_max_height": {"example1": 720, "default": 1080}})
- assert (policy.max_height("EXAMPLE1"), policy.max_height(None)) == (720, 1080)
-
-
def test_a_key_with_no_entry_gets_every_server_device():
serve = {"users": {"k1": {"devices": ["mine"]}}, "devices": [Path("/x/dev.wvd")], "playready_devices": []}
assert KeyPolicy.of("k1", serve).devices("devices") == ["mine"]
@@ -152,8 +147,3 @@ def test_shared_and_username():
)
def test_the_entry_check_names_the_first_problem(entry, problem):
assert problem in KeyPolicy(entry, {"tiers": {"bot": {}}}).entry_error("serve.users.u")
-
-
-@pytest.mark.parametrize("value", [None, 1080, {"EXAMPLE1": 720, "default": None}])
-def test_the_entry_check_accepts_a_good_height_cap(value):
- assert KeyPolicy({"server_cdm_max_height": value, "tier": "bot"}, {"tiers": {"bot": {}}}).entry_error("u") is None
diff --git a/tests/remote/unit/test_licence_cap.py b/tests/remote/unit/test_licence_cap.py
index 021303bd3..e117a2cc4 100644
--- a/tests/remote/unit/test_licence_cap.py
+++ b/tests/remote/unit/test_licence_cap.py
@@ -6,7 +6,6 @@ from unshackle.core.api import licence_cap
from unshackle.core.api.errors import APIError
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.tracks import Audio, Video
-from unshackle.core.tracks.tracks import at_resolution
pytestmark = pytest.mark.unit
@@ -71,10 +70,6 @@ def test_a_track_above_the_cap_gets_no_live_licence(track, refused):
assert (licence_cap.track_refusal(1080, track) is not None) is refused
-def test_no_cap_refuses_no_track():
- assert licence_cap.track_refusal(None, video(4320)) is None
-
-
def test_the_track_refusal_gives_the_client_the_cap():
refusal = licence_cap.track_refusal(1080, video(2160))
assert refusal.error_code is APIErrorCode.SERVER_CDM_CAPPED
@@ -82,13 +77,6 @@ def test_the_track_refusal_gives_the_client_the_cap():
assert "2160p track" in refusal.message
-@pytest.mark.parametrize("size", [(1088, 2048), (1188, 2112), (800, 1920), (1080, 2560), (1080, 1920), (None, 1920)])
-def test_a_track_that_the_cap_quality_selects_gets_a_live_licence(size):
- track = video(*size)
- assert at_resolution(track, 1080)
- assert licence_cap.track_refusal(1080, track) is None
-
-
@pytest.mark.parametrize(
("cap", "quality", "has_device", "server_cdm"),
[
diff --git a/tests/remote/unit/test_licence_declared_kwargs.py b/tests/remote/unit/test_licence_declared_kwargs.py
index c60b0742b..ade545ff7 100644
--- a/tests/remote/unit/test_licence_declared_kwargs.py
+++ b/tests/remote/unit/test_licence_declared_kwargs.py
@@ -220,16 +220,6 @@ def test_server_cdm_widevine_var_kwargs_service_receives_pssh_and_session_id(wid
assert service.calls[0]["session_id"] == SESSION_ID
-def test_server_cdm_widevine_lambda_is_never_itself_filtered(widevine_env: None) -> None:
- # The `(**kw)` lambda would look like a VAR_KEYWORD service if declared_kwargs were ever
- # applied to it, and a classic service would then be handed `pssh` and `session_id`.
- service = ClassicService()
- _server_cdm(service, "widevine")
-
- assert "pssh" not in service.calls[0]
- assert "session_id" not in service.calls[0]
-
-
def test_server_cdm_playready_classic_signature_gets_three_arguments(playready_env: None) -> None:
service = ClassicService()
keys = _server_cdm(service, "playready")
@@ -272,14 +262,6 @@ def test_server_cdm_playready_offers_pssh_b64_and_session_id_not_pssh(playready_
assert service.calls[0]["session_id"] == SESSION_ID
-def test_server_cdm_playready_session_service_receives_session_id(playready_env: None) -> None:
- service = SessionService()
- _server_cdm(service, "playready")
-
- assert set(service.calls[0]) == {"challenge", "title", "track", "session_id"}
- assert service.calls[0]["session_id"] == SESSION_ID
-
-
@pytest.mark.parametrize(
("drm_type", "rejects", "last_call"),
[
@@ -436,29 +418,7 @@ class _DelegatingService(Service):
return b"LIC"
-class _DelegatingVarKwService(_DelegatingService):
- def get_widevine_license(self, *, challenge: bytes, **kwargs: Any) -> bytes: # type: ignore[override]
- self.calls.append({"challenge": challenge, **kwargs})
- return b"LIC"
-
-
def test_base_playready_delegate_filters_to_the_widevine_signature() -> None:
service = _DelegatingService()
assert service.get_playready_license(challenge=b"C", title="T", track="TR") == b"LIC"
assert set(service.calls[0]) == {"challenge", "title", "track"}
-
-
-def test_base_playready_delegate_passes_everything_to_a_var_kwargs_service() -> None:
- service = _DelegatingVarKwService()
- service.get_playready_license(challenge=b"C", title="T", track="TR")
- assert set(service.calls[0]) == {"challenge", "title", "track"}
-
-
-def test_base_playready_delegate_cannot_forward_session_id() -> None:
- # Service.get_playready_license declares (challenge, title, track) only, so the server_cdm
- # filter drops session_id before the delegate ever runs. A session-aware service that wants
- # PlayReady must implement get_playready_license itself.
- from unshackle.core.utilities import declared_kwargs
-
- offered = {"challenge": b"C", "title": "T", "track": "TR", "session_id": SESSION_ID}
- assert "session_id" not in declared_kwargs(Service.get_playready_license, offered)
diff --git a/tests/remote/unit/test_malformed_input.py b/tests/remote/unit/test_malformed_input.py
index a6e68a5e5..d48ba22cd 100644
--- a/tests/remote/unit/test_malformed_input.py
+++ b/tests/remote/unit/test_malformed_input.py
@@ -165,17 +165,6 @@ def test_good_wanted_passes_at_submit(wanted: Any) -> None:
assert handlers.wanted_refusal(wanted) is None
-def test_a_job_error_hides_the_configured_credential(monkeypatch: pytest.MonkeyPatch) -> None:
- from datetime import datetime
-
- from unshackle.core.api.download_manager import DownloadJob, JobStatus
-
- monkeypatch.setattr(handlers.config, "credentials", {"EXAMPLE": {"default": "user:EXAMPLE-pass-123"}})
- job = DownloadJob("j1", JobStatus.FAILED, datetime(2026, 1, 1), "EXAMPLE", "t", {})
- job.error_message = "login failed with EXAMPLE-pass-123"
- assert "EXAMPLE-pass-123" not in job.to_dict(include_full_details=True)["error_message"]
-
-
@pytest.mark.parametrize(
"configured, secret",
[
@@ -244,19 +233,6 @@ def test_a_relayed_login_prompt_loses_its_control_characters() -> None:
assert asked == [("Code[2J:\n", None)]
-def test_a_relayed_qr_code_too_long_to_draw_still_logs_its_line(monkeypatch) -> None:
- from unshackle.core import console
-
- seen: list[str] = []
- service = RemoteService.__new__(RemoteService)
- service._input_bridge, service.auth_qr = None, None
- service.log = SimpleNamespace(log=lambda level, message: seen.append(message))
- monkeypatch.setattr(console.console, "print", lambda *a, **k: pytest.fail("nothing to draw"))
- messages = ServerMessages(service)
- messages.show_logs([{"seq": 1, "level": "INFO", "message": "Scan", "qr": "\u20ac" * 1500}])
- assert seen == ["Scan"] and messages.log_seq == 1
-
-
async def feed(channel: WebSocketChannel, *messages: dict[str, Any]) -> None:
"""Read the given messages on the session channel, then end."""
@@ -274,15 +250,6 @@ def channel_logging_to(seen: list[str]) -> WebSocketChannel:
return WebSocketChannel(messages)
-@pytest.mark.parametrize("seq", ["x", "2", None, [1], {"a": 1}, float("inf")])
-async def test_a_log_record_with_a_malformed_seq_is_skipped(seq: Any) -> None:
- seen: list[str] = []
- channel = channel_logging_to(seen)
- await feed(channel, {"type": "log", "seq": seq, "message": "bad"}, {"type": "log", "seq": 1, "message": "good"})
- assert seen == ["good"]
- assert channel.messages.log_seq == 1
-
-
async def test_relayed_server_logs_lose_their_control_characters() -> None:
seen: list[str] = []
await feed(channel_logging_to(seen), {"type": "log", "seq": 1, "level": "INFO", "message": "a\x1b[2Jb\nc"})
@@ -314,11 +281,3 @@ def test_a_relayed_licence_with_no_licence_is_one_click_error(answer: dict[str,
track = SimpleNamespace(id="v1", drm=[])
with pytest.raises(click.ClickException, match="no valid licence for track v1"):
service.proxy_license(b"challenge", cast(Any, track), "widevine")
-
-
-@pytest.mark.parametrize("chapters", [[{"name": "x"}], [{"timestamp": "not a time"}], [5]])
-def test_malformed_chapters_from_the_server_are_one_remote_error(chapters: list[Any]) -> None:
- service = RemoteService.__new__(RemoteService)
- service._chapters_by_title = {"t": chapters}
- with pytest.raises(RemoteError, match="malformed chapters"):
- service.get_chapters(cast(Any, SimpleNamespace(id="t")))
diff --git a/tests/remote/unit/test_process_exit.py b/tests/remote/unit/test_process_exit.py
deleted file mode 100644
index 24d999a49..000000000
--- a/tests/remote/unit/test_process_exit.py
+++ /dev/null
@@ -1,949 +0,0 @@
-"""Each way a client process dies ends its remote session: a signal, a closed terminal, a cancelled job."""
-
-from __future__ import annotations
-
-import asyncio
-import json
-import os
-import shutil
-import signal
-import subprocess
-import sys
-import tempfile
-import time
-from collections.abc import Callable, Iterator
-from dataclasses import asdict
-from pathlib import Path
-from threading import Event
-from types import SimpleNamespace
-from typing import Any
-
-import pytest
-
-from tests.remote.unit.test_remote_loopback import KEY, StubService, count, make_client, server # noqa: F401
-from tests.remote.unit.test_session_lifetime import ( # noqa: F401
- DEADLINE,
- ROOT,
- HeldDelete,
- answered,
- build,
- held_delete,
- logins,
- sessions,
-)
-from tests.remote.unit.test_tunnel import wait_until
-from unshackle.core import process_exit, tunnel
-from unshackle.core.api import download_manager
-from unshackle.core.api.job_channel import JobPayload, WorkerProcess
-from unshackle.core.config import config
-from unshackle.core.remote_protocol import SESSION_CREATE_ROUTE, SESSION_ROUTE
-from unshackle.core.remote_service import RemoteError
-
-pytestmark = [pytest.mark.unit, pytest.mark.process]
-
-posix = pytest.mark.skipif(sys.platform == "win32", reason="POSIX signals")
-SIGNALS = ["CTRL_BREAK_EVENT"] if sys.platform == "win32" else ["SIGHUP", "SIGTERM"]
-BOUND = 8.0
-
-CLIENT = """
-import asyncio, contextlib, ctypes, os, signal, sys, time
-from threading import Event, Thread
-import click
-from unshackle.core import process_exit
-from unshackle.core.config import config
-config.__init__(directories={"cache": sys.argv[2], "cookies": sys.argv[2] + "/cookies"})
-from tests.remote.unit.test_remote_loopback import make_client
-from unshackle.core.remote_channel import WebSocketChannel
-from unshackle.core.remote_service import RemoteError
-service = make_client(sys.argv[1])
-phase, deadline = sys.argv[3], float(sys.argv[4])
-if phase == "login":
- service._input_bridge = click.UNPROCESSED
- click.UNPROCESSED.request_input = lambda prompt, qr=None: time.sleep(120)
-
-def stuck(*args):
- Event().wait(120)
-
-def say(line):
- print(line, flush=True)
-
-async def take_wakeup_fd():
- if sys.platform != "win32":
- asyncio.get_running_loop().add_signal_handler(signal.SIGUSR1, stuck)
- asyncio.get_running_loop().remove_signal_handler(signal.SIGUSR1)
-
-@click.command()
-@click.pass_context
-def run(ctx):
- ctx.with_resource(process_exit.unwinding(deadline, linger=phase != "job-loop"))
- service.authenticate()
- say("ready")
- if phase.endswith("-loop"):
- asyncio.run(take_wakeup_fd())
- if phase == "close":
- service.close()
- say("closed")
- elif phase == "swallow":
- with contextlib.suppress(KeyboardInterrupt):
- time.sleep(120)
- sys.exit(0)
- elif phase in ("pool", "pool-loop"):
- def late():
- while service.lifetime._held:
- time.sleep(0.01)
- with contextlib.suppress(SystemExit):
- service.get_titles()
- stuck()
- Thread(target=late).start()
- elif phase == "return":
- return
- elif phase in ("print", "prints"):
- def prints(write):
- while True:
- write("x" * 80)
- time.sleep(0.01)
- # Python aborts at exit when a daemon thread is in a print, so the thread does not use sys.stdout
- Thread(target=prints, args=[lambda line: os.write(1, line.encode())], daemon=True).start()
- say("set up")
- if phase == "prints":
- prints(say)
- elif phase == "channel":
- WebSocketChannel.close = stuck
- elif phase == "cdm":
- service.channel.messages.cdm_lock.acquire()
- elif phase == "call":
- thread = Thread(target=stuck, daemon=True)
- thread.start()
- say("set up")
- if sys.platform == "win32":
- ctypes.windll.kernel32.Sleep(120_000)
- else:
- ctypes.CDLL(None).pthread_join(ctypes.c_ulong(thread.ident), None)
- elif phase == "reopen":
- def refuse(credential):
- raise RemoteError("EXAMPLE refused", "EXAMPLE")
- service.open_session = refuse
- service.lifetime.close_channel = lambda: os.kill(os.getpid(), signal.SIGTERM)
- with contextlib.suppress(RemoteError):
- service.authenticate()
- say("goes on")
- elif phase == "finally":
- try:
- say("set up")
- time.sleep(120)
- finally:
- hung_up = Event()
- process_exit.drop_terminals = hung_up.set
- say("unwinds")
- while not hung_up.is_set():
- time.sleep(0.01)
- say("unwound")
- elif phase == "handlers":
- print(*(repr(signal.getsignal(s)) for s in (signal.SIGHUP, signal.SIGTERM)), flush=True)
- say("set up")
- time.sleep(120)
-
-if phase == "handlers":
- signal.signal(signal.SIGHUP, signal.SIG_IGN)
- signal.signal(signal.SIGTERM, lambda *args: os._exit(3))
-run(args=[])
-"""
-
-COMMAND = """
-import json, sys
-from unshackle.core.config import config
-config.__init__(**json.loads(sys.argv[1]))
-from unshackle.core.utils import ip_info
-ip_info.get_ip_info = lambda *args, **kwargs: {"ip": "192.0.2.1", "country": "us"}
-from unshackle.core.__main__ import main
-main(args=sys.argv[2:])
-"""
-
-WORKER = """#!{python}
-import json, runpy, sys
-sys.path.insert(0, {root!r})
-from unshackle.core.config import config
-config.__init__(**json.loads({settings!r}))
-module, sys.argv = sys.argv[2], sys.argv[2:]
-runpy.run_module(module, run_name="__main__", alter_sys=True)
-"""
-
-
-def worker_script(url: str, path: Path) -> Path:
- """An interpreter for a job worker that reaches the test server and nothing else."""
- script = path / "worker"
- text = json.dumps(settings(url, path))
- script.write_text(WORKER.format(python=sys.executable, root=str(ROOT), settings=text), encoding="utf-8")
- script.chmod(0o755)
- return script
-
-
-@pytest.fixture
-def run(tmp_path: Path) -> Iterator[Callable[..., subprocess.Popen[str]]]:
- """Start a process in a session or a console group of its own; a fixture so that no process outlives its test."""
- started: list[subprocess.Popen[str]] = []
-
- def begin(*argv: str, **options: Any) -> subprocess.Popen[str]:
- defaults: dict[str, Any] = {"stdin": subprocess.DEVNULL, "stdout": subprocess.PIPE, "stderr": subprocess.STDOUT}
- if sys.platform == "win32":
- defaults["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
- else:
- defaults["start_new_session"] = True
- argv = (sys.executable, *argv)
- options = {**defaults, **options}
- started.append(subprocess.Popen(argv, cwd=ROOT, text=True, encoding="utf-8", errors="replace", **options))
- return started[-1]
-
- yield begin
- for process in started:
- process.kill()
- process.wait()
- if process.stdout:
- process.stdout.close()
-
-
-def client(run: Callable[..., Any], url: str, cache: Path, phase: str, deadline: float = BOUND, **options: Any) -> Any:
- return run("-c", CLIENT, url, str(cache), phase, str(deadline), **options)
-
-
-def wait_line(process: subprocess.Popen[str], text: str) -> str:
- assert process.stdout is not None
- for line in process.stdout:
- if text in line:
- return line
- pytest.fail(f"the client did not print {text!r}")
-
-
-def still_runs(process: subprocess.Popen[str]) -> None:
- with pytest.raises(subprocess.TimeoutExpired):
- process.wait(0.3)
-
-
-def read_until(controller: int, text: bytes) -> bytes:
- output = b""
- while text not in output:
- output += os.read(controller, 65536)
- return output
-
-
-def send(process: subprocess.Popen[str], name: str) -> None:
- process.send_signal(getattr(signal, name))
-
-
-def settings(url: str, path: Path) -> dict[str, Any]:
- """The config of a client process that reaches the test server and nothing else."""
- folders = ("cache", "cookies", "downloads", "temp", "logs", "services", "wvds", "prds")
- return {
- "remote_services": {"test": {"url": url, "api_key": KEY}},
- "directories": {name: str(path / name) for name in folders},
- "update_checks": False,
- "title_cache_enabled": False,
- "output_template": {"movies": "{title}", "series": "{title}", "songs": "{title}"},
- }
-
-
-@pytest.fixture(autouse=True)
-def lasting_sessions(server: SimpleNamespace) -> None: # noqa: F811
- """A session must not expire on the server while a test holds the DELETE back."""
- config.serve["session_ttl"] = 300
-
-
-@pytest.fixture
-def titles(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- example_service: None,
-) -> Iterator[SimpleNamespace]:
- """A server whose ``get_titles`` waits for ``release``."""
- barrier = SimpleNamespace(server=server, started=Event(), release=Event())
-
- def hold(stub: StubService) -> None:
- barrier.started.set()
- assert barrier.release.wait(DEADLINE), "the test did not release the titles"
-
- StubService.hooks["titles"] = hold
- try:
- yield barrier
- finally:
- barrier.release.set()
-
-
-def store_cache() -> None:
- (entry,) = sessions()
- stored = config.directories.cache / str(entry.cache_tag) / "token.json"
- stored.parent.mkdir(parents=True)
- stored.write_text('"EXAMPLE"', encoding="utf-8")
-
-
-def saved(cache: Path) -> bool:
- return (cache / "EXAMPLE" / "token.json").exists()
-
-
-@pytest.mark.parametrize("name", SIGNALS)
-def test_a_signal_before_the_create_reply_leaves_no_session(
- build: SimpleNamespace, # noqa: F811
- run: Callable[..., Any],
- tmp_path: Path,
- name: str,
-) -> None:
- process = client(run, build.server.url, tmp_path / "client", "idle")
- assert build.started.wait(DEADLINE)
- send(process, name)
- output, _ = process.communicate(timeout=DEADLINE)
- assert process.returncode != 0 and "Traceback" not in output
- assert count(build.server, "DELETE", SESSION_ROUTE) == 1
-
- build.release.set()
- assert wait_until(lambda: answered(build.server, 404), DEADLINE)
- assert sessions() == [] and build.logins == []
-
-
-@pytest.mark.parametrize("name", SIGNALS)
-def test_a_signal_during_the_login_leaves_no_session(
- server: SimpleNamespace, # noqa: F811
- run: Callable[..., Any],
- tmp_path: Path,
- name: str,
-) -> None:
- process = client(run, server.url, tmp_path / "client", "login")
- assert wait_until(lambda: [s for s in sessions() if s.input_bridge and s.channel.attached], DEADLINE)
- send(process, name)
- output, _ = process.communicate(timeout=DEADLINE)
- assert process.returncode != 0 and "Traceback" not in output
- assert sessions() == []
-
-
-@pytest.mark.parametrize("name", SIGNALS)
-@pytest.mark.parametrize("phase", ["idle", "swallow"])
-def test_a_signal_waits_for_the_delete_and_saves_its_cache(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- held_delete: HeldDelete, # noqa: F811
- run: Callable[..., Any],
- tmp_path: Path,
- phase: str,
- name: str,
-) -> None:
- """A second signal does not stop the wait, and a run that goes on after its KeyboardInterrupt is no success."""
- process = client(run, server.url, tmp_path / "client", phase)
- wait_line(process, "ready")
- store_cache()
- send(process, name)
- assert held_delete.started.wait(DEADLINE)
- if sys.platform != "win32":
- send(process, name)
- still_runs(process)
- held_delete.release.set()
- output, _ = process.communicate(timeout=DEADLINE)
-
- assert process.returncode != 0 and "Traceback" not in output
- assert phase == "swallow" or sys.platform == "win32" or "Aborted" in output
- assert saved(tmp_path / "client")
- assert sessions() == [] and count(server, "DELETE", SESSION_ROUTE) == 1
-
-
-@pytest.mark.parametrize("name", SIGNALS)
-@pytest.mark.parametrize("phase", ["close", "return"])
-def test_a_signal_during_the_end_of_the_session_is_no_success(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- held_delete: HeldDelete, # noqa: F811
- run: Callable[..., Any],
- tmp_path: Path,
- phase: str,
- name: str,
-) -> None:
- """The run closes its session, or returns with it open, such as ``--list``."""
- process = client(run, server.url, tmp_path / "client", phase)
- wait_line(process, "ready")
- assert held_delete.started.wait(DEADLINE)
- store_cache()
- send(process, name)
- still_runs(process)
- held_delete.release.set()
- output, _ = process.communicate(timeout=DEADLINE)
-
- assert process.returncode != 0
- assert "closed" not in output and "Traceback" not in output
- assert saved(tmp_path / "client")
- assert sessions() == [] and count(server, "DELETE", SESSION_ROUTE) == 1
-
-
-@pytest.mark.parametrize("name", SIGNALS[-1:])
-@pytest.mark.parametrize("phase", ["pool", "channel", "cdm", "call", "pool-loop", "job-loop"])
-def test_a_wait_that_does_not_end_does_not_hold_the_delete_back(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- run: Callable[..., Any],
- tmp_path: Path,
- phase: str,
- name: str,
-) -> None:
- """A thread that the exit waits for and that calls the server after the end, a channel that does not close, a CDM
- call that does not return, and a call in the main thread that no signal breaks. An event loop takes the wakeup fd.
- """
- process = client(run, server.url, tmp_path / "client", phase, deadline=3)
- wait_line(process, "set up")
- store_cache()
- sent = time.monotonic()
- send(process, name)
- assert wait_until(lambda: sessions() == [], 2.5)
- output, _ = process.communicate(timeout=DEADLINE)
- assert time.monotonic() - sent < 5
- assert process.returncode != 0 and saved(tmp_path / "client")
- assert "error" not in output.lower()
-
-
-@pytest.mark.parametrize("name", SIGNALS[-1:])
-def test_a_delete_that_the_server_does_not_answer_ends_at_the_deadline(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- held_delete: HeldDelete, # noqa: F811
- run: Callable[..., Any],
- tmp_path: Path,
- name: str,
-) -> None:
- ignored = {} if sys.platform == "win32" else {"preexec_fn": lambda: signal.signal(signal.SIGALRM, signal.SIG_IGN)}
- process = client(run, server.url, tmp_path / "client", "idle", deadline=2, **ignored)
- wait_line(process, "ready")
- sent = time.monotonic()
- send(process, name)
- assert held_delete.started.wait(DEADLINE)
- if sys.platform != "win32":
- with pytest.raises(subprocess.TimeoutExpired):
- process.wait(1.5 - (time.monotonic() - sent))
- send(process, name)
- process.communicate(timeout=DEADLINE)
- assert 1.9 <= time.monotonic() - sent < 3.4
- assert process.returncode == (1 if sys.platform == "win32" else -signal.SIGALRM)
-
-
-@posix
-def test_only_the_first_signal_interrupts_the_unwind(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- run: Callable[..., Any],
- tmp_path: Path,
-) -> None:
- process = client(run, server.url, tmp_path / "client", "finally")
- wait_line(process, "set up")
- process.send_signal(signal.SIGTERM)
- wait_line(process, "unwinds")
- process.send_signal(signal.SIGTERM)
- process.send_signal(signal.SIGHUP)
- output, _ = process.communicate(timeout=DEADLINE)
- assert "unwound" in output and "Aborted" in output and process.returncode == 1
-
-
-@posix
-def test_a_signal_after_a_ctrl_c_ends_the_session_that_the_pool_holds(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- run: Callable[..., Any],
- tmp_path: Path,
-) -> None:
- process = client(run, server.url, tmp_path / "client", "pool", deadline=1)
- wait_line(process, "set up")
- process.send_signal(signal.SIGINT)
- wait_line(process, "Aborted")
- with pytest.raises(subprocess.TimeoutExpired):
- process.wait(1.5)
- assert len(sessions()) == 1
- process.send_signal(signal.SIGTERM)
- assert process.wait(DEADLINE) != 0
- assert sessions() == []
-
-
-@posix
-def test_a_signal_during_the_release_of_a_failed_reopen_stops_the_run(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- run: Callable[..., Any],
- tmp_path: Path,
-) -> None:
- output, _ = client(run, server.url, tmp_path / "client", "reopen").communicate(timeout=DEADLINE)
- assert "ready" in output and "goes on" not in output and "Aborted" in output
- assert sessions() == []
-
-
-@posix
-def test_a_session_that_does_not_end_does_not_hold_the_next_one_back(run: Callable[..., Any]) -> None:
- script = """
-import threading, time
-from unshackle.core import process_exit
-
-ran = []
-
-def fail():
- ran.append(1)
- print("fails", flush=True)
- raise RuntimeError
-
-def off_main():
- with process_exit.unwinding():
- print("thread ran", flush=True)
-
-thread = threading.Thread(target=off_main)
-thread.start()
-thread.join()
-process_exit.Stop.raised = False
-with process_exit.unwinding():
- for n in range(2):
- process_exit.ends.add(lambda n=n: fail())
- try:
- print("ready", flush=True)
- time.sleep(120)
- finally:
- while len(ran) < 2:
- time.sleep(0.01)
-"""
- process = run("-c", script)
- wait_line(process, "thread ran")
- assert wait_line(process, "").strip() == "ready"
- process.send_signal(signal.SIGTERM)
- output, _ = process.communicate(timeout=DEADLINE)
- assert output.count("fails") == 2 and "RuntimeError" not in output
-
-
-@posix
-def test_a_signal_does_not_break_an_exit_hook(run: Callable[..., Any]) -> None:
- script = """
-import atexit, time
-from unshackle.core import process_exit
-
-def hook():
- print("exits", flush=True)
- time.sleep(1)
- print("exited", flush=True)
-
-atexit.register(hook)
-with process_exit.unwinding():
- pass
-"""
- process = run("-c", script)
- wait_line(process, "exits")
- process.send_signal(signal.SIGTERM)
- output, _ = process.communicate(timeout=DEADLINE)
- assert output.strip() == "exited"
-
-
-@posix
-@pytest.mark.parametrize(
- ("remote", "outcome", "code"),
- [(True, "return []", 128 + 15), (True, "raise RuntimeError", 1), (False, "return []", -15)],
- ids=["remote", "fails", "local"],
-)
-def test_a_stopped_worker_writes_no_file_again(
- run: Callable[..., Any], tmp_path: Path, remote: bool, outcome: str, code: int
-) -> None:
- """The manager removes the files of a cancelled job at once. A local job has no session, so SIGTERM kills it."""
- script = """
-import sys, time
-from unshackle.core import process_exit
-from unshackle.core.api import download_worker
-
-def perform(*args, progress_callback, **kwargs):
- process_exit.ends.add(lambda: time.sleep(0.3))
- progress_callback({"title": "EXAMPLE"})
- print("ready", flush=True)
- while not process_exit.stopping():
- time.sleep(0.01)
- progress_callback({"title": "OTHER"})
- OUTCOME
-
-download_worker.perform_download = perform
-sys.exit(download_worker.main(sys.argv))
-"""
- files = [tmp_path / name for name in ("payload", "result", "progress")]
- payload = JobPayload("job", "EXAMPLE", "example-1", {"remote": "test"} if remote else {})
- files[0].write_text(json.dumps(asdict(payload)), encoding="utf-8")
- process = run("-c", script.replace("OUTCOME", outcome), *map(str, files), stdin=subprocess.PIPE)
- wait_line(process, "ready")
- for path in files:
- path.unlink(missing_ok=True)
- process.send_signal(signal.SIGTERM)
- output, _ = process.communicate(timeout=DEADLINE)
- assert process.returncode == code, output
- assert list(tmp_path.iterdir()) == []
-
-
-@posix
-def test_the_only_process_of_a_container_ends_at_the_deadline(run: Callable[..., Any]) -> None:
- """The kernel ignores the default action of a signal of PID 1. unshare ignores SIGTERM, so it is SIGHUP here."""
- inside = ["unshare", "-Urpf", "--kill-child"]
- if not shutil.which("unshare") or subprocess.run([*inside, "true"], capture_output=True).returncode:
- pytest.skip("no user namespace")
- script = """
-import os, signal, time
-from unshackle.core import process_exit
-with process_exit.unwinding(1):
- try:
- os.kill(os.getpid(), signal.SIGHUP)
- time.sleep(120)
- finally:
- time.sleep(120)
-"""
- process = run("-c", "import os, sys; os.execvp(sys.argv[1], sys.argv[1:])", *inside, sys.executable, "-c", script)
- assert process.wait(DEADLINE) == 1
-
-
-@posix
-def test_a_job_that_stops_runs_no_post_script(run: Callable[..., Any], tmp_path: Path) -> None:
- ran = tmp_path / "ran"
- script = """
-import shlex, sys, time
-from unshackle.core import process_exit
-from unshackle.core.utils.post_scripts import dispatch
-with process_exit.unwinding(2, linger=False):
- process_exit.ends.add(lambda: time.sleep(120))
- print("ready", flush=True)
- while not process_exit.stopping():
- time.sleep(0.01)
- dispatch("success", "file", {}, [shlex.join([sys.executable, "-c", f"open({sys.argv[1]!r}, 'w')"])])
- print("dispatched", flush=True)
- time.sleep(120)
-"""
- process = run("-c", script, str(ran))
- wait_line(process, "ready")
- process.send_signal(signal.SIGTERM)
- wait_line(process, "dispatched")
- assert process.wait(DEADLINE) == -signal.SIGALRM
- assert not ran.exists()
-
-
-def test_a_process_that_stops_opens_no_session(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """A job worker that ended the sessions it knew exits without a DELETE for a later one."""
- monkeypatch.setattr(process_exit.Stop, "signum", 1)
- monkeypatch.setattr(process_exit.Stop, "raised", True)
- with pytest.raises(RemoteError):
- make_client(server.url).authenticate()
- assert count(server, "POST", SESSION_CREATE_ROUTE) == 0
-
-
-@posix
-def test_a_kill_leaves_the_terminal_as_it_is(run: Callable[..., Any]) -> None:
- import pty
-
- controller, terminal = pty.openpty()
- script = """
-import time
-from unshackle.core import process_exit
-with process_exit.unwinding():
- try:
- print("ready", flush=True)
- time.sleep(120)
- except KeyboardInterrupt:
- print("last line", flush=True)
-"""
- process = run("-c", script, stdin=terminal, stdout=terminal, stderr=terminal)
- os.close(terminal)
- output = read_until(controller, b"ready")
- process.send_signal(signal.SIGTERM)
- assert process.wait(DEADLINE) == 128 + signal.SIGTERM
- output += os.read(controller, 65536)
- os.close(controller)
- assert b"last line" in output
-
-
-@posix
-def test_an_object_that_the_signal_left_half_made_prints_nothing(run: Callable[..., Any]) -> None:
- script = """
-import time
-from unshackle.core import process_exit
-
-class Half:
- def __del__(self):
- raise AttributeError(self.name)
-
-with process_exit.unwinding():
- made = Half()
- made.name = "before"
- del made
- made = Half()
- try:
- print("ready", flush=True)
- time.sleep(120)
- except KeyboardInterrupt:
- del made
-"""
- process = run("-c", script)
- wait_line(process, "Exception ignored")
- wait_line(process, "ready")
- process.send_signal(signal.SIGTERM)
- output, _ = process.communicate(timeout=DEADLINE)
- assert process.returncode == 128 + signal.SIGTERM and output == ""
-
-
-@posix
-def test_nohup_and_the_handler_of_another_owner_stay(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- run: Callable[..., Any],
- tmp_path: Path,
-) -> None:
- process = client(run, server.url, tmp_path / "client", "handlers")
- assert "Handlers.SIG_IGN" in wait_line(process, "lambda")
- process.send_signal(signal.SIGHUP)
- still_runs(process)
- process.send_signal(signal.SIGTERM)
- assert process.wait(DEADLINE) == 3
-
-
-@posix
-def test_the_child_of_a_process_takes_no_handler_and_no_deadline(tmp_path: Path, run: Callable[..., Any]) -> None:
- script = """
-import subprocess, sys, time
-from unshackle.core import process_exit
-with process_exit.unwinding():
- show = "import signal; print(signal.getsignal(1) is signal.getsignal(15) is signal.SIG_DFL)"
- print(subprocess.check_output([sys.executable, "-c", show], text=True, encoding="utf-8", errors="replace"))
-"""
- output, _ = run("-c", script).communicate(timeout=DEADLINE)
- assert output.strip() == "True"
-
-
-@posix
-@pytest.mark.parametrize("first", ["", "SIGTERM"], ids=["close", "term-close"])
-@pytest.mark.parametrize("stderr", ["terminal", "file"])
-def test_a_closed_terminal_ends_the_session_in_silence(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- held_delete: HeldDelete, # noqa: F811
- run: Callable[..., Any],
- tmp_path: Path,
- stderr: str,
- first: str,
-) -> None:
- """The client leads the session of a real pty, and prints to it from a thread until the end.
-
- A service manager that stops a login session sends SIGTERM before the terminal closes.
- """
- import fcntl
- import pty
- import termios
-
- controller, terminal = pty.openpty()
- log = (tmp_path / "stderr.log").open("w")
-
- def take_terminal() -> None:
- os.setsid()
- fcntl.ioctl(terminal, termios.TIOCSCTTY, 0)
-
- process = client(
- run, server.url, tmp_path / "client", "print",
- stdin=terminal, stdout=terminal, stderr=terminal if stderr == "terminal" else log,
- start_new_session=False, preexec_fn=take_terminal,
- ) # fmt: skip
- os.close(terminal)
- read_until(controller, b"set up")
- store_cache()
- if first:
- send(process, first)
- assert held_delete.started.wait(DEADLINE)
- os.close(controller)
- assert held_delete.started.wait(DEADLINE)
- still_runs(process)
- held_delete.release.set()
-
- assert process.wait(DEADLINE) == 1
- log.close()
- assert "Traceback" not in (tmp_path / "stderr.log").read_text(encoding="utf-8")
- assert saved(tmp_path / "client") and sessions() == []
-
-
-@posix
-def test_a_terminal_that_closes_without_a_signal_ends_the_run_in_silence(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- run: Callable[..., Any],
- tmp_path: Path,
-) -> None:
- """The client is in the session of another process, so the writes fail and no SIGHUP comes."""
- import pty
-
- controller, terminal = pty.openpty()
- with (tmp_path / "stderr.log").open("w") as log:
- process = client(
- run, server.url, tmp_path / "client", "prints", stdin=terminal, stdout=terminal, stderr=log
- ) # fmt: skip
- os.close(terminal)
- read_until(controller, b"set up")
- store_cache()
- os.close(controller)
- assert process.wait(DEADLINE) == 1
- assert (tmp_path / "stderr.log").read_text(encoding="utf-8") == ""
- assert saved(tmp_path / "client") and sessions() == []
-
-
-@posix
-@pytest.mark.parametrize("name", SIGNALS)
-def test_a_redirected_file_keeps_its_lines(run: Callable[..., Any], tmp_path: Path, name: str) -> None:
- script = """
-import sys, time
-from unshackle.core import process_exit
-with process_exit.unwinding():
- try:
- print("ready", file=sys.stderr, flush=True)
- time.sleep(120)
- finally:
- print("last line", flush=True)
-"""
- with (tmp_path / "out.log").open("w") as out:
- process = run("-c", script, stdout=out, stderr=subprocess.PIPE)
- assert process.stderr is not None and "ready" in process.stderr.readline()
- send(process, name)
- process.stderr.close()
- process.wait(DEADLINE)
- assert "last line" in (tmp_path / "out.log").read_text(encoding="utf-8")
-
-
-@posix
-def test_an_error_of_a_thread_still_shows(run: Callable[..., Any]) -> None:
- """Only a write to a closed terminal is silent, not the same error of a disk."""
- script = """
-import errno
-from threading import Thread
-from unshackle.core import process_exit
-
-def fail(error):
- raise error
-
-with process_exit.unwinding():
- for error in (RuntimeError("first"), OSError(errno.EIO, "second")):
- Thread(target=fail, args=[error]).start()
-"""
- output, _ = run("-c", script).communicate(timeout=DEADLINE)
- assert "first" in output and "second" in output
-
-
-@pytest.mark.parametrize("name", SIGNALS)
-@pytest.mark.parametrize("command", ["dl", "search"])
-def test_the_command_ends_its_session(
- titles: SimpleNamespace,
- run: Callable[..., Any],
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
- command: str,
- name: str,
-) -> None:
- """The real command line; the search route opens no remote session, so its request is held on the server."""
- if command == "search":
-
- async def held(*args: Any, **kwargs: Any) -> Any:
- titles.started.set()
- await asyncio.to_thread(titles.release.wait, DEADLINE)
- raise RuntimeError("held")
-
- monkeypatch.setattr("unshackle.core.api.routes.search_handler", held)
- argv = [command, "--remote", "EXAMPLE", "example-1"]
- process = run("-c", COMMAND, json.dumps(settings(titles.server.url, tmp_path)), *argv)
- assert titles.started.wait(DEADLINE), process.kill() or process.communicate()[0]
- send(process, name)
- output, _ = process.communicate(timeout=DEADLINE)
- assert process.returncode != 0 and "Traceback" not in output
- if sys.platform != "win32":
- assert process.returncode == 1 and "Aborted" in output
- assert sessions() == []
- assert count(titles.server, "DELETE", SESSION_ROUTE) == (command == "dl")
-
-
-@posix
-@pytest.mark.parametrize("name", SIGNALS)
-def test_the_tunnel_test_closes_its_tunnel(
- server: SimpleNamespace, # noqa: F811
- run: Callable[..., Any],
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
- name: str,
-) -> None:
- started, release = Event(), Event()
-
- async def held(*args: Any, **kwargs: Any) -> Any:
- started.set()
- await asyncio.to_thread(release.wait, DEADLINE)
- raise RuntimeError("held")
-
- monkeypatch.setattr("unshackle.core.api.routes.tunnel_check_handler", held)
- process = run("-c", COMMAND, json.dumps(settings(server.url, tmp_path)), "tunnel-test")
- try:
- assert started.wait(DEADLINE), process.kill() or process.communicate()[0]
- send(process, name)
- output, _ = process.communicate(timeout=DEADLINE)
- finally:
- release.set()
- assert process.returncode == 1 and "Aborted" in output and "Traceback" not in output
- assert wait_until(lambda: not tunnel.TUNNELS, DEADLINE)
-
-
-@posix
-@pytest.mark.parametrize("delete", ["answers", "hangs"])
-def test_a_cancelled_job_ends_its_remote_session(
- titles: SimpleNamespace,
- held_delete: HeldDelete, # noqa: F811
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
- delete: str,
-) -> None:
- """The worker dies before the grace of ``stop`` ends, also on a DELETE with no answer, and writes no result."""
- script = worker_script(titles.server.url, tmp_path)
-
- async def cancel() -> tuple[float, int | None, Any, str]:
- with monkeypatch.context() as patch:
- patch.setattr(sys, "executable", str(script))
- worker = await WorkerProcess.spawn(JobPayload("job", "EXAMPLE", "example-1", {"remote": "test"}))
- try:
- if not await asyncio.to_thread(titles.started.wait, DEADLINE):
- await worker.stop()
- pytest.fail(str(worker.output()))
- store_cache()
- if delete == "answers":
- held_delete.release.set()
- sent = time.monotonic()
- await worker.stop()
- took = time.monotonic() - sent
- assert await worker.wait(DEADLINE)
- return took, worker.returncode, await worker.result(), worker.output()[1]
- finally:
- await worker.close()
-
- took, returncode, result, stderr = asyncio.run(cancel())
- assert took < 5 and returncode not in (0, -signal.SIGKILL) and result is None
- assert "Traceback" not in stderr
- assert held_delete.started.is_set()
- if delete == "answers":
- assert took < 3 and saved(tmp_path / "cache") and sessions() == []
-
-
-@posix
-def test_the_manager_keeps_a_cancelled_job_cancelled(
- titles: SimpleNamespace,
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
-) -> None:
- jobs = tmp_path / "jobs"
- jobs.mkdir()
- monkeypatch.setattr(tempfile, "tempdir", str(jobs))
- monkeypatch.setattr(sys, "executable", str(worker_script(titles.server.url, tmp_path)))
- monkeypatch.setattr("unshackle.core.api.api_proxy.recheck", lambda *args: None)
- monkeypatch.setattr(download_manager, "record_job_history", lambda job: None)
-
- async def cancel() -> Any:
- manager = download_manager.DownloadQueueManager()
- job = manager.create_job("EXAMPLE", "example-1", remote="test")
- running = asyncio.create_task(manager.download_worker("test"))
- assert await asyncio.to_thread(titles.started.wait, DEADLINE)
- worker = manager._workers[job.job_id]
- assert manager.cancel_job(job.job_id)
- await asyncio.wait_for(worker.process.wait(), DEADLINE)
- running.cancel()
- await asyncio.gather(running, return_exceptions=True)
- return job
-
- job = asyncio.run(cancel())
- assert job.status == download_manager.JobStatus.CANCELLED and job.error_message is None
- assert list(jobs.iterdir()) == []
- assert wait_until(lambda: sessions() == [], DEADLINE)
diff --git a/tests/remote/unit/test_progress_sink.py b/tests/remote/unit/test_progress_sink.py
index 532958364..8c535727b 100644
--- a/tests/remote/unit/test_progress_sink.py
+++ b/tests/remote/unit/test_progress_sink.py
@@ -12,9 +12,6 @@ import pytest
from unshackle.core.api.progress import (
DOWNLOAD_PROGRESS_CEILING,
build_job_progress_callables,
- track_log_label,
- track_progress_label,
- track_progress_weight,
)
pytestmark = pytest.mark.unit
@@ -49,27 +46,6 @@ def noop(**kwargs):
pass
-def test_track_log_label_adds_the_track_id():
- video = Video(2160, "DV")
- video.id = "592464997"
-
- assert track_log_label(video) == "video 2160p DV (592464997)"
-
-
-def test_track_progress_label():
- assert track_progress_label(Video(2160, "DV")) == "video 2160p DV"
- assert track_progress_label(Video(1080, "HDR10+")) == "video 1080p HDR10+"
- assert track_progress_label(Audio("en-US", "5.1")) == "audio en-US 5.1"
- assert track_progress_label(Subtitle("ro")) == "subtitle ro"
-
-
-def test_weight_video_over_audio_over_subtitle():
- assert track_progress_weight(Video(bitrate=4_000_000)) == 4_000_000
- assert track_progress_weight(Audio(bitrate=200_000)) == 200_000
- # subtitle has no bitrate -> small fixed weight, far below media
- assert track_progress_weight(Subtitle()) < track_progress_weight(Audio(bitrate=200_000))
-
-
def test_weighting_makes_video_dominate_progress():
updates: list[dict] = []
video, sub = Video(bitrate=4_000_000), Subtitle()
diff --git a/tests/remote/unit/test_progress_throttle.py b/tests/remote/unit/test_progress_throttle.py
index 10d70f109..44569c03d 100644
--- a/tests/remote/unit/test_progress_throttle.py
+++ b/tests/remote/unit/test_progress_throttle.py
@@ -56,18 +56,6 @@ def test_track_finish_bypasses_the_throttle():
assert updates[-1]["completed_tracks"] == 1
-def test_phase_change_bypasses_the_throttle():
- updates: list[dict] = []
- cbs = build_job_progress_callables([Video(2160), Video(720)], [noop, noop], updates.append)
-
- cbs[0](total=100, completed=1)
- first_phase = updates[-1]["phase"]
-
- cbs[1](total=100, completed=1)
- assert len(updates) == 2
- assert updates[-1]["phase"] != first_phase
-
-
def test_filled_track_bypasses_the_throttle_without_a_terminal_string():
"""A track can reach its segment total and never send "Downloaded". That last tick must land,
or the job reports a percentage that is short for good."""
diff --git a/tests/remote/unit/test_relay_stop.py b/tests/remote/unit/test_relay_stop.py
index 1492c9bb6..96dfebe9e 100644
--- a/tests/remote/unit/test_relay_stop.py
+++ b/tests/remote/unit/test_relay_stop.py
@@ -8,11 +8,8 @@ from __future__ import annotations
import asyncio
import json
import signal
-import time
from collections.abc import Callable
-from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
-from threading import Event, Lock, Semaphore
from types import SimpleNamespace
from typing import Any
@@ -20,25 +17,20 @@ import pytest
import requests
from aiohttp import web
-from tests.remote.unit.test_process_exit import BOUND, lasting_sessions, posix, run, settings, wait_line # noqa: F401
+from tests.remote.process import BOUND, lasting_sessions, posix, run, settings, wait_line # noqa: F401
from tests.remote.unit.test_remote_loopback import KEY, StubService, count, forget, make_client, server # noqa: F401
from tests.remote.unit.test_session_lifetime import DEADLINE, error_code, in_thread, logins, sessions # noqa: F401
-from tests.remote.unit.test_tunnel import wait_until
-from unshackle.core.api import handlers, routes
+from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError
from unshackle.core.api.handlers import (
- RelayStop,
RemoteLease,
RemoteLogin,
close_remote_pool,
end_remote_pool,
- end_reopening,
setup_remote_service,
)
from unshackle.core.api.routes import setup_routes
from unshackle.core.remote_protocol import (
- SESSION_ROUTE,
- TITLES_ROUTE,
APIErrorCode,
)
@@ -124,208 +116,10 @@ def ask(stub: StubService) -> None:
stub._input_bridge.request_input("Enter the EXAMPLE code")
-def poll_a_device(stub: StubService) -> None:
- while True:
- stub._input_bridge.ensure_active()
- time.sleep(0.01)
-
-
-def lose_session(server: SimpleNamespace, stub: StubService) -> None: # noqa: F811
- for entry in sessions():
- forget(server, entry.session_id)
- stub._input_bridge.ensure_active()
-
-
def nothing(stub: StubService) -> None:
pass
-@posix
-@pytest.mark.parametrize(
- ("server", "login", "titles"),
- [
- (True, ask, nothing),
- (True, poll_a_device, nothing),
- (True, nothing, ask),
- ],
- ids=["prompt", "device", "prompt-after-login"],
- indirect=["server"],
-)
-def test_a_stop_ends_a_remote_login(
- server: SimpleNamespace, # noqa: F811
- relay: Relay,
- monkeypatch: pytest.MonkeyPatch,
- login: Callable[[StubService], None],
- titles: Callable[[StubService], None],
-) -> None:
- """The login waits on the user, so nothing but the stop can end it, and its list call gets an answer."""
- monkeypatch.setattr(StubService, "authenticate", lambda self, cookies, credential: login(self))
- StubService.hooks["titles"] = titles
- reply = relay.list()
- assert wait_until(lambda: any(entry.channel.attached for entry in sessions()), DEADLINE)
- assert ask not in (login, titles) or wait_until(relay.asks, DEADLINE)
- relay.stop()
- relay.ended_well()
- assert (reply().status_code, error_code(reply())) == (409, APIErrorCode.SERVER_DRAINING)
-
-
-@posix
-def test_no_other_shutdown_hook_delays_the_end_of_a_login(
- run: Callable[..., Any], # noqa: F811
- server: SimpleNamespace, # noqa: F811
- tmp_path: Path,
-) -> None:
- released = tmp_path / "released"
- relay = Relay(run, server.url, tmp_path / "relay", str(released))
- relay.list()
- assert wait_until(relay.asks, DEADLINE)
- relay.stop()
- assert wait_until(lambda: sessions() == [], DEADLINE)
- released.touch()
- relay.ended_well()
-
-
-@posix
-@pytest.mark.parametrize("in_flight", [False, True], ids=["idle", "in-flight"])
-def test_a_stop_ends_the_pooled_sessions_at_the_same_time(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- relay: Relay,
- monkeypatch: pytest.MonkeyPatch,
- in_flight: bool,
-) -> None:
- """No DELETE is answered before the last one has arrived."""
- ids = ("example-1", "example-2", "example-3")
- started, release = Semaphore(0), Event()
-
- def hold(stub: StubService) -> None:
- started.release()
- assert release.wait(DEADLINE), "the test did not release the titles"
-
- if in_flight:
- StubService.hooks["titles"] = hold
- replies = [relay.list(title=title) for title in ids]
- for reply in replies:
- assert started.acquire(timeout=DEADLINE) if in_flight else reply().status_code == 200
- assert len(sessions()) == len(ids)
- together = asyncio.Barrier(len(ids))
- handler = routes.session_delete_handler
-
- async def held(session_id: str, request: Any) -> Any:
- await asyncio.wait_for(together.wait(), DEADLINE)
- return await handler(session_id, request)
-
- monkeypatch.setattr(routes, "session_delete_handler", held)
- relay.stop()
- if in_flight:
- wait_line(relay.process, "the shutdown hooks ended")
- release.set()
- relay.ended_well()
- assert [reply().status_code for reply in replies] == [200] * len(ids)
-
-
-@posix
-@pytest.mark.parametrize("pooled", [False, True], ids=["first-call", "pooled-session"])
-def test_a_request_in_flight_finishes_on_its_own_session(
- run: Callable[..., Any], # noqa: F811
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- tmp_path: Path,
- pooled: bool,
-) -> None:
- """The first call of a session fetches its titles while its login is still listed."""
- relay = Relay(run, server.url, tmp_path / "relay", wait=0.2)
- started, release = Event(), Event()
-
- def hold(stub: StubService) -> None:
- started.set()
- assert release.wait(DEADLINE), "the test did not release the titles"
-
- if pooled:
- assert relay.list("list-tracks")().status_code == 200
- StubService.hooks["titles"] = hold
- reply = relay.list("list-titles" if pooled else "list-tracks")
- assert started.wait(DEADLINE)
- relay.stop()
- wait_line(relay.process, "the reopens ended")
- release.set()
- assert reply().status_code == 200
- relay.ended_well()
- assert len(logins) == 1
- assert count(server, "GET", TITLES_ROUTE) == 1 + pooled
- assert count(server, "DELETE", SESSION_ROUTE) == 1
-
-
-@posix
-def test_a_session_lost_late_in_the_stop_does_not_hold_it(
- run: Callable[..., Any], # noqa: F811
- server: SimpleNamespace, # noqa: F811
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- relay = Relay(run, server.url, tmp_path / "relay", wait=0.2)
- started, release = Event(), Event()
-
- def lose(stub: StubService) -> None:
- started.set()
- assert release.wait(DEADLINE), "the test did not release the titles"
- lose_session(server, stub)
-
- def login(stub: StubService, cookies: Any, credential: Any) -> None:
- if release.is_set():
- poll_a_device(stub)
-
- monkeypatch.setattr(StubService, "authenticate", login)
- StubService.hooks["titles"] = lose
- reply = relay.list()
- assert started.wait(DEADLINE)
- relay.stop()
- wait_line(relay.process, "the reopens ended")
- release.set()
- assert reply().status_code == 409
- relay.ended_well()
-
-
-@posix
-@pytest.mark.parametrize("waits", [True, False], ids=["waits", "finishes"])
-@pytest.mark.parametrize("pooled", [False, True], ids=["first-call", "pooled-session"])
-def test_a_request_that_opens_its_lost_session_again_finishes_in_time_or_is_cut(
- run: Callable[..., Any], # noqa: F811
- server: SimpleNamespace, # noqa: F811
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
- pooled: bool,
- waits: bool,
-) -> None:
- """The upstream server loses the remote session, and the login of the next one waits for an approval."""
- relay = Relay(run, server.url, tmp_path / "relay", wait=0.2 if waits else DEADLINE)
- lost, reopening, approved = Event(), Event(), Event()
-
- def lose(stub: StubService) -> None:
- StubService.hooks.clear()
- lost.set()
- lose_session(server, stub)
-
- def login(stub: StubService, cookies: Any, credential: Any) -> None:
- if lost.is_set():
- reopening.set()
- while not approved.wait(0.01):
- stub._input_bridge.ensure_active()
-
- monkeypatch.setattr(StubService, "authenticate", login)
- if pooled:
- assert relay.list("list-tracks")().status_code == 200
- StubService.hooks["titles"] = lose
- reply = relay.list()
- assert reopening.wait(DEADLINE)
- relay.stop()
- wait_line(relay.process, "the shutdown hooks ended")
- if not waits:
- approved.set()
- assert reply().status_code == (409 if waits else 200)
- relay.ended_well()
-
-
def relay_app() -> web.Application:
app = web.Application()
setup_routes(app)
@@ -378,26 +172,6 @@ def test_a_login_that_starts_as_the_relay_stops_is_refused(
assert server.seen == [] and not handlers._remote_logins
-def test_a_login_that_the_stop_reaches_before_its_create_opens_no_session(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- pool: dict[tuple, RemoteLease],
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- app, client = relay_app(), make_client(server.url)
- authenticate = client.authenticate
-
- def stop_first() -> None:
- asyncio.run(end_remote_pool(app))
- authenticate()
-
- monkeypatch.setattr(client, "authenticate", stop_first)
- with pytest.raises(APIError) as refused:
- log_in(app, client, monkeypatch)
- assert refused.value.error_code == APIErrorCode.SERVER_DRAINING
- assert server.seen == []
-
-
def test_a_request_in_flight_keeps_its_own_error(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
@@ -416,22 +190,6 @@ def test_a_request_in_flight_keeps_its_own_error(
assert sessions() == []
-def test_the_stop_refuses_before_it_reads_the_logins(
- pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch
-) -> None:
- app = relay_app()
- started: list[bool] = []
-
- class Logins(dict[str, Any]):
- def values(self) -> Any:
- started.append(app["relay_stop"].started)
- return super().values()
-
- monkeypatch.setattr(handlers, "_remote_logins", Logins())
- asyncio.run(end_remote_pool(app))
- assert started == [True]
-
-
def test_another_app_of_the_process_still_logs_in(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
@@ -446,73 +204,6 @@ def test_another_app_of_the_process_still_logs_in(
assert len(logins) == 1
-async def test_the_stop_waits_for_the_ends_and_not_for_the_default_executor(
- pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch
-) -> None:
- """The ends finish while the stop waits. A busy remote session stays open."""
- closed: list[str] = []
- begun, finish, free_workers = Event(), Event(), Event()
- workers = ThreadPoolExecutor(1)
- asyncio.get_running_loop().set_default_executor(workers)
- workers.submit(free_workers.wait, DEADLINE)
-
- def end(name: str) -> None:
- begun.set()
- assert finish.wait(DEADLINE)
- closed.append(name)
-
- async def finish_later() -> None:
- while not begun.is_set():
- await asyncio.sleep(0.01)
- finish.set()
-
- monkeypatch.setattr(handlers, "LOGIN_WAIT", DEADLINE / 4)
- for name in ("a", "b", "busy"):
- service = SimpleNamespace(close=lambda name=name: end(name))
- pool[(name,)] = RemoteLease((name,), service=service, busy=int(name == "busy"))
- app = relay_app()
- try:
- later = asyncio.create_task(finish_later())
- await close_remote_pool(app)
- assert sorted(closed) == ["a", "b"] and list(pool) == [("busy",)]
- assert all(thread.daemon for thread in app["relay_stop"].ends)
- await later
- finally:
- free_workers.set()
- finish.set()
-
-
-async def test_an_end_that_does_not_finish_holds_the_stop_no_longer_than_the_wait(
- pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch
-) -> None:
- closed, release = Event(), Event()
-
- def end() -> None:
- release.wait(DEADLINE)
- closed.set()
-
- monkeypatch.setattr(handlers, "LOGIN_WAIT", 0.05)
- pool[("stuck",)] = RemoteLease(("stuck",), service=SimpleNamespace(close=end))
- try:
- await asyncio.wait_for(close_remote_pool(relay_app()), DEADLINE / 2)
- assert not closed.is_set()
- finally:
- release.set()
-
-
-async def test_a_reopen_is_ended_once(pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch) -> None:
- lifetime = SimpleNamespace(ended=False)
- service = SimpleNamespace(lifetime=lifetime, _reopen_lock=Lock(), close=lambda: setattr(lifetime, "ended", True))
- monkeypatch.setattr(handlers, "LOGIN_WAIT", DEADLINE)
- pool[("EXAMPLE",)] = RemoteLease(("EXAMPLE",), service=service, busy=1)
- stop = RelayStop()
- with service._reopen_lock:
- for _ in range(2):
- end_reopening(stop)
- stop.ends[0].join(DEADLINE)
- assert len(stop.ends) == 1
-
-
async def test_the_last_call_ends_also_the_login_of_a_request_that_did_not_finish(
pool: dict[tuple, RemoteLease],
) -> None:
diff --git a/tests/remote/unit/test_remote_client.py b/tests/remote/unit/test_remote_client.py
index 971f05206..cd90784c2 100644
--- a/tests/remote/unit/test_remote_client.py
+++ b/tests/remote/unit/test_remote_client.py
@@ -3,12 +3,10 @@
from __future__ import annotations
import json
-import logging
import socket
import threading
from pathlib import Path
-import click
import pytest
import requests
import responses
@@ -26,49 +24,11 @@ def client() -> RemoteClient:
return RemoteClient(server_url="http://srv:8786", api_key="secret-xyz")
-def test_session_sets_secret_key_header(client: RemoteClient) -> None:
- s = client.session
- assert s.headers.get("X-Secret-Key") == "secret-xyz"
- assert s.headers["User-Agent"].startswith("unshackle/")
-
-
def test_session_omits_secret_key_when_empty() -> None:
c = RemoteClient(server_url="http://srv:8786", api_key="")
assert "X-Secret-Key" not in c.session.headers
-def test_server_url_trailing_slash_stripped() -> None:
- c = RemoteClient(server_url="http://srv:8786/", api_key="")
- assert c.server_url == "http://srv:8786"
-
-
-@responses.activate
-def test_get_returns_json(client: RemoteClient) -> None:
- responses.add(
- responses.GET,
- "http://srv:8786/api/health",
- json={"status": "ok"},
- status=200,
- )
- assert client.get("/api/health") == {"status": "ok"}
-
-
-@responses.activate
-def test_post_sends_json_body(client: RemoteClient) -> None:
- captured = {}
-
- def cb(request):
- captured["body"] = json.loads(request.body)
- return (200, {}, json.dumps({"session_id": "abc"}))
-
- responses.add_callback(
- responses.POST, "http://srv:8786/api/session/create", callback=cb, content_type="application/json"
- )
- result = client.post("/api/session/create", {"service": "EXAMPLE"})
- assert result == {"session_id": "abc"}
- assert captured["body"] == {"service": "EXAMPLE"}
-
-
@responses.activate
def test_4xx_raises_systemexit_with_logged_error(client: RemoteClient, caplog: pytest.LogCaptureFixture) -> None:
responses.add(
@@ -106,19 +66,6 @@ def test_second_proxy_502_page_exits(client: RemoteClient, monkeypatch: pytest.M
assert len(responses.calls) == 2
-@responses.activate
-def test_server_json_503_is_not_retried(client: RemoteClient) -> None:
- responses.add(
- responses.GET,
- "http://srv:8786/api/services",
- json={"error_code": "SERVICE_UNAVAILABLE", "message": "busy"},
- status=503,
- )
- with pytest.raises(SystemExit):
- client.get("/api/services")
- assert len(responses.calls) == 1
-
-
@responses.activate
def test_401_falls_back_to_next_auth_header(client: RemoteClient) -> None:
seen: list[tuple[str | None, str | None]] = []
@@ -178,32 +125,6 @@ def test_single_configured_auth_header_does_not_retry() -> None:
assert c.session.headers.get("X-Api-Key") == "k"
-@responses.activate
-def test_connection_error_raises_systemexit(client: RemoteClient) -> None:
- import requests
-
- responses.add(
- responses.GET,
- "http://srv:8786/api/health",
- body=requests.ConnectionError("boom"),
- )
- with pytest.raises(SystemExit):
- client.get("/api/health")
-
-
-@responses.activate
-def test_timeout_raises_systemexit(client: RemoteClient) -> None:
- import requests
-
- responses.add(
- responses.GET,
- "http://srv:8786/api/health",
- body=requests.Timeout("slow"),
- )
- with pytest.raises(SystemExit):
- client.get("/api/health")
-
-
@responses.activate
def test_late_error_after_heartbeat_is_fatal(client: RemoteClient) -> None:
"""A heartbeat response carries a late failure as a 200 error body after leading newlines."""
@@ -264,36 +185,6 @@ def test_an_answer_cut_off_after_its_headers_is_a_connect_error(
assert e.value.session_broke
-@responses.activate
-def test_heartbeat_body_parses_past_leading_newlines(client: RemoteClient) -> None:
- responses.add(responses.GET, "http://srv:8786/api/session/s/titles", body='\n\n{"titles": []}', status=200)
- assert client.get("/api/session/s/titles") == {"titles": []}
-
-
-def test_read_timeout_in_body_reports_timeout(client: RemoteClient, caplog: pytest.LogCaptureFixture) -> None:
- """requests re-raises a read timeout in the body as a ConnectionError; the client still names the timeout."""
- import requests
- import urllib3
-
- def stalled(*args: object, **kwargs: object) -> None:
- raise requests.ConnectionError(urllib3.exceptions.ReadTimeoutError(None, "", "Read timed out."))
-
- client.session.get = stalled # type: ignore[method-assign]
- with pytest.raises(SystemExit):
- client.get("/api/session/s/titles")
- assert "timed out after 120" in caplog.text
-
-
-@responses.activate
-def test_proxy_error_page_logs_its_title(client: RemoteClient, caplog: pytest.LogCaptureFixture) -> None:
- page = "example.com | 524: A timeout occurredx"
- responses.add(responses.GET, "http://srv:8786/api/session/s/titles", body=page, status=524)
- with pytest.raises(SystemExit):
- client.get("/api/session/s/titles")
- assert "HTTP 524: example.com | 524: A timeout occurred" in caplog.text
- assert "DOCTYPE" not in caplog.text
-
-
@responses.activate
def test_a_429_with_retry_after_waits_then_retries(client: RemoteClient, monkeypatch: pytest.MonkeyPatch) -> None:
waits: list[int] = []
@@ -315,75 +206,6 @@ def test_a_429_without_retry_after_fails_at_once(client: RemoteClient, monkeypat
client.get("/api/services")
-def test_wait_retry_after_waits_out_its_own_deadline(monkeypatch: pytest.MonkeyPatch) -> None:
- from unshackle.core import remote_service
-
- clock = [0.0]
- monkeypatch.setattr(remote_service.time, "monotonic", lambda: clock[0])
- monkeypatch.setattr(remote_service.time, "sleep", lambda s: clock.__setitem__(0, clock[0] + s))
- remote_service.wait_retry_after(3)
- assert clock[0] == 3.0
- remote_service.wait_retry_after(99999)
- assert clock[0] == 3.0 + remote_service.RETRY_AFTER_MAX
-
-
-def test_a_rate_limited_tunnel_waits_then_opens(client: RemoteClient, monkeypatch: pytest.MonkeyPatch) -> None:
- from unshackle.core import remote_service
-
- attempts: list[object] = []
-
- class Refused:
- def __init__(self, *_: object) -> None:
- self.retry_after = 5 if not attempts else None
- self.at_limit = len(attempts) == 1
- attempts.append(self)
-
- def start(self) -> str:
- if self.retry_after or self.at_limit:
- raise ConnectionError("HTTP 429")
- return "id"
-
- waits: list[int] = []
- monkeypatch.setattr(remote_service, "TunnelClient", Refused)
- monkeypatch.setattr(remote_service, "wait_retry_after", lambda s, *_: waits.append(s))
- assert remote_service.start_tunnel(client) is attempts[2]
- assert waits == [5, remote_service.TUNNEL_SLOT_POLL]
-
-
-def test_a_tunnel_refused_for_another_reason_fails_at_once(
- client: RemoteClient, monkeypatch: pytest.MonkeyPatch
-) -> None:
- from unshackle.core import remote_service
-
- class Refused:
- retry_after = None
- at_limit = False
-
- def __init__(self, *_: object) -> None:
- pass
-
- def start(self) -> str:
- raise ConnectionError("HTTP 403")
-
- monkeypatch.setattr(remote_service, "TunnelClient", Refused)
- monkeypatch.setattr(remote_service, "wait_retry_after", pytest.fail)
- with pytest.raises(click.ClickException, match="HTTP 403"):
- remote_service.start_tunnel(client)
-
-
-@responses.activate
-def test_the_429_wait_gives_up_after_its_tries(client: RemoteClient, monkeypatch: pytest.MonkeyPatch) -> None:
- from unshackle.core import remote_service
-
- waits: list[int] = []
- monkeypatch.setattr(remote_service, "wait_retry_after", waits.append)
- responses.add(responses.GET, "http://srv:8786/api/services", status=429, json={}, headers={"Retry-After": "0"})
-
- with pytest.raises(SystemExit):
- client.get("/api/services")
- assert waits == [1] * remote_service.RATE_LIMIT_TRIES
-
-
@responses.activate
def test_a_401_after_a_header_worked_keeps_that_header(client: RemoteClient) -> None:
responses.add(responses.GET, "http://srv:8786/api/services", json={"services": []})
@@ -420,14 +242,6 @@ def test_a_probe_reads_a_gateway_page_as_the_request_does(
assert client.probe("/api/health") == {}
-@responses.activate
-def test_a_probe_that_cannot_connect_logs_no_error(client: RemoteClient, caplog: pytest.LogCaptureFixture) -> None:
- responses.add(responses.GET, "http://srv:8786/api/health", body=requests.ConnectionError("refused"))
-
- assert client.probe("/api/health") == {}
- assert not [r for r in caplog.records if r.levelno >= logging.WARNING]
-
-
@responses.activate
def test_any_other_requests_failure_is_one_remote_error(client: RemoteClient) -> None:
leak = requests.TooManyRedirects("http://user:pw@gw.example/login?token=SECRET")
diff --git a/tests/remote/unit/test_remote_command_unknown_tag.py b/tests/remote/unit/test_remote_command_unknown_tag.py
index 546fdec39..05bcb57f3 100644
--- a/tests/remote/unit/test_remote_command_unknown_tag.py
+++ b/tests/remote/unit/test_remote_command_unknown_tag.py
@@ -41,12 +41,6 @@ def test_unknown_name_raises_with_typed_name_and_available_list() -> None:
_make("NOPE")
-def test_served_tag_builds_full_command() -> None:
- with patch.object(Services, "fetch_remote_services", return_value=SERVED):
- cmd = _make("EXAMPLE")
- assert cmd.help == "Example service."
-
-
def test_server_alias_resolves_to_server_tag() -> None:
with patch.object(Services, "fetch_remote_services", return_value=SERVED):
cmd = _make("alt")
@@ -54,19 +48,6 @@ def test_server_alias_resolves_to_server_tag() -> None:
assert cmd.help == "Demo service."
-def test_empty_service_list_raises_no_services_message() -> None:
- with patch.object(Services, "fetch_remote_services", return_value=[]):
- with pytest.raises(click.ClickException, match=r"offers no services to your API key"):
- _make("EXAMPLE")
-
-
-def test_fetch_failure_keeps_stub_instead_of_raising() -> None:
- with patch.object(Services, "fetch_remote_services", return_value=None):
- cmd = _make("EXAMPLE")
- assert cmd.name == "EXAMPLE"
- assert cmd.help is None
-
-
def test_options_keep_the_served_name() -> None:
with patch.object(Services, "fetch_remote_services", return_value=SERVED):
cmd = _make("EXAMPLE")
diff --git a/tests/remote/unit/test_remote_flag_options.py b/tests/remote/unit/test_remote_flag_options.py
index 7e1d36abe..1c8502c88 100644
--- a/tests/remote/unit/test_remote_flag_options.py
+++ b/tests/remote/unit/test_remote_flag_options.py
@@ -54,12 +54,6 @@ def test_no_flag_reaches_the_server_service(listing: dict[str, Any]) -> None:
assert served(params) == {"title": "an-id", "flag": False, "loud": False, "quiet": True}
-def test_a_secondary_only_alias_with_a_callable_default_reaches_the_server(listing: dict[str, Any]) -> None:
- params = sent(listing, ["-Q"])
- assert params == {"flag": True, "quiet": False}
- assert served(params)["quiet"] is False
-
-
def test_a_default_value_is_sent_as_before(listing: dict[str, Any]) -> None:
assert sent(listing, []) == {"flag": True}
assert sent(listing, ["--loud"]) == {"flag": True, "loud": True}
diff --git a/tests/remote/unit/test_remote_loopback.py b/tests/remote/unit/test_remote_loopback.py
index 84eba6a52..a8a89fe0c 100644
--- a/tests/remote/unit/test_remote_loopback.py
+++ b/tests/remote/unit/test_remote_loopback.py
@@ -5,15 +5,13 @@ from __future__ import annotations
import asyncio
import json
import logging
-import threading
from collections.abc import Callable, Iterator
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
-from threading import Event, Semaphore, Thread
+from threading import Semaphore, Thread
from types import SimpleNamespace
from typing import Any
-import aiohttp
import click
import pytest
import requests
@@ -24,17 +22,10 @@ from tests.remote.sessions import stub_service_build
from tests.remote.unit.test_tunnel import wait_until
from unshackle.core import remote_channel, remote_service
from unshackle.core.api import handlers, routes, session_store
-from unshackle.core.api.client_presence import LEFT_LIMIT
-from unshackle.core.api.errors import APIError
from unshackle.core.api.handlers import api_key_authentication
from unshackle.core.api.routes import cors_middleware, no_5xx_middleware, setup_routes
-from unshackle.core.cdm import client_relay
from unshackle.core.config import config
-from unshackle.core.console import console, qr_text
-from unshackle.core.remote_channel import WebSocketChannel
-from unshackle.core.remote_protocol import CHANNEL_ROUTE, SESSION_ROUTE, TITLES_ROUTE, APIErrorCode, ClientErrorKind
-from unshackle.core.remote_service import RemoteError, RemoteService
-from unshackle.core.service import Service
+from unshackle.core.remote_service import RemoteService
from unshackle.core.session import RnetSession, record_requests
from unshackle.core.title_source import TitleSource
from unshackle.core.titles.movie import Movie, Movies
@@ -226,234 +217,11 @@ def count(server: SimpleNamespace, method: str, route: str, session_id: str | No
return len([s for s in server.seen if s[:2] == (method, route.format(session_id=session_id))])
-def polled(server: SimpleNamespace) -> list[tuple[str, str, int]]:
- """The requests to a prompt or logs route, which the server no longer has and the client never sends."""
- return [s for s in server.seen if s[1].endswith(("/prompt", "/logs"))]
-
-
def example_messages(caplog: pytest.LogCaptureFixture) -> list[str]:
"""What the client logged as the service's own lines, which the server relayed."""
return [r.getMessage() for r in caplog.records if r.name == "EXAMPLE"]
-def test_a_remote_session_runs_end_to_end_over_the_channel(
- server: SimpleNamespace, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
-) -> None:
- """Create, a login prompt, titles, tracks, a licence that calls the client's CDM and a lost session: none polls."""
- caplog.set_level(logging.DEBUG)
- monkeypatch.setattr(session_store.SessionStore, "_expired", lambda self, entry: False)
- monkeypatch.setattr(client_relay, "answer_cdm_call", lambda cdm, call, sessions: {"op": call["op"]})
- asked: list[str] = []
- service = make_client(server.url, cdm=SimpleNamespace())
- service._input_bridge = SimpleNamespace(request_input=lambda prompt, qr=None: asked.append(prompt) or CODE)
- try:
- service.authenticate()
- first = service._session_id
- assert first
- assert server.seen[0] == ("POST", "/api/session/create", 401)
- assert asked == ["Enter the EXAMPLE code"]
- assert isinstance(service.channel, WebSocketChannel) and service.channel.connected.is_set()
- assert any(r.name == "EXAMPLE" and r.message == "Logged in to EXAMPLE, login 1" for r in caplog.records)
-
- titles = service.get_titles()
- assert [str(t.id) for t in titles] == ["example-1", "example-2", "example-3"]
- m1, m2, m3 = titles
- (audio,) = service.get_tracks(m1).audio
- assert str(audio.id) == "example-1-login1"
- assert service.get_widevine_license(challenge=b"EXAMPLE", title=m1, track=audio) == b'{"op": "close"}'
-
- forget(server, first)
- assert [str(t.id) for t in service.get_tracks(m2).audio] == ["example-2-login2"]
- assert service._session_id not in (None, first)
- assert "The remote session was lost, opening a new one" in caplog.messages
- assert asked == ["Enter the EXAMPLE code"] * 2
-
- with pytest.raises(RemoteError) as late:
- service.get_tracks(m3)
- assert late.value.kind not in (APIErrorCode.SESSION_NOT_FOUND, "UNKNOWN")
- assert not late.value.session_broke
- assert [s for s in server.seen if s[1].endswith("/tracks")][-1][2] == 200
- finally:
- second = service._session_id
- service.close()
- assert service.channel is None
- assert ("DELETE", SESSION_ROUTE.format(session_id=second), 200) in server.seen
- assert not session_store.get_session_store()._sessions
- assert polled(server) == []
-
-
-@pytest.mark.parametrize(
- "server,channel",
- [(False, "refused"), (True, "failed")],
- ids=["refused-upgrade", "failed-connect"],
- indirect=["server"],
-)
-def test_a_channel_that_cannot_open_stops_the_client_with_one_line(
- server: SimpleNamespace, channel: str, monkeypatch: pytest.MonkeyPatch
-) -> None:
- monkeypatch.setattr(remote_channel, "RECONNECT_DELAY", 0.05)
- if channel == "failed":
-
- async def unreachable(self: Any, url: str, **kwargs: Any) -> Any:
- raise aiohttp.ClientConnectionError("EXAMPLE connect failed")
-
- monkeypatch.setattr(aiohttp.ClientSession, "_ws_connect", unreachable)
- service = make_client(server.url)
- try:
- with pytest.raises(RemoteError) as stopped:
- service.authenticate()
- finally:
- service.close()
- if channel == "refused":
- assert stopped.value.message == f"The remote server at {server.url} refused the session channel: HTTP 502"
- assert stopped.value.kind == ClientErrorKind.UNKNOWN
- else:
- assert stopped.value.message == f"Could not open the session channel to {server.url}: EXAMPLE connect failed"
- assert stopped.value.kind == ClientErrorKind.CONNECT
- assert count(server, "GET", TITLES_ROUTE) == 0 and polled(server) == []
- assert wait_until(lambda: not session_store.get_session_store()._sessions, 5)
- assert count(server, "GET", CHANNEL_ROUTE) == (2 if channel == "refused" else 0)
-
-
-@pytest.mark.parametrize(("status", "opens"), [(429, True), (422, False)])
-def test_the_first_channel_open_tries_once_more_after_a_rate_limit_answer(
- server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, status: int, opens: bool
-) -> None:
- monkeypatch.setattr(remote_channel, "RECONNECT_DELAY", 0.05)
- channel_handler = routes.session_channel_handler
- answered: list[int] = []
-
- async def once(session_id: str, request: web.Request) -> web.StreamResponse:
- if not answered:
- answered.append(status)
- return web.Response(status=status, headers={"Retry-After": "0"})
- return await channel_handler(session_id, request)
-
- monkeypatch.setattr(routes, "session_channel_handler", once)
- service = make_client(server.url)
- try:
- if opens:
- service.authenticate()
- assert isinstance(service.channel, WebSocketChannel) and service.channel.connected.is_set()
- else:
- with pytest.raises(RemoteError, match=f"refused the session channel: HTTP {status}$"):
- service.authenticate()
- finally:
- service.close()
- assert answered == [status]
-
-
-def test_a_qr_code_reaches_the_client_terminal_with_its_prompt(
- server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
-) -> None:
- payload = "https://login.example/scan?code=EXAMPLE"
-
- def authenticate(self: StubService, cookies: Any, credential: Any) -> None:
- if self._input_bridge.request_input("Scan the EXAMPLE code, then press Enter", qr=payload) != CODE:
- raise ValueError("wrong code")
-
- monkeypatch.setattr(StubService, "authenticate", authenticate)
- printed: list[Any] = []
- asked: list[str] = []
- monkeypatch.setattr(console, "print", lambda *a, **k: printed.extend(a))
- monkeypatch.setattr(console, "input", lambda prompt: asked.append(str(prompt)) or CODE)
- service = make_client(server.url)
- service._input_bridge = None
- try:
- service.authenticate()
- assert isinstance(service.channel, WebSocketChannel)
- finally:
- service.close()
- assert [p.plain for p in printed if hasattr(p, "plain")] == [qr_text(payload).plain]
- assert len(asked) == 1 and "Scan the EXAMPLE code" in asked[0]
-
-
-def test_a_qr_code_to_approve_reaches_the_client_with_its_log_line(
- server: SimpleNamespace, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
-) -> None:
- caplog.set_level(logging.INFO)
- payload = "https://login.example/approve?code=EXAMPLE"
- printed: list[Any] = []
- monkeypatch.setattr(console, "print", lambda *a, **k: printed.extend(a))
-
- expected = qr_text(payload).plain
-
- def drawn() -> bool | None:
- return any(getattr(p, "plain", None) == expected for p in printed) or None
-
- def authenticate(self: StubService, cookies: Any, credential: Any) -> None:
- Service.wait_for_approval(self, "Scan the EXAMPLE code", drawn, 10, 0.01, payload)
-
- monkeypatch.setattr(StubService, "authenticate", authenticate)
- service = make_client(server.url)
- service._input_bridge = None
- try:
- service.authenticate()
- assert isinstance(service.channel, WebSocketChannel)
- finally:
- service.close()
- assert "Scan the EXAMPLE code" in example_messages(caplog)
- assert [p.plain for p in printed if hasattr(p, "plain")] == [qr_text(payload).plain]
-
-
-def test_the_session_channel_carries_what_the_server_starts(
- server: SimpleNamespace, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
-) -> None:
- caplog.set_level(logging.INFO)
- monkeypatch.setattr(client_relay, "answer_cdm_call", lambda cdm, call, sessions: {"op": call["op"]})
- answers: list[Any] = []
- release = Event()
-
- def titles(stub: StubService) -> None:
- stub.log.info("Listing EXAMPLE titles")
- assert release.wait(10)
- answers.append(stub._input_bridge.request_cdm({"op": "close", "session": "EXAMPLE"}))
- answers.append(stub._input_bridge.request_input("Pick an EXAMPLE profile"))
-
- StubService.hooks["titles"] = titles
- service = make_client(server.url, cdm=SimpleNamespace())
- store = session_store.get_session_store()
- try:
- service.authenticate()
- first = service._session_id
- assert first
- assert isinstance(service.channel, WebSocketChannel) and service.channel.connected.is_set()
- assert "Logged in to EXAMPLE, login 1" in example_messages(caplog)
-
- listed: list[Any] = []
- listing = Thread(target=lambda: listed.append(service.get_titles()), daemon=True)
- listing.start()
- assert wait_until(lambda: "Listing EXAMPLE titles" in example_messages(caplog), 10)
- assert listing.is_alive(), "the log record must arrive while its call still runs"
- release.set()
- listing.join(10)
- assert [str(t.id) for t in listed[0]] == ["example-1", "example-2", "example-3"]
- assert answers == [{"op": "close"}, CODE]
- assert service.get_tracks(listed[0][0]).audio
-
- forget(server, first)
- assert wait_until(lambda: not service.channel.connected.is_set(), 5)
- assert [str(t.id) for t in service.get_tracks(listed[0][1]).audio] == ["example-2-login2"]
- second = service._session_id
- assert second not in (None, first)
- assert isinstance(service.channel, WebSocketChannel) and service.channel.connected.is_set()
- assert wait_until(lambda: store.peek(second).channel.attached, 5)
-
- info = count(server, "GET", SESSION_ROUTE, second)
- server.loop.call_soon_threadsafe(store.start_drain)
- assert wait_until(lambda: service.channel.draining_now, 5)
- assert count(server, "GET", SESSION_ROUTE, second) == info
- assert wait_until(lambda: session_store.DRAIN_WARNING in example_messages(caplog), 5)
- assert service.server_draining()
- server.loop.call_soon_threadsafe(store.stop_drain)
- assert wait_until(lambda: not store.draining, 5)
- assert wait_until(lambda: not service.server_draining(), 5)
- assert polled(server) == []
- finally:
- release.set()
- service.close()
-
-
class Origin(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
@@ -522,132 +290,3 @@ def test_server_request_records_never_reach_the_remote_client(
assert all("body" not in e["response"] for e in entries)
own = [e for e in entries if e["request"]["host"] == server_host and e["request"]["path"].endswith("/titles")]
assert own and all((tmp_path / "server" / e["response"]["body_file"]).is_file() for e in own)
-
-
-def test_an_open_channel_keeps_the_session_alive(server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> None:
- ttl = 0.3
- monkeypatch.setitem(config.serve, "session_ttl", ttl)
- service = make_client(server.url)
- store = session_store.get_session_store()
- try:
- service.authenticate()
- session_id = service._session_id
- entry = store.peek(session_id)
- assert wait_until(lambda: entry.channel.attached, 5)
- assert wait_until(lambda: entry.idle_seconds > 3 * ttl, 10)
- assert on_loop(server, store.cleanup_expired()) == 0
- assert store.peek(session_id) is entry
- assert count(server, "GET", SESSION_ROUTE, session_id) == 0
- assert polled(server) == []
-
- monkeypatch.setitem(config.serve, "session_ttl", 300)
- service.lifetime.close_channel()
- assert wait_until(lambda: not entry.channel.attached, 5)
- assert on_loop(server, store.cleanup_expired()) == 0
- entry.presence.seen_at -= LEFT_LIMIT + 1
- assert on_loop(server, store.cleanup_expired()) == 1
- assert store.peek(session_id) is None
- assert count(server, "GET", SESSION_ROUTE, session_id) == 0
- finally:
- service.close()
-
-
-def gate_channel(monkeypatch: pytest.MonkeyPatch) -> threading.Event:
- """Make the channel route refuse while the returned event is set, as a gateway that drops WebSockets does."""
- monkeypatch.setattr(remote_channel, "RECONNECT_DELAY", 0.05)
- refuse = threading.Event()
- channel_handler = routes.session_channel_handler
-
- async def gated(session_id: str, request: web.Request) -> web.StreamResponse:
- if refuse.is_set():
- raise APIError(APIErrorCode.SERVICE_UNAVAILABLE, "The EXAMPLE channel is down")
- return await channel_handler(session_id, request)
-
- monkeypatch.setattr(routes, "session_channel_handler", gated)
- return refuse
-
-
-def test_a_dropped_channel_reconnects_and_nothing_polls_meanwhile(
- server: SimpleNamespace, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
-) -> None:
- caplog.set_level(logging.INFO)
- refuse = gate_channel(monkeypatch)
- StubService.hooks["titles"] = lambda stub: stub.log.info("Listing EXAMPLE titles")
- service = make_client(server.url)
- store = session_store.get_session_store()
- try:
- service.authenticate()
- session_id = service._session_id
- entry = store.peek(session_id)
- channel = service.channel
- assert isinstance(channel, WebSocketChannel)
- assert wait_until(lambda: entry.channel.attached, 5)
-
- refuse.set()
- on_loop(server, entry.channel.ws.close())
- assert wait_until(lambda: not channel.connected.is_set(), 5)
- titles = service.get_titles()
- assert "Listing EXAMPLE titles" not in example_messages(caplog)
- assert count(server, "GET", SESSION_ROUTE, session_id) == 0 and polled(server) == []
-
- refuse.clear()
- assert wait_until(lambda: channel.connected.is_set() and entry.channel.attached, 10)
- assert wait_until(lambda: "Listing EXAMPLE titles" in example_messages(caplog), 5)
- assert service.get_tracks(titles[0]).audio
- assert example_messages(caplog).count("Listing EXAMPLE titles") == 1
- assert count(server, "GET", SESSION_ROUTE, session_id) == 0 and polled(server) == []
- finally:
- service.close()
-
-
-def test_a_cdm_call_made_while_the_channel_is_down_waits_for_the_reconnect(
- server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
-) -> None:
- refuse = gate_channel(monkeypatch)
- monkeypatch.setattr(client_relay, "answer_cdm_call", lambda cdm, call, sessions: {"op": call["op"]})
- service = make_client(server.url, cdm=SimpleNamespace())
- store = session_store.get_session_store()
- answers: list[Any] = []
-
- def titles(stub: StubService) -> None:
- refuse.set()
- entry = store.peek(service._session_id)
- asyncio.run_coroutine_threadsafe(entry.channel.ws.close(), server.loop).result(5)
- assert wait_until(lambda: not service.channel.connected.is_set() and not entry.channel.attached, 5)
- refuse.clear()
- answers.append(stub._input_bridge.request_cdm({"op": "close", "session": "EXAMPLE"}))
-
- StubService.hooks["titles"] = titles
- try:
- service.authenticate()
- assert isinstance(service.channel, WebSocketChannel)
- service.get_titles()
- assert answers == [{"op": "close"}]
- assert polled(server) == []
- finally:
- service.close()
-
-
-def test_a_prompt_the_client_cannot_answer_fails_the_login_at_once(server: SimpleNamespace) -> None:
- def refuse(prompt: str, qr: str | None = None) -> str:
- raise RuntimeError("the EXAMPLE caller left")
-
- service = make_client(server.url)
- service._input_bridge = SimpleNamespace(request_input=refuse)
- failed: list[BaseException] = []
-
- def login() -> None:
- try:
- service.authenticate()
- except BaseException as e:
- failed.append(e)
-
- try:
- thread = Thread(target=login, daemon=True)
- thread.start()
- thread.join(10)
- assert not thread.is_alive(), "the login waited for an answer that cannot come"
- assert isinstance(failed[0], RemoteError)
- assert "the EXAMPLE caller left" in failed[0].message
- finally:
- service.close()
diff --git a/tests/remote/unit/test_remote_music_collection.py b/tests/remote/unit/test_remote_music_collection.py
index 06dfbc975..53bf16ae2 100644
--- a/tests/remote/unit/test_remote_music_collection.py
+++ b/tests/remote/unit/test_remote_music_collection.py
@@ -11,13 +11,13 @@ from typing import Any
import pytest
import responses
-from tests.core.test_music_renderer import OWN_FACTS, OWN_ROWS, header, mixed
+from tests.core.test_music_renderer import OWN_FACTS, mixed
from tests.remote.sessions import hold_session, session_entry
from tests.remote.unit.test_session_reopen import SERVER, make_service
from unshackle.core.api import handlers
from unshackle.core.remote_service import RemoteError, RemoteService
from unshackle.core.titles import Movie, Movies
-from unshackle.core.titles.music import MUSIC_FIELDS, Album, Music, Song
+from unshackle.core.titles.music import Album, Music, Song
pytestmark = pytest.mark.unit
@@ -72,23 +72,6 @@ def test_a_client_gets_the_facts_of_the_collection(monkeypatch: pytest.MonkeyPat
assert [song.name for song in titles] == ["Name 1", "Name 2"]
-def test_the_remote_listing_is_the_local_one(monkeypatch: pytest.MonkeyPatch) -> None:
- local = mixed(**{**FACTS, "total_discs": None})
- titles = over_remote(monkeypatch, local)
-
- assert header(titles) == header(local) == OWN_ROWS
- assert str(titles) == str(local) == "Own Artist - Own Title (1990)"
-
-
-def test_each_fact_the_constructor_takes_crosses_the_wire() -> None:
- assert set(MUSIC_FIELDS) == set(FACTS) == set(vars(Album([]))) & set(Music.__init__.__annotations__)
-
-
-def test_the_reply_names_only_the_facts_the_collection_has(monkeypatch: pytest.MonkeyPatch) -> None:
- reply = titles_reply(monkeypatch, served(mixed(kind="artist", title="Own Title")))
- assert reply["collection"] == {"kind": "artist", "title": "Own Title"}
-
-
@pytest.mark.parametrize(
"value", ["1990", 0, True, 12.5, float("nan"), b"1990", date(1990, 1, 2), " ", {1}, ""], ids=repr
)
diff --git a/tests/remote/unit/test_remote_own_cdm_stop.py b/tests/remote/unit/test_remote_own_cdm_stop.py
index cf7a21193..a3bdfbecc 100644
--- a/tests/remote/unit/test_remote_own_cdm_stop.py
+++ b/tests/remote/unit/test_remote_own_cdm_stop.py
@@ -190,12 +190,3 @@ def test_a_failed_own_licence_with_only_another_kids_key_stops_a_remote_run(tmp_
licence_step(MemoryKeySource(local_cdm=DEVICE, client_licensed={"vid"}), dash_track(drm), drm, None, tmp_path)
assert DOWNLOAD_CANCELLED.is_set()
-
-
-def test_a_local_run_still_takes_another_kids_key_for_a_failed_licence(tmp_path, caplog):
- drm = own_widevine(KID, OTHER, refuse=ValueError("own CDM refused"))
- drm.content_keys[OTHER] = "cd" * 16
-
- licence_step(None, dash_track(drm), drm, None, tmp_path)
-
- assert "Licence failed, using the 1 known key(s)" in caplog.text
diff --git a/tests/remote/unit/test_remote_plugin.py b/tests/remote/unit/test_remote_plugin.py
index a8f0131bb..226b11def 100644
--- a/tests/remote/unit/test_remote_plugin.py
+++ b/tests/remote/unit/test_remote_plugin.py
@@ -20,7 +20,7 @@ import pytest
import requests
from tests.core.key_resolver import MemoryVault, key_table, resolver, vaults_of
-from tests.drm_plugins import FINISHED, ExampleDevice, xor
+from tests.drm_plugins import ExampleDevice, xor
from tests.remote.key_source import one_title, remote_session
from tests.remote.sessions import session_entry
from unshackle.core import plugins
@@ -148,30 +148,6 @@ def download(track: Video, tmp_path: Path, licence: Any, downloader: Any = segme
return ctx.save_path.read_bytes()
-def test_the_batch_licence_keys_the_client_copy_and_the_client_plugin_decrypts(
- server_track: Video, device: ExampleDevice, tmp_path: Path
-) -> None:
- posts: list[dict] = []
- server = server_of(server_track, device=device)
- remote = client_of(server, posts)
- track = rebuilt(server_track)
- drm = track.drm[0]
- assert isinstance(drm, CustomDRM) and (drm.kid, drm.key, drm.data) == (KID, None, {"ticket": KID.hex})
-
- vault = MemoryVault()
- keys = resolver(vaults_of(vault))
- keys.source = remote
- title = one_title(track)
- keys.take_server_keys(title) # type: ignore[arg-type]
- keys.wait_vault_writes()
-
- assert download(track, tmp_path, keys.licence_for(track, title, key_table())) == b"".join(PLAIN)
- assert [post.get("track_ids") for post in posts] == [["vid"]]
- assert vault.added == {KID: KEY}
- assert server.served_keys == {KID.hex: (KEY, "cdm")}
- assert FINISHED == [tmp_path / "video.ts"]
-
-
def test_a_track_the_batch_did_not_key_asks_the_licence_route_for_it(
server_track: Video, device: ExampleDevice, tmp_path: Path
) -> None:
diff --git a/tests/remote/unit/test_remote_probes.py b/tests/remote/unit/test_remote_probes.py
index 1588d9420..9e53c4550 100644
--- a/tests/remote/unit/test_remote_probes.py
+++ b/tests/remote/unit/test_remote_probes.py
@@ -2,11 +2,8 @@
from __future__ import annotations
-import asyncio
import json
from collections.abc import Callable
-from threading import Thread
-from types import SimpleNamespace
from typing import Any
import pytest
@@ -14,10 +11,8 @@ import responses
from tests.remote.unit.test_session_reopen import SERVER, make_service
from unshackle.core import remote_service
-from unshackle.core.remote_channel import ServerMessages, WebSocketChannel
from unshackle.core.remote_protocol import ClientErrorKind
from unshackle.core.remote_service import RemoteClient
-from unshackle.core.tunnel import TunnelClient, run_loop
pytestmark = pytest.mark.unit
@@ -94,61 +89,3 @@ def test_a_tunnel_copies_the_auth_header_the_server_reads(monkeypatch: pytest.Mo
remote_service.start_tunnel(client)
assert sent[0].get("X-Api-Key") == KEY and "X-Secret-Key" not in sent[0]
-
-
-def test_a_channel_closes_after_its_loop_has_closed() -> None:
- """A refused upgrade closes the loop of the channel thread before the thread ends."""
- service = make_service()
- service.ctx = SimpleNamespace(obj=None)
- messages = ServerMessages(service)
- channel = WebSocketChannel(messages)
- loop = asyncio.new_event_loop()
- loop.close()
- channel.loop, channel.task = loop, SimpleNamespace(cancel=lambda: None)
- channel.thread = SimpleNamespace(is_alive=lambda: True, join=lambda timeout=None: None)
-
- channel.close()
-
-
-def refuse_threads_after_executor_use(monkeypatch: pytest.MonkeyPatch) -> Callable[[Any], Any]:
- """A run that uses the default executor, then refuses every new thread, as Python 3.12.0 to 3.12.2 do at exit."""
-
- def refuse(self: Thread) -> None:
- raise RuntimeError("can't create new thread at interpreter shutdown")
-
- async def run(self: Any) -> None:
- await asyncio.get_running_loop().run_in_executor(None, lambda: None)
- monkeypatch.setattr(Thread, "start", refuse)
-
- return run
-
-
-def test_a_channel_loop_ends_without_starting_a_thread(monkeypatch: pytest.MonkeyPatch) -> None:
- """The channel thread shuts its loop's executor down without a new thread."""
- monkeypatch.setattr(WebSocketChannel, "run", refuse_threads_after_executor_use(monkeypatch))
- service = make_service()
- service.ctx = SimpleNamespace(obj=None)
- messages = ServerMessages(service)
- channel = WebSocketChannel(messages)
-
- channel.thread.run()
-
-
-def test_a_tunnel_loop_ends_without_starting_a_thread(monkeypatch: pytest.MonkeyPatch) -> None:
- """The tunnel thread, which the same atexit close stops, shuts its loop's executor down without a new thread."""
- monkeypatch.setattr(TunnelClient, "run", refuse_threads_after_executor_use(monkeypatch))
- client = TunnelClient(SERVER, {})
-
- client.thread.run()
-
-
-def test_a_thread_loop_cancels_the_tasks_its_run_leaves() -> None:
- """A task that the run leaves, such as a channel answer still sending, ends cancelled when the loop closes."""
- left: list[asyncio.Future[None]] = []
-
- async def main() -> None:
- left.append(asyncio.ensure_future(asyncio.sleep(10)))
-
- run_loop(main)
-
- assert left[0].cancelled()
diff --git a/tests/remote/unit/test_remote_protocol.py b/tests/remote/unit/test_remote_protocol.py
index d58ba5c32..4ac245844 100644
--- a/tests/remote/unit/test_remote_protocol.py
+++ b/tests/remote/unit/test_remote_protocol.py
@@ -4,18 +4,13 @@ from __future__ import annotations
import ast
import functools
-import re
from pathlib import Path
from typing import Any
-import pytest
-import yaml
-
from unshackle.core import remote_channel, remote_lifetime
from unshackle.core import remote_protocol as protocol
from unshackle.core import remote_service
from unshackle.core.api import routes
-from unshackle.core.api.handlers import SESSION_TRANSPORT_KEYS
ROUTE_NAMES = {name for name in vars(protocol) if name.endswith("_ROUTE")}
CLIENT_METHODS = {
@@ -75,20 +70,6 @@ def client_calls() -> tuple[set[tuple[str, str]], set[str]]:
return calls, referenced
-def test_the_client_writes_no_api_path_of_its_own():
- """A path the client writes out by hand escapes the route check below."""
- tree = client_tree()
- docstrings = {id(node.value) for node in ast.walk(tree) if isinstance(node, ast.Expr)}
- assert not [
- node.lineno
- for node in ast.walk(tree)
- if isinstance(node, ast.Constant)
- and isinstance(node.value, str)
- and "/api/" in node.value
- and id(node) not in docstrings
- ]
-
-
def test_every_route_the_client_calls_is_served_with_that_method():
calls, referenced = client_calls()
assert calls, "the scan found no client calls"
@@ -103,22 +84,6 @@ def test_the_server_takes_its_remote_session_routes_from_the_protocol():
assert {path for path in served_paths if path.startswith("/api/session")} <= protocol_paths
-def test_the_protocol_page_lists_each_remote_route():
- """The route table of the protocol page holds the routes that a remote-only server mounts, and no other.
-
- Each route of the table that the page itself documents has a section of its own.
- """
- page = (ROOT / "docs" / "dev" / "rest-api" / "remote-sessions.md").read_text(encoding="utf-8")
- listed = set(re.findall(r"^\| `(GET|POST|DELETE)` \| `([^`]+)` \|", page, re.MULTILINE))
- sections = set(re.findall(r"^### `(GET|POST|DELETE) ([^`]+)`$", page, re.MULTILINE))
- assert listed == {(method, path) for method, path, _, remote in routes.ROUTES if remote}
- assert sections == listed - {
- ("GET", protocol.HEALTH_ROUTE),
- ("GET", protocol.SERVICES_ROUTE),
- ("POST", protocol.SEARCH_ROUTE),
- }
-
-
def test_the_wire_values_stay_pinned():
"""Both halves read one record, so only this list catches a renamed value on the wire."""
assert {name: getattr(protocol, name) for name in ROUTE_NAMES} == {
@@ -156,61 +121,6 @@ def test_the_wire_values_stay_pinned():
]
-def test_session_transport_keys_are_the_create_body():
- """The server keeps these out of the flat service options; it reads them from the session create body."""
- assert SESSION_TRANSPORT_KEYS == {
- "service",
- "title_id",
- "session_id",
- "profile",
- "service_params",
- "season",
- "episode",
- "part",
- "wanted",
- "proxy",
- "no_proxy",
- "credentials",
- "cookies",
- "cache",
- "client_region",
- "proxy_region",
- "server_cdm",
- "cdm_type",
- "cdm_security_level",
- "cdm_system_id",
- "cdm_device_type",
- "service_config",
- "range_",
- "vcodec",
- "quality",
- "best_available",
- "generate_dv",
- "dl_params",
- "plugins",
- }
-
-
-@pytest.mark.parametrize(
- "shape,fields",
- [
- (protocol.ChannelPrompt, {"type", "id", "prompt", "qr"}),
- (protocol.ChannelCdmCall, {"type", "id", "call"}),
- (protocol.ChannelLog, {"type", "seq", "level", "message", "ts", "qr"}),
- (protocol.ChannelStatus, {"type", "status", "error"}),
- (protocol.ChannelDrain, {"type", "draining"}),
- (protocol.ChannelAnswer, {"type", "id", "response", "error"}),
- ],
-)
-def test_the_channel_messages_keep_their_fields(shape, fields):
- """A session channel message is a JSON text frame; the other side reads these keys."""
- assert keys(shape) == fields
-
-
-def test_a_client_error_kind_is_never_a_server_error_code():
- assert not {k.value for k in protocol.ClientErrorKind} & {c.value for c in protocol.APIErrorCode}
-
-
def keys(shape: Any) -> set[str]:
return set(shape.__required_keys__ | shape.__optional_keys__)
@@ -219,24 +129,3 @@ def properties(schema: dict | None) -> set[str]:
return set(
((schema or {}).get("content", {}).get("application/json", {}).get("schema", {}) or {}).get("properties", {})
)
-
-
-@pytest.mark.parametrize(
- "method,route,request_shape,reply_shape",
- [
- ("POST", protocol.SESSION_CREATE_ROUTE, protocol.SessionCreate, protocol.SessionCreated),
- ("POST", protocol.TRACKS_ROUTE, protocol.TracksRequest, None),
- ("POST", protocol.SEGMENT_FILTER_ROUTE, protocol.SegmentFilterRequest, protocol.SegmentFilterReply),
- ("POST", protocol.LICENSE_ROUTE, protocol.LicenseRequest, protocol.LicenseReply),
- ("POST", protocol.KEYS_ROUTE, protocol.TrackKeys, None),
- ("POST", protocol.BAD_KEY_ROUTE, protocol.BadKeyReport, None),
- ("GET", protocol.SESSION_ROUTE, None, protocol.SessionInfo),
- ],
-)
-def test_the_openapi_yaml_names_only_protocol_keys(method, route, request_shape, reply_shape):
- """The Swagger docs of a route list a subset of the keys its protocol shapes declare."""
- spec = yaml.safe_load((SERVED[(method, route)].__doc__ or "").split("---", 1)[1])
- if request_shape:
- assert properties(spec.get("requestBody")) <= keys(request_shape)
- if reply_shape:
- assert properties(spec["responses"].get("200")) <= keys(reply_shape)
diff --git a/tests/remote/unit/test_remote_relay.py b/tests/remote/unit/test_remote_relay.py
index 3136cc50a..edc9f1028 100644
--- a/tests/remote/unit/test_remote_relay.py
+++ b/tests/remote/unit/test_remote_relay.py
@@ -1,5 +1,4 @@
import asyncio
-import json
import time
from types import SimpleNamespace
@@ -53,16 +52,6 @@ def lease(data, request=None, **extra):
DATA = {"service": "EXAMPLE", "title_id": "show", "remote": "srv"}
-async def test_concurrent_leases_share_one_session(pool):
- leases = await asyncio.gather(*(lease(DATA, wanted=f"S01E0{i}") for i in range(1, 7)))
-
- assert pool == ["show"]
- assert len({id(x.service) for x in leases}) == 1
- for x in leases:
- await handlers.release_remote_service(x)
- assert not leases[0].service.closed and handlers._remote_pool
-
-
async def test_a_broken_session_leaves_the_pool_at_once_but_closes_after_its_last_holder(pool):
first = await lease(DATA)
second = await lease(DATA)
@@ -97,12 +86,6 @@ async def test_each_api_key_gets_its_own_pooled_session(pool):
assert pool == ["show", "show"]
-async def test_client_region_splits_the_pool(pool):
- us = await lease(DATA, client_region="us")
- gb = await lease(DATA, client_region="gb")
- assert us.service is not gb.service
-
-
@pytest.fixture
def remote_config(monkeypatch):
monkeypatch.setattr(config, "remote_services", {"srv": {"url": "https://srv", "api_key": "k"}})
@@ -167,19 +150,6 @@ def test_make_remote_service_passes_only_cli_options(remote_config, monkeypatch)
assert built["args"][5]["EXAMPLE"] == {"x": 1}
-def test_a_service_option_named_like_a_dl_value_passes_only_nested():
- info = {"cli_params": [{"kind": "option", "name": "profile"}]}
- assert remote_service.remote_service_params(info, {"service_params": {"profile": "QC"}}) == {"profile": "QC"}
- assert remote_service.remote_service_params(info, {"profile": "QC"}) == {}
-
-
-def test_remote_error_carries_its_reason_and_exits_a_cli_run():
- err = remote_service.RemoteError("Server error [SESSION_NOT_FOUND]: gone", "SESSION_NOT_FOUND")
- assert isinstance(err, SystemExit) and err.code == 1 and err.kind == "SESSION_NOT_FOUND"
- assert err.session_broke
- assert not remote_service.RemoteError("Server error [NOT_FOUND]: no title", "NOT_FOUND").session_broke
-
-
def test_quiet_mutes_a_remote_error_the_caller_reports(caplog):
with caplog.at_level("DEBUG", logger="remote_service"), remote_service.quiet():
with remote_service.quiet(lambda: False):
@@ -206,32 +176,6 @@ def test_an_unreachable_server_list_logs_one_warning(monkeypatch, caplog):
assert [r.levelname for r in caplog.records if r.levelname in ("WARNING", "ERROR")] == ["WARNING"]
-def test_a_quiet_remote_login_shows_its_last_server_lines_as_a_notice(monkeypatch):
- import logging
-
- from unshackle.core import remote_channel
-
- shown = []
- monkeypatch.setattr(remote_channel, "show_notice", lambda message, qr=None: shown.append(message))
- remote = object.__new__(remote_service.RemoteService)
- remote.auth_notice, remote.auth_qr, remote._input_bridge = None, None, None
- remote.log = logging.getLogger("test")
- monkeypatch.setattr(remote_service.RemoteService, "local_cdm", None)
- messages = remote_channel.ServerMessages(remote)
- lines = ["+ IP Region: CA", "+ Open URL: https://example.test/start\n+ Enter pair code: 9835-2503"]
-
- for seq, line in enumerate(lines, 1):
- seen = messages.log_seq
- messages.show_logs([{"seq": seq, "level": "INFO", "message": line}])
- messages.note_waiting(seen)
- messages.note_waiting(messages.log_seq)
- messages.note_waiting(messages.log_seq)
- messages.login_done()
- # silent while the remote was still logging; the pair code once, when it went quiet; cleared when done
- assert shown == ["+ IP Region: CA\n+ Open URL: https://example.test/start\n+ Enter pair code: 9835-2503", None]
- assert remote.auth_notice is None
-
-
def test_a_relayed_login_keeps_its_qr_code_until_the_login_ends(monkeypatch):
import logging
@@ -249,44 +193,3 @@ def test_a_relayed_login_keeps_its_qr_code_until_the_login_ends(monkeypatch):
assert remote.auth_qr == "https://login.example/scan"
messages.login_done()
assert remote.auth_qr is None and shown == [None]
-
-
-async def test_a_remote_login_prompt_waits_for_its_owners_answer(monkeypatch):
- import threading as th
-
- class Remote:
- auth_notice = None
- auth_qr = None
-
- login = handlers.RemoteLogin("owner", "srv", "OTHER", "show", Remote())
- monkeypatch.setattr(handlers, "_remote_logins", {login.id: login})
- monkeypatch.setattr(handlers, "request_policy", lambda request: KeyPolicy({}))
- caller = {"key": "owner"}
- monkeypatch.setattr(handlers, "caller_key", lambda request: caller["key"])
- got = []
- asker = th.Thread(
- target=lambda: got.append(
- login.bridge.request_input("Enter the code sent to your email", qr="https://login.example/scan")
- )
- )
- asker.start()
- while login.bridge.get_pending_ask() is None:
- await asyncio.sleep(0.01)
-
- listed = json.loads((await handlers.remote_logins_handler(None)).text)["logins"]
- assert listed[0]["prompt"] == "Enter the code sent to your email"
- assert listed[0]["qr"] == "https://login.example/scan"
-
- caller["key"] = "someone-else"
- assert json.loads((await handlers.remote_logins_handler(None)).text)["logins"] == []
- with pytest.raises(APIError) as e:
- await handlers.remote_login_input_handler(login.id, {"response": "123456"}, None)
- assert e.value.error_code == APIErrorCode.NOT_FOUND
-
- caller["key"] = "owner"
- await handlers.remote_login_input_handler(login.id, {"response": "123456"}, None)
- asker.join(2)
- assert got == ["123456"] and login.bridge.get_pending_ask() is None
- with pytest.raises(APIError) as e:
- await handlers.remote_login_input_handler(login.id, {"response": "again"}, None)
- assert e.value.error_code == APIErrorCode.CONFLICT
diff --git a/tests/remote/unit/test_remote_resolve.py b/tests/remote/unit/test_remote_resolve.py
index 2342c2f99..843468e42 100644
--- a/tests/remote/unit/test_remote_resolve.py
+++ b/tests/remote/unit/test_remote_resolve.py
@@ -10,13 +10,6 @@ from unshackle.core.remote_service import resolve_proxy_arg, resolve_server
pytestmark = pytest.mark.unit
-@pytest.fixture
-def empty_remote_services(monkeypatch: pytest.MonkeyPatch) -> None:
- from unshackle.core import remote_service as rs
-
- monkeypatch.setattr(rs.config, "remote_services", {})
-
-
@pytest.fixture
def single_remote_service(monkeypatch: pytest.MonkeyPatch) -> None:
from unshackle.core import remote_service as rs
@@ -49,11 +42,6 @@ def multi_remote_services(monkeypatch: pytest.MonkeyPatch) -> None:
)
-def test_resolve_server_default_auth_headers(single_remote_service) -> None:
- _, _, services = resolve_server("primary")
- assert services["_auth_headers"] == ["X-Secret-Key", "X-Api-Key"]
-
-
def test_resolve_server_custom_auth_headers_extend_defaults(monkeypatch: pytest.MonkeyPatch) -> None:
from unshackle.core import remote_service as rs
@@ -86,12 +74,6 @@ def test_resolve_server_bad_auth_headers_raises(monkeypatch: pytest.MonkeyPatch,
assert "auth_headers" in str(exc.value.message)
-def test_resolve_server_no_config_raises_click(empty_remote_services) -> None:
- with pytest.raises(click.ClickException) as exc:
- resolve_server(None)
- assert "remote_services" in str(exc.value.message)
-
-
def test_resolve_server_single_picks_only_entry(single_remote_service) -> None:
url, key, services = resolve_server(None)
assert url == "https://primary:8080"
@@ -100,12 +82,6 @@ def test_resolve_server_single_picks_only_entry(single_remote_service) -> None:
assert services.get("EXAMPLE") is True
-def test_resolve_server_explicit_name(single_remote_service) -> None:
- url, key, services = resolve_server("primary")
- assert url == "https://primary:8080"
- assert services["_server_cdm"] is True
-
-
def test_resolve_server_unknown_name_raises(single_remote_service) -> None:
with pytest.raises(click.ClickException) as exc:
resolve_server("bogus")
@@ -125,20 +101,6 @@ def test_resolve_server_multi_with_name(multi_remote_services) -> None:
assert services["_server_cdm"] is None
-def test_resolve_proxy_none_returns_none() -> None:
- assert resolve_proxy_arg(None) is None
- assert resolve_proxy_arg("") is None
-
-
-def test_resolve_proxy_passes_through_value(monkeypatch: pytest.MonkeyPatch) -> None:
- import unshackle.core.proxies.resolve as resolve_mod
-
- monkeypatch.setattr(resolve_mod, "initialize_proxy_providers", lambda: [])
- monkeypatch.setattr(resolve_mod, "resolve_proxy", lambda arg, providers: f"http://proxy/{arg}")
-
- assert resolve_proxy_arg("us") == "http://proxy/us"
-
-
def test_resolve_proxy_value_error_becomes_click(monkeypatch: pytest.MonkeyPatch) -> None:
import unshackle.core.proxies.resolve as resolve_mod
diff --git a/tests/remote/unit/test_remote_search.py b/tests/remote/unit/test_remote_search.py
index 2547e0f24..cab726cd2 100644
--- a/tests/remote/unit/test_remote_search.py
+++ b/tests/remote/unit/test_remote_search.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import logging
from types import SimpleNamespace
from typing import Any
@@ -74,31 +73,6 @@ def test_search_sends_no_login(server_accounts: Any, anonymous: bool) -> None:
assert client.sent == {"endpoint": "/api/search", "service": "TEST", "query": "query"}
-@pytest.mark.parametrize("proxy", [None, "http://127.0.0.1:8080"])
-def test_local_proxy_sends_the_server_a_tunnel(monkeypatch: pytest.MonkeyPatch, proxy: str | None) -> None:
- class FakeTunnel:
- def __init__(self, server_url: str, headers: dict, exit_proxy: str | None = None) -> None:
- self.id = "abc"
- self.exit_proxy = exit_proxy
-
- def start(self) -> str:
- return self.id
-
- def stop(self) -> None:
- self.stopped = True
-
- monkeypatch.setattr(remote_service, "TunnelClient", FakeTunnel)
- svc, client, _ = make_service({"local_proxy": True, "proxy": proxy})
- svc.log = logging.getLogger("test")
- client.session = SimpleNamespace(headers={"X-Secret-Key": "k"}) # type: ignore[attr-defined]
-
- list(svc.search())
-
- assert client.sent["proxy"] == "tunnel:abc"
- assert client.tunnel.exit_proxy == proxy
- assert client.tunnel.stopped
-
-
def test_a_loopback_proxy_points_to_local_proxy(monkeypatch: pytest.MonkeyPatch) -> None:
import click
diff --git a/tests/remote/unit/test_remote_service_contract.py b/tests/remote/unit/test_remote_service_contract.py
deleted file mode 100644
index c549da3f7..000000000
--- a/tests/remote/unit/test_remote_service_contract.py
+++ /dev/null
@@ -1,19 +0,0 @@
-"""RemoteService licence callbacks that must not touch the remote session."""
-
-from __future__ import annotations
-
-import pytest
-
-from unshackle.core.remote_service import RemoteService
-
-pytestmark = pytest.mark.unit
-
-
-def test_get_clearkey_license_returns_none() -> None:
- # Regression: clearkey uses no CDM, so the adapter returns None and the
- # framework POSTs the manifest Laurl itself. __new__ skips the networked
- # __init__, so the method must not touch self.
- svc = RemoteService.__new__(RemoteService)
- svc._track_alias = {}
- svc._title_alias = {}
- assert svc.get_clearkey_license(challenge=b"", title=None, track=None) is None
diff --git a/tests/remote/unit/test_remote_service_helpers.py b/tests/remote/unit/test_remote_service_helpers.py
index e5cf10733..001fae221 100644
--- a/tests/remote/unit/test_remote_service_helpers.py
+++ b/tests/remote/unit/test_remote_service_helpers.py
@@ -4,16 +4,14 @@ from __future__ import annotations
import base64
import zlib
-from enum import Enum
import pytest
-from tests.remote.sessions import hold_session, session_entry, stub_service_build
+from tests.remote.sessions import hold_session, session_entry
from unshackle.core.manifests.snapshot import match_track
from unshackle.core.remote_service import RemoteService
from unshackle.core.run_plan import session_request
from unshackle.core.titles.episode import Episode
-from unshackle.core.titles.movie import Movie
from unshackle.core.tracks import Audio, Subtitle, Video
from unshackle.core.wire import (
build_title,
@@ -21,7 +19,6 @@ from unshackle.core.wire import (
deserialize_audio,
deserialize_subtitle,
deserialize_video,
- enum_get,
reconstruct_drm,
serialize_audio_track,
serialize_subtitle_track,
@@ -37,23 +34,6 @@ def blob(text: str) -> str:
return base64.b64encode(zlib.compress(text.encode())).decode("ascii")
-class _Color(Enum):
- RED = 1
- BLUE = 2
-
-
-def test_enum_get_known() -> None:
- assert enum_get(_Color, "RED") is _Color.RED
-
-
-def test_enum_get_unknown_returns_default() -> None:
- assert enum_get(_Color, "PURPLE", default=_Color.BLUE) is _Color.BLUE
-
-
-def test_enum_get_none_returns_default() -> None:
- assert enum_get(_Color, None, default=_Color.RED) is _Color.RED
-
-
def test_deserialize_video_minimal() -> None:
v = deserialize_video({"id": "video-1", "codec": "AVC", "width": 1920, "height": 1080, "bitrate": 5000})
assert isinstance(v, Video)
@@ -87,10 +67,6 @@ def test_a_track_note_shows_over_remote_and_export_and_is_not_an_edition() -> No
assert copy.edition == []
-def test_a_note_that_is_not_text_is_dropped_not_fatal() -> None:
- assert deserialize_video({"id": "v1", "codec": "AVC", "width": 1, "height": 1, "note": {"x": 1}}).note is None
-
-
def test_deserialize_video_unknown_codec_falls_back_to_none() -> None:
v = deserialize_video({"id": "v2", "codec": "MADE_UP", "width": 0, "height": 0})
assert v.codec is None
@@ -105,36 +81,6 @@ def test_deserialize_audio_atmos_flag_without_a_count() -> None:
assert a.bitrate == 256_000
-def test_deserialize_audio_atmos_keeps_a_real_joc_count() -> None:
- a = deserialize_audio({"id": "a3", "codec": "EC3", "atmos": True, "joc": 16, "channels": 6})
- assert a.atmos is True
- assert a.joc == 16
-
-
-def test_deserialize_audio_no_atmos() -> None:
- a = deserialize_audio({"id": "a2", "codec": "AAC", "channels": 2})
- assert a.atmos is False
- assert not a.joc
-
-
-def test_deserialize_subtitle_forced_flag() -> None:
- s = deserialize_subtitle({"id": "s1", "codec": "WebVTT", "language": "en", "forced": True})
- assert isinstance(s, Subtitle)
- assert s.forced is True
- assert s.sdh is False
-
-
-def test_deserialize_subtitle_sdh_flag() -> None:
- s = deserialize_subtitle({"id": "s2", "codec": "WebVTT", "language": "en", "sdh": True})
- assert s.sdh is True
- assert s.forced is False
-
-
-def test_reconstruct_drm_empty() -> None:
- assert reconstruct_drm(None) == []
- assert reconstruct_drm([]) == []
-
-
def test_reconstruct_drm_skips_entries_without_pssh() -> None:
assert reconstruct_drm([{"type": "widevine"}]) == []
@@ -143,19 +89,6 @@ def test_reconstruct_drm_invalid_pssh_silently_dropped() -> None:
assert reconstruct_drm([{"type": "widevine", "pssh": "not-real-pssh"}]) == []
-def test_build_tracks_aggregates() -> None:
- data = {
- "video": [{"id": "v", "codec": "AVC", "width": 1280, "height": 720, "bitrate": 2500}],
- "audio": [{"id": "a", "codec": "AAC", "channels": 2, "bitrate": 128}],
- "subtitles": [{"id": "s", "codec": "WebVTT", "language": "en"}],
- "attachments": [],
- }
- t = build_tracks(data)
- assert len(t.videos) == 1
- assert len(t.audio) == 1
- assert len(t.subtitles) == 1
-
-
def test_build_tracks_restores_drm_preference() -> None:
data = {
"video": [{"id": "v", "codec": "AVC", "width": 1280, "height": 720, "drm_preference": "playready"}],
@@ -180,12 +113,6 @@ def test_match_track_by_id() -> None:
assert match_track(remote, [a, b]) is b
-def test_match_track_by_attributes_when_id_missing() -> None:
- local = deserialize_video({"id": "X", "codec": "AVC", "width": 1920, "height": 1080, "language": "en"})
- remote = deserialize_video({"id": "Y", "codec": "AVC", "width": 1920, "height": 1080, "language": "en"})
- assert match_track(remote, [local]) is local
-
-
def test_match_track_by_attributes_keeps_range_and_bitrate_apart() -> None:
sdr = deserialize_video(
{"id": "a", "codec": "HEVC", "width": 1920, "height": 960, "language": "en", "range": "SDR", "bitrate": 8000000}
@@ -223,19 +150,6 @@ def test_match_track_by_attributes_matches_probed_hdr10p_to_local_hdr10() -> Non
assert match_track(remote, [sdr, hdr10]) is hdr10
-def test_match_track_no_candidates_returns_none() -> None:
- remote = deserialize_video({"id": "X", "codec": "AVC", "width": 1, "height": 1})
- assert match_track(remote, []) is None
-
-
-def test_build_title_movie() -> None:
- info = {"type": "movie", "id": "movie-0001", "name": "Foo", "year": 2024, "language": "en"}
- title = build_title(info, "EXAMPLE", "fallback")
- assert isinstance(title, Movie)
- assert title.id == "movie-0001"
- assert title.name == "Foo"
-
-
def test_build_title_episode() -> None:
info = {
"type": "episode",
@@ -254,11 +168,6 @@ def test_build_title_episode() -> None:
assert title.name == "Pilot"
-def test_build_title_falls_back_to_id_when_missing() -> None:
- title = build_title({"type": "movie", "name": "x"}, "EXAMPLE", "fallback-id")
- assert title.id == "fallback-id"
-
-
def test_credential_cache_digests_cover_common_key_schemes() -> None:
import hashlib
@@ -366,51 +275,6 @@ def test_load_cache_files_wiring(tmp_path, monkeypatch) -> None:
assert set(sent) == {"tokens_default", "session_guid"}
-@pytest.mark.parametrize("extra, warned", [(0, False), (1, True)])
-def test_load_cache_files_warns_above_the_server_limit(tmp_path, monkeypatch, caplog, extra, warned) -> None:
- import logging
- from types import SimpleNamespace
-
- from unshackle.core.api.sanitize import MAX_SESSION_CACHE_KEYS
- from unshackle.core.config import config
- from unshackle.core.remote_service import RemoteService
-
- cache_dir = tmp_path / "TESTSVC"
- cache_dir.mkdir()
- count = MAX_SESSION_CACHE_KEYS + extra
- for i in range(count):
- (cache_dir / f"state{i}.json").write_text("{}")
- monkeypatch.setattr(config.directories, "cache", tmp_path)
- monkeypatch.setattr(config, "credentials", {})
- stub = SimpleNamespace(service_tag="TESTSVC", log=logging.getLogger("test"))
-
- with caplog.at_level(logging.WARNING, logger="test"):
- sent = RemoteService.load_cache_files(stub, None)
-
- assert len(sent) == count
- assert (f"has {count} files to send" in caplog.text) is warned
-
-
-@pytest.mark.parametrize("size, warned", [(10, False), (11, True)])
-def test_load_cache_files_warns_above_the_server_byte_limit(tmp_path, monkeypatch, caplog, size, warned) -> None:
- import logging
- from types import SimpleNamespace
-
- from unshackle.core.config import config
-
- (tmp_path / "TESTSVC").mkdir()
- (tmp_path / "TESTSVC" / "state.json").write_text("a" * size)
- monkeypatch.setattr("unshackle.core.api.sanitize.MAX_SESSION_CACHE_BYTES", 10)
- monkeypatch.setattr(config.directories, "cache", tmp_path)
- monkeypatch.setattr(config, "credentials", {})
- stub = SimpleNamespace(service_tag="TESTSVC", log=logging.getLogger("test"))
-
- with caplog.at_level(logging.WARNING, logger="test"):
- RemoteService.load_cache_files(stub, None)
-
- assert (f"has {size} bytes to send" in caplog.text) is warned
-
-
def test_load_cache_files_forwards_nested_keys(tmp_path, monkeypatch) -> None:
"""A service that keeps its cache in subfolders (session_web/.json) must have
those files forwarded under the Cacher key, and the credential filter must still apply
@@ -653,53 +517,6 @@ def test_write_client_cache_refuses_a_bad_map_before_it_writes_a_file(tmp_path,
assert not any(tmp_path.iterdir())
-@pytest.mark.parametrize("stop_at", ["write", "store", "after_insert"])
-def test_a_session_create_that_fails_after_the_cache_write_leaves_no_cache_dir(tmp_path, monkeypatch, stop_at) -> None:
- import asyncio
- import logging
- import uuid
- from types import SimpleNamespace
-
- from unshackle.core.api import handlers
- from unshackle.core.api.session_store import SessionStore
-
- class Stop(Exception):
- pass
-
- real_write = handlers.write_client_cache
- written: list[str] = []
-
- def write_then_maybe_fail(cache_data, cache_tag):
- real_write(cache_data, cache_tag)
- written.extend(p.name for p in tmp_path.rglob("*.json"))
- if stop_at == "write":
- raise Stop()
-
- monkeypatch.setattr(handlers.config.directories, "cache", tmp_path)
- monkeypatch.setattr(handlers, "write_client_cache", write_then_maybe_fail)
- monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: service)
- monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
- monkeypatch.setattr(handlers, "server_account_for", lambda *args: False)
- monkeypatch.setattr(handlers.Services, "load", lambda service: type("Svc", (), {}))
- stub_service_build(monkeypatch, lambda: SimpleNamespace(log=logging.getLogger("Svc")))
- monkeypatch.setattr("unshackle.core.api.session_store.refuse_while_draining", lambda: None)
-
- class RefusingStore(SessionStore):
- async def create(self, *args, **kwargs):
- if stop_at == "after_insert":
- await super().create(*args, **kwargs)
- raise Stop()
-
- store = RefusingStore()
- monkeypatch.setattr("unshackle.core.api.session_store.get_session_store", lambda: store)
-
- data = {"service": "TESTSVC", "title_id": "t", "session_id": str(uuid.uuid4()), "cache": {"token": blob('"t"')}}
- response = asyncio.run(handlers.session_create_handler(data))
- assert response.status == 422
- assert written == ["token.json"]
- assert bool(list(tmp_path.rglob("*.json"))) is (stop_at == "after_insert")
-
-
class _SentCreate(Exception):
pass
diff --git a/tests/remote/unit/test_request_cache.py b/tests/remote/unit/test_request_cache.py
index 5af92d76e..42e597a9a 100644
--- a/tests/remote/unit/test_request_cache.py
+++ b/tests/remote/unit/test_request_cache.py
@@ -201,12 +201,6 @@ async def test_list_tracks_service_sees_dl_params(seen):
assert "dl_params" in handlers.LIST_HANDLER_TRANSPORT_KEYS
-@pytest.mark.asyncio
-async def test_search_service_sees_dl_params(seen):
- await handlers.search_handler({"service": "EXAMPLE", "query": "q", "dl_params": {"a_lang": ["es-419"]}})
- assert seen["parent_params"]["a_lang"] == ["es-419"]
-
-
@pytest.mark.asyncio
async def test_samples_answers_a_service_exit_in_decrypts_samples(monkeypatch):
class Service:
diff --git a/tests/remote/unit/test_routes.py b/tests/remote/unit/test_routes.py
index 1ea2dadee..903bbd713 100644
--- a/tests/remote/unit/test_routes.py
+++ b/tests/remote/unit/test_routes.py
@@ -7,8 +7,6 @@ stubbing the route table for selected paths.
from __future__ import annotations
-import asyncio
-import json
from collections import Counter, defaultdict
import pytest
@@ -17,7 +15,7 @@ from aiohttp import web
from unshackle.core.api import routes
from unshackle.core.api.compression import compression_middleware
from unshackle.core.api.errors import APIError
-from unshackle.core.api.routes import api_handler, cors_middleware, heartbeat, setup_routes
+from unshackle.core.api.routes import api_handler, cors_middleware, setup_routes
from unshackle.core.remote_protocol import APIErrorCode
pytestmark = pytest.mark.unit
@@ -61,31 +59,6 @@ def collect_paths(app: web.Application) -> list[tuple[str, str]]:
return sorted({(r.method, r.resource.canonical) for r in app.router.routes()})
-def test_setup_routes_full_mode_wires_all_endpoints(make_app) -> None:
- app = make_app(remote_only=False)
- paths = collect_paths(app)
- expected = {
- ("GET", "/api/health"),
- ("GET", "/api/services"),
- ("POST", "/api/search"),
- ("POST", "/api/list-titles"),
- ("POST", "/api/list-tracks"),
- ("POST", "/api/download"),
- ("GET", "/api/download/jobs"),
- ("GET", "/api/download/jobs/{job_id}"),
- ("DELETE", "/api/download/jobs/{job_id}"),
- ("POST", "/api/download/jobs/{job_id}/input"),
- ("POST", "/api/session/create"),
- ("GET", "/api/session/{session_id}/titles"),
- ("POST", "/api/session/{session_id}/tracks"),
- ("POST", "/api/session/{session_id}/segments"),
- ("POST", "/api/session/{session_id}/license"),
- ("GET", "/api/session/{session_id}"),
- ("DELETE", "/api/session/{session_id}"),
- }
- assert expected.issubset(set(paths))
-
-
def test_setup_routes_remote_only_excludes_list_and_download(make_app) -> None:
app = make_app(remote_only=True)
paths = set(collect_paths(app))
@@ -131,66 +104,6 @@ async def test_api_handler_maps_apierror(aiohttp_client) -> None:
assert body["details"] == {"x": 1}
-async def test_heartbeat_keeps_slow_request_alive(aiohttp_client, monkeypatch: pytest.MonkeyPatch) -> None:
- """A fast route answers unchanged; a slow one streams newlines, then its body, and a late error arrives as 200."""
- monkeypatch.setattr(routes, "HEARTBEAT_INTERVAL", 0.05)
-
- @heartbeat
- async def fast(request: web.Request) -> web.Response:
- return web.json_response({"x": 1}, status=201)
-
- @heartbeat
- async def slow(request: web.Request) -> web.Response:
- await asyncio.sleep(0.2)
- return web.json_response({"titles": [1]})
-
- @heartbeat
- async def slow_fail(request: web.Request) -> web.Response:
- await asyncio.sleep(0.2)
- raise APIError(APIErrorCode.SERVICE_ERROR, "late")
-
- app = web.Application()
- app["debug_api"] = False
- app.router.add_get("/fast", fast)
- app.router.add_get("/slow", slow)
- app.router.add_get("/slow_fail", slow_fail)
- client = await aiohttp_client(app)
-
- resp = await client.get("/fast")
- assert resp.status == 201 and await resp.json() == {"x": 1}
-
- resp = await client.get("/slow")
- text = await resp.text()
- assert resp.status == 200 and text.startswith("\n") and json.loads(text) == {"titles": [1]}
- assert resp.headers["X-Accel-Buffering"] == "no"
-
- resp = await client.get("/slow_fail")
- body = json.loads(await resp.text())
- assert resp.status == 200 and body["status"] == "error" and body["error_code"] == "SERVICE_ERROR"
-
-
-@pytest.mark.parametrize("delay", [0, 0.2])
-async def test_heartbeat_answers_a_service_exit_and_keeps_serving(
- aiohttp_client, monkeypatch: pytest.MonkeyPatch, delay: float
-) -> None:
- """A SystemExit inside the heartbeat task becomes a SERVICE_ERROR instead of stopping the event loop."""
- monkeypatch.setattr(routes, "HEARTBEAT_INTERVAL", 0.05)
-
- @heartbeat
- async def exits(request: web.Request) -> web.Response:
- await asyncio.sleep(delay)
- raise SystemExit(1)
-
- app = web.Application()
- app["debug_api"] = False
- app.router.add_get("/exits", api_handler(exits))
- client = await aiohttp_client(app)
-
- for _ in range(2):
- resp = await client.get("/exits")
- assert json.loads(await resp.text())["error_code"] == "SERVICE_ERROR"
-
-
async def test_unguarded_route_answers_a_service_exit(aiohttp_client) -> None:
async def exits(request: web.Request) -> web.Response:
raise SystemExit(1)
@@ -204,31 +117,6 @@ async def test_unguarded_route_answers_a_service_exit(aiohttp_client) -> None:
assert resp.status == 422 and (await resp.json())["error_code"] == "SERVICE_ERROR"
-async def test_heartbeat_late_error_counts_as_rejected(aiohttp_client, monkeypatch: pytest.MonkeyPatch) -> None:
- """Stats count a late failure by its real status and the bytes the stream sent (with framing), not as an empty 200."""
- from unshackle.core.api.stats import stats, stats_middleware
-
- monkeypatch.setattr(routes, "HEARTBEAT_INTERVAL", 0.05)
- monkeypatch.setattr(stats, "keys", {})
- monkeypatch.setattr(stats, "errors", defaultdict(Counter))
-
- @heartbeat
- async def slow_fail(request: web.Request) -> web.Response:
- await asyncio.sleep(0.2)
- raise APIError(APIErrorCode.SERVICE_ERROR, "late")
-
- app = web.Application(middlewares=[stats_middleware])
- app["debug_api"] = False
- app.router.add_get("/slow_fail", slow_fail)
- client = await aiohttp_client(app)
-
- resp = await client.get("/slow_fail")
- sent = len(await resp.read())
- (entry,) = stats.keys.values()
- assert resp.status == 200 and entry.rejected == 1 and entry.bytes_out >= sent > 0
- assert stats.errors == {"-": {"SERVICE_ERROR": 1}}
-
-
@pytest.mark.usefixtures("example_service")
@pytest.mark.parametrize(("service", "counted_as"), [("EXAMPLE", "EXAMPLE"), ("NOT_INSTALLED", "-")])
async def test_error_is_counted_by_service_and_logged_with_its_ref(
@@ -256,32 +144,6 @@ async def test_error_is_counted_by_service_and_logged_with_its_ref(
assert f"Error ref {body['ref']}: SERVICE_ERROR 422 POST /fail service={counted_as}" in caplog.text
-async def test_heartbeat_client_disconnect_is_quiet(
- aiohttp_client, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- """A client that leaves during the heartbeat logs no traceback, and the work runs to the end."""
- monkeypatch.setattr(routes, "HEARTBEAT_INTERVAL", 0.02)
- finished = asyncio.Event()
-
- @heartbeat
- async def slow(request: web.Request) -> web.Response:
- await asyncio.sleep(0.3)
- finished.set()
- return web.json_response({})
-
- app = web.Application()
- app["debug_api"] = False
- app.router.add_get("/slow", slow)
- client = await aiohttp_client(app)
-
- resp = await client.get("/slow")
- await resp.content.read(1)
- resp.close()
- await asyncio.wait_for(finished.wait(), 2)
- await asyncio.sleep(0.1)
- assert "Error handling request" not in caplog.text
-
-
async def test_cors_preflight_returns_headers(make_app, aiohttp_client) -> None:
app = make_app(remote_only=True)
client = await aiohttp_client(app)
@@ -292,16 +154,6 @@ async def test_cors_preflight_returns_headers(make_app, aiohttp_client) -> None:
assert "X-Secret-Key" in resp.headers["Access-Control-Allow-Headers"]
-async def test_health_endpoint_responds_ok(make_app, aiohttp_client) -> None:
- app = make_app(remote_only=True)
- client = await aiohttp_client(app)
- resp = await client.get("/api/health")
- assert resp.status == 200
- body = await resp.json()
- assert body["status"] == "ok"
- assert "version" in body
-
-
async def test_every_response_carries_a_generic_server_header(make_app, aiohttp_client) -> None:
"""Returned, raised (404, 405) and streamed responses all lose aiohttp's version banner."""
@@ -376,15 +228,6 @@ async def test_health_needs_an_api_key(make_app, aiohttp_client) -> None:
assert (await client.get("/api/health", headers={"X-Secret-Key": "good-key"})).status == 200
-async def test_auth_middleware_rejects_missing_key(make_app, aiohttp_client) -> None:
- app = make_app(remote_only=True, with_auth_middleware=True)
- client = await aiohttp_client(app)
- resp = await client.get("/api/session/abc")
- assert resp.status == 401
- body = await resp.json()
- assert "Secret Key" in body["message"]
-
-
async def test_auth_middleware_rejects_invalid_key(make_app, aiohttp_client) -> None:
app = make_app(remote_only=True, with_auth_middleware=True)
client = await aiohttp_client(app)
@@ -392,15 +235,6 @@ async def test_auth_middleware_rejects_invalid_key(make_app, aiohttp_client) ->
assert resp.status == 401
-async def test_auth_middleware_accepts_known_key(make_app, aiohttp_client) -> None:
- app = make_app(remote_only=True, with_auth_middleware=True)
- app["config"]["users"]["good-key"] = {"devices": []}
- client = await aiohttp_client(app)
- resp = await client.get("/api/session/nonexistent", headers={"X-Secret-Key": "good-key"})
- # Auth passed; handler then 404s the session; anything other than 401 is fine here.
- assert resp.status != 401
-
-
def test_setup_routes_cdm_only_keeps_health_and_dashboard_only() -> None:
"""A CDM-only server answers health and the dashboard under /api/, nothing else."""
app = web.Application()
@@ -411,16 +245,6 @@ def test_setup_routes_cdm_only_keeps_health_and_dashboard_only() -> None:
assert all(path == "/api/health" or path.startswith("/api/dashboard/") for path in paths)
-def test_setup_routes_with_docs_registers_each_route_once() -> None:
- """Swagger registers the routes itself, so docs add none twice and drop none."""
- plain, documented = web.Application(), web.Application()
- setup_routes(plain, dashboard=True)
- setup_routes(documented, dashboard=True, docs=True)
- routes_with_docs = Counter((r.method, r.resource.canonical) for r in documented.router.routes())
- assert max(routes_with_docs.values()) == 1
- assert {route for route in routes_with_docs if not route[1].startswith("/api/docs")} == set(collect_paths(plain))
-
-
@pytest.mark.parametrize(
"path, handler", [("/api/session/create", "session_create_handler"), ("/api/search", "search_handler")]
)
diff --git a/tests/remote/unit/test_run_cancel.py b/tests/remote/unit/test_run_cancel.py
deleted file mode 100644
index 256b22b67..000000000
--- a/tests/remote/unit/test_run_cancel.py
+++ /dev/null
@@ -1,635 +0,0 @@
-"""Ctrl+C in the download pool ends every wait of a track for the remote server, and a failed track ends none."""
-
-from __future__ import annotations
-
-import asyncio
-import contextlib
-import json
-import signal
-import socket
-import subprocess
-import time
-from collections.abc import Callable, Iterator
-from pathlib import Path
-from threading import Event, Thread, Timer
-from types import SimpleNamespace
-from typing import Any, cast
-from urllib.parse import urlsplit
-
-import pytest
-from aiohttp import web
-
-from tests.remote.unit.test_process_exit import ( # noqa: F401
- COMMAND,
- DEADLINE,
- HeldDelete,
- held_delete,
- lasting_sessions,
- logins,
- posix,
- run,
- sessions,
- settings,
- wait_line,
-)
-from tests.remote.unit.test_remote_loopback import StubService, count, forget, server # noqa: F401
-from tests.remote.unit.test_tunnel import wait_until
-from unshackle.core import remote_channel
-from unshackle.core.api import routes, session_store
-from unshackle.core.constants import RunCancel
-from unshackle.core.proxies.controld import relay
-from unshackle.core.remote_channel import ServerMessages
-from unshackle.core.remote_protocol import (
- SESSION_CREATE_ROUTE,
- SESSION_ROUTE,
- TITLES_ROUTE,
- TRACKS_ROUTE,
-)
-from unshackle.core.tracks import Audio, Tracks
-
-pytestmark = [pytest.mark.unit, pytest.mark.process, posix]
-
-BOUND = 8.0
-WAITING = "Waiting for the remote server"
-LIMITED = "Rate limited by the server"
-
-CLIENT = """
-import contextlib, logging, sys
-from threading import Event
-from types import SimpleNamespace
-from uuid import UUID
-import click
-from unshackle.core import process_exit, remote_channel, remote_service
-from unshackle.core.config import config
-config.__init__(directories={"cache": sys.argv[2], "cookies": sys.argv[2] + "/cookies"})
-logging.basicConfig(level=logging.INFO, stream=sys.stdout, format="%(message)s")
-from tests.core.key_resolver import resolver
-from tests.remote.unit.test_remote_loopback import make_client
-from unshackle.commands.dl import download_tracks_in_passes
-from unshackle.core.constants import DOWNLOAD_CANCELLED, RunCancel
-from unshackle.core.tracks.track import Track
-
-phase = sys.argv[3]
-service = make_client(sys.argv[1])
-keys = resolver()
-if phase == "push":
- remote_service.KEYS_TIMEOUT = 60
-def say(line):
- print(line, flush=True)
-
-def set_and_say(real=DOWNLOAD_CANCELLED.set):
- real()
- if RunCancel.pressed:
- say("cancelled")
-
-def hold(line):
- say(line)
- while not RunCancel.pressed:
- Event().wait(0.01)
-
-def open_session(credential, real=service.open_session):
- real(credential)
- if phase == "login-done" and service._tracks_by_title:
- hold("login done")
-
-service.open_session = open_session
-
-def login_material(profile, real=service.client_login):
- if phase == "login-material" and service._titles:
- hold("login material")
- return real(profile)
-
-DOWNLOAD_CANCELLED.set = set_and_say
-service.client_login = login_material
-
-def titles(sid):
- return service.client.get(f"/api/session/{sid}/titles")
-
-def push():
- track = SimpleNamespace(id="example-1-login1")
- keys.vaults.licensed({UUID(int=1): "ab" * 16}, track, service.server_vault)
-
-calls = {
- "url": service.track_url,
- "licence": lambda track: service.license_track(
- track, type("Widevine", (), {"pssh": SimpleNamespace(dumps=lambda: "AAAA")})()
- ),
- "file": service.license_file,
- "relay": lambda track: service.proxy_license(b"c", track, "widevine"),
- "certificate": lambda track: service.get_widevine_service_certificate(challenge=b"c", title=None, track=track),
- "filter": lambda track: service.remote_segment_filter(track.id)(None),
- "samples": lambda track: service.get_sample_decrypter(track, 0),
-}
-
-def run_one(track, index):
- if phase == "fails" and index == 1:
- sys.stdin.readline()
- DOWNLOAD_CANCELLED.set()
- say("failed")
- raise ValueError("EXAMPLE failed")
- if phase == "push":
- push()
- if phase in calls:
- service._server_cdm_request = phase == "file"
- try:
- calls[phase](track)
- except Exception as e:
- say(type(e).__name__)
- raise
- service.session_call(titles)
- say("called")
-
-def download(count):
- tracks = [SimpleNamespace(id=str(n)) for n in range(count)]
- download_tracks_in_passes(tracks, count, run_one, skip_subtitle_errors=False, on_subtitle_skipped=None)
-
-@click.command()
-@click.pass_context
-def main(ctx):
- ctx.with_resource(process_exit.unwinding(linger="job" not in sys.argv[4:]))
- service.authenticate()
- remote_channel.AUTH_POLL_INTERVAL = 600
- say("ready")
- sys.stdin.readline()
- if phase == "main":
- service.session_call(titles)
- if phase in ("tracks", "login-material", "login-done"):
- service.get_tracks(service.get_titles()[0])
- say("tracks")
- sys.stdin.readline()
- try:
- download(2 if phase in ("pool", "fails") else 1)
- except ValueError:
- say("title failed")
- service.session_call(titles)
- say("next title")
- except KeyboardInterrupt:
- say("Download Cancelled")
- if phase == "lost-push":
- push()
- keys.wait_vault_writes()
- say("vault writes done")
-
-main(args=[])
-"""
-
-
-class Gate:
- """A port in front of the server. ``close`` takes it away as a dead server does, and lets no other process have it."""
-
- def __init__(self, url: str) -> None:
- self.server = (urlsplit(url).hostname, urlsplit(url).port)
- self.port = 0
- self.held = socket.socket()
- self.open()
- self.url = f"http://127.0.0.1:{self.port}"
-
- def open(self) -> None:
- self.links: list[socket.socket] = []
- self.held.close()
- self.listener = socket.create_server(("127.0.0.1", self.port), backlog=32)
- self.port = self.listener.getsockname()[1]
- Thread(target=self.accept, args=[self.listener], daemon=True).start()
-
- def accept(self, listener: socket.socket) -> None:
- with contextlib.suppress(OSError):
- while True:
- near = listener.accept()[0]
- far = socket.create_connection(self.server)
- self.links += [near, far]
- for source, sink in ((near, far), (far, near)):
- Thread(target=relay, args=[source, sink], daemon=True).start()
-
- def close(self) -> None:
- for end in (self.listener, *self.links):
- with contextlib.suppress(OSError):
- end.shutdown(socket.SHUT_RDWR)
- end.close()
- self.held.close()
- self.held = socket.socket()
- self.held.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- self.held.bind(("127.0.0.1", self.port))
-
-
-@pytest.fixture
-def gate(server: SimpleNamespace, logins: list[Any]) -> Iterator[Gate]: # noqa: F811
- gate = Gate(server.url)
- yield gate
- gate.close()
- gate.held.close()
-
-
-def go(process: subprocess.Popen[str]) -> None:
- assert process.stdin is not None
- process.stdin.write("\n")
- process.stdin.flush()
-
-
-def creates(server: SimpleNamespace) -> int: # noqa: F811
- return len([seen for seen in server.seen if seen == ("POST", SESSION_CREATE_ROUTE, 200)])
-
-
-@pytest.fixture
-def launch(run: Callable[..., Any]) -> Iterator[Callable[..., subprocess.Popen[str]]]: # noqa: F811
- """Start a process that does not outlive twice the deadline, so a client that waits on fails its test."""
- timers: list[Timer] = []
-
- def start(*argv: str) -> subprocess.Popen[str]:
- process = run("-c", *argv, stdin=subprocess.PIPE)
- timers.append(Timer(2 * DEADLINE, process.kill))
- timers[-1].start()
- return process
-
- yield start
- for timer in timers:
- timer.cancel()
-
-
-@pytest.fixture
-def client(gate: Gate, launch: Callable[..., Any], tmp_path: Path) -> Callable[..., subprocess.Popen[str]]:
- """Start a client with a remote session, which calls the server when the test says so."""
-
- def start(*argv: str) -> subprocess.Popen[str]:
- process = launch(CLIENT, gate.url, str(tmp_path / "client"), *argv)
- wait_line(process, "ready")
- return process
-
- return start
-
-
-def press(process: subprocess.Popen[str]) -> str:
- """Send Ctrl+C, and return what the client prints before it ends in time."""
- sent = time.monotonic()
- process.send_signal(signal.SIGINT)
- output, _ = process.communicate(timeout=DEADLINE)
- assert time.monotonic() - sent < BOUND, output
- assert "Traceback" not in output
- return output
-
-
-def limit(monkeypatch: pytest.MonkeyPatch, handler: str) -> None:
- """Answer one route of the server with a 429 that asks for an hour, before its first heartbeat sends a 200."""
-
- async def refuse(*args: Any) -> web.Response:
- return web.json_response({"error_code": "RATE_LIMITED"}, status=429, headers={"Retry-After": "3600"})
-
- monkeypatch.setattr(routes, "HEARTBEAT_INTERVAL", 30.0)
- monkeypatch.setattr(routes, handler, refuse)
-
-
-class Held:
- """A handler of the server that waits for ``release`` before it does its work, from the first call that ``when`` takes."""
-
- def __init__(self, monkeypatch: pytest.MonkeyPatch, name: str, when: Callable[[], bool] = lambda: True) -> None:
- self.started, self.release = Event(), Event()
- handler = getattr(routes, name)
-
- async def held(*args: Any) -> Any:
- if when():
- self.started.set()
- while not self.release.is_set():
- await asyncio.sleep(0.01)
- return await handler(*args)
-
- monkeypatch.setattr(routes, name, held)
-
- def __enter__(self) -> Held:
- return self
-
- def __exit__(self, *_: object) -> None:
- self.release.set()
-
-
-def lose(server: SimpleNamespace, gate: Gate, monkeypatch: pytest.MonkeyPatch, wait: str) -> str: # noqa: F811
- """Make the next call of the client wait, and return the line that the client prints for it."""
- if wait == "dead":
- gate.close()
- elif wait == "draining":
- store = session_store.get_session_store()
- monkeypatch.setattr(store, "draining", True)
- forget(server, sessions()[0].session_id)
- else:
- limit(monkeypatch, "session_titles_handler")
- return LIMITED
- return WAITING
-
-
-@pytest.mark.parametrize("wait", ["dead", "draining", "limited"])
-def test_a_ctrl_c_ends_the_wait_of_each_track(
- server: SimpleNamespace, # noqa: F811
- gate: Gate,
- client: Callable[..., Any],
- monkeypatch: pytest.MonkeyPatch,
- wait: str,
-) -> None:
- """Two tracks wait: one in its wait and one for the lock of that wait."""
- process = client("pool")
- line = lose(server, gate, monkeypatch, wait)
- go(process)
- wait_line(process, line)
- if wait != "dead":
- assert wait_until(lambda: count(server, "GET", TITLES_ROUTE) == 2, DEADLINE)
- seen = len(server.seen)
-
- output = press(process)
- assert output.split("\n")[:-1] == ["cancelled", "Download Cancelled", "vault writes done"]
- assert {(method, status) for method, _, status in server.seen[seen:]} <= {("DELETE", 200), ("GET", 101)}
- assert wait == "dead" or sessions() == []
-
-
-@pytest.mark.parametrize("wait", ["dead", "limited", "login"])
-def test_a_ctrl_c_in_the_main_thread_ends_its_wait(
- server: SimpleNamespace, # noqa: F811
- gate: Gate,
- client: Callable[..., Any],
- monkeypatch: pytest.MonkeyPatch,
- wait: str,
-) -> None:
- process = client("main")
- if wait == "login":
- login = hold_login(monkeypatch)
- forget(server, sessions()[0].session_id)
- go(process)
- assert login.started.wait(DEADLINE)
- assert wait_until(lambda: sessions() and sessions()[0].channel.attached, DEADLINE)
- try:
- output = press(process)
- finally:
- login.release.set()
- else:
- line = lose(server, gate, monkeypatch, wait)
- go(process)
- wait_line(process, line)
- output = press(process)
- assert "Aborted" in output
-
-
-def hold_login(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
- login = SimpleNamespace(started=Event(), release=Event())
-
- def hold(stub: StubService, cookies: Any, credential: Any) -> None:
- login.started.set()
- login.release.wait(DEADLINE)
-
- monkeypatch.setattr(StubService, "authenticate", hold)
- return login
-
-
-def test_a_ctrl_c_in_the_login_of_a_reopen_deletes_the_new_session(
- server: SimpleNamespace, # noqa: F811
- client: Callable[..., Any],
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- process = client("pool")
- login = hold_login(monkeypatch)
- forget(server, sessions()[0].session_id)
- go(process)
- try:
- assert login.started.wait(DEADLINE)
- assert wait_until(lambda: sessions()[0].channel.attached, DEADLINE)
- created, (entry,) = count(server, "POST", SESSION_CREATE_ROUTE), sessions()
- output = press(process)
- finally:
- login.release.set()
-
- assert "Download Cancelled" in output and "called" not in output and "error" not in output.lower()
- assert sessions() == [] and count(server, "POST", SESSION_CREATE_ROUTE) == created
- assert count(server, "DELETE", SESSION_ROUTE, entry.session_id) == 1
-
-
-def test_a_failed_track_does_not_stop_the_reopen_of_the_others(
- server: SimpleNamespace, # noqa: F811
- gate: Gate,
- client: Callable[..., Any],
-) -> None:
- """The failed track cancels the downloads while the server restarts, and the next title has a remote session."""
- process = client("fails")
- gate.close()
- forget(server, sessions()[0].session_id)
- go(process)
- wait_line(process, WAITING)
- go(process)
- wait_line(process, "failed")
- gate.open()
- output, _ = process.communicate(timeout=DEADLINE)
-
- assert output.split("\n")[-4:-1] == ["called", "title failed", "next title"], output
- assert creates(server) == 2
-
-
-def test_a_ctrl_c_after_a_failed_track_ends_the_wait_of_the_others(gate: Gate, client: Callable[..., Any]) -> None:
- process = client("fails")
- gate.close()
- go(process)
- wait_line(process, WAITING)
- go(process)
- wait_line(process, "failed")
- assert press(process).split("\n")[:-1] == ["cancelled", "Download Cancelled", "vault writes done"]
-
-
-def test_a_push_in_flight_reaches_the_server_before_the_end(
- server: SimpleNamespace, # noqa: F811
- client: Callable[..., Any],
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- held = Held(monkeypatch, "session_keys_handler")
- limit(monkeypatch, "session_titles_handler")
- process = client("push")
- go(process)
- wait_line(process, LIMITED)
- with held:
- assert held.started.wait(DEADLINE)
- process.send_signal(signal.SIGINT)
- wait_line(process, "Download Cancelled")
- assert count(server, "DELETE", SESSION_ROUTE) == 0
- output, _ = process.communicate(timeout=DEADLINE)
-
- assert "vault writes done" in output
- (push,) = [seen for seen in server.seen if seen[0] == "POST" and seen[1].endswith("/keys")]
- assert [seen for seen in server.seen[server.seen.index(push) :] if seen[0] == "DELETE"] and sessions() == []
-
-
-def test_a_push_to_a_lost_server_gives_up(gate: Gate, client: Callable[..., Any]) -> None:
- process = client("lost-push")
- gate.close()
- go(process)
- wait_line(process, WAITING)
- assert "vault writes done" in press(process)
-
-
-@pytest.mark.parametrize(
- ("phase", "handler"),
- [
- ("url", "session_segments_handler"),
- ("licence", "session_license_handler"),
- ("file", "session_license_handler"),
- ("relay", "session_license_handler"),
- ("certificate", "session_license_handler"),
- ("filter", "session_segment_filter_handler"),
- ("samples", "session_samples_handler"),
- ],
-)
-def test_a_track_whose_wait_was_cancelled_did_not_fail(
- client: Callable[..., Any], monkeypatch: pytest.MonkeyPatch, phase: str, handler: str
-) -> None:
- limit(monkeypatch, handler)
- process = client(phase)
- go(process)
- wait_line(process, LIMITED)
- lines = press(process).split("\n")[:-1]
- assert sorted(lines) == ["Download Cancelled", "DownloadCancelled", "cancelled", "vault writes done"]
-
-
-@pytest.mark.parametrize("cancelled", [False, True])
-def test_a_cancelled_login_shows_no_notice(monkeypatch: pytest.MonkeyPatch, cancelled: bool) -> None:
- shown: list[Any] = []
- monkeypatch.setattr(remote_channel, "show_notice", lambda *args: shown.append(args))
- monkeypatch.setattr(RunCancel, "pressed", cancelled)
- messages = ServerMessages(cast(Any, SimpleNamespace(auth_notice=None, auth_qr=None)))
- messages.recent_logs.append("Approve at example.com")
- messages.note_waiting(0)
- assert bool(shown) is not cancelled
-
-
-def test_a_stop_of_a_job_cancels_its_tracks_too(
- client: Callable[..., Any],
- held_delete: HeldDelete, # noqa: F811
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """A job worker gets no KeyboardInterrupt, and its cancelled track must not look like a failed or a finished one."""
- limit(monkeypatch, "session_segments_handler")
- process = client("url", "job")
- go(process)
- wait_line(process, LIMITED)
- process.send_signal(signal.SIGTERM)
- assert held_delete.started.wait(DEADLINE)
- lines = [wait_line(process, "Download").strip() for _ in range(2)]
- held_delete.release.set()
- assert lines == ["DownloadCancelled", "Download Cancelled"]
- assert process.wait(DEADLINE) == 128 + signal.SIGTERM
-
-
-def cancel_in(process: subprocess.Popen[str], held: Held, then: Callable[[], None] = lambda: None) -> str:
- """Send Ctrl+C while the server holds a request of the pool, which no cancel can reach, and then let it answer."""
- with held:
- assert held.started.wait(DEADLINE)
- process.send_signal(signal.SIGINT)
- wait_line(process, "cancelled")
- then()
- output, _ = process.communicate(timeout=DEADLINE)
- assert "Download Cancelled" in output
- return output
-
-
-@pytest.mark.parametrize(
- ("name", "line"), [("latest_release", WAITING), ("session_info_handler", "The remote session was lost")]
-)
-def test_a_request_of_the_recovery_that_ends_after_the_ctrl_c_is_silent(
- server: SimpleNamespace, # noqa: F811
- gate: Gate,
- client: Callable[..., Any],
- monkeypatch: pytest.MonkeyPatch,
- name: str,
- line: str,
-) -> None:
- process = client("call")
- held = Held(monkeypatch, name)
- forget(server, sessions()[0].session_id)
- go(process)
- output = cancel_in(process, held, gate.close if line == WAITING else lambda: None)
- assert line not in output and creates(server) == 1
-
-
-def test_a_session_that_is_alive_after_the_ctrl_c_gets_no_second_call(
- server: SimpleNamespace, # noqa: F811
- gate: Gate,
- client: Callable[..., Any],
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- process = client("call")
- gate.close()
- go(process)
- wait_line(process, WAITING)
- held = Held(monkeypatch, "session_info_handler")
- gate.open()
- cancel_in(process, held)
- assert count(server, "GET", TITLES_ROUTE) == 0 and sessions() == []
-
-
-@pytest.mark.parametrize(("name", "tracks"), [("session_titles_handler", 1), ("session_tracks_handler", 2)])
-def test_a_reopen_stops_after_the_request_of_the_ctrl_c(
- server: SimpleNamespace, # noqa: F811
- client: Callable[..., Any],
- monkeypatch: pytest.MonkeyPatch,
- name: str,
- tracks: int,
-) -> None:
- process = client("tracks")
- go(process)
- wait_line(process, "tracks")
- held = Held(monkeypatch, name, lambda: creates(server) == 2)
- forget(server, sessions()[0].session_id)
- go(process)
- cancel_in(process, held)
- assert count(server, "GET", TITLES_ROUTE) == 3
- assert count(server, "POST", TRACKS_ROUTE) == tracks and sessions() == []
-
-
-@pytest.mark.parametrize(("phase", "created"), [("login-material", 1), ("login-done", 2)])
-def test_a_ctrl_c_in_a_reopen_stops_it_at_its_next_step(
- server: SimpleNamespace, # noqa: F811
- client: Callable[..., Any],
- phase: str,
- created: int,
-) -> None:
- process = client(phase)
- go(process)
- wait_line(process, "tracks")
- forget(server, sessions()[0].session_id)
- titles = count(server, "GET", TITLES_ROUTE)
- go(process)
- wait_line(process, phase.replace("-", " "))
- press(process)
- assert creates(server) == created and sessions() == []
- assert count(server, "GET", TITLES_ROUTE) == titles + 1
-
-
-def test_a_ctrl_c_ends_the_wait_for_the_channel_of_a_reopen(
- server: SimpleNamespace, # noqa: F811
- client: Callable[..., Any],
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- process = client("call")
- held = Held(monkeypatch, "session_channel_handler", lambda: creates(server) == 2)
- forget(server, sessions()[0].session_id)
- go(process)
- with held:
- assert held.started.wait(DEADLINE)
- press(process)
- assert sessions() == []
-
-
-def test_the_command_prints_one_line_and_starts_with_no_cancel(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any], # noqa: F811
- example_service: None,
- launch: Callable[..., Any],
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
-) -> None:
- def tracks(stub: StubService, title: Any) -> Tracks:
- audio = Audio(url="", language="en", codec=Audio.Codec.AAC, bitrate=128_000, channels=2, id_="a1")
- audio.resolve_url = lambda: "https://cdn.example/a1.m4a"
- return Tracks([audio])
-
- monkeypatch.setattr(StubService, "get_tracks", tracks)
- limit(monkeypatch, "session_segments_handler")
- script = "from unshackle.core.constants import RunCancel\nRunCancel.pressed = True\n" + COMMAND
- argv = ["dl", "--remote", "--no-proxy", "--audio-only", "-l", "en", "-w", "1", "EXAMPLE", "example-1"]
- process = launch(script, json.dumps(settings(server.url, tmp_path)), *argv)
- wait_line(process, LIMITED)
- output = press(process)
-
- assert process.returncode == 0 and sessions() == []
- after = output[output.index("Download Cancelled") :]
- assert after.strip() == "Download Cancelled..." and "FAILED" not in output and "ERROR" not in output
diff --git a/tests/remote/unit/test_segment_filter.py b/tests/remote/unit/test_segment_filter.py
index 09408239d..f3dab452b 100644
--- a/tests/remote/unit/test_segment_filter.py
+++ b/tests/remote/unit/test_segment_filter.py
@@ -56,14 +56,6 @@ async def test_handler_returns_unwanted_absolute_uris(monkeypatch):
assert json.loads(response.body) == {"unwanted": ["https://cdn.test/hls/ad1.ts"]}
-async def test_handler_returns_null_without_a_filter(monkeypatch):
- make_session(monkeypatch, SimpleNamespace(url=BASE, OnSegmentFilter=None))
-
- response = await handlers.session_segment_filter_handler({"track_id": "t1"}, "s1")
-
- assert json.loads(response.body) == {"unwanted": None}
-
-
def make_service(unwanted, status=200, error=None):
service = RemoteService.__new__(RemoteService)
service._track_alias = {}
diff --git a/tests/remote/unit/test_serve_cli.py b/tests/remote/unit/test_serve_cli.py
index 5b1b0a727..b1f675194 100644
--- a/tests/remote/unit/test_serve_cli.py
+++ b/tests/remote/unit/test_serve_cli.py
@@ -17,26 +17,6 @@ def runner() -> CliRunner:
return CliRunner()
-def test_serve_help_lists_documented_flags(runner: CliRunner) -> None:
- result = runner.invoke(serve, ["--help"])
- assert result.exit_code == 0
- out = result.output
- for flag in (
- "--host",
- "--port",
- "--caddy",
- "--api-only",
- "--no-widevine",
- "--no-playready",
- "--no-key",
- "--debug-api",
- "--debug",
- "--remote-only",
- "--quiet",
- ):
- assert flag in out, f"missing flag in --help: {flag}"
-
-
def test_serve_api_only_with_no_widevine_rejected(runner: CliRunner, monkeypatch: pytest.MonkeyPatch) -> None:
"""`--api-only` is mutually exclusive with `--no-widevine`/`--no-playready`."""
monkeypatch.setenv("UNSHACKLE_NO_RUN", "1") # belt-and-braces; not currently checked
@@ -172,20 +152,3 @@ def test_bad_rate_limit_config_stops_the_server(
"""A tier or rate limit the reader would silently treat as "no limit" must fail at startup."""
started, output = start_serve(runner, monkeypatch, serve_cfg)
assert not started and expected in output
-
-
-def test_good_rate_limit_config_starts(runner: CliRunner, monkeypatch: pytest.MonkeyPatch) -> None:
- started, output = start_serve(
- runner,
- monkeypatch,
- {"tiers": {"bot": {"rate_limit": 600}}, "users": {"k": {"username": "bot", "tier": "bot"}}},
- )
- assert started, output
-
-
-def test_serve_cdm_only_with_remote_only_rejected(runner: CliRunner) -> None:
- """`--cdm-only` is mutually exclusive with `--api-only` and `--remote-only`; the check runs before config."""
- result = runner.invoke(serve, ["--cdm-only", "--remote-only"])
- assert result.exit_code != 0
- output = re.sub(r"\x1b\[[0-9;]*m", "", result.output or str(result.exception))
- assert "Cannot use --cdm-only" in output
diff --git a/tests/remote/unit/test_serve_reload.py b/tests/remote/unit/test_serve_reload.py
index a258777c7..86de0cf33 100644
--- a/tests/remote/unit/test_serve_reload.py
+++ b/tests/remote/unit/test_serve_reload.py
@@ -124,29 +124,6 @@ async def test_reload_that_drops_the_dashboard_key_closes_its_routes(
assert b"after" not in await asyncio.wait_for(stream.content.read(), 2)
-def test_reload_that_adds_a_dashboard_key_needs_a_restart(
- running: tuple[web.Application, Path], caplog: pytest.LogCaptureFixture
-) -> None:
- app, path = running
- _write(path, users={"new": {"devices": ["dev"]}}, dashboard={"key": "dash"})
-
- with caplog.at_level(logging.WARNING, logger=LOG.name):
- assert _reload(app) is False
- assert "restart" in caplog.text and "dashboard.key" in caplog.text
- assert "dashboard" not in config.serve
-
-
-def test_reload_without_a_limit_leaves_the_job_limit_to_dl(running: tuple[web.Application, Path]) -> None:
- app, path = running
- _write(path, users={"old": {"devices": ["dev"]}})
-
- assert _reload(app) is True
- assert DownloadQueueManager(max_concurrent_downloads=2).worker_speed_limit() is None
- requests_downloader.set_speed_limit(1_000_000)
- limiter = requests_downloader.speed_limiter
- assert limiter is not None and limiter.rate == 1_000_000
-
-
def test_reload_with_a_limit_changes_the_job_share_only(running: tuple[web.Application, Path]) -> None:
app, path = running
_write(path, users={"old": {"devices": ["dev"]}}, global_speed_limit="6M")
diff --git a/tests/remote/unit/test_serve_service_refresh.py b/tests/remote/unit/test_serve_service_refresh.py
deleted file mode 100644
index 2941ff67e..000000000
--- a/tests/remote/unit/test_serve_service_refresh.py
+++ /dev/null
@@ -1,57 +0,0 @@
-"""Pins the serve refresh loop: staged reloads apply after the pull, not only on the next tick."""
-
-from __future__ import annotations
-
-import asyncio
-from typing import Any
-
-import pytest
-from aiohttp import web
-
-from unshackle.commands.serve import _install_service_refresh
-from unshackle.core import services
-from unshackle.core.api import download_manager
-from unshackle.core.config import config
-
-pytestmark = pytest.mark.unit
-
-
-async def test_refresh_tick_applies_tags_staged_during_the_pull(monkeypatch: pytest.MonkeyPatch) -> None:
- """A tag whose last session ended while the pull ran is staged although idle; the same tick swaps it in."""
- pulled = asyncio.Event()
- seen: list[set[str]] = []
-
- def fake_refresh(busy: set[str]) -> list[dict[str, Any]]:
- # The pull read the busy set before the session ended, so the tag lands in PENDING while idle.
- services.PENDING.add("EXAMPLE")
- pulled.set()
- return []
-
- def fake_apply(busy: set[str]) -> list[str]:
- seen.append(set(services.PENDING))
- ready = sorted(services.PENDING - busy)
- services.PENDING.difference_update(ready)
- return ready
-
- monkeypatch.setattr(config, "serve", {"services_refresh_interval": 1})
- monkeypatch.setattr(services, "PENDING", set())
- monkeypatch.setattr(services, "repo_specs", lambda: ["x"])
- monkeypatch.setattr(services, "log_load_issues", lambda: None)
- monkeypatch.setattr(services, "record_loaded_commits", lambda: None)
- monkeypatch.setattr(services, "refresh_and_reload", fake_refresh)
- monkeypatch.setattr(services, "apply_pending", fake_apply)
- monkeypatch.setattr(download_manager, "busy_services", set)
- monkeypatch.setattr(download_manager, "publish_service_event", lambda *a, **k: None)
- monkeypatch.setattr(download_manager, "_reload_task", None)
-
- app = web.Application()
- _install_service_refresh(app)
- await app.on_startup[-1](app)
- try:
- await asyncio.wait_for(pulled.wait(), timeout=3)
- await asyncio.sleep(0.2)
- finally:
- await app.on_cleanup[-1](app)
-
- assert {"EXAMPLE"} in seen
- assert services.PENDING == set()
diff --git a/tests/remote/unit/test_serve_stop.py b/tests/remote/unit/test_serve_stop.py
index 1d52659e3..27752849f 100644
--- a/tests/remote/unit/test_serve_stop.py
+++ b/tests/remote/unit/test_serve_stop.py
@@ -20,10 +20,9 @@ from typing import Any
import aiohttp
import pytest
-from aiohttp import web
-from tests.remote.unit.test_client_presence import close_code, get, logged_in, silent_for, store_token, sweep
-from tests.remote.unit.test_process_exit import BOUND, posix, run, settings # noqa: F401
+from tests.remote.process import BOUND, posix, run, settings # noqa: F401
+from tests.remote.unit.test_client_presence import get, logged_in, silent_for, store_token, sweep
from tests.remote.unit.test_remote_loopback import KEY, StubService, on_loop, server # noqa: F401
from tests.remote.unit.test_remote_service_helpers import blob
from tests.remote.unit.test_session_lifetime import ( # noqa: F401
@@ -38,13 +37,10 @@ from tests.remote.unit.test_session_lifetime import ( # noqa: F401
from tests.remote.unit.test_tunnel import wait_until
from unshackle.core.api import session_store
from unshackle.core.api.client_presence import AWAY_LIMIT
-from unshackle.core.api.events import bus
-from unshackle.core.api.session_channel import close_channels
from unshackle.core.api.session_store import SessionEntry, SessionStore
from unshackle.core.config import config
from unshackle.core.remote_protocol import (
CHANNEL_ROUTE,
- CHANNEL_SESSION_GONE,
TITLES_ROUTE,
APIErrorCode,
AuthStatus,
@@ -198,69 +194,6 @@ async def read_until(socket: Any, kind: str) -> None:
message = await socket.receive_json(timeout=DEADLINE)
-@posix
-@pytest.mark.parametrize("work", ["login", "prompt", "cdm"])
-async def test_a_stop_ends_the_work_that_waits_for_its_client(serve: Callable[..., Serve], work: str) -> None:
- """The refusal of the open request, and the close code of the channel, make the client open a new session."""
- running = serve(work)
- async with aiohttp.ClientSession(headers={"X-Secret-Key": KEY}) as http:
- sid, socket = await opened(http, running, "prompt" if work == "login" else "status")
- titles = None
- if work != "login":
- titles = asyncio.create_task(http.get(running.url + TITLES_ROUTE.format(session_id=sid)))
- await read_until(socket, "cdm_call" if work == "cdm" else "prompt")
- assert list(running.sessions.rglob("token.json"))
- closed = asyncio.create_task(close_code(socket))
- running.send(signal.SIGTERM)
- await asyncio.to_thread(running.ended_well)
- assert await closed == CHANNEL_SESSION_GONE
- if titles:
- reply = await titles
- assert (reply.status, (await reply.json())["error_code"]) == (404, APIErrorCode.SESSION_NOT_FOUND)
- assert f"released {work} Session was cancelled" in running.output
- assert "event delete" not in running.output
- assert "Closed 1 remote session(s) at shutdown" in running.output
-
-
-@posix
-@pytest.mark.parametrize("options", SERVES.values(), ids=SERVES)
-async def test_two_sigterms_at_once_do_not_cut_the_stop(serve: Callable[..., Serve], options: list[str]) -> None:
- for _ in range(3):
- running = serve(options=options)
- async with aiohttp.ClientSession(headers={"X-Secret-Key": KEY}) as http:
- sockets = [(await opened(http, running, "status"))[1] for _ in range(4)]
- closed = [asyncio.create_task(close_code(socket)) for socket in sockets]
- running.send(signal.SIGTERM, signal.SIGTERM)
- await asyncio.to_thread(running.ended_well)
- assert await asyncio.gather(*closed) == [CHANNEL_SESSION_GONE] * 4
- assert "Closed 4 remote session(s) at shutdown" in running.output
-
-
-@posix
-@pytest.mark.parametrize(("work", "line"), [("hold", "stopping"), ("leave", "leaving")], ids=["stop", "exit"])
-async def test_a_sigterm_after_the_first_does_not_cut_the_stop(
- serve: Callable[..., Serve], work: str, line: str
-) -> None:
- running = serve(work)
- async with aiohttp.ClientSession(headers={"X-Secret-Key": KEY}) as http:
- await opened(http, running, "status")
- running.send(signal.SIGTERM)
- assert running.says(line)
- running.send(signal.SIGTERM)
- running.release.parent.mkdir(exist_ok=True)
- running.release.touch()
- await asyncio.to_thread(running.ended_well)
-
-
-@posix
-def test_a_second_ctrl_c_still_forces_the_stop(serve: Callable[..., Serve]) -> None:
- running = serve("hold")
- running.send(signal.SIGINT)
- assert running.says("stopping")
- running.send(signal.SIGINT)
- assert running.process.wait(DEADLINE) == 1
-
-
@pytest.fixture
def entry(
server: SimpleNamespace, # noqa: F811
@@ -317,43 +250,6 @@ def end_by_a_new_create_of_the_id(server: SimpleNamespace, entry: SessionEntry)
ENDS = [end_by_delete, end_by_eviction, end_by_a_client_that_is_gone, end_by_a_new_create_of_the_id]
-@pytest.mark.parametrize("end", ENDS)
-def test_a_late_write_of_a_service_thread_leaves_no_cache(
- server: SimpleNamespace, # noqa: F811
- entry: SessionEntry,
- titles: SimpleNamespace,
- end: Callable[[SimpleNamespace, SessionEntry], None],
-) -> None:
- """The removal comes after the last request: one that waits behind the writer is refused and writes nothing."""
- waiting = in_thread(lambda: get(server, TITLES_ROUTE, entry))
- assert wait_until(lambda: len(entry.lock._waiters or ()) == 1, DEADLINE)
- end(server, entry)
- assert wait_until(lambda: not titles.directory.exists(), DEADLINE)
- titles.release.set()
- assert titles.reply().status_code == 200
- assert error_code(waiting()) == APIErrorCode.SESSION_NOT_FOUND
- assert wait_until(lambda: not session_store.get_session_store()._logins, DEADLINE)
- assert not titles.directory.exists()
- if end is end_by_a_new_create_of_the_id:
- (new,) = sessions()
- assert (config.directories.cache / str(new.cache_tag) / "token.json").exists()
-
-
-def test_the_dashboard_gets_one_delete_event_and_no_update_after_it(
- server: SimpleNamespace, # noqa: F811
- entry: SessionEntry,
- titles: SimpleNamespace,
-) -> None:
- """A stop ends the work before the store retires the session, so each end runs twice."""
- seq = bus.seq
- on_loop(server, close_channels(web.Application()))
- end_by_delete(server, entry)
- titles.release.set()
- assert titles.reply().status_code == 200
- actions = [e["data"]["action"] for e in bus.since(seq) if e["event"] == "session"]
- assert actions.count("delete") == 1 and actions[-1] == "delete"
-
-
@pytest.mark.parametrize(("cache_tag", "busy"), [("_sessions/EXAMPLE", False), (None, True)], ids=["idle", "no-cache"])
async def test_an_end_with_nothing_to_write_late_starts_no_task(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, cache_tag: str | None, busy: bool
@@ -366,35 +262,6 @@ async def test_an_end_with_nothing_to_write_late_starts_no_task(
assert await store.delete(entry.session_id) and not store._logins
-async def test_the_close_waits_for_a_late_write(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(config.directories, "cache", tmp_path)
- directory = tmp_path / "_sessions" / "EXAMPLE"
- directory.mkdir(parents=True)
- store = SessionStore()
- entry = await store.create("EXAMPLE", None, cache_tag="_sessions/EXAMPLE")
- await entry.lock.acquire()
- closing = asyncio.create_task(store.close())
- assert await asyncio.to_thread(wait_until, lambda: not directory.exists(), DEADLINE)
- directory.mkdir(parents=True)
- entry.lock.release()
- await asyncio.wait_for(closing, DEADLINE)
- assert not directory.exists()
-
-
-async def test_a_late_write_holds_the_close_no_longer_than_a_login(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- monkeypatch.setattr(config.directories, "cache", tmp_path)
- monkeypatch.setattr(session_store, "LOGIN_WAIT", 0.05)
- store = SessionStore()
- entry = await store.create("EXAMPLE", None, cache_tag="_sessions/EXAMPLE")
- await entry.lock.acquire()
- await asyncio.wait_for(store.close(), DEADLINE)
- (tmp_path / "_sessions" / "EXAMPLE").mkdir(parents=True)
- entry.lock.release()
- assert await asyncio.to_thread(wait_until, lambda: not (tmp_path / "_sessions").exists(), DEADLINE)
-
-
@pytest.mark.parametrize("error", [None, RuntimeError, SystemExit], ids=["answers", "fails", "exits"])
@pytest.mark.parametrize(("call", "args"), [("request_input", ["code?"]), ("request_cdm", [{}]), ("ensure_active", [])])
def test_a_request_that_the_end_cuts_is_refused(
diff --git a/tests/remote/unit/test_server_accounts.py b/tests/remote/unit/test_server_accounts.py
index e2fb8a711..cfcc9833b 100644
--- a/tests/remote/unit/test_server_accounts.py
+++ b/tests/remote/unit/test_server_accounts.py
@@ -73,16 +73,6 @@ def test_single_account_always_same(accounts):
assert handlers.next_server_profile("SINGLE", None) is None
-def test_client_managed_gets_nothing(monkeypatch, accounts):
- monkeypatch.setattr(key_policy, "load_service_config", lambda s: {})
- monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
- monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object()))
- built = SimpleNamespace()
- monkeypatch.setattr(handlers, "instantiate_service", lambda *a: built)
- svc, cookies, cred, _ = launch_session("OTHER", "t", {})
- assert (svc, cookies, cred) == (built, None, None)
-
-
def test_per_key_gate(accounts, monkeypatch):
class Req:
def __init__(self, key):
@@ -95,11 +85,6 @@ def test_per_key_gate(accounts, monkeypatch):
assert handlers.server_account_for(handlers.request_policy(Req("k2")), "OTHER") is False
-def test_rotation_per_region_pool(accounts):
- picks = [handlers.next_server_profile("EX", r) for r in ["ca", "gb", "ca", "gb"]]
- assert picks == ["ca_main", "eu_box", "shared", "shared"]
-
-
def test_server_account_ignores_client_credentials(monkeypatch, accounts):
monkeypatch.setattr(key_policy, "load_service_config", lambda s: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
@@ -196,17 +181,6 @@ def test_nested_dl_params_reach_the_parent_ctx(monkeypatch):
assert svc.parent_params["exact_lang"] is True
-def test_absent_dl_params_fall_back_to_the_dl_defaults(monkeypatch):
- svc = _create_with_real_ctx(monkeypatch, {})
- selection = {k: svc.parent_params[k] for k in (*DL_DEFAULTS,)}
- assert selection == DL_DEFAULTS
-
-
-def test_an_empty_lang_list_is_kept(monkeypatch):
- svc = _create_with_real_ctx(monkeypatch, {"dl_params": {"lang": [], "a_lang": []}})
- assert svc.parent_params["lang"] == []
-
-
def test_a_service_lang_option_never_gets_the_dl_lang(monkeypatch):
svc = _create_with_real_ctx(monkeypatch, {"dl_params": {"lang": ["en"]}})
assert svc.lang is None
diff --git a/tests/remote/unit/test_server_cdm_absorbs_headers.py b/tests/remote/unit/test_server_cdm_absorbs_headers.py
deleted file mode 100644
index a3118f9ad..000000000
--- a/tests/remote/unit/test_server_cdm_absorbs_headers.py
+++ /dev/null
@@ -1,83 +0,0 @@
-"""The server CDM must license every WRM header a track carries, not only the first.
-
-A track can hold one `PlayReady` object per header: `ISM` shares a Protection list, `HLS`
-emits one per `EXT-X-KEY`. `track_pssh` returns the first PSSH only, so the
-server folds in the siblings. Without that it returns fewer content keys than a local CDM.
-"""
-
-import base64
-from types import SimpleNamespace
-from uuid import UUID
-
-import pytest
-
-import unshackle.core.cdm as cdm_mod
-import unshackle.core.cdm.detect as detect_mod
-import unshackle.core.drm as drm_mod
-from unshackle.core.api import handlers, server_keys
-from unshackle.core.api.key_policy import KeyPolicy
-
-pytestmark = pytest.mark.unit
-
-KID_A = UUID("161219ec3df64e0eadbb3827c0ccc46d")
-KID_B = UUID("43de497c6d1945f49acc2951696ec628")
-
-
-class _FakePlayReady:
- """Only the headers this object knows about yield keys."""
-
- def __init__(self, pssh=None, pssh_b64=None, kid=None, **kwargs):
- self.kids = [kid] if kid else [KID_A]
- self.content_keys: dict = {}
- self.pssh_b64 = pssh_b64
- self.absorbed: list = []
-
- @classmethod
- def from_pssh_b64(cls, pssh_b64, kid=None):
- return cls(pssh_b64=pssh_b64, kid=kid)
-
- def absorb(self, *others):
- for other in others:
- if other is self:
- continue
- self.absorbed.append(other)
- for kid in other.kids:
- if kid not in self.kids:
- self.kids.append(kid)
-
- def get_content_keys(self, cdm, certificate, licence):
- self.content_keys = {kid: f"key_{kid.hex[:4]}" for kid in self.kids}
-
-
-@pytest.fixture
-def playready_env(monkeypatch):
- monkeypatch.setattr(drm_mod, "PlayReady", _FakePlayReady)
- monkeypatch.setitem(cdm_mod.__dict__, "load_cdm", lambda *a, **k: object())
- monkeypatch.setattr(detect_mod, "is_playready_cdm", lambda cdm: True)
- monkeypatch.setattr(handlers, "ensure_track_drm", lambda track, session=None, init_data=None: None)
- monkeypatch.setattr(server_keys, "ensure_track_drm", lambda track, session=None, init_data=None: None)
- monkeypatch.setattr(server_keys, "resolve_device_name", lambda *a, **k: "dev")
- monkeypatch.setattr(server_keys, "check_vaults", lambda kids, name, **_: None)
- monkeypatch.setattr(server_keys, "cache_to_vaults", lambda keys, name, **_: None)
- monkeypatch.setattr(handlers.config, "serve", {"users": {}}, raising=False)
-
-
-def _keys_for(track):
- return server_keys.handle_single_server_cdm(
- service=SimpleNamespace(),
- title=SimpleNamespace(),
- track=track,
- pssh_b64=base64.b64encode(b"A").decode(),
- drm_type="playready",
- policy=KeyPolicy(),
- )
-
-
-def test_sibling_headers_are_licensed(playready_env):
- track = SimpleNamespace(drm=[_FakePlayReady(kid=KID_A), _FakePlayReady(kid=KID_B)])
- assert set(_keys_for(track)) == {KID_A.hex, KID_B.hex}
-
-
-def test_single_header_track_is_untouched(playready_env):
- track = SimpleNamespace(drm=[_FakePlayReady(kid=KID_A)])
- assert set(_keys_for(track)) == {KID_A.hex}
diff --git a/tests/remote/unit/test_server_cdm_gate.py b/tests/remote/unit/test_server_cdm_gate.py
index fa7402006..9f8796f69 100644
--- a/tests/remote/unit/test_server_cdm_gate.py
+++ b/tests/remote/unit/test_server_cdm_gate.py
@@ -81,7 +81,3 @@ def test_download_gate_follows_entitlement(serve_users, key, allowed):
with pytest.raises(APIError) as ei:
job_admission.enforce_download_gates({}, request(key))
assert ei.value.error_code == APIErrorCode.FORBIDDEN
-
-
-def test_download_gate_without_request(serve_users):
- job_admission.enforce_download_gates({})
diff --git a/tests/remote/unit/test_server_cdm_key_verification.py b/tests/remote/unit/test_server_cdm_key_verification.py
index 850d8a110..59432aee5 100644
--- a/tests/remote/unit/test_server_cdm_key_verification.py
+++ b/tests/remote/unit/test_server_cdm_key_verification.py
@@ -233,26 +233,6 @@ def test_the_server_reads_the_head_of_a_one_file_track_with_drm(example_plugins,
)
-def test_only_an_unanswered_track_draws_a_debug_line(caplog):
- """A requested track the server lists in clear_tracks carries no DRM, so its missing keys draw no line.
-
- An unanswered track gets a debug line only: its own licence follows, and that one fails the run.
- """
- video_track = SimpleNamespace(id="v-1", drm=None)
- audio_track = SimpleNamespace(id="a-1", drm=None)
-
- class Tracks(list):
- videos = [video_track]
- audio = [audio_track]
-
- with caplog.at_level(logging.DEBUG):
- install_reply({"keys": {}, "clear_tracks": ["a-1"]}, SimpleNamespace(tracks=Tracks([video_track, audio_track])))
-
- assert [(r.levelname, r.message) for r in caplog.records if "no content keys" in r.message] == [
- ("DEBUG", "Server CDM returned no content keys for track simplenamespace (v-1)")
- ]
-
-
def test_the_batch_takes_the_key_of_a_whole_file_cipher(caplog):
"""The server licensed the track's whole-file cipher: the client takes its key and keeps the cipher."""
cipher = ClearKeyCTR(None, bytes(range(16)), b"OggS")
diff --git a/tests/remote/unit/test_server_cdm_max_height.py b/tests/remote/unit/test_server_cdm_max_height.py
index d6d2633b9..126d73105 100644
--- a/tests/remote/unit/test_server_cdm_max_height.py
+++ b/tests/remote/unit/test_server_cdm_max_height.py
@@ -302,17 +302,6 @@ def playready_env(monkeypatch):
monkeypatch.setattr("unshackle.core.cdm.load_cdm", no_device)
-def test_playready_raises_the_refusal_before_the_device_loads(playready_env):
- refusal = server_keys.live_licence_refusal(
- session_entry(licensing=LicensingMode(Licensor.SERVER_CDM, 1080)), video(2160)
- )
- with pytest.raises(APIError) as ei:
- server_keys.handle_single_server_cdm(
- SimpleNamespace(), SimpleNamespace(), video(2160), "cHNzaA==", "playready", None, {}, refusal
- )
- assert ei.value is refusal
-
-
KID = UUID("161219ec3df64e0eadbb3827c0ccc46d")
CAP_DETAILS = {"reason": "server_cdm_max_height", "max_height": 1080}
@@ -434,14 +423,6 @@ def test_a_capped_answer_to_the_track_licence_moves_dl_to_the_local_device():
assert svc.client_licensed == {"vid"}
-def test_a_capped_hls_track_with_no_drm_yet_moves_to_the_local_device():
- track = SimpleNamespace(id="vid", drm=[], drm_preference=None)
- svc = remote_session(SimpleNamespace(is_playready=False, security_level=1), CAPPED)
- svc.batch_keys(one_title(track))
- assert svc.client_licensed == {"vid"}
- assert track.drm_preference == "widevine"
-
-
def test_batch_keys_forgets_the_last_titles_handovers():
track = SimpleNamespace(id="vid", drm=[_WV()], drm_preference=None)
svc = remote_session(SimpleNamespace(is_playready=False, security_level=1), {"keys": {}})
@@ -568,13 +549,6 @@ def test_a_cdm_entry_that_did_not_load_the_device_warns_and_does_not_decline(loc
assert "cdm entry for EXAMPLE1" in caplog.text
-def test_server_cdm_true_does_not_warn_about_a_cdm_entry_that_loaded_no_device(caplog):
- with caplog.at_level(logging.WARNING):
- _, data = sent_create(True, cdm_map={"example1": {">=1080": "my_device"}})
- assert "server_cdm" not in data
- assert not caplog.text
-
-
@pytest.mark.parametrize(
("entry", "profile", "names"),
[
@@ -592,11 +566,6 @@ def test_which_cdm_entries_name_a_device_with_no_quality(entry, profile, names):
assert cdm_entry_names_device(entry, profile) is names
-def test_a_client_with_no_device_does_not_decline():
- _, data = sent_create(False, None, local_cdm=None)
- assert "server_cdm" not in data
-
-
def created(answer, monkeypatch):
"""Run ``authenticate()`` to its end for a device the service's cdm entry loaded."""
svc, _ = sent_create(None, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"})
@@ -608,21 +577,6 @@ def created(answer, monkeypatch):
return svc
-def test_the_client_says_when_a_cdm_entry_gave_the_licensing_to_its_device(caplog, monkeypatch):
- with caplog.at_level(logging.INFO):
- svc = created({"server_cdm": False}, monkeypatch)
- assert svc.expected_server_cdm is False
- assert "cdm config has an entry for EXAMPLE1" in caplog.text
-
-
-def test_the_client_does_not_claim_its_device_when_the_server_keeps_the_server_cdm(caplog, monkeypatch):
- with caplog.at_level(logging.INFO):
- svc = created({"server_cdm": True, "server_cdm_max_height": 1080}, monkeypatch)
- assert svc.expected_server_cdm is True
- assert "your own device is not used" in caplog.text
- assert "cdm config has an entry" not in caplog.text
-
-
@pytest.mark.parametrize(
("cdm", "override", "cdm_map", "expected"),
[
@@ -641,34 +595,6 @@ def test_dl_records_whether_the_services_cdm_entry_named_the_loaded_device(cdm,
assert runner.cdm_from_service_entry() is expected
-@pytest.mark.parametrize("max_height", [None, 1080])
-def test_a_declined_server_cdm_that_the_server_keeps_is_reported(max_height, caplog):
- svc = remote_session(SimpleNamespace(is_playready=False), {})
- svc.service_tag = "EXAMPLE1"
- with caplog.at_level(logging.INFO):
- svc.adopt_session_cdm(LicensingMode(Licensor.SERVER_CDM, max_height), False)
- assert svc.expected_server_cdm is True
- assert "your own device is not used" in caplog.text
- assert "pass a higher -q" not in caplog.text
-
- caplog.clear()
- with caplog.at_level(logging.WARNING):
- svc.adopt_session_cdm(LicensingMode(Licensor.SERVER_CDM, max_height), True)
- assert "your own device is not used" not in caplog.text
-
-
-@pytest.mark.parametrize(("cdm_entry", "level"), [(True, logging.INFO), (False, logging.WARNING)])
-def test_a_refused_server_cdm_warns_only_when_no_cdm_entry_loaded_the_fallback(cdm_entry, level, caplog):
- svc = remote_session(SimpleNamespace(is_playready=False), {})
- svc.service_tag = "EXAMPLE1"
- svc.ctx.obj.cdm_entry = cdm_entry
- with caplog.at_level(logging.INFO):
- svc.adopt_session_cdm(LicensingMode(Licensor.CLIENT_DEVICE), True)
- assert svc.expected_server_cdm is False
- [record] = [r for r in caplog.records if "falling back to the local CDM" in r.getMessage()]
- assert record.levelno == level
-
-
@pytest.mark.parametrize("apply_overrides", [True, False])
@pytest.mark.parametrize(
("server_level", "service_entry", "expected"),
diff --git a/tests/remote/unit/test_server_cdm_type_override.py b/tests/remote/unit/test_server_cdm_type_override.py
index 0708cbdf5..6af6841a7 100644
--- a/tests/remote/unit/test_server_cdm_type_override.py
+++ b/tests/remote/unit/test_server_cdm_type_override.py
@@ -23,7 +23,6 @@ from tests.remote.sessions import launch_session, session_entry
from unshackle.core.api import handlers, key_policy, server_keys
from unshackle.core.api.errors import APIError
from unshackle.core.api.key_policy import KeyPolicy
-from unshackle.core.cdm.choice import choose_cdm
from unshackle.core.remote_protocol import LicensingMode, Licensor
pytestmark = pytest.mark.unit
@@ -293,28 +292,6 @@ def test_the_tracks_response_names_the_system_of_the_loaded_device(monkeypatch,
assert asyncio.run(run())["server_cdm_type"] == system
-@pytest.mark.parametrize(
- ("mapping", "both"),
- [
- (BOTH, True),
- ({"default": {"Widevine": "wv_device", "PlayReady": "pr_device"}}, True),
- ({"EXAMPLE1": {"widevine": "wv_device", "playready": None}}, False),
- ({"EXAMPLE1": {"widevine": "wv_device", "default": "pr_device"}}, False),
- ({"EXAMPLE1": "wv_device"}, False),
- ],
-)
-def test_both_systems_need_a_device_each(monkeypatch, mapping, both):
- monkeypatch.setattr(handlers.config, "cdm", mapping, raising=False)
- assert choose_cdm(handlers.config.cdm, "EXAMPLE1").both is both
-
-
-@pytest.mark.parametrize("cdm_type", [5, ["playready"], {"a": 1}])
-def test_a_cdm_type_that_is_not_a_string_takes_the_first_listed_device(monkeypatch, cdm_type):
- monkeypatch.setattr(handlers.config, "cdm", BOTH, raising=False)
- monkeypatch.setitem(cdm_mod.__dict__, "load_cdm", lambda name, **k: name)
- assert handlers.load_full_cdm("EXAMPLE1", None, cdm_type) == "wv_device"
-
-
def _reply_then_licence(monkeypatch, track, drm_type, loaded=None):
"""The tracks reply's server_cdm_type, then the system the single route licenses ``track`` with for ``drm_type``."""
from unshackle.core.api import session_store as store_mod
diff --git a/tests/remote/unit/test_server_cdm_vault_write.py b/tests/remote/unit/test_server_cdm_vault_write.py
index dc3d46a1f..8203237f7 100644
--- a/tests/remote/unit/test_server_cdm_vault_write.py
+++ b/tests/remote/unit/test_server_cdm_vault_write.py
@@ -5,7 +5,6 @@ the vault writes, so a remote run never kept the keys it paid for. Keys that cam
vault in the first place must not be pushed back.
"""
-import threading
from types import SimpleNamespace
from uuid import UUID
@@ -100,13 +99,6 @@ def test_a_capped_track_takes_a_local_vault_key_before_the_refusal():
assert capped_run(memory_vaults({CACHED: "k_cached"})).content_keys == {CACHED: "k_cached"}
-def test_a_capped_track_no_vault_holds_raises_the_refusal():
- import click
-
- with pytest.raises(click.ClickException, match="only Widevine DRM, which your local PlayReady CDM cannot license"):
- capped_run(memory_vaults())
-
-
def test_batch_resolved_keys_are_cached_before_download():
"""The batch licence fills track.drm before prepare_drm, so dl caches it at the call site."""
vaults = memory_vaults()
@@ -175,29 +167,6 @@ def test_a_local_vault_key_goes_before_a_batch_server_vault_key():
)
-def test_tracks_sharing_one_drm_licence_and_push_once():
- """Two tracks on the same DRM run at the same time; the second must find the first one's keys."""
- vaults = memory_vaults()
- drm = FakeWidevine([NEW])
- source = MemoryKeySource({NEW: "k_new"})
- keys = make_resolver(vaults, source)
- both_started = threading.Barrier(2)
-
- def track():
- both_started.wait(10)
- prepare(keys, drm, NEW)
-
- threads = [threading.Thread(target=track) for _ in range(2)]
- for t in threads:
- t.start()
- for t in threads:
- t.join()
- keys.wait_vault_writes()
-
- assert len(source.asked) == 1
- assert vaults.vaults[0].pushes == [{NEW: "k_new"}]
-
-
def test_cdm_only_still_reuses_keys_from_the_run_cache():
"""--cdm-only skips the vaults, not LICENSE_KEY_CACHE, so a second track with the same KID does not licence twice."""
vaults = memory_vaults()
diff --git a/tests/remote/unit/test_server_vault_push.py b/tests/remote/unit/test_server_vault_push.py
index f9732f725..9ee0833d5 100644
--- a/tests/remote/unit/test_server_vault_push.py
+++ b/tests/remote/unit/test_server_vault_push.py
@@ -6,7 +6,6 @@ Over ``--cdm-only`` the session runs on the client's own device and asks the ser
import asyncio
import json
import logging
-import threading
from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -262,24 +261,6 @@ async def test_the_server_stores_only_a_named_kid_no_local_vault_holds(server, c
]
-async def test_the_server_answers_before_the_remote_vaults_take_the_keys(server, monkeypatch) -> None:
- release = threading.Event()
- real = server.remote.add_keys
-
- def slow(service: str, kid_keys: dict) -> int:
- release.wait(10)
- return real(service, kid_keys)
-
- monkeypatch.setattr(server.remote, "add_keys", slow)
- await handlers.session_keys_handler({"track_id": "v2", "keys": {LICENSED.hex: KEY}}, "sess")
-
- assert server.local.get_key(LICENSED, "EXAMPLE") == KEY
- assert server.remote.get_key(LICENSED, "EXAMPLE") is None
- release.set()
- await settled()
- assert server.remote.get_key(LICENSED, "EXAMPLE") == KEY
-
-
async def test_a_client_cannot_replace_a_content_key_a_local_vault_holds(server) -> None:
server.local.add_key("EXAMPLE", LICENSED, OTHER_KEY)
await handlers.session_keys_handler({"track_id": "v2", "keys": {LICENSED.hex: KEY}}, "sess")
@@ -288,13 +269,6 @@ async def test_a_client_cannot_replace_a_content_key_a_local_vault_holds(server)
assert server.remote.get_key(LICENSED, "EXAMPLE") is None
-async def test_the_server_answers_empty_when_it_stores_nothing(server, caplog) -> None:
- caplog.set_level(logging.INFO, logger="api")
- resp = await handlers.session_keys_handler({"track_id": ["v1"], "keys": {UNNAMED.hex: KEY}}, "sess")
- assert (resp.status, json.loads(resp.body)) == (200, {})
- assert [r for r in caplog.records if r.levelno >= logging.INFO] == []
-
-
def cdm_only_client(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, cdm: Any, created: dict) -> RemoteService:
"""A real RemoteService for a ``--cdm-only`` run whose server answers session create with ``created``."""
monkeypatch.setattr(config, "credentials", {})
diff --git a/tests/remote/unit/test_session_channel.py b/tests/remote/unit/test_session_channel.py
index d6171638a..8b76fc4d8 100644
--- a/tests/remote/unit/test_session_channel.py
+++ b/tests/remote/unit/test_session_channel.py
@@ -4,14 +4,12 @@ from __future__ import annotations
import asyncio
import logging
-import threading
from typing import Any
import pytest
from aiohttp import WSMessage
from aiohttp.http_websocket import WS_CLOSED_MESSAGE
-from tests.remote.unit.test_tunnel import wait_until
from unshackle.core.api.input_bridge import InputBridge
from unshackle.core.api.session_log import SessionLogBuffer
from unshackle.core.api.session_store import SessionEntry
@@ -45,35 +43,6 @@ def entry_with_logs(count: int) -> SessionEntry:
return entry
-def log_seqs(socket: FakeSocket) -> list[int]:
- return [m["seq"] for m in socket.sent if m["type"] == "log"]
-
-
-async def test_the_backlog_goes_before_a_record_logged_while_the_old_socket_closes() -> None:
- entry = entry_with_logs(4)
- old = FakeSocket()
-
- async def close_slowly(code: int = 1000, message: bytes = b"") -> bool:
- entry.log_buffer.append(logging.INFO, "EXAMPLE line 5")
- await asyncio.sleep(0)
- old.closed.set()
- return True
-
- old.close = close_slowly # type: ignore[method-assign]
- entry.channel.ws = old # type: ignore[assignment]
- new = FakeSocket()
- serving = asyncio.create_task(entry.channel.serve(new, entry, 2, False)) # type: ignore[arg-type]
- for _ in range(200):
- if len(log_seqs(new)) >= 3:
- break
- await asyncio.sleep(0.01)
- assert log_seqs(new) == [3, 4, 5]
- assert {"type": "status", "status": "authenticating"} in new.sent
- await new.close()
- await serving
- assert not entry.channel.attached
-
-
async def test_a_socket_that_cannot_send_is_closed_and_detached() -> None:
entry = entry_with_logs(1)
broken = FakeSocket()
@@ -85,55 +54,3 @@ async def test_a_socket_that_cannot_send_is_closed_and_detached() -> None:
await asyncio.wait_for(entry.channel.serve(broken, entry, 0, False), 5) # type: ignore[arg-type]
assert broken.closed.is_set()
assert not entry.channel.attached
-
-
-async def sent_cdm_calls(socket: FakeSocket) -> list[dict[str, Any]]:
- for _ in range(200):
- if calls := [m for m in socket.sent if m["type"] == "cdm_call"]:
- return calls
- await asyncio.sleep(0.01)
- return []
-
-
-async def test_a_detached_channel_keeps_its_waiting_asks_for_the_next_attach() -> None:
- entry = entry_with_logs(0)
- bridge = entry.input_bridge
- assert bridge is not None
- socket = FakeSocket()
- serving = asyncio.create_task(entry.channel.serve(socket, entry, 0, False)) # type: ignore[arg-type]
- await asyncio.sleep(0)
- answers: list[Any] = []
- worker = threading.Thread(target=lambda: answers.append(bridge.request_cdm({"op": "close"}, timeout=5)))
- worker.start()
- (call,) = await sent_cdm_calls(socket)
- await socket.close()
- await serving
- again = FakeSocket()
- serving = asyncio.create_task(entry.channel.serve(again, entry, 0, False)) # type: ignore[arg-type]
- assert await sent_cdm_calls(again) == [call]
- assert bridge.answer(call["id"], '{"op": "close"}')
- await asyncio.to_thread(worker.join, 5)
- assert answers == [{"op": "close"}]
- await again.close()
- await serving
-
-
-def test_a_prompt_the_client_refuses_stops_the_service_at_once() -> None:
- bridge = InputBridge()
- offered: list[Any] = []
- bridge.channel = type("Attached", (), {"attached": True, "offer": lambda self, ask: offered.append(ask) or True})()
- failed: list[BaseException] = []
-
- def ask() -> None:
- try:
- bridge.request_input("Enter the EXAMPLE code", timeout=30)
- except RuntimeError as e:
- failed.append(e)
-
- worker = threading.Thread(target=ask)
- worker.start()
- assert wait_until(lambda: bool(offered), 5)
- assert bridge.answer(offered[0].id, "", "stdin is closed")
- worker.join(5)
- assert not worker.is_alive()
- assert "stdin is closed" in str(failed[0])
diff --git a/tests/remote/unit/test_session_lifetime.py b/tests/remote/unit/test_session_lifetime.py
index 41c1831a4..2e2eab648 100644
--- a/tests/remote/unit/test_session_lifetime.py
+++ b/tests/remote/unit/test_session_lifetime.py
@@ -3,8 +3,6 @@
from __future__ import annotations
import asyncio
-import contextlib
-import signal
import subprocess
import sys
import uuid
@@ -29,10 +27,8 @@ from tests.remote.unit.test_remote_loopback import (
)
from tests.remote.unit.test_remote_service_helpers import blob
from tests.remote.unit.test_session_reopen import SERVER, make_service
-from tests.remote.unit.test_tunnel import wait_until
-from unshackle.core import process_exit, remote_channel, remote_lifetime, remote_service
+from unshackle.core import process_exit, remote_lifetime, remote_service
from unshackle.core.api import handlers, routes, session_store
-from unshackle.core.api.download_manager import busy_services
from unshackle.core.api.errors import APIError
from unshackle.core.api.session_store import SessionEntry
from unshackle.core.config import config
@@ -181,22 +177,6 @@ def wait_authenticated(process: subprocess.Popen[str]) -> None:
pytest.fail("the client did not log in")
-@posix_signals
-def test_a_ctrl_c_before_the_create_reply_leaves_no_session(
- build: SimpleNamespace, client: Callable[[str], subprocess.Popen[str]]
-) -> None:
- process = client(build.server.url)
- assert build.started.wait(DEADLINE)
- process.send_signal(signal.SIGINT)
- process.communicate(timeout=DEADLINE)
- assert count(build.server, "DELETE", SESSION_ROUTE) == 1
-
- build.release.set()
- assert wait_until(lambda: answered(build.server, 404) or answered(build.server, 200), DEADLINE)
- assert sessions() == []
- assert build.logins == []
-
-
class HeldDelete:
"""The DELETE route of the server, which waits for ``release`` before it does its work."""
@@ -220,71 +200,6 @@ def held_delete(monkeypatch: pytest.MonkeyPatch) -> Iterator[HeldDelete]:
held.release.set()
-def press_while_it_waits(process: subprocess.Popen[str]) -> None:
- """Send one Ctrl+C that the client must survive."""
- process.send_signal(signal.SIGINT)
- with pytest.raises(subprocess.TimeoutExpired):
- process.wait(0.3)
-
-
-@posix_signals
-@pytest.mark.parametrize("gives_up", [False, True], ids=["one-press", "two-presses"])
-@pytest.mark.parametrize("phase", ["create", "idle"])
-def test_a_ctrl_c_during_the_end_is_ignored_once(
- build: SimpleNamespace,
- held_delete: HeldDelete,
- client: Callable[[str], subprocess.Popen[str]],
- tmp_path: Path,
- phase: str,
- gives_up: bool,
-) -> None:
- """The first Ctrl+C starts the end, and the two that count come while its DELETE waits for the server."""
- process = client(build.server.url)
- assert build.started.wait(DEADLINE)
- if phase == "idle":
- build.release.set()
- wait_authenticated(process)
- (entry,) = sessions()
- stored = config.directories.cache / str(entry.cache_tag) / "token.json"
- stored.parent.mkdir(parents=True)
- stored.write_text('"EXAMPLE"', encoding="utf-8")
-
- process.send_signal(signal.SIGINT)
- assert held_delete.started.wait(DEADLINE)
- press_while_it_waits(process)
- if gives_up:
- process.send_signal(signal.SIGINT)
- else:
- held_delete.release.set()
- output, _ = process.communicate(timeout=DEADLINE)
- held_delete.release.set()
- assert wait_until(lambda: count(build.server, "DELETE", SESSION_ROUTE) == 1, DEADLINE)
- build.release.set()
- assert wait_until(lambda: answered(build.server, 404 if phase == "create" else 200), DEADLINE)
-
- assert "Traceback" not in output and "KeyboardInterrupt" not in output
- saved = (tmp_path / "client-cache" / "EXAMPLE" / "token.json").exists()
- assert saved is (phase == "idle" and not gives_up)
- assert count(build.server, "DELETE", SESSION_ROUTE) == 1 and sessions() == []
- assert len(build.logins) == (phase == "idle")
-
-
-@posix_signals
-def test_giving_up_on_the_close_of_the_run_stops_the_run(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any],
- held_delete: HeldDelete,
- client: Callable[..., subprocess.Popen[str]],
-) -> None:
- process = client(server.url, "close")
- assert held_delete.started.wait(DEADLINE)
- press_while_it_waits(process)
- process.send_signal(signal.SIGINT)
- output, _ = process.communicate(timeout=DEADLINE)
-
- assert "closed" not in output and "Aborted" in output and "Traceback" not in output
-
-
def test_a_delete_of_the_owner_ends_a_create_in_progress(build: SimpleNamespace) -> None:
session_id = str(uuid.uuid4())
reply = in_thread(lambda: create(build.server.url, session_id, cache={"token": blob('"EXAMPLE"')}))
@@ -300,18 +215,6 @@ def test_a_delete_of_the_owner_ends_a_create_in_progress(build: SimpleNamespace)
assert delete(build.server.url, session_id).status_code == 404
-def test_a_delete_of_another_key_leaves_a_create_in_progress(build: SimpleNamespace) -> None:
- session_id = str(uuid.uuid4())
- reply = in_thread(lambda: create(build.server.url, session_id))
- assert build.started.wait(DEADLINE)
-
- assert error_code(delete(build.server.url, session_id, OTHER_KEY)) == APIErrorCode.SESSION_NOT_FOUND
- build.release.set()
-
- assert reply().json()["session_id"] == session_id
- assert [s.session_id for s in sessions()] == [session_id]
-
-
def test_the_id_of_another_key_is_refused(build: SimpleNamespace) -> None:
session_id = str(uuid.uuid4())
reply = in_thread(lambda: create(build.server.url, session_id))
@@ -326,34 +229,6 @@ def test_the_id_of_another_key_is_refused(build: SimpleNamespace) -> None:
assert sessions() == [entry] and not entry.channel.ended
-def test_a_create_sent_again_takes_over_from_the_one_in_progress(build: SimpleNamespace) -> None:
- """A gateway error page makes the client send the same create again while the server still builds the first."""
- session_id = str(uuid.uuid4())
- cache = {"token": blob('"EXAMPLE"')}
- first = in_thread(lambda: create(build.server.url, session_id, cache=cache))
- assert build.started.wait(DEADLINE)
-
- assert create(build.server.url, session_id, cache=cache).status_code == 200
- (entry,) = sessions()
- build.release.set()
-
- assert error_code(first()) == APIErrorCode.SESSION_NOT_FOUND
- assert sessions() == [entry] and entry.owner_key == KEY
- assert cache_files() == [config.directories.cache / str(entry.cache_tag) / "token.json"]
-
-
-def test_a_create_sent_again_after_its_delete_is_refused(build: SimpleNamespace) -> None:
- session_id = str(uuid.uuid4())
- first = in_thread(lambda: create(build.server.url, session_id))
- assert build.started.wait(DEADLINE)
- assert delete(build.server.url, session_id).status_code == 200
-
- assert error_code(create(build.server.url, session_id)) == APIErrorCode.SESSION_NOT_FOUND
- build.release.set()
- assert error_code(first()) == APIErrorCode.SESSION_NOT_FOUND
- assert sessions() == []
-
-
def test_a_create_sent_again_replaces_the_open_session_when_it_is_stored(build: SimpleNamespace) -> None:
build.started.set()
session_id = str(uuid.uuid4())
@@ -393,21 +268,6 @@ def test_a_create_sent_again_that_fails_leaves_the_open_session(
assert cache_files() == stored and len(stored) == 1
-def test_a_delete_ends_both_the_open_session_and_the_create_that_would_replace_it(build: SimpleNamespace) -> None:
- build.started.set()
- session_id = str(uuid.uuid4())
- assert create(build.server.url, session_id).status_code == 200
- build.started.clear()
- reply = in_thread(lambda: create(build.server.url, session_id))
- assert build.started.wait(DEADLINE)
-
- assert delete(build.server.url, session_id).status_code == 200
- assert sessions() == []
- build.release.set()
- assert error_code(reply()) == APIErrorCode.SESSION_NOT_FOUND
- assert sessions() == []
-
-
@pytest.mark.skipif(sys.platform == "darwin", reason="macOS has only one loopback address")
@pytest.mark.parametrize("state", ["pending", "open"])
def test_an_id_stays_with_the_address_that_made_it(build: SimpleNamespace, state: str) -> None:
@@ -440,55 +300,6 @@ def test_an_id_stays_with_the_address_that_made_it(build: SimpleNamespace, state
assert entry.session_id == session_id and not entry.channel.ended
-def test_the_end_of_a_replaced_create_leaves_the_next_one_pending(build: SimpleNamespace) -> None:
- """The first create finishes while the second one still builds, and a DELETE must still find the second."""
- session_id = str(uuid.uuid4())
- second = SimpleNamespace(started=Event(), release=Event())
- hold_first = StubService.hooks["init"]
-
- def hold(stub: StubService) -> None:
- if not build.started.is_set():
- hold_first(stub)
- else:
- second.started.set()
- assert second.release.wait(DEADLINE)
-
- StubService.hooks["init"] = hold
- first = in_thread(lambda: create(build.server.url, session_id))
- assert build.started.wait(DEADLINE)
- again = in_thread(lambda: create(build.server.url, session_id))
- assert second.started.wait(DEADLINE)
- build.release.set()
- assert error_code(first()) == APIErrorCode.SESSION_NOT_FOUND
-
- assert delete(build.server.url, session_id).status_code == 200
- second.release.set()
- assert error_code(again()) == APIErrorCode.SESSION_NOT_FOUND
- assert sessions() == []
-
-
-def test_a_create_ended_before_its_build_builds_nothing(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any],
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- started, release = Event(), Event()
-
- def resolve(*args: Any) -> Any:
- started.set()
- assert release.wait(DEADLINE)
- return None, []
-
- monkeypatch.setattr(handlers, "resolve_handler_proxy", resolve)
- session_id = str(uuid.uuid4())
- reply = in_thread(lambda: create(server.url, session_id))
- assert started.wait(DEADLINE)
- assert delete(server.url, session_id).status_code == 200
- release.set()
- assert error_code(reply()) == APIErrorCode.SESSION_NOT_FOUND
- assert StubService.logins == 0
-
-
def test_a_session_deleted_between_its_store_and_its_login_starts_no_login(
server: SimpleNamespace, # noqa: F811
logins: list[Any],
@@ -508,20 +319,6 @@ def test_a_session_deleted_between_its_store_and_its_login_starts_no_login(
assert logins == []
-def test_a_service_that_a_create_builds_is_not_reloaded(
- build: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
-) -> None:
- monkeypatch.setattr("unshackle.core.api.stats.stats.mode", "remote_only")
- scheduled: list[str] = []
- monkeypatch.setattr(session_store, "_schedule_pending_reload", scheduled.append)
- reply = in_thread(lambda: create(build.server.url, str(uuid.uuid4())))
- assert build.started.wait(DEADLINE)
- assert busy_services() == {"EXAMPLE"} and scheduled == []
- build.release.set()
- assert reply().status_code == 200
- assert scheduled == ["EXAMPLE"]
-
-
def test_a_create_that_is_refused_holds_no_id(
server: SimpleNamespace, # noqa: F811
logins: list[Any],
@@ -567,22 +364,6 @@ def test_the_server_takes_the_id_that_the_client_names() -> None:
assert e.value.error_code == APIErrorCode.CLIENT_OUTDATED
-def test_a_create_that_times_out_is_deleted(build: SimpleNamespace) -> None:
- service = make_client(build.server.url)
- service.client.timeout = 1.0
- with pytest.raises(RemoteError) as e:
- service.authenticate()
- assert e.value.kind == ClientErrorKind.TIMEOUT
- assert count(build.server, "DELETE", SESSION_ROUTE) == 1
- assert service._session_id is None
-
- build.release.set()
- assert wait_until(lambda: answered(build.server, 404) or answered(build.server, 200), DEADLINE)
- assert sessions() == [] and build.logins == []
- service.close()
- assert count(build.server, "DELETE", SESSION_ROUTE) == 1
-
-
def test_a_create_that_answers_after_the_end_leaves_no_session(
build: SimpleNamespace, caplog: pytest.LogCaptureFixture
) -> None:
@@ -614,14 +395,6 @@ def test_an_ended_owner_never_opens_again(server: SimpleNamespace, logins: list[
assert len(logins) == 1 and sessions() == []
-def test_the_end_does_not_wait_for_a_reopen(server: SimpleNamespace, logins: list[Any]) -> None: # noqa: F811
- service = make_client(server.url)
- service.authenticate()
- with service._reopen_lock:
- assert in_thread(service.close)() is None
- assert sessions() == []
-
-
@pytest.fixture
def exit_hooks(monkeypatch: pytest.MonkeyPatch) -> list[Any]:
hooks: list[Any] = []
@@ -727,18 +500,6 @@ def test_the_end_gives_up_after_a_failed_delete_and_saves_before_the_rest(
assert not [r for r in caplog.records if r.levelname in ("WARNING", "ERROR")]
-def test_the_end_on_another_thread_leaves_the_signal_handlers() -> None:
- before = signal.getsignal(signal.SIGINT)
- seen: list[Any] = []
- service = make_service()
- service.client.send = lambda *a, **k: seen.append(signal.getsignal(signal.SIGINT)) or interrupt() # type: ignore
-
- assert isinstance(in_thread(service.close)(), KeyboardInterrupt)
- service.lifetime.end_at_exit()
- assert seen[0] is before and seen[1] is not before
- assert signal.getsignal(signal.SIGINT) is before
-
-
@pytest.mark.parametrize(
"kind,deleted",
[(ClientErrorKind.TUNNEL_CLOSED, True), (ClientErrorKind.TIMEOUT, True), (APIErrorCode.SESSION_NOT_FOUND, False)],
@@ -758,39 +519,6 @@ def test_a_reopen_ends_the_session_it_gives_up(monkeypatch: pytest.MonkeyPatch,
assert service._session_id is None and not service.lifetime.ended
-def test_a_search_interrupted_in_its_tunnel_stops_it(monkeypatch: pytest.MonkeyPatch) -> None:
- service, stopped = local_proxy_client(monkeypatch, interrupt)
- with pytest.raises(KeyboardInterrupt):
- list(service.search())
- assert len(stopped) == 1
-
-
-def test_an_end_during_the_login_is_silent(
- server: SimpleNamespace, # noqa: F811
- monkeypatch: pytest.MonkeyPatch,
- caplog: pytest.LogCaptureFixture,
-) -> None:
- asked, release = Event(), Event()
-
- def login(stub: StubService, cookies: Any, credential: Any) -> None:
- asked.set()
- release.wait(DEADLINE)
-
- monkeypatch.setattr(StubService, "authenticate", login)
- service = make_client(server.url)
- opened = in_thread(service.authenticate)
- try:
- assert asked.wait(DEADLINE)
- assert wait_until(lambda: isinstance(service.channel, WebSocketChannel), DEADLINE)
- service.close()
- assert isinstance(opened(), RemoteError)
- finally:
- release.set()
- assert sessions() == []
- assert not [seen for seen in server.seen if "/None" in seen[1]]
- assert not [r for r in caplog.records if r.levelname == "ERROR" and r.name.startswith("remote_")]
-
-
def test_an_end_during_the_channel_open_is_silent(
server: SimpleNamespace, # noqa: F811
logins: list[Any],
@@ -843,92 +571,6 @@ def test_a_reopen_after_a_drain_ends_the_session_and_not_its_owner(
assert sessions() == [] and exit_hooks == [] and process_exit.ends == set()
-def test_the_save_of_the_returned_cache_is_not_interrupted() -> None:
- service = make_service()
- saved: list[dict[str, str]] = []
-
- def save(cache: dict[str, str]) -> None:
- signal.raise_signal(signal.SIGINT)
- signal.raise_signal(signal.SIGINT)
- saved.append(cache)
-
- service.lifetime.save_cache = save
- service.client.send = lambda *a, **k: SimpleNamespace(ok=True, json=lambda: {"cache": {"token": "x"}}) # type: ignore
- service.close()
- assert saved == [{"token": "x"}]
-
-
-def test_a_press_that_a_destructor_swallows_does_not_disable_the_next() -> None:
- service = make_service()
-
- def send(*args: Any, **kwargs: Any) -> Any:
- signal.raise_signal(signal.SIGINT)
- with contextlib.suppress(KeyboardInterrupt):
- signal.raise_signal(signal.SIGINT)
- signal.raise_signal(signal.SIGINT)
- pytest.fail("the third press did not stop the end")
-
- service.client.send = send # type: ignore[method-assign]
- with pytest.raises(KeyboardInterrupt):
- service.close()
-
-
-def test_a_user_who_gave_up_waits_for_no_other_end(exit_hooks: list[Any]) -> None:
- first, second = make_service(), make_service()
-
- def send(*args: Any, **kwargs: Any) -> Any:
- signal.raise_signal(signal.SIGINT)
- signal.raise_signal(signal.SIGINT)
-
- first.client.send = second.client.send = send # type: ignore[method-assign,assignment]
- with pytest.raises(KeyboardInterrupt):
- first.close()
- second.client.send = pytest.fail # type: ignore[method-assign,assignment]
- second.lifetime.end_at_exit()
- assert second.lifetime.ended
-
-
-def test_an_ignored_ctrl_c_stays_ignored(monkeypatch: pytest.MonkeyPatch) -> None:
- """A process that nohup or a shell started with SIGINT ignored keeps that during the end."""
- service = make_service()
- seen: list[Any] = []
- service.client.send = lambda *a, **k: seen.append(signal.getsignal(signal.SIGINT)) # type: ignore
- before = signal.signal(signal.SIGINT, signal.SIG_IGN)
- try:
- service.close()
- finally:
- signal.signal(signal.SIGINT, before)
- assert seen == [signal.SIG_IGN]
-
-
-@pytest.mark.parametrize("fault", ["send", "body", "shape", "save"])
-def test_a_fault_of_one_delete_does_not_stop_the_rest(exit_hooks: list[Any], fault: str) -> None:
- service = make_service()
- service.lifetime.name()
- sent: list[str] = []
- stopped: list[int] = []
-
- def broken(*args: Any) -> Any:
- raise {"save": SystemExit, "body": RecursionError}.get(fault, RuntimeError)("EXAMPLE fault")
-
- def send(method: str, endpoint: str, timeout: float, background: bool) -> Any:
- sent.append(endpoint)
- if fault == "send":
- broken()
- return SimpleNamespace(ok=True, json=broken if fault == "body" else lambda: [] if fault == "shape" else {})
-
- service.client.send = send # type: ignore[method-assign]
- service.client.tunnel = SimpleNamespace(stop=lambda: stopped.append(1), lost=False) # type: ignore[assignment]
- if fault == "save":
- service.lifetime.save_cache = broken
- exit_hooks.append(service.lifetime.end_at_exit)
-
- service.close()
- assert len(sent) == 2 and stopped == [1] and exit_hooks == []
- service.close()
- assert len(sent) == 2
-
-
@responses.activate
def test_the_error_of_a_failed_create_is_the_one_that_the_user_sees() -> None:
service = make_client(SERVER)
@@ -939,17 +581,6 @@ def test_the_error_of_a_failed_create_is_the_one_that_the_user_sees() -> None:
service.authenticate()
-def test_an_interrupted_channel_close_runs_again() -> None:
- service = make_service()
- closes = iter([interrupt, lambda: None])
- service.lifetime.channel = SimpleNamespace(close=lambda: next(closes)()) # type: ignore[assignment]
- service.client.send = lambda *a, **k: SimpleNamespace(ok=False) # type: ignore
- with pytest.raises(KeyboardInterrupt):
- service.close()
- service.close()
- assert next(closes, None) is None and service.channel is None
-
-
def test_a_release_keeps_what_another_thread_opened_meanwhile() -> None:
service = make_service()
channel: Any = SimpleNamespace(close=lambda: None)
@@ -962,35 +593,6 @@ def test_a_release_keeps_what_another_thread_opened_meanwhile() -> None:
assert service.channel is channel and service.client.tunnel is tunnel
-@pytest.mark.parametrize("at", ["hook", "create", "end"])
-def test_an_end_of_another_thread_stops_the_opening(
- server: SimpleNamespace, # noqa: F811
- logins: list[Any],
- exit_hooks: list[Any],
- monkeypatch: pytest.MonkeyPatch,
- at: str,
-) -> None:
- """Each test hook ends the owner from another thread at one point of the opening."""
- service = make_client(server.url)
-
- def end(*args: Any) -> Any:
- assert in_thread(service.close)() is None
- return {}
-
- if at == "hook":
- monkeypatch.setattr(remote_lifetime.atexit, "register", lambda hook: end() and None or exit_hooks.append(hook))
- elif at == "create":
- monkeypatch.setattr(remote_service, "launch_keys", end)
- else:
- opened = remote_channel.open_channel
- monkeypatch.setattr(remote_channel, "open_channel", lambda service: (opened(service), end())[0])
-
- with pytest.raises(RemoteError):
- service.authenticate()
- assert sessions() == [] and exit_hooks == []
- assert count(server, "POST", SESSION_CREATE_ROUTE) == (2 if at == "end" else 0)
-
-
def test_an_ended_owner_opens_no_tunnel(monkeypatch: pytest.MonkeyPatch) -> None:
service, _ = local_proxy_client(monkeypatch, lambda: pytest.fail("the ended owner opened a tunnel"))
service.close()
@@ -1019,48 +621,3 @@ def test_a_stop_before_the_thread_runs_keeps_it_from_connecting(monkeypatch: pyt
channel.thread.run()
assert channel.attempted.is_set()
assert connected == []
-
-
-def test_the_end_does_not_wait_for_a_cdm_call(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(remote_channel, "CDM_CLOSE_TIMEOUT", 0.01)
- service = make_service()
- service.ctx = SimpleNamespace(obj=None) # type: ignore[assignment]
- messages = ServerMessages(service)
- with messages.cdm_lock:
- assert in_thread(messages.close_cdm_sessions)() is None
-
-
-def test_the_tunnel_test_stops_the_tunnel_it_was_interrupted_in(monkeypatch: pytest.MonkeyPatch) -> None:
- from unshackle.commands import tunnel_test
-
- service, stopped = local_proxy_client(monkeypatch, interrupt)
- monkeypatch.setattr(tunnel_test, "get_ip_info", lambda session=None: {"ip": "192.0.2.1"})
- monkeypatch.setattr(tunnel_test, "remote_client", lambda name: service.client)
- with pytest.raises(KeyboardInterrupt):
- tunnel_test.tunnel_test.callback(None, None)
- assert len(stopped) == 1
-
-
-def test_a_press_after_the_end_does_not_leave_its_handler(monkeypatch: pytest.MonkeyPatch) -> None:
- service = make_service()
- service.client.send = lambda *a, **k: SimpleNamespace(ok=False) # type: ignore
- before, set_handler = signal.getsignal(signal.SIGINT), signal.signal
-
- def press_first(signum: int, handler: Any) -> Any:
- if handler is before:
- signal.raise_signal(signal.SIGINT)
- signal.raise_signal(signal.SIGINT)
- return set_handler(signum, handler)
-
- monkeypatch.setattr(signal, "signal", press_first)
- service.close()
- assert signal.getsignal(signal.SIGINT) is before
-
-
-def test_a_channel_of_an_ended_owner_stops_by_itself() -> None:
- service = make_service()
- service.ctx = SimpleNamespace(obj=None) # type: ignore[assignment]
- channel = WebSocketChannel(ServerMessages(service))
- service.lifetime.ended = True
- channel.thread.run()
- assert channel.attempted.is_set() and not channel.connected.is_set()
diff --git a/tests/remote/unit/test_session_log.py b/tests/remote/unit/test_session_log.py
index b0747ccdf..f26da6eb2 100644
--- a/tests/remote/unit/test_session_log.py
+++ b/tests/remote/unit/test_session_log.py
@@ -36,14 +36,6 @@ def test_mirror_copies_all_levels_and_lazy_formatting() -> None:
assert messages == [("INFO", "hello world"), ("WARNING", "warn"), ("ERROR", "bad")]
-def test_mirror_buffers_below_logger_level() -> None:
- logger = logging.getLogger("test-session-log-level")
- logger.setLevel(logging.WARNING)
- buf = SessionLogBuffer()
- SessionLogMirror(logger, buf).info("still captured")
- assert [r["message"] for r in buf.since(0)] == ["still captured"]
-
-
def test_capture_service_logs_attaches_and_detaches() -> None:
logger = logging.getLogger("test-capture-tag")
buf = SessionLogBuffer()
@@ -54,13 +46,6 @@ def test_capture_service_logs_attaches_and_detaches() -> None:
assert not logger.handlers
-def test_capture_service_logs_none_buffer_noop() -> None:
- logger = logging.getLogger("test-capture-none")
- with capture_service_logs("test-capture-none", None):
- logger.warning("nothing captured")
- assert not logger.handlers
-
-
def test_capture_service_logs_lowers_level_for_window() -> None:
logger = logging.getLogger("test-capture-level")
logger.setLevel(logging.WARNING)
@@ -72,15 +57,6 @@ def test_capture_service_logs_lowers_level_for_window() -> None:
assert [r["message"] for r in buf.since(0)] == ["info inside window"]
-def test_transport_keys_block_profile_and_service_params() -> None:
- from unshackle.core.api.handlers import LIST_HANDLER_TRANSPORT_KEYS, SESSION_TRANSPORT_KEYS
-
- assert "profile" in SESSION_TRANSPORT_KEYS
- assert "service_params" in SESSION_TRANSPORT_KEYS
- assert "profile" in LIST_HANDLER_TRANSPORT_KEYS
- assert "service_params" in LIST_HANDLER_TRANSPORT_KEYS
-
-
def test_service_params_are_the_only_service_options_when_present() -> None:
import click
@@ -122,15 +98,3 @@ def test_service_params_keyed_by_flag_reach_an_option_with_another_name() -> Non
data = {"service_params": {"zone": "eu", "svc_lang": "de", "lang": "fr"}}
built = instantiate_service(click.Context(click.Command("dl")), module, "t", data, SESSION_TRANSPORT_KEYS)
assert built == {"zone_code": "eu", "svc_lang": "de"}
-
-
-def test_mirror_buffers_exception_cause() -> None:
- buf = SessionLogBuffer()
- mirror = SessionLogMirror(logging.getLogger("test-mirror-exc"), buf)
- try:
- raise ValueError("boom")
- except ValueError:
- mirror.exception("step failed")
- record = buf.since(0)[0]
- assert record["level"] == "ERROR"
- assert record["message"] == "step failed | ValueError: boom"
diff --git a/tests/remote/unit/test_session_plugins.py b/tests/remote/unit/test_session_plugins.py
index 57c83f478..0b0422ff8 100644
--- a/tests/remote/unit/test_session_plugins.py
+++ b/tests/remote/unit/test_session_plugins.py
@@ -71,12 +71,6 @@ def test_the_create_body_lists_each_plugin_with_its_version_and_device_facts(tmp
assert str(tmp_path) not in json.dumps(data["plugins"])
-def test_a_client_with_no_local_device_sends_no_device_facts() -> None:
- data = sent_create(lambda system, quality=None: pytest.fail("a device was loaded"), local_cdm=None)
-
- assert data["plugins"] == {"example": {"version": "1.0"}, "other": {"version": ""}}
-
-
def test_a_plugin_device_that_does_not_load_sends_no_facts(caplog: pytest.LogCaptureFixture) -> None:
def broken(system: str, quality: int | None = None) -> Any:
raise ValueError("EXAMPLE device file is damaged")
@@ -105,12 +99,6 @@ def test_a_malformed_plugin_list_is_refused(plugins: Any) -> None:
assert e.value.error_code == APIErrorCode.INVALID_INPUT
-def test_an_old_client_sends_no_plugin_list() -> None:
- assert handlers.client_plugins(None) is None
- assert handlers.client_plugins({"example": {"version": "1.0"}}) == {"example": {"version": "1.0"}}
- assert handlers.client_plugins({"example": {"device": {"name": None}}}) == {"example": {"device": {"name": None}}}
-
-
def plugin_tracks() -> Tracks:
track = Video(
id_="vid",
@@ -248,11 +236,6 @@ def test_a_client_device_session_gives_the_service_a_stand_in_with_the_client_de
assert cdm_for("playready") is None
-def test_a_fact_the_client_did_not_send_is_none_on_the_stand_in(monkeypatch: pytest.MonkeyPatch) -> None:
- cdm_for = launched_cdm_for(monkeypatch, Licensor.CLIENT_DEVICE, {"example": {"version": "1.0", "device": {}}})
- assert cdm_for("example").device_name is None
-
-
def test_a_client_device_session_with_no_device_facts_gives_no_plugin_device(monkeypatch: pytest.MonkeyPatch) -> None:
cdm_for = launched_cdm_for(monkeypatch, Licensor.CLIENT_DEVICE, {"example": {"version": "1.0"}})
assert cdm_for("example") is None
diff --git a/tests/remote/unit/test_session_reopen.py b/tests/remote/unit/test_session_reopen.py
index f8def07d2..6423a3103 100644
--- a/tests/remote/unit/test_session_reopen.py
+++ b/tests/remote/unit/test_session_reopen.py
@@ -212,17 +212,6 @@ def test_a_session_lost_under_quiet_is_left_to_the_caller(monkeypatch, caplog, r
assert not [r for r in caplog.records if r.levelname == "ERROR"]
-@responses.activate
-def test_closing_a_session_the_server_lost_logs_no_error(caplog):
- service = make_service()
- responses.add(responses.DELETE, f"{SERVER}/api/session/s1", json=GONE, status=404)
-
- service.close()
-
- assert service._session_id is None
- assert not [r for r in caplog.records if r.levelname in ("WARNING", "ERROR")]
-
-
@responses.activate
def test_a_certificate_the_server_fails_to_fetch_is_no_certificate():
service = make_service()
diff --git a/tests/remote/unit/test_session_reporting.py b/tests/remote/unit/test_session_reporting.py
index 1c2daa33a..97de57c80 100644
--- a/tests/remote/unit/test_session_reporting.py
+++ b/tests/remote/unit/test_session_reporting.py
@@ -31,12 +31,6 @@ def make_entry() -> SessionEntry:
return entry
-def test_summary_falls_back_to_the_first_title() -> None:
- summary = make_entry().summary()
- assert summary["title_id"] == "t1"
- assert summary["title"] == "Example Show 2024 S01E01"
-
-
def test_summary_reports_the_title_the_client_asked_for() -> None:
entry = make_entry()
entry.current_title_id = "t3"
@@ -45,12 +39,6 @@ def test_summary_reports_the_title_the_client_asked_for() -> None:
assert summary["title"] == "Example Show 2024 S01E03"
-def test_summary_ignores_a_title_id_that_left_the_map() -> None:
- entry = make_entry()
- entry.current_title_id = "gone"
- assert entry.summary()["title_id"] == "t1"
-
-
def test_unknown_track_resolves_to_the_live_title() -> None:
entry = make_entry()
entry.current_title_id = "t3"
diff --git a/tests/remote/unit/test_session_service_lock.py b/tests/remote/unit/test_session_service_lock.py
deleted file mode 100644
index 220644cf2..000000000
--- a/tests/remote/unit/test_session_service_lock.py
+++ /dev/null
@@ -1,299 +0,0 @@
-"""One remote session owns one service instance, so its handlers must take turns.
-
-``session_titles_handler`` and ``session_tracks_handler`` call the service from a worker
-thread. Both calls reach the same long-lived ``SessionEntry.service_instance``, and services
-keep per-title state on it: HTTP session headers, per-title tokens, cached manifest
-attributes. Two requests on one remote session that run in that instance at the same time
-corrupt each other's state, and the track response then hands the client the wrong headers.
-
-The probe here reports how many service calls are inside the instance at once. Its first
-entrant waits a short window for company, so the test sees a genuinely concurrent run instead
-of racing past it. A slow machine can only make a concurrent run look serialised, so these
-tests cannot flake red.
-"""
-
-from __future__ import annotations
-
-import asyncio
-import contextlib
-import json
-import threading
-from collections.abc import Iterator
-from types import SimpleNamespace
-from typing import Any
-
-import pytest
-
-from unshackle.core.api import handlers
-from unshackle.core.api.session_store import SessionEntry, get_session_store
-from unshackle.core.titles.movie import Movie
-
-pytestmark = pytest.mark.unit
-
-# How long the first service call waits for a second one to join it.
-OVERLAP_WINDOW = 0.5
-
-# Bounds the wait when the loop is blocked, so a regression fails the test instead of hanging.
-HANDSHAKE_TIMEOUT = 5.0
-
-
-class Overlap:
- """Records how many service calls are inside the service instance at once."""
-
- def __init__(self, window: float = OVERLAP_WINDOW) -> None:
- self.window = window
- self.max_active = 0
- self.trace: list[str] = []
- self._lock = threading.Lock()
- self._active = 0
- self._joined = threading.Event()
- self._waited = False
-
- @contextlib.contextmanager
- def call(self, label: str) -> Iterator[None]:
- with self._lock:
- self._active += 1
- self.max_active = max(self.max_active, self._active)
- self.trace.append(f"+{label}")
- if self._active > 1:
- self._joined.set()
- first = not self._waited
- self._waited = True
- # Only the first call pays the window. Serialised handlers then cost one wait, not one
- # per call, and a concurrent second call releases it as soon as it arrives.
- if first:
- self._joined.wait(timeout=self.window)
- try:
- yield
- finally:
- with self._lock:
- self._active -= 1
- self.trace.append(f"-{label}")
-
-
-def a_movie(title_id: str) -> Movie:
- return Movie(id_=title_id, service=object, name=f"Film {title_id}", year=2024, language=None)
-
-
-def empty_tracks() -> Any:
- return SimpleNamespace(videos=[], audio=[], subtitles=[], attachments=[])
-
-
-class ServiceProbe:
- """A service whose calls report their overlap into a shared recorder."""
-
- def __init__(self, overlap: Overlap, name: str = "probe") -> None:
- self.overlap = overlap
- self.name = name
- self.session = SimpleNamespace(headers={}, cookies=[])
-
- def get_titles(self) -> list[Movie]:
- with self.overlap.call(f"{self.name}:titles"):
- return [a_movie("movie-0001"), a_movie("movie-0002")]
-
- def get_tracks(self, title: Any) -> Any:
- with self.overlap.call(f"{self.name}:tracks:{title.id}"):
- return empty_tracks()
-
- def get_chapters(self, title: Any) -> list[Any]:
- with self.overlap.call(f"{self.name}:chapters:{title.id}"):
- return []
-
-
-def seed_titles(session: SessionEntry) -> None:
- """Put both titles in the remote session, as a prior titles call would."""
- for title_id in ("movie-0001", "movie-0002"):
- session.title_map[title_id] = a_movie(title_id)
-
-
-def bodies(responses: list[Any]) -> list[dict]:
- parsed = [json.loads(response.body) for response in responses]
- for body in parsed:
- assert "error" not in body, body
- return parsed
-
-
-async def two_track_calls(session_id: str) -> list[Any]:
- return list(
- await asyncio.gather(
- handlers.session_tracks_handler({"title_id": "movie-0001"}, session_id),
- handlers.session_tracks_handler({"title_id": "movie-0002"}, session_id),
- )
- )
-
-
-@pytest.mark.asyncio
-async def test_two_track_requests_never_share_the_service() -> None:
- overlap = Overlap()
- store = get_session_store()
- session = await store.create("EXAMPLE", ServiceProbe(overlap), session_id="lock-test-tracks")
- session.presence.attached()
- seed_titles(session)
- try:
- responses = await two_track_calls(session.session_id)
- finally:
- await store.delete(session.session_id)
-
- bodies(responses)
- assert overlap.max_active == 1, overlap.trace
-
-
-@pytest.mark.asyncio
-async def test_the_track_lock_covers_the_chapters_call() -> None:
- overlap = Overlap()
- store = get_session_store()
- session = await store.create("EXAMPLE", ServiceProbe(overlap), session_id="lock-test-chapters")
- session.presence.attached()
- seed_titles(session)
- try:
- responses = await two_track_calls(session.session_id)
- finally:
- await store.delete(session.session_id)
-
- bodies(responses)
- # Every call closes before the next one opens, so one title's chapters are read before the
- # other title's tracks are fetched.
- assert len(overlap.trace) == 8, overlap.trace
- for opened, closed in zip(overlap.trace[0::2], overlap.trace[1::2], strict=True):
- assert closed == f"-{opened[1:]}", overlap.trace
-
-
-@pytest.mark.asyncio
-async def test_titles_and_tracks_never_overlap() -> None:
- overlap = Overlap()
- store = get_session_store()
- session = await store.create("EXAMPLE", ServiceProbe(overlap), session_id="lock-test-mixed")
- session.presence.attached()
- seed_titles(session)
- try:
- responses = list(
- await asyncio.gather(
- handlers.session_titles_handler(session.session_id),
- handlers.session_tracks_handler({"title_id": "movie-0001"}, session.session_id),
- )
- )
- finally:
- await store.delete(session.session_id)
-
- bodies(responses)
- assert overlap.max_active == 1, overlap.trace
-
-
-@pytest.mark.asyncio
-async def test_a_second_session_still_runs_in_parallel() -> None:
- overlap = Overlap()
- store = get_session_store()
- first = await store.create("EXAMPLE", ServiceProbe(overlap, "a"), session_id="lock-test-parallel-a")
- first.presence.attached()
- second = await store.create("EXAMPLE", ServiceProbe(overlap, "b"), session_id="lock-test-parallel-b")
- second.presence.attached()
- try:
- responses = list(
- await asyncio.gather(
- handlers.session_titles_handler(first.session_id),
- handlers.session_titles_handler(second.session_id),
- )
- )
- finally:
- await store.delete(first.session_id)
- await store.delete(second.session_id)
-
- bodies(responses)
- assert first.lock is not second.lock
- assert overlap.max_active == 2, overlap.trace
-
-
-class BlockingTracks:
- """Holds ``get_tracks`` open until the event loop releases it."""
-
- def __init__(self) -> None:
- self.entered = threading.Event()
- self.resume = threading.Event()
- self.loop_was_blocked = False
- self.session = SimpleNamespace(headers={}, cookies=[])
-
- def get_tracks(self, title: Any) -> Any:
- self.entered.set()
- self.loop_was_blocked = not self.resume.wait(timeout=HANDSHAKE_TIMEOUT)
- return empty_tracks()
-
- def get_chapters(self, title: Any) -> list[Any]:
- return []
-
-
-@pytest.mark.asyncio
-async def test_the_loop_stays_free_while_the_lock_is_held() -> None:
- service = BlockingTracks()
- store = get_session_store()
- session = await store.create("EXAMPLE", service, session_id="lock-test-loop")
- session.presence.attached()
- seed_titles(session)
- try:
- task = asyncio.create_task(handlers.session_tracks_handler({"title_id": "movie-0001"}, session.session_id))
- try:
- # Reached only while the loop is free, which is what the lock placement buys.
- await asyncio.to_thread(service.entered.wait, HANDSHAKE_TIMEOUT)
- held = session.lock.locked()
- finally:
- service.resume.set()
- response = await asyncio.wait_for(task, HANDSHAKE_TIMEOUT)
- finally:
- await store.delete(session.session_id)
-
- bodies([response])
- assert not service.loop_was_blocked, "get_tracks blocked the event loop"
- assert held, "the session lock was not held around the threaded service call"
-
-
-@pytest.mark.asyncio
-async def test_each_session_entry_gets_its_own_lock() -> None:
- store = get_session_store()
- first = await store.create("EXAMPLE", object(), session_id="lock-test-field-a")
- second = await store.create("EXAMPLE", object(), session_id="lock-test-field-b")
- try:
- assert isinstance(first.lock, asyncio.Lock)
- assert isinstance(second.lock, asyncio.Lock)
- assert first.lock is not second.lock
- finally:
- await store.delete(first.session_id)
- await store.delete(second.session_id)
-
-
-class LookupTrack:
- """A track whose URL costs a service request, as one sent with ``resolve_url``."""
-
- def __init__(self, track_id: str, overlap: Overlap) -> None:
- self.id = track_id
- self.url: str | None = None
- self.descriptor = SimpleNamespace(name="URL")
- self.drm = None
- self.data: dict = {}
- self.overlap = overlap
-
- def ensure_url(self) -> None:
- with self.overlap.call(f"url:{self.id}"):
- self.url = f"https://cdn.example.com/{self.id}.mp4"
-
-
-@pytest.mark.asyncio
-async def test_two_segment_requests_never_share_the_service() -> None:
- """The client asks the segments route for each lookup track's URL in parallel."""
- overlap = Overlap()
- store = get_session_store()
- session = await store.create("EXAMPLE", ServiceProbe(overlap), session_id="lock-test-segments")
- session.presence.attached()
- session.authenticated = True
- session.tracks = {tid: LookupTrack(tid, overlap) for tid in ("v-1", "a-1")}
- try:
- responses = list(
- await asyncio.gather(
- handlers.session_segments_handler({"track_ids": ["v-1"]}, session.session_id),
- handlers.session_segments_handler({"track_ids": ["a-1"]}, session.session_id),
- )
- )
- finally:
- await store.delete(session.session_id)
-
- urls = [body["tracks"][tid]["url"] for body, tid in zip(bodies(responses), ("v-1", "a-1"), strict=True)]
- assert urls == ["https://cdn.example.com/v-1.mp4", "https://cdn.example.com/a-1.mp4"]
- assert overlap.max_active == 1, overlap.trace
diff --git a/tests/remote/unit/test_session_store.py b/tests/remote/unit/test_session_store.py
index 6d5cf3b69..69d938720 100644
--- a/tests/remote/unit/test_session_store.py
+++ b/tests/remote/unit/test_session_store.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import asyncio
import threading
import time
from datetime import UTC, datetime, timedelta
@@ -12,7 +11,7 @@ import pytest
from unshackle.core.api import session_store as session_store_module
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
-from unshackle.core.api.session_store import SessionEntry, SessionStore, get_session_store
+from unshackle.core.api.session_store import SessionEntry, SessionStore
from unshackle.core.remote_protocol import AuthStatus
pytestmark = pytest.mark.unit
@@ -30,34 +29,6 @@ def store() -> SessionStore:
return SessionStore()
-async def test_create_returns_entry_with_uuid(store: SessionStore) -> None:
- entry = await store.create("EXAMPLE", _FakeService())
- assert isinstance(entry, SessionEntry)
- assert entry.service_tag == "EXAMPLE"
- assert entry.session_id and len(entry.session_id) >= 32
- assert store.session_count == 1
-
-
-async def test_create_with_explicit_session_id(store: SessionStore) -> None:
- entry = await store.create("DEMO", _FakeService(), session_id="fixed-id")
- assert entry.session_id == "fixed-id"
-
-
-async def test_get_returns_none_for_missing(store: SessionStore) -> None:
- assert await store.get("nope") is None
-
-
-async def test_get_touches_last_accessed(store: SessionStore) -> None:
- entry = await store.create("DEMO", _FakeService())
- before = entry.last_accessed
- entry.idle_since -= 100
- await asyncio.sleep(0.01)
- fetched = await store.get(entry.session_id)
- assert fetched is entry
- assert fetched.last_accessed > before
- assert fetched.idle_seconds < 100
-
-
async def test_delete_removes_and_cancels_bridge(store: SessionStore) -> None:
entry = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge())
@@ -70,10 +41,6 @@ async def test_delete_removes_and_cancels_bridge(store: SessionStore) -> None:
assert store.session_count == 0
-async def test_delete_returns_false_when_missing(store: SessionStore) -> None:
- assert await store.delete("missing") is False
-
-
@pytest.mark.parametrize("via", ["get", "sweep"])
@pytest.mark.parametrize(
("ttl", "status", "idle", "expires"),
@@ -157,77 +124,6 @@ async def test_close_ends_every_session_and_removes_its_cache_dir(
assert published == []
-async def test_close_waits_for_a_login_and_stops_the_sweep(store: SessionStore) -> None:
- login = asyncio.create_task(asyncio.sleep(0.05))
- store.track_login(login)
- await store.start_cleanup_loop()
- sweep = store._cleanup_task
-
- await store.close()
- assert login.done()
- assert store._logins == set()
- assert sweep is not None and sweep.cancelled()
-
-
-async def test_close_gives_up_on_a_login_that_does_not_end(
- store: SessionStore, monkeypatch: pytest.MonkeyPatch
-) -> None:
- monkeypatch.setattr(session_store_module, "LOGIN_WAIT", 0.01)
- login = asyncio.create_task(asyncio.Event().wait())
- store.track_login(login)
- await store.start_cleanup_loop()
-
- await asyncio.wait_for(store.close(), 5)
- assert not login.done()
- assert store._cleanup_task is None
- login.cancel()
-
-
-async def test_get_session_store_returns_singleton() -> None:
- a = get_session_store()
- b = get_session_store()
- assert a is b
-
-
-async def test_max_sessions_evicts_oldest(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(type(store), "max_sessions", property(lambda _: 2))
-
- await store.create("A", _FakeService(), session_id="a")
- await asyncio.sleep(0.01)
- b = await store.create("B", _FakeService(), session_id="b")
- await asyncio.sleep(0.01)
- c = await store.create("C", _FakeService(), session_id="c")
-
- assert store.session_count == 2
- assert await store.get("a") is None # evicted
- assert (await store.get("b")) is b
- assert (await store.get("c")) is c
-
-
-async def test_max_sessions_evicts_the_oldest_session_of_the_key_that_holds_the_most(
- store: SessionStore, monkeypatch: pytest.MonkeyPatch
-) -> None:
- monkeypatch.setattr(type(store), "max_sessions", property(lambda _: 3))
- await store.create("EXAMPLE", _FakeService(), session_id="a-1", owner_key="KEY-A")
- for n in (1, 2, 3):
- await asyncio.sleep(0.01)
- await store.create("EXAMPLE", _FakeService(), session_id=f"b-{n}", owner_key="KEY-B")
-
- assert set(store._sessions) == {"a-1", "b-2", "b-3"}
-
-
-async def test_max_sessions_evicts_a_session_with_work_in_progress_last(
- store: SessionStore, monkeypatch: pytest.MonkeyPatch
-) -> None:
- monkeypatch.setattr(type(store), "max_sessions", property(lambda _: 2))
- busy = await store.create("EXAMPLE", _FakeService(), session_id="busy")
- async with busy.lock:
- await asyncio.sleep(0.01)
- await store.create("EXAMPLE", _FakeService(), session_id="idle")
- await store.create("EXAMPLE", _FakeService(), session_id="new")
- assert set(store._sessions) == {"busy", "new"}
-
-
async def test_get_expiry_removes_cache_dir(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
removed: list = []
monkeypatch.setattr(SessionStore, "cleanup_cache_dir", staticmethod(removed.append))
@@ -238,121 +134,6 @@ async def test_get_expiry_removes_cache_dir(store: SessionStore, monkeypatch: py
assert removed == ["_sessions/k/s/EXAMPLE"]
-async def test_session_end_applies_staged_service_reload(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
- """A staged reload swaps in as soon as the last session on that tag ends, not on the next refresh tick."""
- from unshackle.core import services
- from unshackle.core.api import download_manager
-
- applied: list[set[str]] = []
-
- def fake_apply(busy: set[str]) -> list[str]:
- applied.append(busy)
- return sorted(services.PENDING - busy)
-
- monkeypatch.setattr(services, "PENDING", {"EXAMPLE"})
- monkeypatch.setattr(services, "apply_pending", fake_apply)
- monkeypatch.setattr(download_manager, "publish_service_event", lambda *a, **k: None)
-
- entry = await store.create("EXAMPLE", _FakeService())
- assert await store.delete(entry.session_id)
- await asyncio.sleep(0.05)
- assert applied == [set()]
-
-
-def _stage_reload(monkeypatch: pytest.MonkeyPatch, pending: set[str], delay: float = 0.0) -> list[set[str]]:
- """Stage ``pending`` for reload and record every apply_pending call; returns the call log."""
- from unshackle.core import services
- from unshackle.core.api import download_manager
-
- applied: list[set[str]] = []
-
- def fake_apply(busy: set[str]) -> list[str]:
- if delay:
- time.sleep(delay)
- applied.append(busy)
- return sorted(services.PENDING - busy)
-
- monkeypatch.setattr(services, "PENDING", pending)
- monkeypatch.setattr(services, "apply_pending", fake_apply)
- monkeypatch.setattr(download_manager, "publish_service_event", lambda *a, **k: None)
- monkeypatch.setattr(download_manager, "_reload_task", None)
- return applied
-
-
-async def test_session_end_on_unstaged_tag_skips_reload(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
- applied = _stage_reload(monkeypatch, {"OTHER"})
-
- entry = await store.create("EXAMPLE", _FakeService())
- assert await store.delete(entry.session_id)
- await asyncio.sleep(0.05)
- assert applied == []
-
-
-async def test_concurrent_session_ends_reload_once(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
- """Session ends that overlap an in-flight reload share it instead of each re-importing the tag."""
- applied = _stage_reload(monkeypatch, {"EXAMPLE"}, delay=0.05)
-
- ids = [(await store.create("EXAMPLE", _FakeService())).session_id for _ in range(10)]
- await asyncio.gather(*(store.delete(sid) for sid in ids))
- await asyncio.sleep(0.3)
- assert len(applied) == 1
-
-
-async def test_eviction_applies_staged_service_reload(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
- applied = _stage_reload(monkeypatch, {"EXAMPLE"})
- monkeypatch.setattr(type(store), "max_sessions", property(lambda _: 1))
-
- await store.create("EXAMPLE", _FakeService(), session_id="a")
- await store.create("OTHER", _FakeService(), session_id="b")
- await asyncio.sleep(0.05)
- assert len(applied) == 1
-
-
-async def test_inline_expiry_applies_staged_service_reload(
- store: SessionStore, monkeypatch: pytest.MonkeyPatch
-) -> None:
- applied = _stage_reload(monkeypatch, {"EXAMPLE"})
-
- entry = await store.create("EXAMPLE", _FakeService())
- entry.idle_since = time.monotonic() - store.ttl - 100
- assert await store.get(entry.session_id) is None
- await asyncio.sleep(0.05)
- assert applied == [set()]
-
-
-async def test_cleanup_expired_applies_staged_service_reload_once(
- store: SessionStore, monkeypatch: pytest.MonkeyPatch
-) -> None:
- """A cleanup sweep that drops several sessions on one tag schedules one reload for that tag."""
- applied = _stage_reload(monkeypatch, {"EXAMPLE"})
- stale = time.monotonic() - store.ttl - 100
- for sid in ("a", "b"):
- (await store.create("EXAMPLE", _FakeService(), session_id=sid)).idle_since = stale
-
- assert await store.cleanup_expired() == 2
- await asyncio.sleep(0.05)
- assert applied == [set()]
-
-
-async def test_live_session_on_same_tag_keeps_it_busy(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
- """Ending one of two sessions on a staged tag reports the tag busy; ending the last one frees it."""
- from unshackle.core.api import download_manager
-
- applied = _stage_reload(monkeypatch, {"EXAMPLE"})
- monkeypatch.setattr(session_store_module, "session_store", store)
- monkeypatch.setattr(download_manager, "download_manager", None)
-
- first = await store.create("EXAMPLE", _FakeService())
- second = await store.create("EXAMPLE", _FakeService())
- assert await store.delete(first.session_id)
- await asyncio.sleep(0.05)
- assert applied == [{"EXAMPLE"}]
-
- assert await store.delete(second.session_id)
- await asyncio.sleep(0.05)
- assert applied == [{"EXAMPLE"}, set()]
-
-
def test_the_login_state_is_the_one_its_bridge_holds(monkeypatch: pytest.MonkeyPatch) -> None:
"""A waiting prompt keeps the session authenticating; the bridge alone moves it to authenticated or failed."""
entry = SessionEntry("s", "EXAMPLE", None, input_bridge=InputBridge())
diff --git a/tests/remote/unit/test_track_manifest_fragments.py b/tests/remote/unit/test_track_manifest_fragments.py
index 0bc2621c4..e0f1e6411 100644
--- a/tests/remote/unit/test_track_manifest_fragments.py
+++ b/tests/remote/unit/test_track_manifest_fragments.py
@@ -71,41 +71,6 @@ def test_detached_adaptation_set_round_trips() -> None:
assert client_track.descriptor == Subtitle.Descriptor.DASH
-def test_single_track_manifest_round_trips_by_id() -> None:
- """A manifest that holds only its own track ships as a fragment, so the client needs no attribute match."""
- manifest = etree.fromstring(MPD.encode())
- period = manifest.find("Period")
- adaptation_set = period.find("AdaptationSet")
- track = Subtitle(
- id_="abc123",
- url="https://cdn.example/manifest.mpd",
- codec=Subtitle.Codec.WebVTT,
- language=Language.get("en"),
- sdh=True,
- descriptor=Subtitle.Descriptor.DASH,
- data={
- "dash": {
- "manifest": manifest,
- "period": period,
- "adaptation_set": adaptation_set,
- "representation": adaptation_set.find("Representation"),
- }
- },
- )
- client_track = Subtitle(
- id_="abc123",
- url=track.url,
- codec=Subtitle.Codec.WebVTT,
- language=Language.get("en"),
- sdh=True,
- descriptor=Subtitle.Descriptor.URL,
- )
- restore(Tracks([client_track]), capture(Tracks([track])))
-
- assert client_track.descriptor == Subtitle.Descriptor.DASH
- assert client_track.data["dash"]["representation_id"] == "sub-0"
-
-
def test_in_tree_adaptation_set_is_not_shipped() -> None:
manifest = etree.fromstring(MPD.encode())
period = manifest.find("Period")
diff --git a/tests/remote/unit/test_tunnel.py b/tests/remote/unit/test_tunnel.py
index 2e9232731..a12602f2d 100644
--- a/tests/remote/unit/test_tunnel.py
+++ b/tests/remote/unit/test_tunnel.py
@@ -222,11 +222,6 @@ def test_a_dial_that_reaches_the_client_itself_is_refused(monkeypatch: pytest.Mo
assert writer.closed
-def test_localhost_is_refused() -> None:
- with pytest.raises(PermissionError):
- asyncio.run(connect_public("localhost", 443))
-
-
@pytest.mark.parametrize(
("host", "address"),
[
@@ -318,22 +313,6 @@ def test_the_check_route_is_only_for_the_tunnel_owner(server: str) -> None:
client.stop()
-@pytest.mark.parametrize(
- ("uri", "line"),
- [
- ("socks5://127.0.0.1:1080", "Using a local proxy on port 1080"),
- ("http://localhost:8888", "Using a local proxy on port 8888"),
- ("http://1.2.3.4:8080", "Using explicit Proxy: http://1.2.3.4:8080"),
- ("http://localhost", "Using a local proxy"),
- ("http://127.0.0.1:99999", "Using a local proxy"),
- ],
-)
-def test_a_local_proxy_logs_only_its_port(uri: str, line: str) -> None:
- from unshackle.core.proxies.resolve import describe_explicit_proxy
-
- assert describe_explicit_proxy(uri) == line
-
-
def test_another_api_key_cannot_reattach_to_a_tunnel(server: str) -> None:
client = TunnelClient(server, {"X-Secret-Key": "alice"})
tunnel_id = client.start()
@@ -356,32 +335,6 @@ def test_a_request_that_is_not_a_websocket_opens_no_tunnel(server: str) -> None:
assert len(TUNNELS) == before
-def test_a_malformed_frame_still_leaves_the_tunnel_to_expire(server: str) -> None:
- async def send_short_frame() -> str:
- async with aiohttp.ClientSession(headers={"X-Secret-Key": "mallory"}) as http:
- async with http.ws_connect(server + ROUTE) as ws:
- tunnel_id = (await ws.receive_json())["id"]
- await ws.send_bytes(b"\x01")
- await ws.close(code=aiohttp.WSCloseCode.GOING_AWAY)
- return str(tunnel_id)
-
- tunnel_id = asyncio.run(send_short_frame())
- deadline = time.monotonic() + 5
- while TUNNELS[tunnel_id].expiry is None and time.monotonic() < deadline:
- time.sleep(0.05)
- assert TUNNELS[tunnel_id].expiry is not None
-
-
-def test_an_api_key_has_a_tunnel_limit(server: str) -> None:
- clients = [TunnelClient(server, {"X-Secret-Key": "bob"}) for _ in range(tunnel.MAX_TUNNELS)]
- for client in clients:
- client.start()
- with pytest.raises(ConnectionError, match="429, the API key already has the maximum number of tunnels open"):
- TunnelClient(server, {"X-Secret-Key": "bob"}).start()
- for client in clients:
- client.stop()
-
-
@pytest.mark.parametrize("shared", [True, False])
def test_a_shared_api_key_counts_tunnels_for_each_client(
server: str, monkeypatch: pytest.MonkeyPatch, shared: bool
@@ -421,53 +374,6 @@ def test_another_client_of_a_shared_api_key_cannot_reattach(server: str, monkeyp
owner.stop()
-def test_stopping_one_client_leaves_the_other_tunnels_of_its_api_key_open(
- server: str, target: int, monkeypatch: pytest.MonkeyPatch
-) -> None:
- monkeypatch.setattr(tunnel, "is_public_ip", lambda address: True)
- monkeypatch.setattr(tunnel, "dialled_itself", lambda writer: False)
- clients = [TunnelClient(server, {"X-Secret-Key": "erin"}) for _ in range(3)]
- stopped, *running = [client.start() for client in clients]
- try:
- clients[0].stop()
- assert wait_until(lambda: stopped not in TUNNELS, 5)
- for tunnel_id in running:
- proxy = tunnel_proxy(tunnel_id, "erin")
- assert proxy
- resp = requests.get(f"http://127.0.0.1:{target}/", proxies={"all": proxy}, timeout=10)
- assert resp.text == "hello through the tunnel"
- finally:
- for client in clients[1:]:
- client.stop()
-
-
-@pytest.mark.parametrize(
- ("value", "seconds"),
- [
- ("5", 5),
- ("0", 1),
- (None, None),
- ("", None),
- ("\u00b2", None),
- ("9" * 5000, None),
- ("Wed, 21 Oct 2026 07:28:00 GMT", None),
- ],
- ids=["seconds", "zero", "absent", "empty", "superscript", "huge", "http-date"],
-)
-def test_parse_retry_after(value: str | None, seconds: int | None) -> None:
- assert tunnel.parse_retry_after(value) == seconds
-
-
-def test_a_client_that_exits_frees_its_tunnel_at_once(server: str) -> None:
- async def open_then_leave() -> str:
- async with aiohttp.ClientSession(headers={"X-Secret-Key": "dave"}) as http:
- async with http.ws_connect(server + ROUTE) as ws:
- return str((await ws.receive_json())["id"])
-
- tunnel_id = asyncio.run(open_then_leave())
- assert wait_until(lambda: tunnel_id not in TUNNELS, 5)
-
-
@pytest.mark.parametrize(
("status", "headers", "reason"),
[
@@ -530,19 +436,6 @@ def test_a_server_error_after_the_tunnel_closed_names_the_tunnel() -> None:
assert e.value.kind == "TUNNEL_CLOSED"
-def spy_links(monkeypatch: pytest.MonkeyPatch) -> list:
- """Record every Link the client makes, so a test can look at its open streams."""
- links: list = []
-
- class SpyLink(tunnel.Link):
- def __init__(self, ws: object) -> None:
- super().__init__(ws)
- links.append(self)
-
- monkeypatch.setattr(tunnel, "Link", SpyLink)
- return links
-
-
def wait_until(check: Callable[[], bool], seconds: float = 3) -> bool:
deadline = time.monotonic() + seconds
while not check() and time.monotonic() < deadline:
@@ -550,73 +443,6 @@ def wait_until(check: Callable[[], bool], seconds: float = 3) -> bool:
return check()
-def test_a_dial_the_server_gave_up_on_is_dropped_by_the_client(
- server: str, target: int, monkeypatch: pytest.MonkeyPatch
-) -> None:
- """When the server times out an OPEN, the client must not keep the connection it makes later."""
- monkeypatch.setattr(tunnel, "is_public_ip", lambda address: True)
- monkeypatch.setattr(tunnel, "dialled_itself", lambda writer: False)
- monkeypatch.setattr(tunnel, "OPEN_TIMEOUT", 0.3)
- real_connect = tunnel.connect_public
-
- async def slow_connect(host: str, port: int) -> tuple:
- await asyncio.sleep(1)
- return await real_connect(host, port)
-
- monkeypatch.setattr(tunnel, "connect_public", slow_connect)
- links = spy_links(monkeypatch)
- client = TunnelClient(server, {"X-Secret-Key": "alice"})
- proxy = tunnel_proxy(client.start(), "alice")
- with pytest.raises(requests.exceptions.ConnectionError):
- requests.get(f"http://127.0.0.1:{target}/", proxies={"all": proxy}, timeout=10)
- assert wait_until(lambda: not links[-1].streams and not client.relays)
- client.stop()
-
-
-def socks5_connect(proxy: str, host: bytes) -> int:
- """Send one SOCKS5 CONNECT for ``host`` with the credentials in ``proxy`` and return the reply code."""
- from urllib.parse import urlsplit
-
- parts = urlsplit(proxy)
- user, password = (parts.username or "").encode(), (parts.password or "").encode()
- with socket.create_connection(("127.0.0.1", parts.port or 0), timeout=10) as sock:
- sock.sendall(b"\x05\x01\x02")
- assert sock.recv(2) == b"\x05\x02"
- sock.sendall(b"\x01" + bytes([len(user)]) + user + bytes([len(password)]) + password)
- assert sock.recv(2) == b"\x01\x00"
- sock.sendall(b"\x05\x01\x00\x03" + bytes([len(host)]) + host + (443).to_bytes(2, "big"))
- return sock.recv(10)[1]
-
-
-def test_a_hostname_the_resolver_rejects_closes_its_stream(server: str, monkeypatch: pytest.MonkeyPatch) -> None:
- async def resolve(self: object, host: str, port: int, **_: object) -> list:
- host.encode("idna") # as socket.getaddrinfo does, so a long label raises UnicodeError
- return []
-
- monkeypatch.setattr(asyncio.BaseEventLoop, "getaddrinfo", resolve)
- monkeypatch.setattr(tunnel, "OPEN_TIMEOUT", 1)
- links = spy_links(monkeypatch)
- client = TunnelClient(server, {"X-Secret-Key": "alice"})
- proxy = tunnel_proxy(client.start(), "alice")
- assert proxy
- assert socks5_connect(proxy, b"a" * 64 + b".example") == 5
- assert wait_until(lambda: not links[-1].streams)
- client.stop()
-
-
-def test_a_failed_start_leaves_no_thread_behind() -> None:
- silent = socket.socket()
- silent.bind(("127.0.0.1", 0))
- silent.listen()
- try:
- client = TunnelClient(f"http://127.0.0.1:{silent.getsockname()[1]}", {"X-Secret-Key": "alice"})
- with pytest.raises(ConnectionError, match="timed out"):
- client.start(timeout=0.5)
- assert not client.thread.is_alive()
- finally:
- silent.close()
-
-
class ExitProxy(socketserver.BaseRequestHandler):
"""An exit proxy on this machine: takes one HTTP CONNECT or SOCKS5 CONNECT and pipes it to the test target."""
diff --git a/tests/remote/unit/test_worker_speed_limit.py b/tests/remote/unit/test_worker_speed_limit.py
index 0b4103251..7c7397289 100644
--- a/tests/remote/unit/test_worker_speed_limit.py
+++ b/tests/remote/unit/test_worker_speed_limit.py
@@ -8,7 +8,7 @@ import click
import pytest
import unshackle.commands.dl as dl_module
-from unshackle.core.api import download_manager, download_worker, handlers
+from unshackle.core.api import download_manager, handlers
from unshackle.core.api.download_manager import DownloadQueueManager
from unshackle.core.config import config
from unshackle.core.services import Services
@@ -46,26 +46,6 @@ def test_run_download_async_sends_share_in_payload(monkeypatch, tmp_path):
assert seen["payload"]["speed_limit"] == 2_000_000.0
-@pytest.mark.parametrize("limit", [500_000, None])
-def test_worker_main_passes_payload_limit_to_the_download(monkeypatch, tmp_path, limit):
- seen = {}
-
- def fake_perform(*args, **kwargs):
- seen.update(kwargs)
- return []
-
- monkeypatch.setattr(download_worker, "perform_download", fake_perform)
- monkeypatch.setattr(download_worker, "relay_prompts", lambda progress: None)
- payload = tmp_path / "payload.json"
- payload.write_text(
- json.dumps({"job_id": "j1", "service": "SVC", "title_id": "t", "parameters": {}, "speed_limit": limit}),
- encoding="utf-8",
- )
- assert download_worker.main(["w", str(payload), str(tmp_path / "result.json")]) == 0
- assert seen["speed_limit"] == limit
- assert requests_downloader.speed_limiter is None
-
-
@pytest.mark.parametrize("share", [500_000.0, None])
@pytest.mark.parametrize("params", [{}, {"speed_limit": "1M"}])
def test_perform_download_gives_dl_result_the_job_share(monkeypatch, tmp_path, share, params):
diff --git a/tests/test_client_session_auth.py b/tests/test_client_session_auth.py
index 603bd0474..e23bd3149 100644
--- a/tests/test_client_session_auth.py
+++ b/tests/test_client_session_auth.py
@@ -3,7 +3,7 @@ from types import SimpleNamespace
import pytest
import requests
-from tests.remote.sessions import hold_session, session_entry, stub_service_build
+from tests.remote.sessions import hold_session, session_entry
from unshackle.core.api import server_keys
from unshackle.core.api.errors import APIError
from unshackle.core.api.handlers import client_session_auth, resolve_handler_proxy, scrub_track_data
@@ -190,13 +190,6 @@ def test_remote_get_tracks_scopes_server_cookies():
assert service.session.cookies.get("sid", domain=".example.com") == "secret"
-def test_server_login_strips_auth():
- headers, cookies = client_session_auth(_session(False))
- assert headers == {"User-Agent": "ua"}
- assert cookies == []
- assert scrub_track_data({"token": "t", "hls": {}}, _session(False)) == {"hls": {}}
-
-
def test_server_account_rejects_client_proxy_uri(monkeypatch):
monkeypatch.setattr("unshackle.core.api.handlers.server_account_for", lambda request, service: True)
with pytest.raises(APIError):
@@ -293,15 +286,6 @@ def test_server_login_strips_nested_and_unlisted_secrets():
assert scrub_track_data(data, _session(False)) == {"license": {"url": "u"}, "items": [{"id": 1}]}
-def test_track_own_pssh_passes_without_kids(monkeypatch):
-
- monkeypatch.setattr(server_keys, "track_pssh", lambda track, drm_type: "OWN")
- monkeypatch.setattr(server_keys, "pssh_kids", lambda pssh, drm_type: set())
- server_keys.require_track_pssh(SimpleNamespace(id="t", drm=[]), "OWN", "widevine")
- with pytest.raises(APIError):
- server_keys.require_track_pssh(SimpleNamespace(id="t", drm=[]), "OTHER", "widevine")
-
-
def test_download_rejects_path_profile_and_bad_output_dir(tmp_path, monkeypatch):
from tests.admission import refusal
from unshackle.core.api.handlers import config
@@ -310,143 +294,3 @@ def test_download_rejects_path_profile_and_bad_output_dir(tmp_path, monkeypatch)
assert refusal({"profile": "../x"})
assert refusal({"profile": "ok"}) is None
assert refusal({"output_dir": "a\x00b"})
-
-
-def test_safe_inflate_rejects_non_str_via_isinstance():
- # A non-string cache value must be caught before base64.b64decode raises a 500.
- # Mirror the guard used in session_create_handler.
- from unshackle.core.api.errors import APIError
- from unshackle.core.remote_protocol import APIErrorCode
-
- def guard(content):
- if not isinstance(content, str):
- raise APIError(APIErrorCode.INVALID_INPUT, "cache values must be base64 strings")
-
- guard("ok") # no raise
- for bad in (1, {"a": 1}, ["x"], None):
- with pytest.raises(APIError):
- guard(bad)
-
-
-def _run_session(monkeypatch, tmp_path, data, answer, server_account=False, fail=False):
- """Run session_create_handler with a service that prompts during login; return the settled remote session."""
- import asyncio
- import base64
- import json
- import uuid
- import zlib
-
- from unshackle.core.api import handlers
- from unshackle.core.api.session_store import get_session_store
- from unshackle.core.config import config
- from unshackle.core.remote_protocol import AuthStatus
-
- class PromptingService:
- _input_bridge = None
- log = None
- cache = None
-
- def authenticate(self, cookies, credential):
- if answer is not None:
- self._input_bridge.request_input("Enter code")
- if fail:
- raise ValueError("bad code")
-
- monkeypatch.setattr(config.directories, "cache", tmp_path)
- monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: service)
- monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
- monkeypatch.setattr(handlers, "server_account_for", lambda *args: server_account)
- monkeypatch.setattr(handlers, "next_server_profile", lambda *args: None)
- monkeypatch.setattr(handlers.Services, "load", lambda service: PromptingService)
- stub_service_build(monkeypatch, PromptingService)
- if data.get("cache") == "tokens":
- data["cache"] = {"tokens_default": base64.b64encode(zlib.compress(b"{}")).decode("ascii")}
-
- async def run():
- body = {"service": "EXAMPLE", "title_id": "t", "session_id": str(uuid.uuid4()), **data}
- resp = await handlers.session_create_handler(body)
- session = get_session_store().peek(json.loads(resp.body)["session_id"])
- for _ in range(200):
- if answer is not None:
- for ask in session.input_bridge.claim_for_channel():
- session.input_bridge.answer(ask.id, answer)
- if session.auth_status in (AuthStatus.AUTHENTICATED, AuthStatus.FAILED):
- break
- await asyncio.sleep(0.01)
- await get_session_store().delete(session.session_id)
- return session
-
- return asyncio.run(run())
-
-
-@pytest.mark.parametrize(
- "data, answer, server_account, fail, expected",
- [
- ({}, None, False, False, True), # no prompt: a pair code shown in the log, approved on another device
- ({}, "CODE", False, False, True), # device code the client approved
- ({}, "CODE", False, True, False), # answered, but the login failed
- ({}, "CODE", True, False, False), # server account OTP answered by the client
- ({"cache": "tokens"}, None, False, False, True), # client uploaded its own earlier login
- ({}, None, True, False, False), # server account
- ],
-)
-def test_client_auth_follows_login_provenance(monkeypatch, tmp_path, data, answer, server_account, fail, expected):
- session = _run_session(monkeypatch, tmp_path, dict(data), answer, server_account, fail)
- assert session.client_auth is expected
-
-
-def test_a_failed_login_reports_its_error(monkeypatch, tmp_path):
- from unshackle.core.remote_protocol import AuthStatus
-
- session = _run_session(monkeypatch, tmp_path, {}, "CODE", fail=True)
- assert (session.auth_status, session.auth_error) == (AuthStatus.FAILED, "bad code")
-
-
-def test_login_that_outlives_its_session_leaves_no_cache(monkeypatch, tmp_path):
- """A login loop that finishes after DELETE must not leave its tokens on the server's disk."""
- import asyncio
- import json
- import threading
- import uuid
-
- from unshackle.core.api import handlers
- from unshackle.core.api.session_store import get_session_store
- from unshackle.core.config import config
-
- paired = threading.Event()
- finished = threading.Event()
-
- class SlowPairingService:
- _input_bridge = None
- log = None
- cache = None
-
- def authenticate(self, cookies, credential):
- paired.wait(5)
- self.cache.get("tokens").set("token")
- finished.set()
-
- monkeypatch.setattr(config.directories, "cache", tmp_path)
- monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: service)
- monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
- monkeypatch.setattr(handlers, "server_account_for", lambda *args: False)
- monkeypatch.setattr(handlers.Services, "load", lambda service: SlowPairingService)
- stub_service_build(monkeypatch, SlowPairingService)
-
- async def run():
- resp = await handlers.session_create_handler(
- {"service": "EXAMPLE", "title_id": "t", "session_id": str(uuid.uuid4())}
- )
- session = get_session_store().peek(json.loads(resp.body)["session_id"])
- await get_session_store().delete(session.session_id)
- paired.set()
- for _ in range(200):
- if finished.is_set() and session.auth_status.value == "authenticated":
- break
- await asyncio.sleep(0.01)
- await asyncio.sleep(0.05)
- return session
-
- session = asyncio.run(run())
- assert session.auth_status.value == "authenticated"
- assert not (tmp_path / session.cache_tag).exists()
diff --git a/tests/test_downloader_leaks.py b/tests/test_downloader_leaks.py
index b7e4f8e39..16510defa 100644
--- a/tests/test_downloader_leaks.py
+++ b/tests/test_downloader_leaks.py
@@ -24,6 +24,8 @@ import urllib3
from unshackle.core.constants import DOWNLOAD_CANCELLED, DownloadCancelled
from unshackle.core.downloaders.requests import requests as download_batch
+pytestmark = pytest.mark.slow
+
dl_mod = importlib.import_module("unshackle.core.downloaders.requests")
SEG_SIZE = 256 * 1024
diff --git a/tests/test_post_scripts.py b/tests/test_post_scripts.py
index 282c619d1..62b01fdb1 100644
--- a/tests/test_post_scripts.py
+++ b/tests/test_post_scripts.py
@@ -2,8 +2,6 @@
from __future__ import annotations
-import re
-import sys
from pathlib import Path
from types import SimpleNamespace
@@ -40,11 +38,6 @@ def test_metacharacters_in_a_value_stay_one_argument():
assert argv == ["upload.py", "/downloads/Bob's Burgers S01E01.mkv", '--title=Bob"; rm -rf ~']
-def test_empty_variable_substitutes_empty():
- argv = build("upload.py {filepath} --tmdb={tmdb}", {"filepath": "/x.mkv", "tmdb": ""})
- assert argv == ["upload.py", "/x.mkv", "--tmdb="]
-
-
def test_sidecars_join_as_a_single_token():
subs = [Path("/dl/Show S01E01.en.srt"), Path("/dl/Show S01E01.fr.srt")]
argv = build("upload.py --subs={sidecars}", {"sidecars": SIDECAR_SEPARATOR.join(map(str, subs))})
@@ -175,57 +168,10 @@ def test_typoed_event_or_mode_warns_instead_of_silently_dropping(monkeypatch, ca
assert caplog.text.count("unknown event/mode") == 1 # warned once, not per dispatch
-def test_tagging_ids_are_read_at_dispatch_not_snapshotted():
- """A series' TMDB ID is resolved inside the title loop, after any pre-loop snapshot.
-
- Guards a regression where ``post_script_ids`` was a dict built before the loop, so
- ``{tmdb}`` was empty for every download that did not pass ``--tmdb`` by hand.
- """
- import ast
- import inspect
- import textwrap
-
- from unshackle.commands.dl import dl
- from unshackle.core.title_metadata import TitleMetadata
-
- metadata = TitleMetadata(imdb_id="tt0000001")
- assert build_context(SimpleNamespace(), ids=metadata.post_script_ids())["tmdb"] == ""
- metadata.tmdb_id = 1396
- assert build_context(SimpleNamespace(), ids=metadata.post_script_ids())["tmdb"] == "1396"
-
- body = ast.parse(textwrap.dedent(inspect.getsource(dl.result)))
- for node in ast.walk(body):
- targets = getattr(node, "targets", [])
- assert not any(isinstance(t, ast.Name) and t.id == "post_script_ids" for t in targets), (
- "post_script_ids is snapshotted again; it must be read per dispatch"
- )
-
-
if __name__ == "__main__":
raise SystemExit(pytest.main([__file__, "-q"]))
-def _dispatch_seconds(monkeypatch, entry: dict) -> float:
- import time
-
- monkeypatch.setattr(config, "post_scripts", [entry])
- start = time.monotonic()
- dispatch("success", "file", {})
- return time.monotonic() - start
-
-
-def test_wait_true_waits_for_the_script_and_logs_the_exit_code(monkeypatch, caplog):
- caplog.set_level("DEBUG", logger="post-script")
- slow = f'"{sys.executable}" -c "import time,sys; time.sleep(0.3); sys.exit(3)"'
- assert _dispatch_seconds(monkeypatch, {"command": slow, "wait": True}) >= 0.3
- assert "Post-script exited 3" in caplog.text
-
-
-def test_wait_defaults_to_fire_and_forget(monkeypatch):
- slow = f'"{sys.executable}" -c "import time; time.sleep(0.3)"'
- assert _dispatch_seconds(monkeypatch, {"command": slow}) < 0.3
-
-
def test_no_postscript_override_silences_every_event_and_mode(monkeypatch):
"""``dl --no-postscript`` passes NO_POST_SCRIPTS as the override list. Nothing may spawn."""
monkeypatch.setattr(config, "post_scripts", [{"command": "should_not_run.py", "mode": mode} for mode in MODES])
@@ -246,43 +192,9 @@ def _episode(part):
return Episode(id_="episode-id", service=Svc, title="T", season=1, number=5, part=part, name="Ep")
-def test_part_is_a_plain_number_on_success_and_failure():
- """{part} agrees on both paths, and the failure path carries every title-owned variable."""
- title = _episode(1)
- success = build_context(title, SimpleNamespace(video_tracks=[], audio_tracks=[]), service="SVC")
- failure = build_context(title, None, service="SVC", error="Boom")
- for context in (success, failure):
- assert context["part"] == "1"
- assert context["episode"] == "5"
- assert context["season_episode"] == "S01E05.Part.1"
- assert failure["quality"] == ""
- assert build_context(_episode(None), None, service="SVC")["part"] == ""
-
-
def test_season_context_blanks_every_episode_identity_field():
context = build_context(_episode(1), None, service="SVC")
season = ps.season_context(context, Path("/out"))
assert season["season"] == "1"
for key in ("episode", "part", "season_episode", "absolute", "date", "episode_name"):
assert season[key] == ""
-
-
-def test_every_documented_variable_is_one_build_context_produces():
- """The variable tables in docs/reference/configuration/post-scripts.md must not drift from the code."""
- from unshackle.core.titles.music import Song
-
- doc = Path(__file__).resolve().parents[1] / "docs" / "reference" / "configuration" / "post-scripts.md"
- documented = {
- name
- for line in doc.read_text(encoding="utf-8").splitlines()
- if line.startswith("| `{")
- for name in re.findall(r"`\{(\w+)\}`", line.split("|")[1])
- }
- assert documented, "no variable table rows found"
-
- class Svc:
- pass
-
- song = Song(id_="song-id", service=Svc, name="Tr", artist="Ar", album="Al", track=1)
- produced = set(build_context(_episode(1), None, service="SVC")) | set(build_context(song, None, service="SVC"))
- assert documented <= produced, sorted(documented - produced)
diff --git a/tests/test_post_scripts_music.py b/tests/test_post_scripts_music.py
index 62d6ef55e..25d30ef31 100644
--- a/tests/test_post_scripts_music.py
+++ b/tests/test_post_scripts_music.py
@@ -14,7 +14,7 @@ from types import SimpleNamespace
import pytest
-from unshackle.core.utils.post_scripts import build_context, dispatch, season_context, substitute, tokenize
+from unshackle.core.utils.post_scripts import build_context, season_context
class FakeSong(SimpleNamespace):
@@ -75,14 +75,6 @@ def test_song_context_has_music_fields_and_blank_episode_fields():
assert context["episode"] == ""
-def test_song_context_survives_without_media_info():
- """The failure path and any pre-mux dispatch pass no MediaInfo."""
- context = build_context(song(), None, service="EXAMPLE", error="HTTPError: 403")
- assert context["title"] == "Example Track"
- assert context["error"] == "HTTPError: 403"
- assert context["filepath"] == ""
-
-
def test_album_grouping_matches_the_season_grouping_rule():
"""post_script_group's music branch: albums group by (album artist, album)."""
from unshackle.commands.dl import post_script_group
@@ -107,90 +99,6 @@ def test_album_grouping_matches_the_season_grouping_rule():
assert post_script_group(a)[0] == "album"
-@pytest.mark.parametrize("mode", ["season", "run"])
-def test_album_and_run_contexts_blank_the_file_variables(mode):
- """Mirrors the blanking dl.py applies before dispatching an album or run post-script."""
- base = build_context(
- song(),
- media_info=object(),
- filepath=Path("/dl/Example Artist/04. Example Track.flac"),
- service="EXAMPLE",
- )
- folder = Path("/dl/Example Artist")
- if mode == "season":
- context = season_context(base, folder)
- else:
- context = dict.fromkeys(base, "")
- context["folder"] = str(folder)
-
- assert context["filepath"] == ""
- assert context["sidecars"] == ""
- assert context["folder"] == str(folder)
- if mode == "run":
- assert context["title"] == ""
- assert set(context) == set(base)
- else:
- assert context["album"] == "Example Album, Live & Remastered"
-
-
-def test_a_music_post_script_command_builds_the_argv_a_script_would_get(monkeypatch, tmp_path):
- """End to end through the real dispatcher: config entry in, argv out."""
- from unshackle.core.config import config
-
- marker = tmp_path / "argv.txt"
- script = tmp_path / "hook.py"
- script.write_text("import sys, pathlib\npathlib.Path(sys.argv[1]).write_text(chr(10).join(sys.argv[2:]))\n")
-
- import sys
-
- command = (
- f'"{sys.executable}" "{script}" "{marker}" '
- "--album={album} --artist={artist} --track={track_number} --file={filepath}"
- )
- monkeypatch.setattr(config, "post_scripts", [{"command": command, "mode": "file", "event": "success"}])
-
- context = build_context(
- song(),
- media_info=object(),
- filepath=Path("/dl/Example Artist/04. Example Track.flac"),
- service="EXAMPLE",
- )
- dispatch("success", "file", context)
-
- for _ in range(100):
- if marker.exists() and marker.stat().st_size:
- break
- import time
-
- time.sleep(0.05)
- assert marker.exists(), "the post-script process never ran"
- argv = marker.read_text().splitlines()
- assert "--album=Example Album, Live & Remastered" in argv
- assert "--artist=Example Artist" in argv
- assert "--track=04" in argv
- assert f"--file={Path('/dl/Example Artist/04. Example Track.flac')}" in argv
-
-
-def test_season_context_blanks_the_file_variables_and_sets_the_folder():
- """An album post-script describes the release folder, so no track's file may leak into it."""
- folder = Path("/dl/Example Artist - Example Album, Live & Remastered (1983)")
- context = build_context(
- song(),
- media_info=object(),
- filepath=folder / "04. Example Track.flac",
- sidecars=[folder / "04. Example Track.lrc"],
- service="EXAMPLE",
- )
-
- album = season_context(context, folder)
-
- for key in ("filepath", "filename", "ext", "sidecars", "episode", "episode_name"):
- assert album[key] == "", f"{key} still describes a file"
- assert album["folder"] == str(folder)
- assert album["service"] == "EXAMPLE"
- assert context["filepath"] != "", "the file context handed in must not be mutated"
-
-
def test_season_context_identifies_the_album_not_the_last_track():
"""A Song's ``{title}`` is the song, so blanking only the file fields is not enough.
@@ -218,28 +126,6 @@ def test_season_context_identifies_the_album_not_the_last_track():
assert album["year"] == "1983" # album-level, kept
-def test_season_context_leaves_a_non_music_context_untouched():
- """The music branch is gated on ``{album}``; a season post-script must not lose its own keys."""
- folder = Path("/dl/Some Show/Season 1")
- context = build_context(
- episode(),
- media_info=object(),
- filepath=folder / "Some Show S01E05 Pilot.mkv",
- service="EXAMPLE",
- )
- context["disc"] = "sentinel" # only the music branch clears this
-
- season = season_context(context, folder)
-
- assert season["title"] == "Some Show"
- assert season["title_raw"] == "Some Show"
- assert season["season"] == "1"
- assert season["disc"] == "sentinel"
- assert season["episode"] == ""
- assert season["episode_name"] == ""
- assert season["folder"] == str(folder)
-
-
def test_a_failed_track_gets_a_track_scoped_failure_context():
"""Failure is per-track, like every other title type, and does not describe the album.
@@ -255,11 +141,5 @@ def test_a_failed_track_gets_a_track_scoped_failure_context():
assert context["season"] == ""
-def test_an_album_name_with_a_comma_stays_one_argument():
- """'Example Album, Live & Remastered' must not split, which is the whole tokenize-first point."""
- argv = substitute(tokenize("upload.py --album={album}"), {"album": "Example Album, Live & Remastered"})
- assert argv == ["upload.py", "--album=Example Album, Live & Remastered"]
-
-
if __name__ == "__main__":
raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/test_sample.py b/tests/test_sample.py
index d728888f5..a604329a7 100644
--- a/tests/test_sample.py
+++ b/tests/test_sample.py
@@ -13,14 +13,10 @@ from unittest.mock import MagicMock
import click
import pytest
-from requests import Session
from tests.admission import refusal
from unshackle.core.config import config
from unshackle.core.manifests.dash import DASH
-from unshackle.core.placement import sample_name
-from unshackle.core.services import Services
-from unshackle.core.titles import Episode, Movie
from unshackle.core.tracks import Audio, Chapter, Subtitle, Tracks, Video
from unshackle.core.tracks.track import parse_sidx
from unshackle.core.utils.click_types import SAMPLE_RANGE
@@ -37,10 +33,6 @@ def make_audio(url: str = "https://x/a") -> Audio:
return Audio(id_="a", url=url, codec=Audio.Codec.AAC, language="en", bitrate=128000)
-def test_no_window_keeps_every_segment() -> None:
- assert make_audio().sample_slice(STARTS, 1000) == slice(None)
-
-
def test_the_window_is_measured_from_the_first_segment() -> None:
track = make_audio()
assert track.sample_slice(STARTS, 1000, (62, 120)) == slice(15, 30)
@@ -63,11 +55,6 @@ def test_a_subtitle_keeps_one_segment_on_each_side_of_the_window() -> None:
assert subtitle.sample_slice(STARTS, 1000, None) == slice(None)
-def test_a_subtitle_that_ends_before_the_window_keeps_its_last_segment() -> None:
- subtitle = Subtitle(id_="s", url="https://x/s", codec=Subtitle.Codec.WebVTT, language="en")
- assert subtitle.sample_slice([0, 4000], 1000, (120, 180)) == slice(0, None)
-
-
def test_a_window_after_the_end_stops_the_run() -> None:
with pytest.raises(click.ClickException, match="ends before the sample window"):
make_audio().sample_slice(STARTS[:10], 1000, (120, 180))
@@ -180,30 +167,6 @@ def served(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> str:
server.shutdown()
-def test_an_hls_subtitle_downloads_the_segments_around_the_window(
- tmp_path: Path, served: str, monkeypatch: pytest.MonkeyPatch
-) -> None:
- for n in range(8):
- (tmp_path / f"s{n}.vtt").write_text(
- f"WEBVTT\n\n00:00:{n * 10 + 1:02}.000 --> 00:00:{n * 10 + 2:02}.000\ncue {n}\n"
- )
- (tmp_path / "s.m3u8").write_text(
- "#EXTM3U\n#EXT-X-TARGETDURATION:10\n"
- + "".join(f"#EXTINF:10.0,\ns{n}.vtt\n" for n in range(8))
- + "#EXT-X-ENDLIST\n"
- )
- monkeypatch.setattr(config, "sample", (32, 38))
- subtitle = Subtitle(
- id_="s", url=f"{served}/s.m3u8", codec=Subtitle.Codec.WebVTT, language="en", descriptor=Subtitle.Descriptor.HLS
- )
-
- subtitle.download(session=Session(), prepare_drm=lambda *a, **k: None, progress=lambda **k: None)
-
- text = subtitle.path.read_text()
- assert [n for n in range(8) if f"cue {n}" in text] == [2, 3, 4]
- assert "00:00:31.000 --> 00:00:32.000" in text, "cue times stay absolute"
-
-
def test_subtitle_trim_keeps_the_cues_of_the_window_from_zero(tmp_path: Path) -> None:
subtitle = Subtitle(id_="s", url="https://x/s", codec=Subtitle.Codec.SubRip, language="en")
subtitle.path = tmp_path / "s.srt"
@@ -221,15 +184,6 @@ def test_subtitle_trim_keeps_the_cues_of_the_window_from_zero(tmp_path: Path) ->
assert subtitle.sample_start == 120
-def test_subtitle_trim_leaves_an_unreadable_file_whole(tmp_path: Path) -> None:
- subtitle = Subtitle(id_="s", url="https://x/s", codec=Subtitle.Codec.fTTML, language="en")
- subtitle.path = tmp_path / "s.stpp"
- subtitle.path.write_bytes(b"\x00\x01not a subtitle")
-
- assert subtitle.trim(120, 180) is False
- assert subtitle.path.read_bytes() == b"\x00\x01not a subtitle"
-
-
def mux_command(tmp_path: Path, mux_args: Callable[..., list[str]]) -> list[str]:
video, audio = make_video(), make_audio()
trimmed = Subtitle(id_="s1", url="https://x/s1", codec=Subtitle.Codec.SubRip, language="en")
@@ -299,15 +253,6 @@ def test_the_api_refuses_sample_with_include_sample() -> None:
assert "--include-sample" in (refusal({"sample": True, "include_sample": True}) or "")
-def test_sample_name_uses_the_separator_of_the_template(monkeypatch: pytest.MonkeyPatch) -> None:
- separators = {"movies": ".", "series": " "}
- monkeypatch.setattr(config, "get_template_separator", lambda kind="movies": separators[kind])
- movie = Movie.__new__(Movie)
- episode = Episode.__new__(Episode)
- assert sample_name("Some.Movie.2026.1080p-TAG", movie) == "Some.Movie.2026.1080p-TAG.SAMPLE"
- assert sample_name("Some Show S01E01 1080p-TAG", episode) == "Some Show S01E01 1080p-TAG SAMPLE"
-
-
SIDX_MPD = """
@@ -345,30 +290,6 @@ def test_parse_sidx_refuses_what_it_cannot_cut() -> None:
assert parse_sidx(sidx_box(count=3)[:-4], 0) == (0, [])
-def test_parse_sidx_is_right_when_tracks_parse_at_the_same_time() -> None:
- boxes = {758: sidx_box(count=758), 1408: sidx_box(count=1408, size=500)}
- wrong: list[int] = []
-
- def parse(count: int) -> None:
- for _ in range(100):
- if len(parse_sidx(boxes[count], 0)[1]) != count:
- wrong.append(count)
-
- threads = [threading.Thread(target=parse, args=(count,)) for count in (758, 1408, 758, 1408)]
- for thread in threads:
- thread.start()
- for thread in threads:
- thread.join(timeout=30)
- assert not wrong
- assert not any(thread.is_alive() for thread in threads)
-
-
-def test_parse_sidx_refuses_a_box_that_counts_more_references_than_it_holds() -> None:
- box = bytearray(sidx_box(count=3))
- box[30:32] = (5).to_bytes(2, "big")
- assert parse_sidx(bytes(box) + bytes(100), 0) == (0, [])
-
-
def test_a_single_file_dash_track_is_cut_by_its_segment_index(monkeypatch: pytest.MonkeyPatch) -> None:
box = sidx_box()
requested: list[str] = []
@@ -407,35 +328,6 @@ def test_a_single_file_dash_track_is_cut_by_its_segment_index(monkeypatch: pytes
assert len(whole) == 1 and not any("800-" in r for r in requested), "a full download does not read the index"
-@pytest.mark.parametrize(
- ("args", "window"),
- [
- (["--sample", "TAG", "-t", "x", "id"], (120, 180)),
- (["--sample", "60-120", "TAG", "id"], (60, 120)),
- (["TAG", "id"], None),
- ],
-)
-def test_a_bare_sample_option_does_not_take_the_service_tag(args: list[str], window: object) -> None:
- seen: dict[str, object] = {}
-
- class Group(Services):
- def list_commands(self, ctx: click.Context) -> list[str]:
- return ["TAG"]
-
- def get_command(self, ctx: click.Context, name: str) -> click.Command:
- return click.Command(
- name, params=[click.Option(["-t"]), click.Argument(["title"])], callback=lambda **k: None
- )
-
- @click.group(cls=Group)
- @click.option("--sample", type=SAMPLE_RANGE, default=None)
- def group(sample: object) -> None:
- seen["sample"] = sample
-
- group(args, standalone_mode=False)
- assert seen["sample"] == window
-
-
class RangeSession:
"""Serves byte ranges of one in-memory file and records each range it was asked for."""
diff --git a/tests/test_setup.py b/tests/test_setup.py
index 9a5ad080f..2b4e7524d 100644
--- a/tests/test_setup.py
+++ b/tests/test_setup.py
@@ -17,63 +17,12 @@ import yaml
from click.testing import CliRunner
from unshackle.commands import setup as setup_mod
-from unshackle.commands.env import get_dependencies
from unshackle.core import binaries
from unshackle.core.config import Config, config
EXT = ".exe" if sys.platform == "win32" else ""
-@pytest.mark.parametrize(
- ("tool", "system", "machine", "suffix"),
- [
- ("shaka-packager", "linux", "x86_64", "/v2.6.1/packager-linux-x64"),
- ("shaka-packager", "linux", "aarch64", "/v2.6.1/packager-linux-arm64"),
- ("shaka-packager", "win32", "AMD64", "/v2.6.1/packager-win-x64.exe"),
- ("FFmpeg", "linux", "x86_64", "-linux64-gpl.tar.xz"),
- ("FFmpeg", "win32", "AMD64", "-win64-gpl.zip"),
- ("MKVToolNix", "win32", "AMD64", "mkvtoolnix-64-bit-102.0.zip"),
- ("dovi_tool", "linux", "arm64", "-aarch64-unknown-linux-musl.tar.gz"),
- ("CCExtractor", "linux", "x86_64", "/v0.96.6/ccextractor-minimal-x86_64.AppImage"),
- ("CCExtractor", "win32", "AMD64", "/v0.96.6/CCExtractor.0.96.6_win_portable.zip"),
- ],
-)
-def test_asset_url_matches_platform(tool: str, system: str, machine: str, suffix: str) -> None:
- url = setup_mod.asset_url(tool, system, machine)
- assert url is not None and url.startswith("https://") and url.endswith(suffix)
-
-
-@pytest.mark.parametrize(
- ("tool", "system", "machine"),
- [
- ("MKVToolNix", "linux", "x86_64"),
- ("CCExtractor", "linux", "aarch64"),
- ("mp4decrypt", "linux", "aarch64"),
- ("shaka-packager", "darwin", "arm64"),
- ("FFmpeg", "win32", "ARM64"),
- ],
-)
-def test_asset_url_is_none_without_a_portable_build(tool: str, system: str, machine: str) -> None:
- assert setup_mod.asset_url(tool, system, machine) is None
-
-
-def test_every_url_and_hint_is_filled_from_the_version() -> None:
- for tool, spec in setup_mod.TOOLS.items():
- hint = setup_mod.versioned(tool, spec["hint"])
- assert hint and "{" not in hint
- for key in spec["urls"]:
- url = setup_mod.asset_url(tool, *key.split("-", 1))
- assert url is not None and url.startswith("https://") and "{" not in url
- assert spec["version"].replace(".", "-") in url or spec["version"] in url
-
-
-def test_label_shows_pinned_versions_only() -> None:
- assert setup_mod.label("shaka-packager") == "shaka-packager 2.6.1"
- assert setup_mod.label("FFmpeg") == "FFmpeg"
- assert setup_mod.label("CCExtractor", "linux") == "CCExtractor 0.96.6"
- assert setup_mod.label("CCExtractor", "win32") == "CCExtractor 0.96.6, 88 MB"
-
-
def make_zip(path: Path, members: dict[str, bytes]) -> Path:
with zipfile.ZipFile(path, "w") as zf:
for name, data in members.items():
@@ -132,15 +81,6 @@ def test_extract_moves_a_lone_binary(tmp_path: Path) -> None:
assert not download.exists()
-def test_is_clone_follows_pyproject(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- package = tmp_path / "unshackle"
- package.mkdir()
- monkeypatch.setattr(config.directories, "namespace_dir", package)
- assert setup_mod.is_clone() is False
- (tmp_path / "pyproject.toml").write_text("")
- assert setup_mod.is_clone() is True
-
-
def test_write_config_tool_mode_moves_data_dirs(tmp_path: Path) -> None:
path = tmp_path / "config" / "unshackle.yaml"
data_root = tmp_path / "data"
@@ -181,13 +121,6 @@ def make_exe(folder: Path, name: str) -> Path:
return path
-def test_find_checks_the_user_binaries_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(binaries, "user_binaries_dir", tmp_path / "user")
- tool = make_exe(tmp_path / "user", "setup-test-tool")
-
- assert binaries.find("setup-test-tool") == tool
-
-
def test_find_prefers_the_package_binaries_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(binaries, "package_binaries_dir", tmp_path / "unshackle" / "binaries")
monkeypatch.setattr(binaries, "user_binaries_dir", tmp_path / "user")
@@ -255,18 +188,6 @@ def fake_deps(missing: Iterable[str]) -> list[dict[str, object]]:
]
-def test_tools_deps_exist_in_env_check(monkeypatch: pytest.MonkeyPatch) -> None:
- # Set in the module dict: a setattr reads the old value first, and that read runs the PATH search.
- for attr in set(binaries.__all__) - {"find", "register", "get_registered_dependencies"}:
- monkeypatch.setitem(vars(binaries), attr, None)
-
- deps = {dep["name"]: dep["required"] for dep in get_dependencies()}
-
- names = {dep for spec in setup_mod.TOOLS.values() for dep in spec["deps"]}
- assert names <= deps.keys()
- assert {name for name in names if deps[name]} == REQUIRED_DEPS
-
-
@pytest.fixture
def sandbox(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
"""Point every path setup touches into tmp_path and record its prompts and installs.
@@ -424,13 +345,6 @@ def test_device_files_expands_a_folder_without_recursion(tmp_path: Path) -> None
assert setup_mod.device_files(str(make_devices(tmp_path / "empty", {}))) == []
-def test_device_files_keeps_quotes_and_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setenv("HOME", str(tmp_path))
- monkeypatch.setenv("USERPROFILE", str(tmp_path))
-
- assert setup_mod.device_files('"~/x.wvd"') == [tmp_path / "x.wvd"]
-
-
@pytest.mark.usefixtures("fake_devices")
def test_cdm_prompt_repeats_and_asks_for_the_default(
sandbox: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
@@ -468,21 +382,6 @@ def test_one_bad_device_does_not_stop_the_rest(
assert not (sandbox.package / "WVDs" / "bad.wvd").exists()
-@pytest.mark.usefixtures("fake_devices")
-def test_folder_without_devices_says_so(
- sandbox: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
-) -> None:
- # Longer than the 80-column console, so a wrapped line would split the path.
- folder = make_devices(tmp_path / ("long" * 20) / "in", {"notes.txt": b""})
- script_cdm_prompts(monkeypatch, [str(folder)])
-
- result = CliRunner().invoke(setup_mod.setup, [])
-
- assert result.exit_code == 0, result.output
- assert f"No .wvd or .prd files in {folder}" in result.output
- assert "cdm" not in yaml.safe_load((sandbox.package / "unshackle.yaml").read_text())
-
-
@pytest.mark.usefixtures("fake_devices")
def test_destination_folder_is_already_in_place(sandbox: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> None:
wvds = make_devices(sandbox.package / "WVDs", {"x.wvd": b"device"})
@@ -592,13 +491,3 @@ def test_appimage_is_kept_only_when_it_runs(
output = capsys.readouterr().out
assert "the AppImage does not run, it needs FUSE" in output
assert "Install it manually: see the fake docs" in output
-
-
-def test_group_prompt_shows_the_download_size(sandbox: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setitem(setup_mod.TOOLS["CCExtractor"], "size", "88 MB")
- monkeypatch.setattr(setup_mod, "get_dependencies", lambda: fake_deps({"SubtitleEdit", "CCExtractor"}))
-
- result = CliRunner().invoke(setup_mod.setup, [])
-
- assert result.exit_code == 0, result.output
- assert sandbox.prompts == [("Install the Subtitle tools (SubtitleEdit 5.2.0, CCExtractor 0.96.6, 88 MB)?", False)]
diff --git a/tests/tracks/test_ass_style.py b/tests/tracks/test_ass_style.py
index ec7be3ff4..ca398ce4c 100644
--- a/tests/tracks/test_ass_style.py
+++ b/tests/tracks/test_ass_style.py
@@ -89,11 +89,6 @@ def test_bad_style_fields_raise(fields):
sc.build_ass_style(fields)
-def test_ass_field_names_are_accepted():
- style = sc.build_ass_style({"Fontname": "My Font", "PrimaryColour": "&H0000FFFF", "MarginV": 40.0})
- assert (style.fontname, style.primarycolor, style.marginv) == ("My Font", pysubs2.Color(255, 255, 0, 0), 40)
-
-
def test_the_look_goes_only_to_subtitles_that_are_not_already_ass(tmp_path):
style = sc.build_ass_style({})
vtt = make_sub(tmp_path, "x.vtt", VTT, Codec.WebVTT)
@@ -107,22 +102,6 @@ def test_the_look_goes_only_to_subtitles_that_are_not_already_ass(tmp_path):
assert vtt.ass_video_size == ass.ass_video_size == (3840, 1600)
-def test_a_stripped_styled_track_with_no_cues_left_stays_srt(tmp_path, monkeypatch):
- monkeypatch.setattr("unshackle.core.config.config.subtitle", {"sdh_method": "auto"}, raising=False)
- sub = make_sub(tmp_path, "x.vtt", VTT.split("00:00:03")[0], Codec.WebVTT, sc.build_ass_style({}))
- sub.convert(Codec.SubStationAlphav4)
- sub.strip_hearing_impaired()
- assert sub.codec == Codec.SubRip
-
-
-def test_a_stripped_native_ass_track_is_not_restyled(tmp_path, monkeypatch):
- monkeypatch.setattr("unshackle.core.config.config.subtitle", {"sdh_method": "auto"}, raising=False)
- sub = make_sub(tmp_path, "x.ass", NATIVE_ASS, Codec.SubStationAlphav4)
- set_subtitle_look([sub], sc.build_ass_style({"fontname": "My Font"}), [])
- sub.strip_hearing_impaired()
- assert sub.codec == Codec.SubRip
-
-
def test_vtt_to_ass_gets_the_style_on_a_canvas_shaped_like_the_video(tmp_path):
sub = make_sub(tmp_path, "x.vtt", VTT, Codec.WebVTT, sc.build_ass_style({"fontname": "My Font"}))
sub.convert(Codec.SubStationAlphav4)
@@ -134,15 +113,6 @@ def test_vtt_to_ass_gets_the_style_on_a_canvas_shaped_like_the_video(tmp_path):
assert subs.styles["Default"].fontsize == 72
-def test_vtt_to_ass_without_a_style_is_left_as_converted(tmp_path):
- sub = make_sub(tmp_path, "x.vtt", VTT, Codec.WebVTT)
- sub.convert(Codec.SubStationAlphav4)
-
- subs = pysubs2.load(str(sub.path))
- assert "PlayResY" not in subs.info
- assert subs.styles["Default"].fontname == "Arial"
-
-
@pytest.mark.parametrize("target", [Codec.SubStationAlphav4, Codec.SubStationAlpha])
def test_a_native_ass_track_is_never_restyled(tmp_path, target):
sub = make_sub(tmp_path, "x.ass", NATIVE_ASS, Codec.SubStationAlphav4, sc.build_ass_style({}))
@@ -167,14 +137,6 @@ def test_a_converter_canvas_is_kept_and_the_style_scales_to_it(tmp_path):
assert (top.fontname, top.alignment, top.italic) == ("My Font", pysubs2.Alignment.TOP_CENTER, True)
-def test_restyling_twice_gives_the_same_file(tmp_path):
- sub = make_sub(tmp_path, "x.vtt", VTT, Codec.WebVTT, sc.build_ass_style({}))
- sub.convert(Codec.SubStationAlphav4)
- first = sub.path.read_text("utf8")
- sc.style_substation(sub.path, sub.ass_style, sub.ass_video_size)
- assert sub.path.read_text("utf8") == first
-
-
def test_a_stripped_styled_track_stays_styled_ass(tmp_path, monkeypatch):
monkeypatch.setattr("unshackle.core.config.config.subtitle", {"sdh_method": "auto"}, raising=False)
sub = make_sub(tmp_path, "x.vtt", VTT, Codec.WebVTT, sc.build_ass_style({"fontname": "My Font"}))
@@ -203,11 +165,6 @@ def test_subtitle_look_picks_the_format_and_style(sub_format, sub_font, fields,
assert (out_format, style.fontname if style else None) == expected
-def test_a_typed_font_overrides_a_format_from_config():
- out_format, style = subtitle_look(Codec.SubRip, "My Font", None, typed_format=False)
- assert (out_format, style.fontname if style else None) == (Codec.SubStationAlphav4, "My Font")
-
-
def test_a_font_from_config_is_ignored_with_another_format():
assert subtitle_look(Codec.SubRip, "My Font", None, typed_font=False) == (Codec.SubRip, None)
assert subtitle_look("original", "My Font", {"fontsize": 60}, typed_font=False) == ("original", None)
diff --git a/tests/tracks/test_attachment_download.py b/tests/tracks/test_attachment_download.py
index 4b59165ca..f1cf45085 100644
--- a/tests/tracks/test_attachment_download.py
+++ b/tests/tracks/test_attachment_download.py
@@ -106,22 +106,6 @@ def test_download_with_flag_bypasses_proxy(server, monkeypatch) -> None:
assert attachment.path is not None and attachment.path.read_bytes() == BODY
-def test_download_with_proxy_download_uses_only_that_proxy(server, monkeypatch) -> None:
- seen: dict = {}
-
- def fake_direct(session, proxy=None):
- seen["proxy"] = proxy
- return Recorder()
-
- monkeypatch.setattr(track_module, "direct_session", fake_direct)
- proxied = Recorder(proxies={"https": "http://manifest-proxy:1"})
- attachment = Attachment.from_url(url(server), name="thumbnail", session=proxied)
- attachment.download(proxied, proxy_download="http://dl-proxy:2")
- assert not proxied.got
- assert seen["proxy"] == "http://dl-proxy:2"
- assert proxied.proxies == {"https": "http://manifest-proxy:1"}
-
-
def test_no_proxy_download_wins_over_proxy_download(server, monkeypatch) -> None:
seen: dict = {}
monkeypatch.setattr(track_module, "direct_session", lambda s, proxy=None: seen.setdefault("p", proxy) or Recorder())
@@ -170,13 +154,6 @@ def test_direct_session_routes_through_the_given_proxy() -> None:
assert requests.utils.select_proxy("https://cdn.example.com/a", new.proxies) == "http://dl-proxy:2"
-def test_direct_session_proxy_beats_environment(monkeypatch) -> None:
- monkeypatch.setenv("HTTPS_PROXY", "http://env-proxy:9")
- new = track_module.direct_session(requests.Session(), "http://dl-proxy:2")
- settings = new.merge_environment_settings("https://cdn.example.com/a", {}, None, None, None)
- assert settings["proxies"]["https"] == "http://dl-proxy:2"
-
-
def test_direct_session_copies_rnet_cookies_set_by_name() -> None:
from unshackle.core.session import RnetSession
diff --git a/tests/tracks/test_attachment_mime.py b/tests/tracks/test_attachment_mime.py
index f0ab0bc97..090437990 100644
--- a/tests/tracks/test_attachment_mime.py
+++ b/tests/tracks/test_attachment_mime.py
@@ -22,18 +22,6 @@ def test_a_png_saved_as_jpg_is_image_png(tmp_path: Path) -> None:
assert Attachment(path=path).mime_type == "image/png"
-def test_an_unknown_signature_falls_back_to_the_suffix(tmp_path: Path) -> None:
- path = tmp_path / "font.ttf"
- path.write_bytes(b"junk" * 8)
- assert Attachment(path=path).mime_type == "application/x-truetype-font"
-
-
-def test_a_given_mime_type_stays(tmp_path: Path) -> None:
- path = tmp_path / "thumb.jpg"
- path.write_bytes(PNG)
- assert Attachment(path=path, mime_type="image/jpeg").mime_type == "image/jpeg"
-
-
@pytest.fixture
def png_download(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
def fake_download(url: str, path: Path, **kwargs: object) -> Iterator[dict]:
diff --git a/tests/tracks/test_audio_channel_layouts.py b/tests/tracks/test_audio_channel_layouts.py
index ddffe119a..cf9d960df 100644
--- a/tests/tracks/test_audio_channel_layouts.py
+++ b/tests/tracks/test_audio_channel_layouts.py
@@ -13,11 +13,6 @@ from unshackle.core.tracks import Audio
from unshackle.core.wire import track_from_dict, track_to_dict
-@pytest.mark.parametrize("layout", ["5.1.4", "7.1.2", "9.1.6"])
-def test_an_immersive_layout_survives_construction(layout: str) -> None:
- assert Audio(id_="a1", url="https://example.test/a", language="en", channels=layout).channels == layout
-
-
@pytest.mark.parametrize(
("value", "expected"),
[("5.1", 5.1), ("2ch", 2.0), ("2", 2.0), ("2.0", 2.0), ("A000", 2.0), ("F801", 5.1), (6, 6.0)],
diff --git a/tests/tracks/test_audio_codec_mime.py b/tests/tracks/test_audio_codec_mime.py
index 6860cae50..4b590b3ee 100644
--- a/tests/tracks/test_audio_codec_mime.py
+++ b/tests/tracks/test_audio_codec_mime.py
@@ -2,7 +2,6 @@ import textwrap
import pytest
-from unshackle.core.constants import SPACED_AUDIO_CODECS
from unshackle.core.manifests.hls import HLS
from unshackle.core.tracks.audio import Audio
@@ -36,11 +35,6 @@ def test_dts_hd_and_mpeg_h_sample_entries_map(mime: str, codec: Audio.Codec) ->
assert Audio.Codec.from_mime(mime) == codec
-def test_unknown_mime_still_raises() -> None:
- with pytest.raises(ValueError):
- Audio.Codec.from_mime("dtsz")
-
-
@pytest.mark.parametrize(
("uri", "expected"),
[
@@ -80,12 +74,6 @@ def test_select_audio_codec_holds_a_single_declaration() -> None:
assert HLS.select_audio_codec(None, None) is None
-def test_spaced_codec_constants_name_real_codecs() -> None:
- """The constant holds bare strings, so a rename must not silently stop matching."""
- for value in SPACED_AUDIO_CODECS:
- assert value in {c.value for c in Audio.Codec}, f"{value} is not an Audio.Codec value"
-
-
def test_a_short_ladder_rung_cannot_hide_a_group_codec() -> None:
"""
One GROUP-ID is reached from every variant that references it, and a low rung may
diff --git a/tests/tracks/test_fragment_decrypted.py b/tests/tracks/test_fragment_decrypted.py
index 7dc5adda5..a39844c77 100644
--- a/tests/tracks/test_fragment_decrypted.py
+++ b/tests/tracks/test_fragment_decrypted.py
@@ -65,12 +65,6 @@ def test_surviving_senc_raises(tmp_path: Path) -> None:
assert_fragments_decrypted(f)
-def test_surviving_cenc_senc_raises(tmp_path: Path) -> None:
- f = write(tmp_path, "cenc.mp4", FTYP, MOOV, moof(senc()), MDAT)
- with pytest.raises(ValueError, match=r"1/1 fragment"):
- assert_fragments_decrypted(f)
-
-
def test_leftover_piff_uuid_after_senc_removed_does_not_raise(tmp_path: Path) -> None:
# live DASH shape: the traf shipped senc+saiz+saio plus a duplicate PIFF uuid. mp4decrypt
# consumed senc, detached senc/saiz/saio, and left the uuid on a fully decrypted fragment.
@@ -86,12 +80,6 @@ def test_stray_senc_bytes_in_mdat_ignored(tmp_path: Path) -> None:
assert_fragments_decrypted(f)
-def test_senc_text_without_plausible_size_ignored(tmp_path: Path) -> None:
- # "senc" inside a free-box string has no valid box size before it
- f = write(tmp_path, "text.mp4", FTYP, MOOV, moof(box(b"free", b"presence sencoded here")), MDAT)
- assert_fragments_decrypted(f)
-
-
def test_senc_bytes_inside_trun_payload_ignored(tmp_path: Path) -> None:
# a trun sample entry spelling "senc" after a size-looking duration; only a byte scan bites
trun = box(b"trun", b"\x00\x00\x03\x01" + struct.pack(">I", 2) + struct.pack(">I", 512) + b"senc")
@@ -125,13 +113,6 @@ def test_senc_outside_traf_ignored(tmp_path: Path) -> None:
assert_fragments_decrypted(f)
-def test_senc_nested_under_non_traf_ignored(tmp_path: Path) -> None:
- # senc two levels down under a non-traf container: only traf children count
- meta = box(b"meta", senc())
- f = write(tmp_path, "nested.mp4", FTYP, MOOV, box(b"moof", box(b"mfhd", b"\x00" * 8) + meta), MDAT)
- assert_fragments_decrypted(f)
-
-
def test_undersized_largesize_box_does_not_desync_walk(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
# size==1 reads a 16-byte header, so a largesize of 12 clears the 8-byte floor but
# still stalls the cursor onto payload; only a header-aware floor catches it
diff --git a/tests/tracks/test_hybrid_selection.py b/tests/tracks/test_hybrid_selection.py
index 76de5c675..a2a2ed6ef 100644
--- a/tests/tracks/test_hybrid_selection.py
+++ b/tests/tracks/test_hybrid_selection.py
@@ -64,12 +64,6 @@ def test_select_hybrid_picks_base_per_resolution_and_lowest_dv(ladder: list[Vide
assert ids(chosen) == {"hdr10p-2160", "hdr10p-1080", "dv-360"}
-def test_select_hybrid_ingredient_is_lowest_dv_regardless_of_quality(ladder: list[Video]) -> None:
- # Even when only 2160 is requested, the ingredient is the globally lowest DV.
- chosen = list(filter(Tracks().select_hybrid(ladder, [2160]), ladder))
- assert ids(chosen) == {"hdr10p-2160", "dv-360"}
-
-
def test_select_hybrid_prefers_hdr10p_over_hdr10() -> None:
H = Video.Codec.HEVC
tracks = [
@@ -108,13 +102,6 @@ def test_select_hybrid_skips_a_base_that_is_not_hevc() -> None:
assert ids(chosen) == {"hdr10p-2160", "dv-360"}
-def test_select_hybrid_no_dv_selects_only_base() -> None:
- H = Video.Codec.HEVC
- tracks = [make_video("hdr10p-2160", range_=Video.Range.HDR10P, height=2160, bitrate=20_000_000, codec=H)]
- chosen = list(filter(Tracks().select_hybrid(tracks, [2160]), tracks))
- assert ids(chosen) == {"hdr10p-2160"}
-
-
def dv_hdr10p(track_id: str, height: int, bitrate: int) -> Video:
video = make_video(track_id, range_=Video.Range.DV, height=height, bitrate=bitrate, codec=Video.Codec.HEVC)
video.hdr10plus = True
@@ -147,17 +134,6 @@ def test_select_hybrid_builds_a_hybrid_only_where_no_dv_track_carries_hdr10p() -
assert {t.id for t in chosen if t.hybrid_base_only} == {"hdr10-1080", "dv-360"}
-def test_a_dv_hdr10p_track_used_only_for_its_rpu_stays_an_ingredient() -> None:
- H = Video.Codec.HEVC
- tracks = [
- make_video("hdr10-1080", range_=Video.Range.HDR10, height=1080, bitrate=8_000_000, codec=H),
- dv_hdr10p("dvp-360", 360, 700_000),
- ]
- chosen = list(filter(Tracks().select_hybrid(tracks, [1080]), tracks))
- Tracks.flag_hybrid_ingredients(chosen, [])
- assert all(t.hybrid_base_only for t in chosen) and ids(chosen) == {"hdr10-1080", "dvp-360"}
-
-
def dv_hdr10(track_id: str, height: int, bitrate: int, range_: Video.Range = Video.Range.HDR10) -> Video:
video = make_video(track_id, range_=range_, height=height, bitrate=bitrate, codec=Video.Codec.HEVC)
video.dv_compatible_bitstream = True
@@ -175,16 +151,6 @@ def test_select_hybrid_takes_a_dv_hdr10_track_and_no_profile_5_donor() -> None:
assert ids(chosen) == {"dvhdr-2160"} and chosen[0].native_hybrid
-def test_select_hybrid_prefers_a_finished_hybrid_that_carries_hdr10p() -> None:
- tracks = [
- dv_hdr10("dvhdr-2160", 2160, 9_000_000),
- dv_hdr10("dvhdrp-2160", 2160, 7_000_000, Video.Range.HDR10P),
- dv_hdr10p("dvp-2160", 2160, 6_000_000),
- ]
- assert ids(list(filter(Tracks().select_hybrid(tracks, [2160]), tracks))) == {"dvhdrp-2160"}
- assert ids(list(filter(Tracks().select_hybrid(tracks, [2160], worst=True), tracks))) == {"dvp-2160"}
-
-
def test_select_hybrid_picks_no_base_that_has_no_dv_track_to_take_an_rpu_from() -> None:
H = Video.Codec.HEVC
tracks = [
@@ -207,15 +173,6 @@ def test_merge_dedups_shared_ingredient_and_deliverable() -> None:
assert [t.id for t in merged] == ["hdr10p-2160", "dv-1080", "sdr-2160"]
-def test_merge_preserves_order_and_keeps_distinct_dv() -> None:
- H = Video.Codec.HEVC
- ingredient = make_video("dv-360", range_=Video.Range.DV, height=360, bitrate=1_000_000, codec=H)
- deliverable = make_video("dv-2160", range_=Video.Range.DV, height=2160, bitrate=25_000_000, codec=H)
-
- merged = Tracks.merge_video_selections([ingredient], [deliverable])
- assert [t.id for t in merged] == ["dv-360", "dv-2160"]
-
-
def test_merge_dedup_uses_track_identity_by_id() -> None:
# Tracks compare equal by id; merge must treat same-id tracks as one.
H = Video.Codec.HEVC
@@ -241,22 +198,6 @@ def test_partition_admits_hdr10p_to_pool_when_requested(ladder: list[Video]) ->
assert ids(candidates) == {"hdr10p-2160", "hdr10p-1080", "dv-2160", "dv-1080", "dv-360"}
-def test_partition_admits_dv_and_hdr10p_when_both_requested(ladder: list[Video]) -> None:
- """`-r HYBRID,HDR10P,DV`: both ranges enter the deliverable pool."""
- _, pool = Tracks.partition_hybrid_videos(ladder, [Video.Range.HDR10P, Video.Range.DV])
- assert {"hdr10p-2160", "hdr10p-1080", "dv-2160", "dv-1080", "dv-360"} <= ids(pool)
-
-
-def test_partition_hdr10_requested_does_not_admit_hdr10p() -> None:
- H = Video.Codec.HEVC
- tracks = [
- make_video("hdr10-2160", range_=Video.Range.HDR10, height=2160, bitrate=20_000_000, codec=H),
- make_video("hdr10p-2160", range_=Video.Range.HDR10P, height=2160, bitrate=20_000_000, codec=H),
- ]
- _, pool = Tracks.partition_hybrid_videos(tracks, [Video.Range.HDR10])
- assert ids(pool) == {"hdr10-2160"}
-
-
def flagged(tracks: list[Video]) -> set[str]:
return {t.id for t in tracks if t.hybrid_base_only}
@@ -278,16 +219,6 @@ def test_flag_hybrid_plus_hdr10p_keeps_base_deliverable(ladder: list[Video]) ->
assert flagged(ladder) == {"dv-360"}
-def test_flag_hybrid_plus_hdr10p_and_dv_keeps_both_deliverables(ladder: list[Video]) -> None:
- """`-r HYBRID,HDR10P,DV`: best DV is a deliverable, lowest DV stays
- ingredient-only; hybrid + HDR10+ + DV are muxed."""
- hybrid_selected = list(filter(Tracks().select_hybrid(ladder, [1080]), ladder))
- base = next(t for t in ladder if t.id == "hdr10p-1080")
- best_dv = next(t for t in ladder if t.id == "dv-1080")
- Tracks.flag_hybrid_ingredients(hybrid_selected, [base, best_dv])
- assert flagged(ladder) == {"dv-360"}
-
-
def test_flag_single_dv_rendition_as_deliverable_stays_unflagged() -> None:
"""`-r HYBRID,DV` with one DV rendition: the same track is ingredient and
deliverable, so it must still be muxed standalone."""
@@ -300,32 +231,3 @@ def test_flag_single_dv_rendition_as_deliverable_stays_unflagged() -> None:
dv = next(t for t in tracks if t.id == "dv-1080")
Tracks.flag_hybrid_ingredients(hybrid_selected, [dv])
assert flagged(tracks) == {"hdr10p-1080"}
-
-
-def test_hybrid_plus_dv_deliverable_end_state(ladder: list[Video]) -> None:
- """`-r SDR,HDR10P,DV,HYBRID -q 2160,1080`: hybrid base + lowest DV ingredient,
- de-duplicated against the best-DV-per-resolution deliverables and SDR."""
- quality = [2160, 1080]
-
- hybrid_selected = list(filter(Tracks().select_hybrid(ladder, quality), ladder))
-
- # Deliverables: best DV and SDR per requested resolution (what the dl Cartesian picks).
- def best_per_res(range_: Video.Range, codec: Video.Codec | None = None) -> list[Video]:
- out = []
- for res in quality:
- cands = [t for t in ladder if t.range == range_ and t.height == res and (codec is None or t.codec == codec)]
- if cands:
- out.append(max(cands, key=lambda t: t.bitrate))
- return out
-
- dv_deliverable = best_per_res(Video.Range.DV)
- sdr_deliverable = [t for t in ladder if t.range == Video.Range.SDR]
-
- final = Tracks.merge_video_selections(hybrid_selected, dv_deliverable + sdr_deliverable)
-
- # No duplicates, and the lowest DV ingredient coexists with the DV deliverables.
- assert len(final) == len({t.id for t in final})
- assert "dv-360" in ids(final) # ingredient retained for hybrid build
- assert {"dv-2160", "dv-1080"} <= ids(final) # standalone DV deliverables
- assert {"hdr10p-2160", "hdr10p-1080"} <= ids(final)
- assert {"sdr-2160", "sdr-1080-avc", "sdr-1080-hevc"} <= ids(final)
diff --git a/tests/tracks/test_mux_default_language.py b/tests/tracks/test_mux_default_language.py
index 407022cdc..3a6ff6e30 100644
--- a/tests/tracks/test_mux_default_language.py
+++ b/tests/tracks/test_mux_default_language.py
@@ -5,7 +5,6 @@ from collections.abc import Callable
from pathlib import Path
import pytest
-from langcodes import Language
from unshackle.core.config import config
from unshackle.core.tracks import Audio, Subtitle, Tracks
@@ -61,17 +60,6 @@ def test_default_subtitle_index(language: str | None, types: list[str], expected
assert Tracks.default_subtitle_index(subtitles, language, types) == expected
-@pytest.mark.parametrize(
- ("audio", "expected"),
- [("en", 1), ("ar", 0), ("fr", 2), (None, 2)],
-)
-def test_a_forced_default_with_no_language_follows_the_audio(audio: str | None, expected: int) -> None:
- kinds = [("ar", "forced"), ("en", "forced"), ("en", "normal")]
- subtitles = [subtitle(i, lang, kind) for i, (lang, kind) in enumerate(kinds)]
- audio_language = Language.get(audio) if audio else None
- assert Tracks.default_subtitle_index(subtitles, None, ["forced", "normal"], audio_language) == expected
-
-
def downloaded_tracks(tmp_path: Path, audio: list[tuple[str, bool]], subtitles: list[tuple[str, str]]) -> Tracks:
tracks = Tracks()
for i, (lang, original) in enumerate(audio):
diff --git a/tests/tracks/test_mux_embedded_audio_metadata.py b/tests/tracks/test_mux_embedded_audio_metadata.py
index caa1f1eac..9d863c8d0 100644
--- a/tests/tracks/test_mux_embedded_audio_metadata.py
+++ b/tests/tracks/test_mux_embedded_audio_metadata.py
@@ -1,11 +1,7 @@
-import json
-from types import SimpleNamespace
-
import pytest
from unshackle.core import binaries
from unshackle.core.tracks import Audio, Tracks, Video
-from unshackle.core.tracks.tracks import file_track_ids
def make_video(track_id: str, **data) -> Video:
@@ -36,18 +32,6 @@ def mux_until_mkvmerge_check(tracks: Tracks) -> None:
tracks.mux("Test Title")
-def test_names_undeclared_video(monkeypatch):
- monkeypatch.setattr(binaries, "MKVToolNix", None)
- video = make_video("v1")
- tracks = Tracks(video)
-
- mux_until_mkvmerge_check(tracks)
-
- assert video.needs_repack
- assert video.data["audio_language"] == "zh"
- assert video.embedded_audio_name() == "Chinese"
-
-
def test_service_declaration_is_preserved(monkeypatch):
monkeypatch.setattr(binaries, "MKVToolNix", None)
declared = make_video("v1", audio_language="th", audio_language_name="Thai [Original]")
@@ -100,17 +84,3 @@ def test_an_audio_track_with_own_stream_only_muxes_without_its_video(tmp_path, m
args = mux_args(Tracks(audio), {"video": 0, "audio": 1})
assert ("--no-video" in args) == own
assert args[args.index("--language") + 1] == ("1:th" if own else "0:th")
-
-
-def test_repack_and_mux_share_the_embedded_audio_name():
- assert make_video("v1", audio_language="zh").embedded_audio_name() == "Chinese"
- assert make_video("v1", audio_language="zh", audio_language_name="Mandarin").embedded_audio_name() == "Mandarin"
-
-
-def test_file_track_ids_reads_the_first_id_of_each_type(monkeypatch, tmp_path):
- tracks = [{"id": 0, "type": "audio"}, {"id": 1, "type": "video"}, {"id": 2, "type": "audio"}]
- reply = SimpleNamespace(stdout=json.dumps({"tracks": tracks}))
- monkeypatch.setattr("unshackle.core.tracks.tracks.subprocess.run", lambda *a, **k: reply)
- assert file_track_ids(tmp_path / "v.ts") == {"audio": 0, "video": 1}
- monkeypatch.setattr("unshackle.core.tracks.tracks.subprocess.run", lambda *a, **k: SimpleNamespace(stdout=""))
- assert file_track_ids(tmp_path / "v.ts") == {"video": 0, "audio": 1}
diff --git a/tests/tracks/test_subtitle_convert.py b/tests/tracks/test_subtitle_convert.py
index d5373c069..829731fd8 100644
--- a/tests/tracks/test_subtitle_convert.py
+++ b/tests/tracks/test_subtitle_convert.py
@@ -79,23 +79,12 @@ def cue_count(path) -> int:
return len(re.findall(r"-->", path.read_text("utf8")))
-def test_resolve_webvtt_to_srt_order():
- chain = [b.name for b in sc.resolve_backends(Codec.WebVTT, Codec.SubRip)]
- assert chain == ["subby", "pysubs2", "pycaption"]
-
-
def test_resolve_ass_to_srt_only_pysubs2_without_subtitleedit():
# subby and pycaption cannot read ASS, so only pysubs2 remains.
chain = [b.name for b in sc.resolve_backends(Codec.SubStationAlphav4, Codec.SubRip)]
assert chain == ["pysubs2"]
-def test_subtitleedit_ranks_first_when_available(monkeypatch):
- monkeypatch.setattr(binaries, "SubtitleEdit", "/usr/bin/seconv")
- chain = [b.name for b in sc.resolve_backends(Codec.WebVTT, Codec.SubRip)]
- assert chain[0] == "subtitleedit"
-
-
def test_styled_ass_to_ttml_vtt_prefers_pysubs2_over_subtitleedit(monkeypatch):
# Measured: SE flattens ASS inline styling to TTML/VTT; pysubs2 keeps i/b/u.
monkeypatch.setattr(binaries, "SubtitleEdit", "/usr/bin/seconv")
@@ -183,14 +172,6 @@ def test_ass_to_ssa_keeps_file_order(tmp_path, monkeypatch):
assert text.index("Sign") < text.index("Hello")
-def test_webvtt_to_srt_conversion(tmp_path, monkeypatch):
- monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
- sub = make_sub(tmp_path, "x.vtt", VTT_SAMPLE, Codec.WebVTT)
- out = sub.convert(Codec.SubRip, forced=True)
- assert sub.codec == Codec.SubRip
- assert cue_count(out) == 2
-
-
SCC_SAMPLE = """Scenarist_SCC V1.0
00:00:00;00 9420 9152 9723 5bc2 4f43 49ce c120 c445 20c2 c152 434f 5d80 9420 942c 942f
@@ -205,11 +186,6 @@ SCC_SAMPLE = """Scenarist_SCC V1.0
"""
-def test_scc_mime_maps_to_the_scc_codec():
- assert Codec.from_mime("x-scc") is Codec.SCC
- assert Codec.from_mime("scc") is Codec.SCC
-
-
@pytest.mark.parametrize(
"sub_format, expected",
[
@@ -231,44 +207,11 @@ def test_scc_converts_to_the_requested_format_or_srt(tmp_path, monkeypatch, sub_
assert "¿Te gusta, Blanca Flor?" in sub.path.read_text("utf8")
-def test_scc_to_webvtt_keeps_the_caption_row(tmp_path, monkeypatch):
- from unshackle.commands.dl import convert_scc
-
- monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
- sub = make_sub(tmp_path, "x.scc", SCC_SAMPLE, Codec.SCC)
- convert_scc(sub, Codec.WebVTT)
- assert "line:" in sub.path.read_text("utf8")
-
-
-def test_scc_as_srt_converts_on_to_ass(tmp_path, monkeypatch):
- from unshackle.commands.dl import convert_scc
-
- monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
- sub = make_sub(tmp_path, "x.scc", SCC_SAMPLE, Codec.SCC)
- convert_scc(sub, Codec.SubStationAlphav4)
- assert sub.convert(Codec.SubStationAlphav4, forced=True).read_text("utf8").count("Dialogue:") == 2
-
-
-def test_scc_without_cc1_captions_warns(tmp_path, monkeypatch, caplog):
- from unshackle.commands.dl import convert_scc
-
- monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
- cc3 = "Scenarist_SCC V1.0\n\n00:00:01:00\t1520 1520 1552 1552 c8e5 ecec ef80 152f 152f\n\n00:00:03:00\t152c 152c\n"
- convert_scc(make_sub(tmp_path, "x.scc", cc3, Codec.SCC), None)
- assert "has no CC1 captions" in caplog.text
-
-
def test_scc_with_a_bad_timecode_is_a_syntax_error():
with pytest.raises(SyntaxError):
Subtitle.parse(b"Scenarist_SCC V1.0\n\n00:00:xx;00\t9420 942f\n", Codec.SCC)
-def test_same_codec_is_noop(tmp_path):
- sub = make_sub(tmp_path, "x.srt", "1\n00:00:01,000 --> 00:00:02,000\nHi\n", Codec.SubRip)
- assert sub.convert(Codec.SubRip) == sub.path
- assert sub.codec == Codec.SubRip
-
-
FONT_ASS = """[Script Info]
ScriptType: v4.00+
@@ -345,16 +288,6 @@ Hello there.
"""
-def test_sdh_stripping_removes_effects_keeps_dialogue(tmp_path, monkeypatch):
- # subby's SDHStripper runs on SRT without SubtitleEdit installed.
- monkeypatch.setattr("unshackle.core.config.config.subtitle", {"sdh_method": "subby"}, raising=False)
- sub = make_sub(tmp_path, "x.srt", SDH_SRT, Codec.SubRip)
- sub.strip_hearing_impaired()
- out = sub.path.read_text("utf8")
- assert "Hello there." in out # real dialogue kept
- assert "door creaks" not in out # bracketed effect removed (subby SDHStripper)
-
-
SDH_ASS = """[Script Info]
ScriptType: v4.00+
@@ -457,30 +390,6 @@ def test_segmented_fttml_joins_a_cue_split_at_a_segment_boundary():
]
-def test_segmented_fttml_parses_and_converts(tmp_path, monkeypatch):
- monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
- frag = (
- ''
- '"
- )
- data = build_stpp_mp4(frag.format(a=1, b=2), frag.format(a=3, b=4))
-
- caption_set = Subtitle.parse(data, Codec.fTTML)
- assert caption_total(caption_set) == 2
-
- seg = tmp_path / "seg.stpp"
- seg.write_bytes(data)
- sub = Subtitle(url="https://example.test/x", language="en", codec=Codec.fTTML)
- sub.path = seg
- # download() converts fTTML -> TTML (only pycaption can read fTTML); then -> SRT.
- sub.convert(Codec.TimedTextMarkupLang)
- assert sub.codec == Codec.TimedTextMarkupLang
- out = sub.convert(Codec.SubRip, forced=True)
- assert cue_count(out) == 2
-
-
def downloaded_subtitle(tmp_path, monkeypatch, codec, data: bytes, descriptor: Track.Descriptor, track_data: dict):
"""A Subtitle whose base download is a no-op, so download() runs only the post-processing on data."""
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
@@ -688,12 +597,3 @@ def test_ttml_parse_raises_no_bs4_warning(data, codec, cues):
with warnings.catch_warnings():
warnings.simplefilter("error", XMLParsedAsHTMLWarning)
assert caption_total(Subtitle.parse(data, codec)) == cues
-
-
-def test_ttml_parse_keeps_a_declaration_inside_the_cue_text():
- cue = ttml_fragment(("00:00:01.000", "00:00:02.000", " there]]>"))
- expected = pycaption.DFXPReader().read(cue)
-
- caption_set = Subtitle.parse((TTML_DECLARATION + cue).encode(), Codec.TimedTextMarkupLang)
-
- assert pycaption.DFXPWriter().write(caption_set) == pycaption.DFXPWriter().write(expected)
diff --git a/tests/tracks/test_subtitle_skip.py b/tests/tracks/test_subtitle_skip.py
index ed1e85b14..c661232f9 100644
--- a/tests/tracks/test_subtitle_skip.py
+++ b/tests/tracks/test_subtitle_skip.py
@@ -12,7 +12,7 @@ from __future__ import annotations
import pytest
-from unshackle.commands.dl import SkippedSubtitle, download_tracks_in_passes
+from unshackle.commands.dl import download_tracks_in_passes
from unshackle.core import process_exit
from unshackle.core.constants import DOWNLOAD_CANCELLED, RunCancel
from unshackle.core.tracks import Audio, Subtitle, Video
@@ -77,28 +77,6 @@ class Harness:
self.skipped.append(track)
-def test_ctrl_c_cancels_the_tracks_still_downloading():
- seen = {}
-
- def run_one(track, _index):
- if track.id == "a":
- raise KeyboardInterrupt
- # a deadline, not a delay: without the cancel this waits it out and records False
- seen[track.id] = DOWNLOAD_CANCELLED.wait(timeout=10)
-
- with pytest.raises(KeyboardInterrupt):
- download_tracks_in_passes(
- [make_video(), make_audio()],
- 2,
- run_one,
- skip_subtitle_errors=False,
- on_subtitle_skipped=lambda track: None,
- )
-
- assert seen == {"v": True}
- assert DOWNLOAD_CANCELLED.is_set() and RunCancel.pressed
-
-
def test_a_failed_track_is_not_a_cancel_of_the_user():
"""A child process that the cancel of the failed track ends can look like Ctrl+C."""
@@ -155,23 +133,6 @@ def test_failed_subtitle_does_not_truncate_video_or_audio():
assert h.skipped == [sub] # the subtitle was recorded as skipped
-def test_good_subtitle_kept_bad_subtitle_skipped():
- video = make_video()
- good, bad = make_subtitle("s-en", "en"), make_subtitle("s-fr", "fr")
- h = Harness(fail_ids={"s-fr"})
-
- download_tracks_in_passes(
- [video, good, bad],
- 4,
- h.run_one,
- skip_subtitle_errors=True,
- on_subtitle_skipped=h.on_subtitle_skipped,
- )
-
- assert "s-en" in h.completed # the available subtitle still downloaded
- assert h.skipped == [bad] # only the failing one was skipped
-
-
def test_subtitle_failure_stays_fatal_without_flag():
"""Default behaviour (flag off) is unchanged: a subtitle failure aborts the title."""
video = make_video()
@@ -206,62 +167,3 @@ def test_cancel_event_is_reset_between_titles():
assert set(h.completed) == {"v", "a"}
assert h.early_returned == []
-
-
-def test_cancel_event_cleared_after_failed_final_subtitle():
- """A subtitle failing in the last pass leaves the event clear on exit, not set."""
- video = make_video()
- sub = make_subtitle("s-he", "he")
- h = Harness(fail_ids={"s-he"})
-
- download_tracks_in_passes(
- [video, sub],
- 4,
- h.run_one,
- skip_subtitle_errors=True,
- on_subtitle_skipped=h.on_subtitle_skipped,
- )
-
- assert not DOWNLOAD_CANCELLED.is_set() # the helper clears it on exit for any later code
-
-
-def test_all_subtitles_skipped_video_audio_kept():
- """Every subtitle failing must not stop the video/audio, and each is recorded."""
- video, audio = make_video(), make_audio()
- s1, s2 = make_subtitle("s-en", "en"), make_subtitle("s-he", "he")
- h = Harness(fail_ids={"s-en", "s-he"})
-
- download_tracks_in_passes(
- [video, audio, s1, s2],
- 4,
- h.run_one,
- skip_subtitle_errors=True,
- on_subtitle_skipped=h.on_subtitle_skipped,
- )
-
- assert set(h.completed) == {"v", "a"} # both fatal tracks survived
- assert {t.id for t in h.skipped} == {"s-en", "s-he"} # every failing subtitle recorded
-
-
-def test_duplicate_language_subtitles_distinguished_by_id():
- """Forced + SDH share a language; a failure of each must be distinguishable by track id -
- the reason ``SkippedSubtitle`` carries ``id`` and not just ``language``."""
- forced, sdh = make_subtitle("en-forced", "en"), make_subtitle("en-sdh", "en")
- h = Harness(fail_ids={"en-forced", "en-sdh"})
-
- download_tracks_in_passes(
- [make_video(), forced, sdh],
- 4,
- h.run_one,
- skip_subtitle_errors=True,
- on_subtitle_skipped=h.on_subtitle_skipped,
- )
-
- assert [t.id for t in h.skipped] == ["en-forced", "en-sdh"] # same language, distinct ids
-
-
-def test_skipped_subtitle_contract():
- """Pin the public ``skipped_subtitles`` entry shape - #113 serializes it into the job, so a
- field rename/removal here is a breaking change and must fail a test."""
- assert set(SkippedSubtitle.__annotations__) == {"id", "language", "title"}
- assert SkippedSubtitle.__required_keys__ == frozenset({"id", "language", "title"})
diff --git a/tests/tracks/test_subtitle_sort.py b/tests/tracks/test_subtitle_sort.py
index c55c7442b..0a9c89320 100644
--- a/tests/tracks/test_subtitle_sort.py
+++ b/tests/tracks/test_subtitle_sort.py
@@ -158,31 +158,12 @@ def many() -> Tracks:
return t
-def test_priority_orders_listed_then_rest_alphabetically(many: Tracks) -> None:
- many.sort_subtitles(by_language=["en", "es", "fr"], group_by="language")
- assert langs(many) == ["en", "es", "fr", "ar", "bg", "ja"]
-
-
def test_priority_outranks_the_original_language(many: Tracks) -> None:
# "all" resolves to the original language (ja), which must stay below the named ones
many.sort_subtitles(by_language=["en", "es", "all"], group_by="language")
assert langs(many) == ["en", "es", "ja", "ar", "bg", "fr"]
-def test_priority_matches_regional_variants() -> None:
- t = Tracks()
- t.add([sub("ar"), sub("en-US"), sub("es-419"), sub("ja")])
- t.sort_subtitles(by_language=["en", "es"], group_by="language")
- assert langs(t) == ["en-US", "es-419", "ar", "ja"]
-
-
-def test_priority_overlapping_entries_are_harmless() -> None:
- t = Tracks()
- t.add([sub("ar"), sub("en-GB"), sub("en-US"), sub("es"), sub("ja")])
- t.sort_subtitles(by_language=["en", "en-US", "es"], group_by="language")
- assert langs(t) == ["en-US", "en-GB", "es", "ar", "ja"]
-
-
@pytest.mark.parametrize("group_by", ["language", "type"])
def test_a_regional_priority_outranks_its_sibling(group_by: str) -> None:
t = Tracks()
@@ -191,23 +172,12 @@ def test_a_regional_priority_outranks_its_sibling(group_by: str) -> None:
assert langs(t) == ["en-US", "en-GB", "fr"]
-def test_no_priority_leaves_order_unchanged(many: Tracks) -> None:
- many.sort_subtitles(by_language=[], group_by="language")
- assert langs(many) == ["ar", "bg", "en", "es", "fr", "ja"]
-
-
@pytest.mark.parametrize("token", ["all", "best"])
def test_magic_token_alone_floats_the_original_language(many: Tracks, token: str) -> None:
many.sort_subtitles(by_language=[token], group_by="language")
assert langs(many) == ["ja", "ar", "bg", "en", "es", "fr"]
-@pytest.mark.parametrize("token", ["all", "best"])
-def test_priority_outranks_either_magic_token(many: Tracks, token: str) -> None:
- many.sort_subtitles(by_language=["en", "es", token], group_by="language")
- assert langs(many) == ["en", "es", "ja", "ar", "bg", "fr"]
-
-
@pytest.fixture
def regionals() -> Tracks:
t = Tracks()
@@ -215,11 +185,6 @@ def regionals() -> Tracks:
return t
-def test_fuzzy_priority_floats_regional_variants(regionals: Tracks) -> None:
- regionals.sort_subtitles(by_language=["en"], group_by="language")
- assert langs(regionals) == ["en", "en-GB", "en-US", "ar", "ja"]
-
-
def test_exact_priority_floats_only_the_named_tag(regionals: Tracks) -> None:
# CLDR rates en/en-US at distance 0, so exact mode needs the RFC 4647 string preference
# to hold en-US back; without it en-US floats and en-GB does not.
@@ -234,13 +199,6 @@ def test_exact_priority_still_falls_back_when_no_tag_is_string_equal() -> None:
assert langs(t) == ["cmn", "ar", "ja"]
-@pytest.mark.parametrize("exact", [False, True])
-def test_unparseable_priority_entry_is_ignored(many: Tracks, exact: bool) -> None:
- # a config typo in language_priority must not crash the sort
- many.sort_subtitles(by_language=["en", "engrish", "f", ""], group_by="language", exact_match=exact)
- assert langs(many) == ["en", "ar", "bg", "es", "fr", "ja"]
-
-
def test_a_bare_audio_priority_sorts_the_meant_variant_then_its_other_forms() -> None:
from unshackle.core.tracks import Audio
diff --git a/tests/tracks/test_track_language_names.py b/tests/tracks/test_track_language_names.py
index 10ac3487a..7f7eff2b9 100644
--- a/tests/tracks/test_track_language_names.py
+++ b/tests/tracks/test_track_language_names.py
@@ -7,7 +7,7 @@ from rich.text import Text
from unshackle.core.config import config
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
-from unshackle.core.utilities import language_name, multi_script_languages, with_script
+from unshackle.core.utilities import with_script
def sub(lang: str, name: str | None = None, sdh: bool = False, original: bool = False) -> Subtitle:
@@ -22,11 +22,6 @@ def sub(lang: str, name: str | None = None, sdh: bool = False, original: bool =
)
-def test_multi_script_languages_come_from_cldr() -> None:
- assert {"zh", "yue", "sr"} <= multi_script_languages()
- assert not {"en", "pt", "ja"} & multi_script_languages()
-
-
@pytest.mark.parametrize(
("tag", "expected"),
[
@@ -50,66 +45,6 @@ def test_with_script(tag: str, expected: str) -> None:
assert str(with_script(Language.get(tag))) == expected
-@pytest.mark.parametrize(
- ("tag", "expected"),
- [
- ("zh-Hant-TW", "Chinese (Traditional)"),
- ("zh-Hans-CN", "Chinese (Simplified)"),
- ("zh-Hant-HK", "Chinese (Traditional, Hong Kong)"),
- ("zh-TW", "Chinese (Taiwan)"),
- ("pt-BR", "Portuguese"),
- ("pt-PT", "Portuguese (Portugal)"),
- ("en-US", "English"),
- ("en-GB", "English (United Kingdom)"),
- ("ja-JP", "Japanese"),
- ("fr-CA", "French (Canada)"),
- ("ar-001", "Arabic"),
- ("es-419", "Spanish (Latin America)"),
- ("en", "English"),
- ("de-DE", "German"),
- ("en-ZZ", "English"),
- ("en-XA", "English"),
- ("en-Zzzz", "English"),
- ("sq-XK", "Albanian (Kosovo)"),
- ("mn-Mong-CN", "Mongolian (China)"),
- ("und", None),
- ("qaa", None),
- ("x-foo", None),
- ],
-)
-def test_language_name(tag: str, expected: str | None) -> None:
- assert language_name(Language.get(tag)) == expected
-
-
-@pytest.mark.parametrize(
- ("tag", "expected"),
- [
- ("zh-Hant-TW", "中文(繁體)"),
- ("zh-Hans-CN", "中文(简体)"),
- ("zh-Hant-HK", "中文(繁體,香港)"),
- ("zh-Hans-MO", "中文(简体,澳门)"),
- ("zh-TW", "中文(台灣)"),
- ("zh-HK", "中文(香港)"),
- ("cmn-Hant", "中文(繁體)"),
- ("yue-Hant", "粵語(繁體)"),
- ("sr-ME", "Srpski (Crna Gora)"),
- ("ka", "ქართული"),
- ("hy", "Հայերեն"),
- ("pt-BR", "Português"),
- ("pt-PT", "Português (Portugal)"),
- ("es-419", "Español (Latinoamérica)"),
- ("sr-Latn-ME", "Srpski (latinica, Crna Gora)"),
- ("ja-JP", "日本語"),
- ("en-GB", "English (United Kingdom)"),
- ("en-HK", "English (Hong Kong)"),
- ("qaa", None),
- ],
-)
-def test_native_language_name(tag: str, expected: str | None, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(config, "muxing", {"track_names": "native"})
- assert language_name(Language.get(tag)) == expected
-
-
def test_native_subtitle_name_keeps_the_flag(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "muxing", {"track_names": "native"})
assert sub("zh-TW", sdh=True).get_track_name() == "中文(繁體) (SDH)"
@@ -147,12 +82,6 @@ def test_original_label_is_not_added_twice(name: str, monkeypatch: pytest.Monkey
assert sub("ja", name=name, original=True).get_track_name() == name
-@pytest.mark.parametrize("label", [True, 1, ["Original"], " "])
-def test_original_label_that_is_not_text_is_ignored(label: object, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(config, "muxing", {"original_label": label, "track_names": "none"})
- assert sub("ja", sdh=True, original=True).get_track_name() == "SDH"
-
-
def test_embedded_audio_takes_the_original_label(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "muxing", {"original_label": "[Original]"})
video = Video(id_="v", url="https://x/v", codec=Video.Codec.AVC, language="ja", is_original_lang=True)
@@ -175,10 +104,6 @@ def test_subtitle_names_and_tags_the_script_but_keeps_its_language() -> None:
assert str(track.language) == "zh-TW"
-def test_subtitle_flag_follows_the_default_name() -> None:
- assert sub("zh-CN", sdh=True).get_track_name() == "Chinese (Simplified) (SDH)"
-
-
def test_audio_gets_no_script() -> None:
track = Audio(id_="a", url="https://x/a", codec=Audio.Codec.AAC, language="zh-TW", bitrate=1)
assert track.get_track_name() == "Chinese (Taiwan)"
@@ -209,12 +134,6 @@ def test_mkvmerge_gets_the_subtitle_script_and_name(tmp_path: Path, mux_args: Ca
assert last_option("a.mp4", "--language") == "0:zh-TW"
-def test_the_default_name_follows_a_later_language_change() -> None:
- track = sub("yue")
- track.language = Language.get("zh-Hant")
- assert track.get_track_name() == "Chinese (Traditional)"
-
-
def test_a_language_assigned_as_text_later_is_parsed() -> None:
track = sub("pt")
track.language = "pt-PT"
diff --git a/tests/tracks/test_track_name_region.py b/tests/tracks/test_track_name_region.py
deleted file mode 100644
index 0de53d5d5..000000000
--- a/tests/tracks/test_track_name_region.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from langcodes import Language
-
-from unshackle.core.tracks import Audio, Tracks
-
-
-def audio(lang: str, bitrate: int, id_: str) -> Audio:
- return Audio(url=f"http://x/{id_}", id_=id_, language=lang, codec=Audio.Codec.AAC, bitrate=bitrate, channels=2.0)
-
-
-def test_naming_a_track_keeps_its_region() -> None:
- track = audio("fr-FR", 128000, "a1")
- assert track.name is None
- assert track.language.territory == "FR"
- assert Language.get("fr-FR").territory == "FR"
-
-
-def test_a_regional_request_picks_its_own_variant_over_a_higher_bitrate_sibling() -> None:
- tracks = [audio("fr-FR", 128000, "a1"), audio("fr-CA", 192000, "a2")]
- assert [str(t.language) for t in Tracks.by_language(tracks, ["fr-FR"])] == ["fr-FR"]
diff --git a/tests/tracks/test_webvtt_merge.py b/tests/tracks/test_webvtt_merge.py
index f7fe2cf12..efef9c189 100644
--- a/tests/tracks/test_webvtt_merge.py
+++ b/tests/tracks/test_webvtt_merge.py
@@ -113,13 +113,6 @@ def test_merge_dedupes_repeated_style_blocks_before_cues():
assert out.index("STYLE") < out.index("-->")
-def test_merge_skips_malformed_timing_line():
- vtt = "WEBVTT\n\ngarbage --> not-a-time\nBroken\n\n00:00:01.000 --> 00:00:02.000\nGood\n"
- out = merge_segmented_webvtt(vtt)
- assert "Good" in out
- assert "Broken" not in out
-
-
def test_rebase_moves_live_clock_cues_to_zero():
vtt = "WEBVTT\n\n498024:05:44.300 --> 498024:05:44.829 line:0.01%\nText\n"
out = rebase_webvtt(vtt, timestamp_ms("498024:00:14.700"))
@@ -133,11 +126,6 @@ def test_rebase_moves_cues_when_the_first_is_carried_over_from_before_the_offset
assert "00:03:48.598 --> 00:03:48.698\nNext" in out
-def test_rebase_leaves_a_later_period_with_a_small_offset_alone():
- vtt = "WEBVTT\n\n00:00:05.000 --> 00:00:12.000\nText\n"
- assert rebase_webvtt(vtt, 10_000, 2000) == vtt
-
-
def test_rebase_leaves_presentation_time_cues_alone():
# a second pass, or a VOD period with a non-zero offset, must not shift again
vtt = "WEBVTT\n\n00:05:29.600 --> 00:05:30.129\nText\n"
diff --git a/tests/tracks/test_webvtt_timestamp_map.py b/tests/tracks/test_webvtt_timestamp_map.py
index 1f6429992..82398b11a 100644
--- a/tests/tracks/test_webvtt_timestamp_map.py
+++ b/tests/tracks/test_webvtt_timestamp_map.py
@@ -9,14 +9,6 @@ def test_strips_timestamp_map_keeps_cues():
assert out.startswith("WEBVTT\n")
-def test_strips_lowercase_timestamp_map():
- # SubtitleEdit honours the header case-insensitively, so the strip must too
- text = "WEBVTT\nx-timestamp-map=MPEGTS:900000,LOCAL:00:00:00.000\n\n00:00:22.690 --> 00:00:24.710\nHi\n"
- out = Subtitle.strip_webvtt_timestamp_map(text)
- assert "x-timestamp-map" not in out.lower()
- assert "00:00:22.690 --> 00:00:24.710" in out
-
-
def test_no_timestamp_map_is_untouched():
text = "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nHi\n"
assert Subtitle.strip_webvtt_timestamp_map(text) == text