test: delete slow, timing-based and redundant tests

This commit is contained in:
imSp4rky
2026-12-05 15:20:05 -07:00
parent 783a2fc185
commit 3a0a74e694
292 changed files with 153 additions and 15174 deletions
+1 -255
View File
@@ -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