Files
unshackle/tests/remote/unit/test_download_manager.py
T

581 lines
21 KiB
Python

"""Unit tests for DownloadJob + DownloadQueueManager state machine.
These tests focus on the queue manager's data layer (create/get/list/cancel/
cleanup/serialize); they do not exercise the actual subprocess download path.
"""
from __future__ import annotations
import asyncio
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
pytestmark = pytest.mark.unit
@pytest.fixture
def manager() -> DownloadQueueManager:
"""Fresh manager. We never call start_workers() so no async tasks are created."""
return DownloadQueueManager(max_concurrent_downloads=2, job_retention_hours=24)
def test_to_dict_short_vs_full(manager: DownloadQueueManager) -> None:
job = manager.create_job("EXAMPLE", "t", profile="p")
short = job.to_dict()
assert "parameters" not in short
assert short["status"] == "queued"
assert short["service"] == "EXAMPLE"
full = job.to_dict(include_full_details=True)
assert full["parameters"] == {"profile": "p"}
assert "error_message" in full
assert "output_files" in full
def test_cancel_queued_job_sets_cancelled_and_signals_event(manager: DownloadQueueManager) -> None:
job = manager.create_job("EXAMPLE", "t")
assert manager.cancel_job(job.job_id) is True
assert job.status is JobStatus.CANCELLED
assert job.cancel_event.is_set()
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_cleanup_old_jobs_drops_old_terminal_states(manager: DownloadQueueManager) -> None:
now = datetime.now()
old = now - timedelta(hours=48)
keep_recent = manager.create_job("EXAMPLE", "recent")
drop_old_done = manager.create_job("EXAMPLE", "old-done")
drop_old_failed = manager.create_job("EXAMPLE", "old-failed")
keep_running = manager.create_job("EXAMPLE", "running")
keep_recent.status = JobStatus.COMPLETED
keep_recent.completed_time = now
drop_old_done.status = JobStatus.COMPLETED
drop_old_done.completed_time = old
drop_old_failed.status = JobStatus.FAILED
drop_old_failed.created_time = old # never set completed_time
keep_running.status = JobStatus.DOWNLOADING
removed = manager.cleanup_old_jobs()
assert removed == 2
remaining = {j.job_id for j in manager.list_jobs()}
assert keep_recent.job_id in remaining
assert keep_running.job_id in remaining
assert drop_old_done.job_id not in remaining
assert drop_old_failed.job_id not in remaining
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
store = get_session_store()
session = await store.create("EXAMPLE", object(), session_id="busy-session")
try:
assert "EXAMPLE" in busy_services()
finally:
await store.delete(session.session_id)
assert "EXAMPLE" not in busy_services()
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
from unshackle.core.dl_options import cast_dl_params
from unshackle.core.tracks import Subtitle
assert cast_dl_params(dl.cli, {"sub_format": "ORIGINAL"})["sub_format"] == "original"
assert cast_dl_params(dl.cli, {"sub_format": "srt"})["sub_format"] is Subtitle.Codec.SubRip
def test_worker_write_result_retries_denied_replace(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Windows denies os.replace while the parent holds the progress file open, so the write must retry.
Without the retry a denied replace loses that update. A value the worker writes once, such as a
phase change, then stays invisible until the next write.
"""
import json
import os
from unshackle.core.api import job_channel
target = tmp_path / "progress.json"
real_replace = os.replace
attempts = []
def flaky_replace(src: Path, dst: Path) -> None:
attempts.append(dst)
if len(attempts) == 1:
raise PermissionError(13, "Permission denied", str(dst))
real_replace(src, dst)
monkeypatch.setattr(job_channel.os, "replace", flaky_replace)
job_channel.write_json(target, {"progress": 42.0})
assert json.loads(target.read_text(encoding="utf-8")) == {"progress": 42.0}
assert len(attempts) == 2
class _CapturedCtx(Exception):
pass
@pytest.mark.parametrize(
("params", "expected"),
[
({}, (["orig"], [], [], ["all"], [], False, False)),
(
{
"lang": ["es-419"],
"v_lang": ["en"],
"a_lang": ["ja"],
"s_lang": ["ko"],
"acodec": "AAC,EC3",
"forced_subs": True,
"exact_lang": True,
},
(["es-419"], ["en"], ["ja"], ["ko"], ["AAC", "EC3"], True, True),
),
],
)
def test_perform_download_puts_the_lang_selection_in_the_service_ctx(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, params: dict, expected: tuple
) -> None:
"""Services read the language selection from ctx.parent.params, not from dl.result()."""
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:
raise _CapturedCtx(ctx)
monkeypatch.setattr(dl_module, "dl", FakeDl)
monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path))
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
with pytest.raises(_CapturedCtx) as exc:
download_manager.perform_download("job-1", "EXAMPLE", "t1", dict(params))
ctx = exc.value.args[0]
p = ctx.params
acodec = [c.name for c in p["acodec"]]
selection = (p["lang"], p["v_lang"], p["a_lang"], p["s_lang"], acodec, p["forced_subs"], p["exact_lang"])
assert selection == expected
def test_perform_download_gives_dl_the_defaults_for_null_and_empty_values(
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
seen: dict[str, dict] = {}
class FakeDl:
cli = dl_module.dl.cli
def __init__(self, ctx: click.Context, **kwargs: object) -> None:
seen["init"] = kwargs
def result(self, **kwargs: object) -> None:
seen["result"] = kwargs
raise RuntimeError("stop")
class FakeService:
cli = click.Command(
"svc", callback=click.pass_context(lambda ctx, title: seen.update(parent=dict(ctx.parent.params)))
)
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)
params: dict[str, object] = {"quality": None, "vcodec": None, "acodec": None, "lang": None, "output_dir": ""}
with pytest.raises(RuntimeError, match="stop"):
download_manager.perform_download("job-1", "EXAMPLE", "t1", params)
assert seen["init"]["output_dir"] is None
for view in (seen["parent"], seen["result"]):
assert view["quality"] == [] and view["vcodec"] == [] and view["acodec"] == [] and view["lang"] == ["orig"]
def test_perform_download_casts_service_options(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 build(title: str, episodes: object, tag: object) -> None:
raise _CapturedCtx(episodes, tag)
class FakeService:
cli = click.Command(
"svc",
params=[click.Option(["--episodes"], type=int), click.Option(["--tag"], multiple=True)],
callback=build,
)
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", {"service_params": {"episodes": "2", "tag": ["a", "b"]}}
)
assert exc.value.args == (2, ("a", "b"))
def test_worker_relays_a_prompt_and_reads_the_answer(monkeypatch: pytest.MonkeyPatch) -> None:
import json
import os
import sys
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))
updates: list[dict] = []
def answer_on_prompt(update: dict) -> None:
"""Answer only once the prompt is out: the prompt discards answers that arrived before it."""
updates.append(update)
if update.get("input_prompt"):
os.write(write_fd, (json.dumps("12\n34") + "\n").encode("utf-8"))
download_worker.relay_prompts(answer_on_prompt)
try:
assert prompt_user("Enter PIN", qr="https://login.example/scan") == "12\n34"
finally:
set_prompt_handler(None)
os.close(write_fd)
assert updates == [
{"input_prompt": "Enter PIN", "qr": "https://login.example/scan"},
{"input_prompt": None, "qr": None},
]
def test_worker_relays_a_notice_as_progress(monkeypatch: pytest.MonkeyPatch) -> None:
"""A show_notice() message reaches the parent as ``notice`` progress, and None clears it."""
import os
import sys
from types import SimpleNamespace
from unshackle.core.api import download_worker
from unshackle.core.console import set_notice_handler, set_prompt_handler, show_notice
read_fd, write_fd = os.pipe()
monkeypatch.setattr(sys, "stdin", SimpleNamespace(fileno=lambda: read_fd))
updates: list[dict] = []
download_worker.relay_prompts(updates.append)
try:
show_notice("Enter pair code ABCD", "https://login.example/pair")
show_notice(None)
finally:
set_prompt_handler(None)
set_notice_handler(None)
os.close(write_fd)
assert updates == [
{"notice": "Enter pair code ABCD", "qr": "https://login.example/pair"},
{"notice": None, "qr": None},
]
def test_a_prompt_discards_an_answer_sent_before_it(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""A late answer to an earlier prompt must not answer the next one; the timeout is not retryable."""
import sys
import threading
from unshackle.core.api import download_worker
from unshackle.core.api.errors import categorize_exception
from unshackle.core.console import prompt_user, set_prompt_handler
from unshackle.core.remote_protocol import APIErrorCode
answers = tmp_path / "stdin"
answers.write_text('"stale"\n', encoding="utf-8")
monkeypatch.setattr(sys, "stdin", answers.open("rb"))
monkeypatch.setattr(download_worker, "AUTH_INPUT_TIMEOUT", 0.2)
download_worker.relay_prompts(lambda update: None)
# The reader exits at EOF, so a finished join means the stale line is already queued.
for reader in [t for t in threading.enumerate() if t.name == "prompt-answers"]:
reader.join(timeout=5)
try:
with pytest.raises(TimeoutError) as exc_info:
prompt_user("Enter PIN")
finally:
set_prompt_handler(None)
assert categorize_exception(exc_info.value).error_code is APIErrorCode.AUTH_FAILED
assert exc_info.value.error_code is APIErrorCode.AUTH_FAILED # type: ignore[attr-defined]
def test_submit_input_writes_one_json_line_to_the_worker(manager: DownloadQueueManager) -> None:
import io
from types import SimpleNamespace
from unshackle.core.api.job_channel import WorkerProcess
job = manager.create_job("EXAMPLE", "t")
stdin = io.BytesIO()
manager._workers[job.job_id] = WorkerProcess(job.job_id, SimpleNamespace(stdin=stdin), {}) # type: ignore[arg-type]
assert manager.submit_input(job, "1234") is False
job.input_prompt = "Enter PIN"
assert manager.submit_input(job, "1234") is True
assert stdin.getvalue() == b'"1234"\n'
assert job.input_prompt is None
assert manager.submit_input(job, "5678") is False
FAKE_PROMPT_WORKER = """
import sys
from pathlib import Path
from typing import Any
from unshackle.core.api import download_worker, job_channel
from unshackle.core.console import prompt_user
result_path, progress_path = Path(sys.argv[-2]), Path(sys.argv[-1])
download_worker.relay_prompts(job_channel.ProgressFile(progress_path))
answers = [prompt_user("Enter OTP"), prompt_user("Enter OTP")]
job_channel.write_result(result_path, job_channel.WorkerResult("success", answers))
"""
async def test_input_handler_rejects_bad_requests(
monkeypatch: pytest.MonkeyPatch, manager: DownloadQueueManager
) -> None:
from unshackle.core.api import download_manager
from unshackle.core.api.errors import APIError
from unshackle.core.api.handlers import download_job_input_handler
from unshackle.core.remote_protocol import APIErrorCode
monkeypatch.setattr(download_manager, "get_download_manager", lambda: manager)
job = manager.create_job("EXAMPLE", "t")
async def error_code(data: dict, job_id: str) -> APIErrorCode:
with pytest.raises(APIError) as exc_info:
await download_job_input_handler(data, job_id)
return exc_info.value.error_code
assert await error_code({"response": "1"}, "missing") is APIErrorCode.JOB_NOT_FOUND
assert await error_code({}, job.job_id) is APIErrorCode.INVALID_INPUT
assert await error_code({"response": "1"}, job.job_id) is APIErrorCode.CONFLICT
job.owner_key = "another-key"
assert await error_code({"response": "1"}, job.job_id) is APIErrorCode.JOB_NOT_FOUND
FAKE_FAILING_WORKER = """
import sys
from unshackle.core.api import download_worker
def fail(*args, **kwargs):
{}[[1]] = 2
download_worker.perform_download = fail
sys.exit(download_worker.main(["worker"] + sys.argv[1:]))
"""
def test_client_job_view_hides_debug_fields_without_debug_api() -> None:
from types import SimpleNamespace
from unshackle.core.api.handlers import client_job_view
job = {"job_id": "j", "error_traceback": "tb", "worker_stderr": "err"}
off: Any = SimpleNamespace(app={"debug_api": False})
on: Any = SimpleNamespace(app={"debug_api": True})
assert client_job_view(job, off) == {"job_id": "j"}
assert client_job_view(job, None) == {"job_id": "j"}
assert client_job_view(job, on) == job
FAKE_SKIPPING_WORKER = """
import sys
from unshackle.core.api import download_worker
def skip_then_stop(*args, progress_callback, **kwargs):
progress_callback({"skipped_titles": [{"title": "Show S01E02", "reason": "missing ko"}]})
raise RuntimeError("Download failed: Skipped all 2 titles")
download_worker.perform_download = skip_then_stop
sys.exit(download_worker.main(["worker"] + sys.argv[1:]))
"""
def test_a_stopped_run_names_its_reason_in_the_job_error(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.api.errors import APIError
from unshackle.core.run_plan import RunStopped
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 RunStopped("Show S01E01: Required audio language(s) not found: ko")
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(APIError, match=r"^Download failed: Show S01E01: Required audio language\(s\) not found: ko$"):
download_manager.perform_download("job-1", "EXAMPLE1", "t1", {})
def test_job_history_keeps_the_skipped_titles(tmp_path: Path, manager: DownloadQueueManager) -> None:
import json
from unshackle.core.api.download_manager import record_job_history
job = manager.create_job("EXAMPLE", "t")
job.status = JobStatus.COMPLETED
job.skipped_titles = [{"title": "Show S01E02", "reason": "missing ko"}]
record_job_history(job)
entry = json.loads((tmp_path / "api_history.jsonl").read_text(encoding="utf-8").splitlines()[-1])
assert entry["skipped_titles"] == job.skipped_titles
@pytest.mark.parametrize("carrier", ["error", "cause", "none"])
def test_a_download_error_keeps_the_code_its_raiser_named(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, carrier: str
) -> None:
import click
import unshackle.commands.dl as dl_module
from unshackle.core.api import download_manager, handlers
from unshackle.core.api.errors import APIError
from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.run_plan import RunOutcome
from unshackle.core.services import Services
error = ValueError("no key for the track")
if carrier == "error":
coded(error, APIErrorCode.DRM_ERROR)
elif carrier == "cause":
error.__cause__ = coded(KeyError("kid"), APIErrorCode.DRM_ERROR)
class FakeDl:
cli = dl_module.dl.cli
def __init__(self, ctx: click.Context, **kwargs: object) -> None:
pass
def result(self, **kwargs: object) -> RunOutcome:
return RunOutcome(error=error)
def failure_lines(self, error: BaseException) -> tuple[str, str]:
return "", str(error)
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(APIError, match="^download worker failed: no key for the track$") as exc:
download_manager.perform_download("job-1", "EXAMPLE1", "t1", {})
assert exc.value.error_code == (APIErrorCode.WORKER_ERROR if carrier == "none" else APIErrorCode.DRM_ERROR)
@pytest.fixture
def downloading(monkeypatch: pytest.MonkeyPatch, manager: DownloadQueueManager) -> Any:
"""A manager whose jobs download until cancelled, with no history file written."""
from unshackle.core.api import download_manager
started = asyncio.Event()
async def block(job: DownloadJob) -> None:
started.set()
await asyncio.Event().wait()
monkeypatch.setattr(manager, "execute_download", block)
monkeypatch.setattr(download_manager, "record_job_history", lambda job: None)
return started
async def test_a_cancel_of_the_worker_task_ends_it_while_a_job_downloads(
manager: DownloadQueueManager, downloading: Any
) -> None:
worker = asyncio.create_task(manager.download_worker("w"))
job = manager.create_job("EXAMPLE", "t")
await asyncio.wait_for(downloading.wait(), timeout=10)
worker.cancel()
with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(worker, timeout=10)
assert job.status is JobStatus.CANCELLED
assert job.completed_time is not None
async def test_shutdown_cancels_every_job_and_ends_each_stream_on_its_terminal_event(
manager: DownloadQueueManager, downloading: Any
) -> None:
from unshackle.core.api.errors import APIError
worker = asyncio.create_task(manager.download_worker("w"))
running = manager.create_job("EXAMPLE", "t")
await asyncio.wait_for(downloading.wait(), timeout=10)
queued = manager.create_job("EXAMPLE", "u")
streams = {job.job_id: manager.subscribe(job.job_id) for job in (running, queued)}
await manager.shutdown()
await asyncio.wait_for(worker, timeout=10)
for job in (running, queued):
assert job.status is JobStatus.CANCELLED
assert job.completed_time is not None
events = []
while (item := await asyncio.wait_for(streams[job.job_id].get(), timeout=10)) is not None:
events.append(item["event"])
assert events[-1] == "cancelled"
with pytest.raises(APIError):
manager.create_job("EXAMPLE", "v")