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.
152 lines
4.9 KiB
Python
152 lines
4.9 KiB
Python
"""API E2E fixtures: an in-process ASGI client, a fake pipeline subprocess, and
|
|
an event-based queue helper.
|
|
|
|
``httpx.ASGITransport`` is used on purpose: ``starlette.testclient.TestClient``
|
|
runs the app's lifespan (which starts the queue worker, the resume scanner and
|
|
the drain signal handler) on its own event loop, which leaks tasks and fights
|
|
the test's loop. The client below never runs lifespan; the startup-recovery
|
|
test is the one place that opts into ``LifespanManager`` explicitly.
|
|
"""
|
|
|
|
import asyncio
|
|
import contextlib
|
|
import io
|
|
import json
|
|
|
|
import pytest
|
|
|
|
|
|
class FakePopen:
|
|
"""Stand-in for ``subprocess.Popen`` on the real worker path.
|
|
|
|
Parses the ``-o``/``--output`` directory out of ``cmd``, writes a canonical
|
|
``<base>_clip_1.mp4`` plus a metadata JSON there, and exposes the surface
|
|
``run_job`` needs (``stdout``, ``poll()``, ``returncode``, ``kill()``).
|
|
The canonical filename keeps ``_clips_actually_rendered`` deterministic
|
|
even though ``enqueue_output`` runs on a thread and may not have consumed
|
|
the ``CLIP_READY`` line yet.
|
|
"""
|
|
|
|
# Per-test knobs.
|
|
base_name = "clipwright"
|
|
clips = 1
|
|
returncode = 0
|
|
lines = None
|
|
|
|
instances = []
|
|
|
|
def __init__(self, cmd, stdout=None, stderr=None, env=None, cwd=None, **kwargs):
|
|
self.cmd = list(cmd)
|
|
self.returncode = type(self).returncode
|
|
self.killed = False
|
|
type(self).instances.append(self)
|
|
|
|
output_dir = self._output_dir(self.cmd)
|
|
if output_dir:
|
|
self._write_outputs(output_dir)
|
|
|
|
self.stdout = io.BytesIO(self._stdout_bytes())
|
|
|
|
@staticmethod
|
|
def _output_dir(cmd):
|
|
for flag in ("-o", "--output"):
|
|
if flag in cmd:
|
|
idx = cmd.index(flag)
|
|
if idx + 1 < len(cmd):
|
|
return cmd[idx + 1]
|
|
return None
|
|
|
|
def _stdout_bytes(self):
|
|
lines = self.lines
|
|
if lines is None:
|
|
lines = [f"CLIP_READY 0 {self.base_name}_clip_1.mp4", "done"]
|
|
return ("\n".join(lines) + "\n").encode("utf-8")
|
|
|
|
def _write_outputs(self, output_dir):
|
|
import os
|
|
|
|
os.makedirs(output_dir, exist_ok=True)
|
|
shorts = []
|
|
for i in range(self.clips):
|
|
shorts.append({
|
|
"start": float(i * 10),
|
|
"end": float(i * 10 + 8),
|
|
"predicted_score": 80 - i,
|
|
"video_title_for_youtube_short": f"Fake clip {i + 1}",
|
|
"viral_hook_text": f"Hook {i + 1}",
|
|
"video_description_for_tiktok": "Fake #test",
|
|
"video_description_for_instagram": "Fake #test",
|
|
})
|
|
with open(os.path.join(output_dir, f"{self.base_name}_clip_{i + 1}.mp4"), "wb") as fh:
|
|
fh.write(b"\x00" * 2048)
|
|
with open(os.path.join(output_dir, f"{self.base_name}_metadata.json"), "w") as fh:
|
|
json.dump({"shorts": shorts, "cost_analysis": {"total_cost": 0.0}}, fh)
|
|
|
|
def poll(self):
|
|
return self.returncode
|
|
|
|
def kill(self):
|
|
self.killed = True
|
|
|
|
def wait(self, timeout=None):
|
|
return self.returncode
|
|
|
|
|
|
@pytest.fixture
|
|
def fake_popen(monkeypatch):
|
|
"""Install ``FakePopen`` as ``app.subprocess.Popen`` for one test.
|
|
|
|
``app.subprocess`` is the shared ``subprocess`` module, so this also covers
|
|
any other module that resolves ``subprocess.Popen`` at call time.
|
|
"""
|
|
import clipwright.api.app as app
|
|
|
|
FakePopen.instances = []
|
|
monkeypatch.setattr(app.subprocess, "Popen", FakePopen)
|
|
return FakePopen
|
|
|
|
|
|
@pytest.fixture
|
|
async def client(app_state):
|
|
"""In-process HTTP client bound to the app under test (no lifespan)."""
|
|
from httpx import ASGITransport, AsyncClient
|
|
|
|
app = app_state.app
|
|
transport = ASGITransport(app=app.app)
|
|
async with AsyncClient(transport=transport, base_url="http://testserver") as c:
|
|
yield c
|
|
|
|
|
|
@pytest.fixture
|
|
def job_done(monkeypatch):
|
|
"""Return ``await job_done(job_id)``: run the queue until that job ends.
|
|
|
|
Wraps ``app.run_job_wrapper`` (resolved by global name at call time) so the
|
|
wrapper can set an ``asyncio.Event`` once the original returns, then runs
|
|
``app.process_queue()`` as a task and waits on the event with a bound. No
|
|
sleeps. The worker is cancelled in ``finally``.
|
|
"""
|
|
|
|
async def _wait(job_id, timeout=10.0):
|
|
import clipwright.api.app as app
|
|
|
|
done = asyncio.Event()
|
|
original = app.run_job_wrapper
|
|
|
|
async def wrapper(jid):
|
|
try:
|
|
await original(jid)
|
|
finally:
|
|
if jid == job_id:
|
|
done.set()
|
|
|
|
monkeypatch.setattr(app, "run_job_wrapper", wrapper)
|
|
worker = asyncio.create_task(app.process_queue())
|
|
try:
|
|
await asyncio.wait_for(done.wait(), timeout)
|
|
finally:
|
|
worker.cancel()
|
|
with contextlib.suppress(asyncio.CancelledError):
|
|
await worker
|
|
|
|
return _wait
|