clipwright/tests/e2e/api/test_process_worker.py
pedro-bento 026f3ff271
Some checks failed
CI / unit (pull_request) Failing after 24s
CI / backend-e2e (pull_request) Successful in 1m18s
CI / dashboard-e2e (pull_request) Successful in 1m44s
test: add full E2E coverage (API, pipeline, browser)
Three-level end-to-end suite, all deterministic (no retries, no sleeps, no
unmocked network):

- tests/e2e/api (209 tests): every route in clipwright/api/app.py +
  free_tools — health/config, uploads, process submit matrix + worker/webhook/
  auto-retry/resume, status/source/download-all, edit/effects, transcript/EDL/
  rerender, scenes/reframe, subtitle, hook, Postiz, thumbnails, free tools,
  and the security/path guards.
- tests/e2e/pipeline (136 tests): every stage with real ffmpeg and stubbed
  Gemini/yt-dlp/ASR/ML — download, transcribe, scene detect, selection,
  layout, reframe/render, subtitles, hooks, watermark, thumbnails, plus the
  real CLI full pipeline via stub_env.
- dashboard/e2e (19 Playwright specs): route-interception state machine
  covering every dashboard flow; one real-backend spec left test.fixme.
- Foundation: tests/e2e/conftest.py (state isolation, no-network guard, ffmpeg
  media factory, disk-seeded jobs), FakePopen worker harness, child-process
  stub_env, architecture-consistent fixtures.
- CI: unit + backend-e2e + dashboard-e2e jobs in the python+node container;
  ffmpeg + Playwright installed in-job; no setup-node/cache (act runner).

Verified: unit 790 passed; API E2E 209 passed; pipeline E2E 136 passed;
Playwright 19 passed / 1 skipped.
2026-10-04 21:58:28 +01:00

188 lines
6.2 KiB
Python

