clipwright/tests/e2e/conftest.py
pedro-bento 97f813553d 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 22:12:21 +01:00

199 lines
7.6 KiB
Python

"""Shared E2E fixtures: state isolation, a no-network guard, ffmpeg media, and
disk-seeded jobs.
Design notes
------------
* ``no_network`` (autouse) makes any unmocked DNS lookup fail loudly. The API
tests drive the app through ``httpx.ASGITransport``, which never touches a
socket; the pipeline tests run the real CLI with the stub_env fakes.
* ``app_state`` rebinds the module globals in ``clipwright.api.app`` per test so
two tests never share a ``jobs`` dict, a queue, or a semaphore. All names were
verified against ``clipwright/api/app.py`` (see the note in the report).
* ``media_factory`` is session-scoped and generates the fixture videos with
ffmpeg ``lavfi`` sources, so no binaries live in git. Tests assert on
globs/ffprobe values, never on exact ``<timestamp>`` filenames.
"""
import asyncio
import json
import socket
import subprocess
from types import SimpleNamespace
import pytest
@pytest.fixture(autouse=True)
def no_network(monkeypatch):
"""Fail on any unmocked outbound DNS lookup.
Loopback is allowed so local servers (an OpenAI-compatible LLM, a test
Postiz) can be reached; everything else must be mocked explicitly.
"""
real = socket.getaddrinfo
def guard(host, *args, **kwargs):
if host in ("127.0.0.1", "localhost", "::1", None, "", b"127.0.0.1"):
return real(host, *args, **kwargs)
raise AssertionError(f"unmocked network access to {host!r}")
monkeypatch.setattr(socket, "getaddrinfo", guard)
@pytest.fixture
def app_state(tmp_path, monkeypatch):
"""Point ``clipwright.api.app`` at a per-test output/upload tree.
Rebind the module globals the routes read at call time. ``job_queue`` and
``concurrency_semaphore`` are recreated because asyncio primitives latch
onto the first event loop they touch, and each test gets a fresh loop.
"""
import clipwright.api.app as app
out = tmp_path / "output"
up = tmp_path / "uploads"
out.mkdir()
up.mkdir()
(out / "thumbnails").mkdir()
monkeypatch.setattr(app, "OUTPUT_DIR", str(out))
monkeypatch.setattr(app, "UPLOAD_DIR", str(up))
monkeypatch.setattr(app, "THUMBNAILS_DIR", str(out / "thumbnails"))
# The /videos and /thumbnails mounts captured their directory at import
# time (`app.mount(..., directory=OUTPUT_DIR)`), so rebinding the module
# globals is not enough: repoint the mounted StaticFiles instances too or
# route tests would read the real `output/` tree. Both `.directory` (used
# for the directory-redirect check) and `.all_directories` (used by
# lookup_path) must move together.
def _repoint(name, directory):
for route in getattr(app.app, "routes", []):
if getattr(route, "name", None) == name:
sub = getattr(route, "app", None)
if sub is not None and hasattr(sub, "all_directories"):
sub.directory = str(directory)
sub.all_directories = [str(directory)]
_repoint("videos", out)
_repoint("thumbnails", out / "thumbnails")
for name, empty in (
("jobs", {}),
("thumbnail_sessions", {}),
("publish_jobs", {}),
("pending_uploads", {}),
("_rerender_locks", {}),
("_scenes_locks", {}),
("_recent_job_seconds", []),
("_admitting", set()),
("_running_jobs", set()),
):
monkeypatch.setattr(app, name, empty)
# Rebind loop-bound primitives (see docstring).
monkeypatch.setattr(app, "job_queue", asyncio.PriorityQueue())
monkeypatch.setattr(app, "concurrency_semaphore", asyncio.Semaphore(5))
monkeypatch.setattr(app, "_draining", False)
monkeypatch.setattr(app, "_stopping", False)
# Hermetic defaults: never gate on source height/length/size in tests.
monkeypatch.setattr(app, "QUALITY_GATE_MIN_HEIGHT", 0)
monkeypatch.setattr(app, "MIN_SOURCE_SECONDS", 0)
monkeypatch.setattr(app, "MAX_FILE_SIZE_MB", 0)
return SimpleNamespace(out=out, up=up, app=app)
@pytest.fixture(scope="session")
def media_factory(tmp_path_factory):
"""Generate the shared E2E fixture videos once per session.
Returns a ``SimpleNamespace`` whose attributes are ``pathlib.Path``s:
* ``sixty`` — 160x90, 60 s, with audio (uploads / process)
* ``six`` — 320x180, 6 s, with audio (fast stage tests)
* ``cuts`` — 320x180, 4 hard-colour segments (scene detection)
* ``silent`` — 320x180, 6 s, no audio (vision / no-audio paths)
"""
root = tmp_path_factory.mktemp("media")
def _run(args):
subprocess.run(
["ffmpeg", "-y", "-hide_banner", "-loglevel", "error", *args],
check=True,
)
sixty = root / "sixty.mp4"
six = root / "six.mp4"
cuts = root / "cuts.mp4"
silent = root / "silent.mp4"
if not sixty.exists():
_run([
"-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=60",
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=60",
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-shortest", str(sixty),
])
if not six.exists():
_run([
"-f", "lavfi", "-i", "testsrc=size=320x180:rate=10:duration=6",
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=6",
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-shortest", str(six),
])
if not cuts.exists():
_run([
"-f", "lavfi", "-i", "color=c=red:s=320x180:d=1.5",
"-f", "lavfi", "-i", "color=c=green:s=320x180:d=1.5",
"-f", "lavfi", "-i", "color=c=blue:s=320x180:d=1.5",
"-f", "lavfi", "-i", "color=c=yellow:s=320x180:d=1.5",
"-filter_complex", "[0:v][1:v][2:v][3:v]concat=n=4:v=1:a=0[v]",
"-map", "[v]", "-c:v", "libx264", "-preset", "ultrafast",
"-pix_fmt", "yuv420p", str(cuts),
])
if not silent.exists():
_run([
"-f", "lavfi", "-i", "testsrc=size=320x180:rate=10:duration=6",
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
str(silent),
])
return SimpleNamespace(sixty=sixty, six=six, cuts=cuts, silent=silent)
@pytest.fixture
def seeded_job(app_state):
"""Factory: write a completed job to disk and recover it into ``jobs``.
Mirrors the restart path: ``output/<job_id>/<base>_metadata.json`` plus a
non-empty ``<base>_clip_<n>.mp4`` per clip, then
``app._recover_jobs_from_disk()``. Returns the ``job_id`` (the recovered
record is available as ``app_state.app.jobs[job_id]``).
"""
def _seed(job_id="job-seeded", base="clipwright", clips=1):
import clipwright.api.app as app
job_dir = app_state.out / job_id
job_dir.mkdir(parents=True, exist_ok=True)
shorts = []
for i in range(clips):
shorts.append({
"start": float(i * 10),
"end": float(i * 10 + 8),
"predicted_score": 80 - i,
"video_title_for_youtube_short": f"Seeded clip {i + 1}",
"viral_hook_text": f"Hook {i + 1}",
"video_description_for_tiktok": "Seeded #test",
"video_description_for_instagram": "Seeded #test",
})
(job_dir / f"{base}_clip_{i + 1}.mp4").write_bytes(b"\x00" * 2048)
(job_dir / f"{base}_metadata.json").write_text(json.dumps({
"shorts": shorts,
"cost_analysis": {"total_cost": 0.0, "model": "seeded"},
}))
app._recover_jobs_from_disk()
return job_id
return _seed