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

150 lines
5.9 KiB
Python

"""L2 API editing E2E: POST /api/hook (add / update / remove).
The overlay is a REAL ffmpeg pass using the repo's bundled fonts (the fonts/
directory is present in the test checkout, so no network fetch happens). The
clip is a real fixture video with audio.
"""
import json
import os
import shutil
import subprocess
import pytest
pytestmark = pytest.mark.e2e
app_module = pytest.importorskip("clipwright.api.app")
def _probe(path):
out = subprocess.run(
["ffprobe", "-v", "error", "-show_entries",
"stream=codec_type:format=duration", "-of", "json", str(path)],
capture_output=True, text=True, check=True)
return json.loads(out.stdout)
def _make_job(app_state, media_factory, job_id="job-hook", base="hk"):
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": "Hook clip",
"video_url": f"/videos/{job_id}/{base}_clip_1.mp4",
}
(job_dir / f"{base}_metadata.json").write_text(json.dumps({
"shorts": [clip], "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 hook_job(app_state, media_factory):
return _make_job(app_state, media_factory)
def _hooked_files(job):
return sorted(job["dir"].glob("hooked_*_hk_clip_1.mp4"))
# --- POST /api/hook ---------------------------------------------------------
class TestHook:
async def test_add_burns_hook(self, client, hook_job):
resp = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0,
"text": "HELLO WORLD", "style": "pill", "position": "top",
"size": "M", "font": "anton"})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["success"] is True
assert data["burned_hook"]["text"] == "HELLO WORLD"
assert data["burned_hook"]["style"] == "pill"
assert data["new_video_url"].startswith(
f"/videos/{hook_job['job_id']}/hooked_")
assert data["new_video_url"].endswith("_hk_clip_1.mp4")
out = _hooked_files(hook_job)
assert len(out) == 1
assert out[0].stat().st_size > 0
assert "video" in {s["codec_type"] for s in _probe(out[0])["streams"]}
meta = json.loads(hook_job["meta"].read_text())
assert meta["shorts"][0]["auto_hook"]["text"] == "HELLO WORLD"
assert meta["shorts"][0]["video_url"] == data["new_video_url"]
mem = app_module.jobs[hook_job["job_id"]]["result"]["clips"][0]
assert mem["auto_hook"]["text"] == "HELLO WORLD"
async def test_update_replaces_without_stacking(self, client, hook_job):
first = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0,
"text": "FIRST", "style": "pill"})
assert first.status_code == 200, first.text
second = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0,
"text": "SECOND", "style": "dark"})
assert second.status_code == 200, second.text
name = second.json()["new_video_url"].split("/")[-1]
# Exactly one hooked_ prefix: the old burn was walked back, not stacked.
assert name.count("hooked_") == 1
assert name.endswith("_hk_clip_1.mp4")
meta = json.loads(hook_job["meta"].read_text())
assert meta["shorts"][0]["auto_hook"]["text"] == "SECOND"
assert meta["shorts"][0]["auto_hook"]["style"] == "dark"
async def test_remove_strips_hook(self, client, hook_job):
add = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0,
"text": "REMOVE ME", "style": "pill"})
assert add.status_code == 200
resp = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0, "remove": True})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["burned_hook"] is None
assert data["new_video_url"] == (
f"/videos/{hook_job['job_id']}/hk_clip_1.mp4")
meta = json.loads(hook_job["meta"].read_text())
assert "auto_hook" not in meta["shorts"][0]
mem = app_module.jobs[hook_job["job_id"]]["result"]["clips"][0]
assert "auto_hook" not in mem
async def test_empty_text_400(self, client, hook_job):
resp = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0, "text": " "})
assert resp.status_code == 400
assert "Hook text" in resp.json()["detail"]
async def test_404_unknown_job(self, client):
resp = await client.post("/api/hook", json={
"job_id": "nope", "clip_index": 0, "text": "x"})
assert resp.status_code == 404
async def test_404_missing_metadata(self, client, hook_job):
os.remove(hook_job["meta"])
resp = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0, "text": "x"})
assert resp.status_code == 404
async def test_404_clip_out_of_range(self, client, hook_job):
resp = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 5, "text": "x"})
assert resp.status_code == 404
async def test_404_missing_file(self, client, hook_job):
resp = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0, "text": "x",
"input_filename": "gone.mp4"})
assert resp.status_code == 404