"""L1 API core: the real worker path.
``fake_popen`` replaces ``subprocess.Popen`` so ``run_job`` sees a finished
child that already wrote a canonical clip + metadata; ``job_done`` runs
``process_queue`` as a task and waits on an event set by a wrapper around
``run_job_wrapper`` (no sleeps, bounded wait). Webhook delivery, transient
auto-retry, and resume-from-manifest are covered here too.
"""
import asyncio
import json
import os
import sys
import pytest
pytestmark = pytest.mark.e2e
KEY = {"X-Gemini-Key": "test-key"}
async def _submit_file(client, media_factory, **form):
data = {"acknowledged": "true", **form}
return await client.post(
"/api/process",
data=data,
files={"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
headers=KEY,
)
async def test_queued_job_runs_to_completion(client, app_state, media_factory,
fake_popen, job_done):
resp = await _submit_file(client, media_factory)
assert resp.status_code == 200, resp.text
job_id = resp.json()["job_id"]
assert app_state.app.jobs[job_id]["status"] == "queued"
await job_done(job_id)
job = app_state.app.jobs[job_id]
assert job["status"] == "completed"
clips = job["result"]["clips"]
assert len(clips) == 1
assert clips[0]["video_url"] == f"/videos/{job_id}/clipwright_clip_1.mp4"
assert (app_state.out / job_id / "clipwright_clip_1.mp4").stat().st_size > 0
# Terminal state drops the resume manifest.
assert not (app_state.out / job_id / ".resume.json").exists()
# The fake was actually invoked with the queued command (other FakePopen
# instances are the ffprobe duration probes, which share the module Popen).
workers = [i for i in fake_popen.instances if "clipwright.pipeline.main" in i.cmd]
assert workers and workers[0].cmd[0] == sys.executable
async def test_webhook_delivered_with_signature(client, app_state, media_factory,
fake_popen, job_done, monkeypatch):
captured = {}
class FakeAsyncClient:
def __init__(self, *a, **k):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
async def post(self, url, content=None, headers=None):
captured["url"] = url
captured["body"] = content
captured["headers"] = headers
delivered.set()
class _Resp:
status_code = 200
return _Resp()
delivered = asyncio.Event()
monkeypatch.setattr(app_state.app.httpx, "AsyncClient", FakeAsyncClient)
monkeypatch.delenv("PUBLIC_API_URL", raising=False)
resp = await _submit_file(
client, media_factory,
webhook_url="http://8.8.8.8/hook",
webhook_secret="s3cret",
)
assert resp.status_code == 200, resp.text
job_id = resp.json()["job_id"]
await job_done(job_id)
await asyncio.wait_for(delivered.wait(), 5)
payload = json.loads(captured["body"].decode())
assert payload["event"] == "job.completed"
assert payload["job_id"] == job_id
assert payload["status"] == "completed"
assert payload["clips"][0]["index"] == 0
assert payload["clips"][0]["title"] == "Fake clip 1"
assert payload["clips"][0]["video_url"] == (
f"http://testserver/videos/{job_id}/clipwright_clip_1.mp4")
expected = app_state.app._sign_webhook(captured["body"], "s3cret")
assert captured["headers"]["X-Clipwright-Signature"] == expected
async def test_transient_failure_is_auto_retried(app_state, media_factory,
fake_popen, monkeypatch):
app = app_state.app
monkeypatch.setattr(app, "AUTO_RETRY_DELAY_SECONDS", 0)
fake_popen.returncode = 1
fake_popen.lines = ["CUDA out of memory while starting"]
job_id = "job-retry"
out_dir = app_state.out / job_id
out_dir.mkdir()
app.jobs[job_id] = {
"status": "queued",
"logs": app._TimedLog(["❌ CUDA out of memory while starting"]),
"cmd": [sys.executable, "-m", "clipwright.pipeline.main",
"-i", "x", "-o", str(out_dir)],
"env": {},
"output_dir": str(out_dir),
"webhook_url": None,
"webhook_secret": None,
"user_id": None,
}
enqueued = []
retried = asyncio.Event()
original_enqueue = app._enqueue_job
def capture(jid, priority=2):
original_enqueue(jid, priority)
enqueued.append((jid, priority))
retried.set()
monkeypatch.setattr(app, "_enqueue_job", capture)
# Balance the queue's task_done() and the semaphore's release().
await app.concurrency_semaphore.acquire()
app.job_queue.put_nowait((2, 0, job_id))
await app.job_queue.get()
await app.run_job_wrapper(job_id)
await asyncio.wait_for(retried.wait(), 5)
job = app.jobs[job_id]
assert job["status"] == "queued"
assert job["auto_retries"] == 1
assert enqueued == [(job_id, 1)]
# Half-made outputs are cleared; the source survives for the retry.
assert not (out_dir / "clipwright_clip_1.mp4").exists()
assert not (out_dir / "clipwright_metadata.json").exists()
async def test_manifest_resumes_an_interrupted_job(app_state):
app = app_state.app
job_id = "job-resume"
job_dir = app_state.out / job_id
job_dir.mkdir()
app._write_resume_manifest(job_id, ["python", "-m", "clipwright.pipeline.main"],
priority=2, user_id=None, reservation_id=None)
keep = app._resume_interrupted_jobs()
assert keep == set()
job = app.jobs[job_id]
assert job["status"] == "queued"
assert any("Resuming" in line for line in job["logs"])
assert app.job_queue.qsize() == 1
assert app._read_manifest(job_id)["attempts"] == 1
async def test_manifest_gives_up_after_max_attempts(app_state):
app = app_state.app
job_id = "job-poison"
job_dir = app_state.out / job_id
job_dir.mkdir()
(job_dir / ".resume.json").write_text(json.dumps({
"cmd": ["python"], "priority": 2, "attempts": app.MAX_RESUME_ATTEMPTS,
}))
app._resume_interrupted_jobs()
assert job_id not in app.jobs
assert app.job_queue.qsize() == 0
assert not (job_dir / ".resume.json").exists()