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

263 lines
11 KiB
Python

"""L2 API editing E2E: ``POST /api/edit`` and ``POST /api/effects/generate``.
Both routes resolve their heavy ``VideoEditor`` by module-global name at call
time, so the editor (Gemini upload + ffmpeg filter build/apply) is stubbed at
``app.VideoEditor``. The clip on disk is a REAL ffmpeg video because the edit
route probes it with OpenCV and the effects route probes it with ffprobe.
"""
import json
import os
import shutil
import pytest
pytestmark = pytest.mark.e2e
app_module = pytest.importorskip("clipwright.api.app")
class StubVideoEditor:
"""Records calls; writes the edited output; can fail at any stage."""
filter_data = {"filter_string": "hue=s=0", "edits": [{"type": "bw_moment"}]}
effects_config = {
"segments": [{
"startSec": 0, "endSec": 6, "zoom": 1.1,
"zoomCenterX": 0.5, "zoomCenterY": 0.5,
"brightness": 1.0, "contrast": 1.0, "saturate": 1.0,
}]
}
error_stage = None
instances = []
def __init__(self, api_key=None):
self.api_key = api_key
self.uploaded = []
type(self).instances.append(self)
def upload_video(self, path):
if self.error_stage == "upload":
raise RuntimeError("upload exploded")
self.uploaded.append(path)
return {"name": "files/fake"}
def get_ffmpeg_filter(self, vid, duration, **kwargs):
if self.error_stage == "filter":
raise RuntimeError("filter exploded")
self.filter_kwargs = kwargs
return self.filter_data
def get_effects_config(self, vid, duration, **kwargs):
if self.error_stage == "effects":
raise RuntimeError("effects exploded")
self.effects_kwargs = kwargs
return self.effects_config
def apply_edits(self, input_path, output_path, filter_data):
if self.error_stage == "apply":
raise RuntimeError("apply exploded")
with open(output_path, "wb") as fh:
fh.write(b"edited-bytes")
@pytest.fixture
def stub_editor(monkeypatch):
StubVideoEditor.instances = []
StubVideoEditor.error_stage = None
StubVideoEditor.filter_data = {
"filter_string": "hue=s=0", "edits": [{"type": "bw_moment"}]}
StubVideoEditor.effects_config = {
"segments": [{
"startSec": 0, "endSec": 6, "zoom": 1.1,
"zoomCenterX": 0.5, "zoomCenterY": 0.5,
"brightness": 1.0, "contrast": 1.0, "saturate": 1.0,
}]
}
monkeypatch.setattr(app_module, "VideoEditor", StubVideoEditor)
return StubVideoEditor
def _make_job(app_state, media_factory, job_id="job-edit", base="edit",
output_format="auto"):
"""A completed job whose canonical clip is a real, probeable video."""
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")
clip = {
"start": 0.0,
"end": 6.0,
"video_title_for_youtube_short": "Edit clip",
"viral_hook_text": "Hook",
"video_url": f"/videos/{job_id}/{base}_clip_1.mp4",
}
(job_dir / f"{base}_metadata.json").write_text(json.dumps({
"shorts": [clip],
"transcript": {
"language": "en",
"segments": [{"start": 0.0, "end": 6.0, "text": "hi there",
"words": [{"word": "hi", "start": 1.0, "end": 1.4}]}],
},
"output_format": output_format,
"cost_analysis": {"total_cost": 0.0},
}))
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, "clip": clip}
@pytest.fixture
def editor_job(app_state, media_factory):
return _make_job(app_state, media_factory)
# --- POST /api/edit ---------------------------------------------------------
class TestEdit:
async def test_success_writes_file_and_persists(self, client, app_state,
stub_editor, editor_job):
job_id, base = editor_job["job_id"], editor_job["base"]
resp = await client.post("/api/edit", json={
"job_id": job_id, "clip_index": 0, "api_key": "test-key"})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["success"] is True
assert data["edit_plan"] == stub_editor.filter_data
assert data["new_video_url"] == (
f"/videos/{job_id}/edited_{base}_clip_1.mp4")
# The edited file exists on disk...
assert (editor_job["dir"] / f"edited_{base}_clip_1.mp4").is_file()
# ...and the new current version is persisted to metadata + memory.
meta = json.loads((editor_job["dir"] / f"{base}_metadata.json").read_text())
assert meta["shorts"][0]["video_url"] == data["new_video_url"]
mem = app_module.jobs[job_id]["result"]["clips"][0]
assert mem["video_url"] == data["new_video_url"]
# The temp ASCII copy the editor used was cleaned up.
assert not (editor_job["dir"] / f"temp_input_{job_id}.mp4").exists()
async def test_404_unknown_job(self, client, stub_editor):
resp = await client.post("/api/edit", json={
"job_id": "nope", "clip_index": 0, "api_key": "k"})
assert resp.status_code == 404
async def test_missing_file_is_wrapped_as_500(self, client, stub_editor,
editor_job):
# The route raises its 404 INSIDE the try that ends in a catch-all
# `except Exception -> 500`, so a missing input file surfaces as 500
# (documented deviation from the 404 the spec expected).
resp = await client.post("/api/edit", json={
"job_id": editor_job["job_id"], "clip_index": 0, "api_key": "k",
"input_filename": "does-not-exist.mp4"})
assert resp.status_code == 500
async def test_400_no_result(self, client, stub_editor):
app_module.jobs["job-noresult"] = {
"status": "completed", "result": {}, "user_id": None}
resp = await client.post("/api/edit", json={
"job_id": "job-noresult", "clip_index": 0, "api_key": "k"})
assert resp.status_code == 400
async def test_400_missing_key(self, client, monkeypatch, stub_editor,
editor_job):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
resp = await client.post("/api/edit", json={
"job_id": editor_job["job_id"], "clip_index": 0})
assert resp.status_code == 400
assert "Gemini" in resp.json()["detail"]
async def test_500_editor_error(self, client, stub_editor, editor_job):
stub_editor.error_stage = "filter"
resp = await client.post("/api/edit", json={
"job_id": editor_job["job_id"], "clip_index": 0, "api_key": "k"})
assert resp.status_code == 500
async def test_input_filename_is_basenamed(self, client, app_state,
stub_editor, editor_job):
# The target exists ONLY inside the job dir; the traversal path one
# level up does not. Success proves the name was basenamed.
(editor_job["dir"] / "secret.mp4").write_bytes(b"inside")
assert not (app_state.out / "secret.mp4").exists()
resp = await client.post("/api/edit", json={
"job_id": editor_job["job_id"], "clip_index": 0, "api_key": "k",
"input_filename": "../secret.mp4"})
assert resp.status_code == 200, resp.text
assert resp.json()["new_video_url"].endswith("/edited_secret.mp4")
assert (editor_job["dir"] / "edited_secret.mp4").is_file()
# --- POST /api/effects/generate --------------------------------------------
class TestEffects:
async def test_success_returns_config(self, client, stub_editor,
editor_job):
resp = await client.post(
"/api/effects/generate",
headers={"X-Gemini-Key": "test-key"},
json={"job_id": editor_job["job_id"], "clip_index": 0})
assert resp.status_code == 200, resp.text
assert resp.json() == {"effects": stub_editor.effects_config}
# The real clip was probed and the transcript from metadata was loaded.
assert stub_editor.instances[-1].effects_kwargs["width"] == 320
assert stub_editor.instances[-1].effects_kwargs["height"] == 180
assert stub_editor.instances[-1].effects_kwargs["transcript"] is not None
async def test_404_unknown_job(self, client, stub_editor):
resp = await client.post(
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
json={"job_id": "nope", "clip_index": 0})
assert resp.status_code == 404
async def test_404_missing_file(self, client, stub_editor, editor_job):
resp = await client.post(
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
json={"job_id": editor_job["job_id"], "clip_index": 0,
"input_filename": "nope.mp4"})
assert resp.status_code == 404
async def test_400_no_result(self, client, stub_editor):
app_module.jobs["job-noresult-2"] = {
"status": "completed", "result": {}, "user_id": None}
resp = await client.post(
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
json={"job_id": "job-noresult-2", "clip_index": 0})
assert resp.status_code == 400
async def test_400_missing_key(self, client, monkeypatch, stub_editor,
editor_job):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
resp = await client.post(
"/api/effects/generate",
json={"job_id": editor_job["job_id"], "clip_index": 0})
assert resp.status_code == 400
async def test_500_editor_error(self, client, stub_editor, editor_job):
stub_editor.error_stage = "effects"
resp = await client.post(
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
json={"job_id": editor_job["job_id"], "clip_index": 0})
assert resp.status_code == 500
async def test_500_none_config(self, client, stub_editor, editor_job):
stub_editor.effects_config = None
resp = await client.post(
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
json={"job_id": editor_job["job_id"], "clip_index": 0})
assert resp.status_code == 500
async def test_input_filename_is_basenamed(self, client, app_state,
media_factory, stub_editor,
editor_job):
# Real video only inside the job dir; the traversal target one level
# up is absent, so success proves the name was basenamed.
shutil.copy(media_factory.six, editor_job["dir"] / "secret.mp4")
assert not (app_state.out / "secret.mp4").exists()
resp = await client.post(
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
json={"job_id": editor_job["job_id"], "clip_index": 0,
"input_filename": "../secret.mp4"})
assert resp.status_code == 200, resp.text