clipwright/tests/e2e/api/test_transcript_edl_rerender.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

288 lines
12 KiB
Python

"""L2 API editing E2E: transcript, EDL and the clip-editor re-render.
The render work is stubbed at the ``recut.perform_recut`` seam (the endpoint's
own contract is what these tests own): request validation, the fast/source path
choice, the 409 on a gone source, and the recipe persisted to metadata.json and
the in-memory job. The source is a real ffmpeg video so duration probing is
genuine.
"""
import json
import os
import shutil
import pytest
pytestmark = pytest.mark.e2e
app_module = pytest.importorskip("clipwright.api.app")
from clipwright.media import recut # noqa: E402
TRANSCRIPT = {
"language": "en",
"segments": [
{
"start": 0.0, "end": 60.0, "text": "hello world again tail",
"words": [
{"word": "hello", "start": 1.0, "end": 1.4},
{"word": "world", "start": 2.0, "end": 2.4},
{"word": "again", "start": 4.0, "end": 4.4},
{"word": "tail", "start": 5.2, "end": 5.6},
],
},
],
}
def _make_job(app_state, media_factory, job_id="job-edl", base="edl"):
job_dir = app_state.out / job_id
job_dir.mkdir(parents=True, exist_ok=True)
shutil.copy(media_factory.six, job_dir / f"{base}_clip_1.mp4") # canonical
shutil.copy(media_factory.six, job_dir / "src.mp4") # source
clip = {
"start": 1.0,
"end": 5.0,
"video_title_for_youtube_short": "EDL clip",
"video_url": f"/videos/{job_id}/{base}_clip_1.mp4",
}
(job_dir / f"{base}_metadata.json").write_text(json.dumps({
"shorts": [clip],
"transcript": TRANSCRIPT,
"source_video": "src.mp4",
"output_format": "auto",
"cost_analysis": {},
}))
app_module.jobs[job_id] = {
"status": "completed",
"logs": [],
"result": {"clips": [dict(clip)], "cost_analysis": {}},
"user_id": None,
}
return {"job_id": job_id, "base": base, "dir": job_dir,
"meta": job_dir / f"{base}_metadata.json"}
@pytest.fixture
def edl_job(app_state, media_factory):
return _make_job(app_state, media_factory)
@pytest.fixture
def fake_recut(monkeypatch):
calls = []
def fake(**kwargs):
calls.append(kwargs)
name = f"recut_1_{kwargs['clean_name']}"
with open(os.path.join(kwargs["output_dir"], name), "wb") as fh:
fh.write(b"recut")
return name, name
monkeypatch.setattr(recut, "perform_recut", fake)
return calls
# --- GET /api/clip/{job}/{clip}/transcript ----------------------------------
class TestTranscript:
async def test_returns_words_in_clip_range(self, client, edl_job):
resp = await client.get(
f"/api/clip/{edl_job['job_id']}/0/transcript")
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["durationSec"] == 4.0
assert data["language"] == "en"
by_text = {c["text"]: c for c in data["captions"]}
# Clip starts at source 1.0s -> "hello" is 0ms into the clip.
assert by_text["hello"]["startMs"] == 0
assert by_text["world"]["startMs"] == 1000
assert by_text["again"]["startMs"] == 3000
# "tail" (5.2s) is past the clip end.
assert "tail" not in by_text
async def test_404_unknown_job(self, client, edl_job):
resp = await client.get("/api/clip/nope/0/transcript")
assert resp.status_code == 404
async def test_404_missing_metadata(self, client, edl_job):
os.remove(edl_job["meta"])
resp = await client.get(f"/api/clip/{edl_job['job_id']}/0/transcript")
assert resp.status_code == 404
async def test_400_missing_transcript(self, client, edl_job):
meta = json.loads(edl_job["meta"].read_text())
meta.pop("transcript")
edl_job["meta"].write_text(json.dumps(meta))
resp = await client.get(f"/api/clip/{edl_job['job_id']}/0/transcript")
assert resp.status_code == 400
async def test_404_clip_index_out_of_range(self, client, edl_job):
resp = await client.get(f"/api/clip/{edl_job['job_id']}/5/transcript")
assert resp.status_code == 404
# --- GET /api/clip/{job}/{clip}/edl -----------------------------------------
class TestEdl:
async def test_source_present(self, client, edl_job):
resp = await client.get(f"/api/clip/{edl_job['job_id']}/0/edl")
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["segments"] == [{"start": 1.0, "end": 5.0}]
assert data["canonical_range"] == {"start": 1.0, "end": 5.0}
assert data["duration"] == 4.0
assert data["current_file"] == "edl_clip_1.mp4"
assert data["source"]["available"] is True
assert data["source"]["url"] == f"/api/source/{edl_job['job_id']}"
assert data["source"]["duration_estimated"] is False
assert data["source"]["duration"] == pytest.approx(6.0, abs=0.5)
assert [w["w"] for w in data["words"]] == [
"hello", "world", "again", "tail"]
assert data["limits"]["max_segments"] == recut.MAX_SEGMENTS
async def test_deleted_source_is_estimated(self, client, edl_job):
os.remove(edl_job["dir"] / "src.mp4")
data = (await client.get(
f"/api/clip/{edl_job['job_id']}/0/edl")).json()
assert data["source"]["available"] is False
assert data["source"]["url"] is None
assert data["source"]["duration_estimated"] is True
# Best remaining scale: the last word or the recipe end.
assert data["source"]["duration"] == pytest.approx(5.6, abs=0.01)
async def test_404_unknown_job(self, client, edl_job):
assert (await client.get("/api/clip/nope/0/edl")).status_code == 404
async def test_404_missing_metadata(self, client, edl_job):
os.remove(edl_job["meta"])
assert (await client.get(
f"/api/clip/{edl_job['job_id']}/0/edl")).status_code == 404
async def test_404_clip_index_out_of_range(self, client, edl_job):
assert (await client.get(
f"/api/clip/{edl_job['job_id']}/9/edl")).status_code == 404
# --- POST /api/clip/rerender ------------------------------------------------
class TestRerenderValidation:
async def test_404_unknown_job(self, client, fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": "nope", "clip_index": 0,
"segments": [{"start": 1, "end": 3}]})
assert resp.status_code == 404
async def test_404_clip_out_of_range(self, client, edl_job, fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 5,
"segments": [{"start": 1, "end": 3}]})
assert resp.status_code == 404
async def test_400_bad_segments(self, client, edl_job, fake_recut):
for segments in ([], [{"start": 2, "end": 2.1}]):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"segments": segments})
assert resp.status_code == 400, segments
assert fake_recut == []
async def test_400_bad_framing(self, client, edl_job, fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"framing": "cinematic",
"segments": [{"start": 1, "end": 3}]})
assert resp.status_code == 400
assert fake_recut == []
async def test_409_source_gone_outside_segment(self, client, edl_job,
fake_recut):
os.remove(edl_job["dir"] / "src.mp4")
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"segments": [{"start": 5, "end": 6}]})
assert resp.status_code == 409
assert fake_recut == []
async def test_409_framing_without_source(self, client, edl_job,
fake_recut):
os.remove(edl_job["dir"] / "src.mp4")
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"framing": "full",
"segments": [{"start": 1, "end": 3}]})
assert resp.status_code == 409
assert "framing" in resp.json()["detail"]
assert fake_recut == []
class TestRerenderPaths:
async def test_fast_path_cuts_from_canonical(self, client, edl_job,
fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"segments": [{"start": 1, "end": 3}, {"start": 3, "end": 5}]})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["render_path"] == "fast"
assert data["duration"] == 4.0
call = fake_recut[0]
assert call["input_path"].endswith("edl_clip_1.mp4")
assert call["reframe"] is False
# Rebated onto the canonical file (t=0 == source 1.0s).
assert call["segments"] == [{"start": 0.0, "end": 2.0},
{"start": 2.0, "end": 4.0}]
assert call["captions_transcript"]["segments"][0]["words"]
async def test_source_path_reframes(self, client, edl_job, fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"segments": [{"start": 5, "end": 6}]})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["render_path"] == "source"
call = fake_recut[0]
assert call["input_path"].endswith("src.mp4")
assert call["reframe"] is True
assert call["segments"] == [{"start": 5.0, "end": 6.0}]
async def test_reapply_captions_false(self, client, edl_job, fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"reapply_captions": False,
"segments": [{"start": 1, "end": 3}]})
assert resp.status_code == 200
assert fake_recut[0]["captions_transcript"] is None
async def test_framing_forces_source_and_persists(self, client, edl_job,
fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0, "framing": "full",
"segments": [{"start": 1, "end": 3}]})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["render_path"] == "source"
assert data["framing"] == "full"
assert data["recipe"]["framing"] == "full"
assert fake_recut[0]["force_strategy"] == "WIDE"
class TestRerenderPersistence:
async def test_recipe_lands_in_metadata_and_memory(self, client, edl_job,
fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"segments": [{"start": 1, "end": 3}, {"start": 4.5, "end": 6}]})
assert resp.status_code == 200, resp.text
data = resp.json()
expected = [{"start": 1.0, "end": 3.0}, {"start": 4.5, "end": 6.0}]
assert data["recipe"]["segments"] == expected
assert data["recipe"]["canonical_range"] == {"start": 1.0, "end": 5.0}
assert (data["start"], data["end"]) == (1.0, 6.0)
meta = json.loads(edl_job["meta"].read_text())
stored = meta["shorts"][0]
assert stored["recipe"]["segments"] == expected
assert stored["video_url"] == data["new_video_url"]
mem = app_module.jobs[edl_job["job_id"]]["result"]["clips"][0]
assert mem["recipe"]["segments"] == expected
assert mem["video_url"] == data["new_video_url"]