mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-06 07:55:10 +00:00
test: delete slow, timing-based and redundant tests
This commit is contained in:
@@ -14,7 +14,6 @@ import pytest
|
||||
|
||||
import unshackle.core.cdm as cdm_mod
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.cdm import loader
|
||||
from unshackle.core.config import config
|
||||
|
||||
|
||||
@@ -61,19 +60,6 @@ def test_repeated_calls_build_the_cdm_once(builds, monkeypatch) -> None:
|
||||
assert builds == [("device_a", "EXAMPLE")]
|
||||
|
||||
|
||||
def test_the_title_loop_guard_sees_the_same_object(builds, monkeypatch) -> None:
|
||||
"""The call site keeps its CDM when ``get_cdm`` returns what it already holds."""
|
||||
monkeypatch.setattr(config, "cdm", {"EXAMPLE": "device_a"})
|
||||
runner = make_dl()
|
||||
|
||||
held = runner.get_cdm("EXAMPLE", "default")
|
||||
for _ in range(3):
|
||||
quality_based_cdm = runner.get_cdm("EXAMPLE", "default", drm="widevine", quality=2160)
|
||||
assert not (quality_based_cdm and quality_based_cdm != held)
|
||||
|
||||
assert len(builds) == 1
|
||||
|
||||
|
||||
def test_a_different_service_gets_its_own_cdm(builds, monkeypatch) -> None:
|
||||
"""A CDM is built with its ``service_name``, so two services must not share one."""
|
||||
monkeypatch.setattr(config, "cdm", {"EXAMPLE": "device_a", "OTHER": "device_a"})
|
||||
@@ -86,18 +72,6 @@ def test_a_different_service_gets_its_own_cdm(builds, monkeypatch) -> None:
|
||||
assert builds == [("device_a", "EXAMPLE"), ("device_a", "OTHER")]
|
||||
|
||||
|
||||
def test_a_different_profile_gets_its_own_cdm(builds, monkeypatch) -> None:
|
||||
monkeypatch.setattr(config, "cdm", {"EXAMPLE": {"one": "device_one", "two": "device_two"}})
|
||||
runner = make_dl()
|
||||
|
||||
one = runner.get_cdm("EXAMPLE", "one")
|
||||
two = runner.get_cdm("EXAMPLE", "two")
|
||||
|
||||
assert one is not two
|
||||
assert runner.get_cdm("EXAMPLE", "one") is one
|
||||
assert builds == [("device_one", "EXAMPLE"), ("device_two", "EXAMPLE")]
|
||||
|
||||
|
||||
def test_quality_selection_reuses_the_device_it_resolves_to(builds, monkeypatch) -> None:
|
||||
"""Two spellings of the same device share one CDM; a different device does not."""
|
||||
monkeypatch.setattr(config, "cdm", {"EXAMPLE": {">=1080": "device_hd", "<1080": "device_sd"}})
|
||||
@@ -120,25 +94,3 @@ def test_an_override_is_cached_under_the_name_it_resolves_to(builds, monkeypatch
|
||||
|
||||
assert runner.get_cdm("EXAMPLE", "default") is override
|
||||
assert builds == [("device_b", "EXAMPLE")]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def leaked_shadow(monkeypatch) -> None:
|
||||
"""Reproduce the residue that a ``setattr`` on the CDM package leaves behind.
|
||||
|
||||
``load_cdm`` reaches the package only through its lazy ``__getattr__``. A ``setattr`` on
|
||||
the package writes the real function into the package dict when it undoes, which shadows
|
||||
``__getattr__`` for the rest of the process. Two remote tests do exactly that.
|
||||
"""
|
||||
monkeypatch.setitem(cdm_mod.__dict__, "load_cdm", loader.load_cdm)
|
||||
|
||||
|
||||
def test_a_shadowed_package_attribute_still_reaches_the_stub(leaked_shadow, builds, monkeypatch) -> None:
|
||||
"""The stub intercepts ``get_cdm`` whatever an earlier test left on the CDM package."""
|
||||
monkeypatch.setattr(config, "cdm", {"EXAMPLE": "device_a"})
|
||||
runner = make_dl()
|
||||
|
||||
cdm = runner.get_cdm("EXAMPLE", "default")
|
||||
|
||||
assert isinstance(cdm, StubCdm)
|
||||
assert builds == [("device_a", "EXAMPLE")]
|
||||
|
||||
@@ -45,21 +45,6 @@ def test_a_duplicate_key_blocks_a_write(config_file: Path) -> None:
|
||||
assert config_file.read_text(encoding="utf-8") == original
|
||||
|
||||
|
||||
def test_a_valid_config_still_reads_a_key(config_file: Path) -> None:
|
||||
config_file.write_text("theme: rainbow\n", encoding="utf-8")
|
||||
result = CliRunner().invoke(cfg_module.cfg, ["theme"])
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "rainbow" in result.output
|
||||
|
||||
|
||||
def test_a_duplicate_only_ruamel_sees_still_gives_its_line(config_file: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||
config_file.write_text("a: 1\n1: x\n0x1: y\n", encoding="utf-8")
|
||||
with caplog.at_level(logging.WARNING):
|
||||
result = CliRunner().invoke(cfg_module.cfg, ["a"])
|
||||
assert result.exit_code == 1
|
||||
assert caplog.messages == [f"{config_file}: duplicate key on line 3. Unshackle uses the later one."]
|
||||
|
||||
|
||||
def test_lowercase_true_and_false_are_written_as_booleans_and_no_stays_a_language(config_file: Path) -> None:
|
||||
config_file.write_text("theme: rainbow\n", encoding="utf-8")
|
||||
for key, value in (("wide_output", "false"), ("debug_requests", "TRUE"), ("lang", "no")):
|
||||
|
||||
@@ -5,7 +5,6 @@ from typing import Any
|
||||
|
||||
import click
|
||||
import pytest
|
||||
import rich_click
|
||||
from click.testing import CliRunner
|
||||
from pyplayready import main as prd_upstream
|
||||
from pywidevine import main as wvd_upstream
|
||||
@@ -35,59 +34,6 @@ def files(folder: Path, *names: str) -> Path:
|
||||
return folder
|
||||
|
||||
|
||||
def test_prd_new_from_a_folder_passes_its_files_and_saves_into_the_folder(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
folder = files(tmp_path / "dev", "zgpriv.dat", "bgroupcert.dat")
|
||||
calls = record(monkeypatch, prd_upstream, "create_device")
|
||||
|
||||
result = CliRunner().invoke(prd_module.prd, ["new", str(folder)])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert calls == [
|
||||
{
|
||||
"group_key": folder / "zgpriv.dat",
|
||||
"protected_group_key": None,
|
||||
"group_certificate": folder / "bgroupcert.dat",
|
||||
"encryption_key": None,
|
||||
"signing_key": None,
|
||||
"output": folder,
|
||||
}
|
||||
]
|
||||
assert set(calls[0]) == names(prd_upstream, "create_device")
|
||||
|
||||
|
||||
def test_prd_new_from_two_paths_passes_the_keys_and_output(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
src = files(tmp_path, "key.dat", "cert.dat", "enc.dat", "sig.dat")
|
||||
monkeypatch.setattr(config.directories, "prds", tmp_path / "PRDs")
|
||||
calls = record(monkeypatch, prd_upstream, "create_device")
|
||||
|
||||
result = CliRunner().invoke(
|
||||
prd_module.prd,
|
||||
[
|
||||
"new",
|
||||
str(src / "key.dat"),
|
||||
str(src / "cert.dat"),
|
||||
"-e",
|
||||
str(src / "enc.dat"),
|
||||
"-s",
|
||||
str(src / "sig.dat"),
|
||||
"-o",
|
||||
str(tmp_path / "out.prd"),
|
||||
],
|
||||
)
|
||||
default = CliRunner().invoke(prd_module.prd, ["new", str(src / "key.dat"), str(src / "cert.dat")])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert default.exit_code == 0, default.output
|
||||
assert calls[1]["output"] == tmp_path / "PRDs"
|
||||
assert calls[0]["group_key"] == src / "key.dat"
|
||||
assert calls[0]["group_certificate"] == src / "cert.dat"
|
||||
assert calls[0]["encryption_key"] == src / "enc.dat"
|
||||
assert calls[0]["signing_key"] == src / "sig.dat"
|
||||
assert calls[0]["output"] == tmp_path / "out.prd"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("args", "message"),
|
||||
[
|
||||
@@ -111,53 +57,6 @@ def test_prd_new_refuses_bad_paths_before_the_upstream_command(
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_prd_reprovision_passes_its_arguments(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
device = files(tmp_path, "d.prd") / "d.prd"
|
||||
calls = record(monkeypatch, prd_upstream, "reprovision_device")
|
||||
|
||||
result = CliRunner().invoke(prd_module.prd, ["reprovision", str(device), "-o", str(tmp_path / "new.prd")])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert calls == [{"prd_path": device, "encryption_key": None, "signing_key": None, "output": tmp_path / "new.prd"}]
|
||||
assert set(calls[0]) == names(prd_upstream, "reprovision_device")
|
||||
|
||||
|
||||
def test_prd_test_sends_the_upstream_content_key_type(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
device = files(tmp_path, "d.prd") / "d.prd"
|
||||
calls = record(monkeypatch, prd_upstream, "test")
|
||||
|
||||
result = CliRunner().invoke(prd_module.prd, ["test", str(device), "-c", "AESCBC", "-sl", "3000"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert calls == [{"device": device, "ckt": "AES128BitCBC", "security_level": "3000"}]
|
||||
ckt = next(param for param in prd_upstream.test.params if param.name == "ckt")
|
||||
assert set(prd_module.CONTENT_KEY_TYPES.values()) == set(ckt.type.choices)
|
||||
assert set(calls[0]) == names(prd_upstream, "test")
|
||||
|
||||
|
||||
def test_prd_lists_the_upstream_export_and_inspect_commands() -> None:
|
||||
assert prd_module.prd.commands["export"] is prd_upstream.export_device
|
||||
assert prd_module.prd.commands["inspect"] is prd_upstream.inspect
|
||||
|
||||
|
||||
def test_wvd_dump_exports_each_device_and_resolves_a_bare_name_in_the_wvds_directory(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(config.directories, "wvds", files(tmp_path / "WVDs", "example.wvd"))
|
||||
monkeypatch.chdir(tmp_path)
|
||||
other = files(tmp_path / "elsewhere", "other.wvd") / "other.wvd"
|
||||
calls = record(monkeypatch, wvd_upstream, "export_device")
|
||||
|
||||
result = CliRunner().invoke(wvd_module.wvd, ["dump", "example", str(other), "out"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert calls == [
|
||||
{"wvd_path": tmp_path / "WVDs" / "example.wvd", "out_dir": Path("out")},
|
||||
{"wvd_path": other, "out_dir": Path("out")},
|
||||
]
|
||||
assert set(calls[0]) == names(wvd_upstream, "export_device")
|
||||
|
||||
|
||||
def test_wvd_dump_names_a_missing_device_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(config.directories, "wvds", tmp_path / "WVDs")
|
||||
calls = record(monkeypatch, wvd_upstream, "export_device")
|
||||
@@ -167,18 +66,3 @@ def test_wvd_dump_names_a_missing_device_path(tmp_path: Path, monkeypatch: pytes
|
||||
assert isinstance(result.exception, click.UsageError)
|
||||
assert str(tmp_path / "WVDs" / "missing.wvd") in result.exception.message
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_ctx_invoke_runs_a_command_of_another_package_in_a_sub_context() -> None:
|
||||
seen: list[tuple[str | None, int]] = []
|
||||
foreign = rich_click.RichCommand(
|
||||
"foreign",
|
||||
params=[click.Option(["--value"], type=int, default=5)],
|
||||
callback=click.pass_context(lambda ctx, value: seen.append((ctx.info_name, value))),
|
||||
)
|
||||
outer = click.Command("outer", callback=lambda: click.get_current_context().invoke(foreign))
|
||||
|
||||
result = CliRunner().invoke(outer)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert seen == [("foreign", 5)]
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""The free-space preflight warns before the downloads when the temp volume cannot hold a title's tracks."""
|
||||
|
||||
import threading
|
||||
import time
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
@@ -11,14 +9,13 @@ import m3u8
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from tests.lang_selection import test_kind_only_selection as harness
|
||||
from unshackle.commands import dl as dl_module
|
||||
from unshackle.commands.dl import DiskCheck
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.manifests import DASH, HLS, ISM
|
||||
from unshackle.core.tracks import Audio, Subtitle, Tracks
|
||||
from unshackle.core.tracks import Audio, Tracks
|
||||
from unshackle.core.tracks.track import Track
|
||||
from unshackle.core.utils.bitrate import manifest_seconds, playlist_size
|
||||
from unshackle.core.utils.bitrate import manifest_seconds
|
||||
|
||||
GB = 1_000_000_000
|
||||
|
||||
@@ -95,20 +92,6 @@ def test_a_temp_volume_too_small_for_twice_the_tracks_gets_one_warning_line(
|
||||
assert line == f"Temp volume {tmp_path} has 3.1 GB free, the selected tracks need about 15.0 GB"
|
||||
|
||||
|
||||
def test_enough_free_space_gives_no_warning(free_space: list[int]) -> None:
|
||||
free_space[0] = 15 * GB
|
||||
|
||||
assert low_disk_warning(dash_tracks(mpd(period()))) is None
|
||||
|
||||
|
||||
def test_hls_tracks_count_nothing_before_their_playlist_is_read(free_space: list[int]) -> None:
|
||||
free_space[0] = 0
|
||||
tracks = HLS.from_text(HLS_MASTER, "https://cdn.example/x.m3u8").to_tracks("en")
|
||||
|
||||
assert tracks.videos and manifest_seconds(tracks.videos[0]) is None
|
||||
assert low_disk_warning(tracks) is None
|
||||
|
||||
|
||||
def test_a_dash_track_counts_only_its_content_periods() -> None:
|
||||
manifest = mpd(period('id="ad" duration="PT10M"') + period('id="main" duration="PT50M"'))
|
||||
track = DASH.from_text(manifest, "https://cdn.example/x.mpd").to_tracks("en").videos[0]
|
||||
@@ -117,21 +100,6 @@ def test_a_dash_track_counts_only_its_content_periods() -> None:
|
||||
assert manifest_seconds(track) == 3000
|
||||
|
||||
|
||||
def test_a_dash_track_skips_a_period_that_does_not_carry_it() -> None:
|
||||
other = period('id="b" duration="PT30M"').replace('width="3840" height="2160"', 'width="1920" height="1080"')
|
||||
manifest = mpd(period('id="a" duration="PT30M"') + other)
|
||||
video = dash_tracks(manifest).videos[0]
|
||||
|
||||
assert video.height == 2160
|
||||
assert manifest_seconds(video) == 1800
|
||||
|
||||
|
||||
def test_a_duration_the_parser_cannot_read_gives_no_warning(free_space: list[int]) -> None:
|
||||
free_space[0] = 0
|
||||
|
||||
assert low_disk_warning(dash_tracks(mpd(period(), total="P0DT1H"))) is None
|
||||
|
||||
|
||||
def test_a_dash_period_of_unknown_length_takes_the_presentation_length() -> None:
|
||||
manifest = mpd(period('id="a"') + period('id="b"'), total="PT1H")
|
||||
|
||||
@@ -168,19 +136,6 @@ def test_an_unreadable_temp_volume_gives_no_warning(free_space: list[int], monke
|
||||
assert low_disk_warning(dash_tracks(mpd(period()))) is None
|
||||
|
||||
|
||||
def test_dl_logs_the_warning_once_per_title_and_not_with_skip_dl(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
monkeypatch.setattr(dl_module, "DiskCheck", lambda tracks, warn: warn("Temp volume is short"))
|
||||
|
||||
harness.run(monkeypatch, caplog, {1: {}, 2: {}}, to_end=True, no_mux=True)
|
||||
assert caplog.text.count("Temp volume is short") == 2
|
||||
|
||||
caplog.clear()
|
||||
harness.run(monkeypatch, caplog, {1: {}}, to_end=True, skip_dl=True)
|
||||
assert "Temp volume is short" not in caplog.text
|
||||
|
||||
|
||||
def test_an_hls_track_warns_once_when_its_playlist_is_read(free_space: list[int], tmp_path: Path) -> None:
|
||||
free_space[0] = 3_100_000_000
|
||||
video = HLS.from_text(HLS_MASTER, "https://cdn.example/x.m3u8").to_tracks("en").videos[0]
|
||||
@@ -206,38 +161,6 @@ def test_a_mixed_title_counts_each_track_once_against_one_free_space_reading(
|
||||
assert lines == [f"Temp volume {tmp_path} has 20.0 GB free, the selected tracks need about 21.0 GB"]
|
||||
|
||||
|
||||
def test_a_second_worker_waits_for_the_first_and_gives_no_second_warning(free_space: list[int]) -> None:
|
||||
free_space[0] = GB
|
||||
check, lines = new_check()
|
||||
second_started = threading.Event()
|
||||
|
||||
def first_size() -> float:
|
||||
assert second_started.wait(5)
|
||||
return 2 * GB
|
||||
|
||||
second = threading.Thread(target=lambda: (second_started.set(), check.add(lambda: 2 * GB)))
|
||||
first = threading.Thread(target=check.add, args=(first_size,))
|
||||
first.start()
|
||||
deadline = time.monotonic() + 5
|
||||
while not check.lock.locked() and time.monotonic() < deadline:
|
||||
time.sleep(0.001)
|
||||
second.start()
|
||||
first.join(5)
|
||||
second.join(5)
|
||||
|
||||
assert len(lines) == 1
|
||||
|
||||
|
||||
def test_a_subtitle_counts_nothing(free_space: list[int]) -> None:
|
||||
free_space[0] = 0
|
||||
check, lines = new_check()
|
||||
subtitle = Subtitle(url="https://cdn.example/s.m3u8", language="en", codec=Subtitle.Codec.WebVTT)
|
||||
|
||||
check.add_segments(subtitle, media_segments(3, byterange="1000000000"))
|
||||
|
||||
assert lines == []
|
||||
|
||||
|
||||
def test_an_estimate_error_ends_the_check(free_space: list[int]) -> None:
|
||||
free_space[0] = 0
|
||||
check, lines = new_check()
|
||||
@@ -248,20 +171,6 @@ def test_an_estimate_error_ends_the_check(free_space: list[int]) -> None:
|
||||
assert lines == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("bitrate", "segments", "size"),
|
||||
[
|
||||
(16_000_000, media_segments(3, byterange="1000@0"), 3000),
|
||||
(16_000_000, media_segments(2, byterange="1000@0") + media_segments(1), 16_000_000 * 18 / 8),
|
||||
(8, media_segments(1, byterange="x"), 6),
|
||||
(None, media_segments(3), 0),
|
||||
],
|
||||
ids=["byte ranges", "a segment without a range", "an unreadable range", "no bitrate"],
|
||||
)
|
||||
def test_playlist_size(bitrate: int | None, segments: list[Any], size: float) -> None:
|
||||
assert playlist_size(bitrate, segments) == size
|
||||
|
||||
|
||||
def test_the_hls_step_hands_over_its_wanted_segments_before_any_segment_downloads(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
@@ -293,25 +202,3 @@ def test_the_hls_step_hands_over_its_wanted_segments_before_any_segment_download
|
||||
|
||||
assert handed == [(track, ["seg.m4s"])]
|
||||
assert not list(tmp_path.glob("*_segments/*"))
|
||||
|
||||
|
||||
def test_dl_hands_each_track_download_the_check_of_its_title(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
class Recorder(DiskCheck):
|
||||
def __init__(self, tracks: Tracks, warn: Any) -> None:
|
||||
checks.append(self)
|
||||
|
||||
checks: list[Recorder] = []
|
||||
handed: list[Any] = []
|
||||
monkeypatch.setattr(dl_module, "DiskCheck", Recorder)
|
||||
monkeypatch.setattr(Track, "download", lambda self, *a, **k: handed.append(k["on_segments"]))
|
||||
|
||||
def download_all(tracks: Any, workers: int, run_one: Any, **_: Any) -> None:
|
||||
for i, track in enumerate(tracks):
|
||||
run_one(track, i)
|
||||
|
||||
harness.run(monkeypatch, caplog, {1: {}}, to_end=True, no_mux=True, download=download_all)
|
||||
|
||||
assert len(checks) == 1 and len(handed) == 3
|
||||
assert all(on_segments == checks[0].add_segments for on_segments in handed)
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import click
|
||||
import pytest
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.commands.serve import serve
|
||||
|
||||
CLI_REFERENCE = Path(__file__).parents[2] / "docs" / "guide" / "cli-reference.md"
|
||||
|
||||
COMMANDS = [pytest.param("dl", dl.cli, id="dl"), pytest.param("serve", serve, id="serve")]
|
||||
|
||||
|
||||
def section(command: str) -> str:
|
||||
text = CLI_REFERENCE.read_text(encoding="utf-8")
|
||||
start = text.index(f"## `{command}`")
|
||||
return text[start : text.index("\n## ", start)]
|
||||
|
||||
|
||||
def table_flags(command: str) -> set[str]:
|
||||
"""The flags in the first cell of each table row of one command's section of the CLI reference."""
|
||||
return {
|
||||
flag
|
||||
for line in section(command).splitlines()
|
||||
if line.startswith("|")
|
||||
for flag in re.findall(r"`(--?[a-zA-Z][\w-]*)[` ]", line.split("|")[1])
|
||||
}
|
||||
|
||||
|
||||
def option_flags(command: click.Command) -> set[str]:
|
||||
return {
|
||||
flag
|
||||
for param in command.params
|
||||
if param.param_type_name == "option" and not getattr(param, "hidden", False)
|
||||
for flag in (*param.opts, *param.secondary_opts)
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("name", "command"), COMMANDS)
|
||||
def test_every_option_is_in_the_cli_reference(name: str, command: click.Command) -> None:
|
||||
assert option_flags(command) - table_flags(name) == set()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("name", "command"), COMMANDS)
|
||||
def test_every_flag_in_the_cli_reference_is_an_option(name: str, command: click.Command) -> None:
|
||||
"""Table flags of any length, and long flags anywhere in the section: a short flag in prose can be a value."""
|
||||
long_flags = set(re.findall(r"`(--[a-zA-Z][\w-]*)", section(name)))
|
||||
assert (table_flags(name) | long_flags) - option_flags(command) == set()
|
||||
@@ -39,11 +39,6 @@ def test_dl_starts_a_forwarder_for_a_control_d_resolver(monkeypatch: pytest.Monk
|
||||
assert params["proxy_query"] is None
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("example_service")
|
||||
def test_dl_keeps_a_host_and_port_as_given(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
assert run_dl(monkeypatch, tmp_path, "nas:3128").params["proxy"] == "nas:3128"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("example_service")
|
||||
@pytest.mark.parametrize("proxy", ["nope:us", "us", "controld://bad id@dns.controld.com"])
|
||||
def test_a_dl_proxy_error_is_a_proxy_error(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, proxy: str) -> None:
|
||||
|
||||
@@ -46,29 +46,6 @@ def test_a_nearly_full_temp_volume_is_named_on_the_line(temp: Path, monkeypatch:
|
||||
assert line == f" CalledProcessError: {str(error).rstrip('.')}, 38.0 MB free on {temp}"
|
||||
|
||||
|
||||
def test_enough_free_space_leaves_the_line_as_it_was(temp: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
free_space(monkeypatch, LOW_FREE_SPACE)
|
||||
error = ValueError("boom")
|
||||
|
||||
assert dl.failure_lines(error) == [":x: Download Failed...", " ValueError: boom"]
|
||||
|
||||
|
||||
def test_a_temp_dir_that_cannot_be_read_adds_nothing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path / "missing")
|
||||
|
||||
assert dl.failure_lines(ValueError("boom"))[1] == " ValueError: boom"
|
||||
|
||||
|
||||
def test_a_later_report_reuses_the_first_reading(temp: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
reads = free_space(monkeypatch, 38_000_000)
|
||||
error = OSError(28, "No space left on device")
|
||||
first = dl.failure_lines(error)
|
||||
free_space(monkeypatch, 5 * LOW_FREE_SPACE)
|
||||
|
||||
assert dl.failure_lines(error) == first
|
||||
assert len(reads) == 1
|
||||
|
||||
|
||||
def test_a_click_exception_keeps_only_its_message(temp: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
reads = free_space(monkeypatch, 0)
|
||||
|
||||
|
||||
@@ -148,14 +148,6 @@ def test_with_the_hook_the_fairplay_only_tracks_compete_and_nothing_is_probed(
|
||||
assert service.session.urls == []
|
||||
|
||||
|
||||
def test_a_quality_with_only_fairplay_only_tracks_skips_with_the_existing_reason(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
assert run(monkeypatch, caplog, Example(), quality=[2160]) == 1
|
||||
assert "Left out 2 FairPlay-only tracks" in caplog.text
|
||||
assert "Show S01E01: There's no 2160p Video Track..." in caplog.text
|
||||
|
||||
|
||||
def test_best_available_falls_back_to_the_track_that_licenses(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
"""dl builds its content-key resolution from the run's flags and installs the verified decrypt as the hook."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import create_autospec
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.drm import verify
|
||||
from unshackle.core.export_writer import ExportWriter
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def runner() -> dl:
|
||||
cmd = dl.__new__(dl)
|
||||
cmd.vaults = SimpleNamespace()
|
||||
cmd.service = "EXAMPLE"
|
||||
cmd.debug_logger = None
|
||||
cmd._remote_service = SimpleNamespace()
|
||||
return cmd
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cdm_only, vaults_only, best_available", [(True, False, False), (False, True, True)])
|
||||
def test_the_resolver_takes_the_run_flags_and_becomes_the_decrypt_hook(
|
||||
cdm_only: bool, vaults_only: bool, best_available: bool
|
||||
) -> None:
|
||||
writer = create_autospec(ExportWriter, instance=True)
|
||||
cmd = runner()
|
||||
service = SimpleNamespace()
|
||||
|
||||
cmd.start_key_resolution(
|
||||
service,
|
||||
cdm_only=cdm_only,
|
||||
vaults_only=vaults_only,
|
||||
best_available=best_available,
|
||||
export=writer,
|
||||
)
|
||||
|
||||
keys = cmd.keys
|
||||
assert verify.DECRYPT_HOOK == cmd.keys.decrypt_verified
|
||||
assert (keys.cdm_only, keys.vaults_only, keys.best_available) == (cdm_only, vaults_only, best_available)
|
||||
assert keys.source is cmd._remote_service and keys.service is service and keys.cdms is cmd
|
||||
assert keys.vaults is cmd.vaults and keys.tag == "EXAMPLE"
|
||||
assert keys.export is not None
|
||||
keys.export("title", "track", "drm")
|
||||
writer.record.assert_called_once_with("title", "track", "drm")
|
||||
|
||||
|
||||
def test_no_export_gives_no_export_callback() -> None:
|
||||
cmd = runner()
|
||||
|
||||
cmd.start_key_resolution(SimpleNamespace(), cdm_only=False, vaults_only=True, best_available=False, export=None)
|
||||
|
||||
assert cmd.keys.export is None
|
||||
@@ -180,18 +180,6 @@ def test_kv_add_without_service_writes_the_generic_table(tmp_path: Path, monkeyp
|
||||
assert SQLite("check", dest).get_key(KID, "generic") == KEY
|
||||
|
||||
|
||||
@pytest.mark.parametrize("no_push", [False, True])
|
||||
def test_kv_add_without_vault_stops_when_no_configured_vault_takes_pushes(
|
||||
no_push: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
local_vaults(monkeypatch, no_push=tmp_path / "read_only.db" if no_push else None)
|
||||
|
||||
result = CliRunner().invoke(kv_module.kv, ["add", f"{KID}:{KEY}", "-s", "EXAMPLE"], standalone_mode=False)
|
||||
|
||||
assert isinstance(result.exception, click.ClickException)
|
||||
assert result.exception.message == "No Key Vaults without no_push are configured."
|
||||
|
||||
|
||||
@pytest.mark.parametrize("arg", [f"{KID}:{KEY[:-1]}", f"{KID}{KEY}", "missing.txt"])
|
||||
def test_kv_add_rejects_an_argument_that_is_neither_a_pair_nor_a_file(
|
||||
arg: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
|
||||
@@ -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")
|
||||
Reference in New Issue
Block a user