forked from kenzuya/unshackle
refactor(api): put the job and worker process channels in job_channel
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
"""Tests of the job-worker channel: the progress record and its presence rule, the progress sink, answers and results."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from dataclasses import asdict, fields
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api.download_manager import HISTORY_FIELDS, DownloadQueueManager, JobStatus, record_job_history
|
||||
from unshackle.core.api.job_channel import (
|
||||
PROGRESS_FIELDS,
|
||||
JobProgress,
|
||||
ProgressFile,
|
||||
WorkerProcess,
|
||||
WorkerResult,
|
||||
apply_progress,
|
||||
decode_answer,
|
||||
encode_answer,
|
||||
write_result,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def test_a_key_in_the_update_replaces_the_field_none_and_zero_too() -> None:
|
||||
state = JobProgress(total_tracks=3, speed="1 MB/s", title="Show")
|
||||
assert apply_progress(state, {"total_tracks": 0, "speed": None}) is True
|
||||
assert state.total_tracks == 0 and state.speed is None
|
||||
assert state.title == "Show"
|
||||
|
||||
|
||||
def test_an_update_that_changes_nothing_reports_no_change() -> None:
|
||||
state = JobProgress(phase="muxing")
|
||||
assert apply_progress(state, {"phase": "muxing"}) is False
|
||||
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"),
|
||||
[
|
||||
({"status": "downloading"}, "status"),
|
||||
({"phase": "x", "progress": None}, "progress"),
|
||||
({"progress": "x"}, "progress"),
|
||||
({"total_tracks": float("inf")}, "total_tracks"),
|
||||
(None, "NoneType"),
|
||||
([], "list"),
|
||||
],
|
||||
)
|
||||
def test_a_bad_update_raises_and_changes_nothing(update: Any, names: str) -> None:
|
||||
state = JobProgress()
|
||||
with pytest.raises(ValueError, match=names):
|
||||
apply_progress(state, update)
|
||||
assert state == JobProgress()
|
||||
|
||||
|
||||
def test_the_progress_file_holds_the_whole_merged_record(tmp_path: Path) -> None:
|
||||
path = tmp_path / "progress.json"
|
||||
sink = ProgressFile(path)
|
||||
sink({"title": "Show", "current_title": "S01E01"})
|
||||
sink({"phase": "muxing"})
|
||||
written = json.loads(path.read_text(encoding="utf-8"))
|
||||
assert set(written) == set(PROGRESS_FIELDS)
|
||||
assert (written["title"], written["current_title"], written["phase"]) == ("Show", "S01E01", "muxing")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", [{"phase": "x", "typo": 1}, {"phase": "x", "title": object()}], ids=["key", "value"])
|
||||
def test_the_progress_file_drops_a_bad_update_and_keeps_writing(
|
||||
tmp_path: Path, caplog: pytest.LogCaptureFixture, bad: dict[str, Any]
|
||||
) -> None:
|
||||
"""A value JSON cannot hold must not stay in the record, or each later write fails too."""
|
||||
path = tmp_path / "progress.json"
|
||||
sink = ProgressFile(path)
|
||||
sink({"phase": "muxing"})
|
||||
sink(bad)
|
||||
assert json.loads(path.read_text(encoding="utf-8"))["phase"] == "muxing"
|
||||
assert "Failed to write progress update" in caplog.text
|
||||
sink({"phase": "done"})
|
||||
assert json.loads(path.read_text(encoding="utf-8"))["phase"] == "done"
|
||||
|
||||
|
||||
def test_the_aggregate_track_progress_fits_the_record() -> None:
|
||||
from unshackle.core.api.progress import build_job_progress_callables
|
||||
|
||||
class Video:
|
||||
height, width, range, bitrate = 1080, 1920, None, 4_000_000
|
||||
|
||||
state = JobProgress()
|
||||
|
||||
def sink(update: dict[str, Any]) -> None:
|
||||
apply_progress(state, update)
|
||||
|
||||
callables = build_job_progress_callables([Video()], [lambda **kw: None], sink) # type: ignore[list-item]
|
||||
callables[0](total=10, completed=5, downloaded="1.0 MB/s")
|
||||
callables[0](downloaded="Downloaded")
|
||||
assert (state.completed_tracks, state.total_tracks, state.progress) == (1, 1, 90.0)
|
||||
|
||||
|
||||
def test_an_answer_survives_the_pipe_with_a_newline() -> None:
|
||||
line = encode_answer("12\n34")
|
||||
assert line.count(b"\n") == 1 and line.endswith(b"\n")
|
||||
assert decode_answer(line) == "12\n34"
|
||||
|
||||
|
||||
def test_the_parent_reads_the_progress_file_once_per_change(tmp_path: Path) -> None:
|
||||
path = tmp_path / "progress.json"
|
||||
worker = WorkerProcess("j", SimpleNamespace(), {"progress": str(path)}) # type: ignore[arg-type]
|
||||
ProgressFile(path)({"phase": "muxing"})
|
||||
update = worker.read_progress()
|
||||
assert update is not None and update["phase"] == "muxing"
|
||||
assert worker.read_progress() is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("content", "expected"),
|
||||
[
|
||||
(json.dumps(asdict(WorkerResult("success", ["a.mkv"]))), WorkerResult("success", ["a.mkv"])),
|
||||
(json.dumps({"status": "error", "message": "boom"}), WorkerResult("error", message="boom")),
|
||||
("", None),
|
||||
("{}", None),
|
||||
],
|
||||
ids=["success", "error", "empty", "no-status"],
|
||||
)
|
||||
def test_the_parent_reads_the_worker_result(
|
||||
tmp_path: Path, caplog: pytest.LogCaptureFixture, content: str, expected: WorkerResult | None
|
||||
) -> None:
|
||||
path = tmp_path / "result.json"
|
||||
path.write_text(content, encoding="utf-8")
|
||||
worker = WorkerProcess("j", SimpleNamespace(), {"result": str(path)}) # type: ignore[arg-type]
|
||||
assert asyncio.run(worker.result()) == expected
|
||||
assert "Failed to parse" not in caplog.text
|
||||
|
||||
|
||||
def test_write_result_round_trips(tmp_path: Path) -> None:
|
||||
path = tmp_path / "result.json"
|
||||
result = WorkerResult("error", message="m", error_details="d", error_code="WORKER_ERROR", traceback="tb")
|
||||
write_result(path, result)
|
||||
worker = WorkerProcess("j", SimpleNamespace(), {"result": str(path)}) # type: ignore[arg-type]
|
||||
assert asyncio.run(worker.result()) == result
|
||||
|
||||
|
||||
def test_a_job_shows_every_progress_field_and_the_full_view_adds_output_files() -> None:
|
||||
job = DownloadQueueManager().create_job("EXAMPLE", "t")
|
||||
apply_progress(job, {"phase": "muxing", "output_files": ["a.mkv"]})
|
||||
short, full = job.to_dict(), job.to_dict(include_full_details=True)
|
||||
assert set(PROGRESS_FIELDS) - set(short) == {"output_files"}
|
||||
assert short["phase"] == "muxing" and full["output_files"] == ["a.mkv"]
|
||||
assert {f.name for f in fields(JobProgress)} <= set(full)
|
||||
|
||||
|
||||
def test_the_history_entry_takes_its_fields_from_the_full_job_view(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from unshackle.core.api import download_manager
|
||||
|
||||
history = tmp_path / "api_history.jsonl"
|
||||
monkeypatch.setattr(download_manager, "history_path", lambda: history)
|
||||
job = DownloadQueueManager().create_job("EXAMPLE", "t", credential="user:secretpass")
|
||||
job.status = JobStatus.FAILED
|
||||
job.error_message = "login failed for user:secretpass"
|
||||
job.skipped_titles = [{"title": "Show S01E02", "reason": "missing ko"}]
|
||||
record_job_history(job)
|
||||
entry = json.loads(history.read_text(encoding="utf-8"))
|
||||
full = job.to_dict(include_full_details=True)
|
||||
assert set(entry) == {"owner", *HISTORY_FIELDS}
|
||||
assert {name: entry[name] for name in HISTORY_FIELDS} == {name: full[name] for name in HISTORY_FIELDS}
|
||||
assert "secretpass" not in json.dumps(entry)
|
||||
Reference in New Issue
Block a user