clipwright/tests/e2e/api/test_thumbnail_routes.py
pedro-bento 0040aa49da
All checks were successful
CI / dashboard-e2e (push) Successful in 1m44s
CI / unit (push) Successful in 29s
CI / backend-e2e (push) Successful in 1m17s
test/e2e-coverage (#5)
Reviewed-on: #5
Co-authored-by: pedro-bento <mail@pbento.pt>
Co-committed-by: pedro-bento <mail@pbento.pt>
2026-10-04 22:28:46 +01:00

585 lines
24 KiB
Python

"""L3 E2E: the Thumbnail Studio routes.
The Gemini seams (``analyze_video_for_titles`` / ``refine_titles`` /
``generate_thumbnail`` / ``generate_youtube_description`` / ``extract_face_frames``)
and the Postiz client are stubbed; the Whisper background path is kept off the
heavy ``clipwright.pipeline.main`` module by injecting a fake one. The routes
themselves — session bookkeeping, background tasks, path validation — run for
real through the shared ``client`` fixture.
"""
import asyncio
import os
import sys
import types
from types import SimpleNamespace
import pytest
pytestmark = pytest.mark.e2e
POSTIZ_HEADERS = {"X-Postiz-Url": "https://postiz.example", "X-Postiz-Key": "k"}
@pytest.fixture
def fake_pipeline(monkeypatch):
"""Fake ``clipwright.pipeline.main`` + ``transcribe_backends``.
``main`` imports ultralytics/mediapipe at module level, so it must never be
imported in the thin E2E environment. The upload route imports it lazily
inside its background task; this fixture puts a light stand-in in
``sys.modules`` first.
"""
import clipwright.pipeline as pkg
calls = SimpleNamespace(download=[], transcribe=[], release=[])
main = types.ModuleType("clipwright.pipeline.main")
def download_youtube_video(url, out_dir):
calls.download.append((url, out_dir))
path = os.path.join(out_dir, "downloaded.mp4")
with open(path, "wb") as fh:
fh.write(b"\x00" * 32)
return path, {"title": "Downloaded"}
def transcribe_video(path):
calls.transcribe.append(path)
return {"language": "en", "text": "hi there",
"segments": [{"start": 0.0, "end": 2.0, "text": "hi there"}]}
main.download_youtube_video = download_youtube_video
main.transcribe_video = transcribe_video
monkeypatch.setitem(sys.modules, "clipwright.pipeline.main", main)
backends = types.ModuleType("clipwright.pipeline.transcribe_backends")
backends.release_models = lambda: calls.release.append(True)
monkeypatch.setitem(sys.modules, "clipwright.pipeline.transcribe_backends", backends)
monkeypatch.setattr(pkg, "transcribe_backends", backends, raising=False)
return calls
@pytest.fixture
def thumb_stubs(monkeypatch):
"""Stub every thumbnail Gemini seam and record the calls."""
import clipwright.api.app as app
calls = SimpleNamespace(analyze=[], refine=[], generate=[], describe=[], frames=[])
results = SimpleNamespace(
analyze={"titles": ["T1", "T2"], "thumbnail_texts": ["TT1"],
"transcript_summary": "sum", "language": "en",
"segments": [{"start": 0.0, "end": 1.0, "text": "hi"}],
"video_duration": 1.0, "recommended": []},
refine={"titles": ["R1"], "thumbnail_texts": ["RT1"], "language": "es"},
generate=[{"url": "/thumbnails/gen1.jpg"}],
describe={"description": "A description"},
frames=[{"url": "/videos/x/frame1.jpg", "score": 1.0}],
)
errors = SimpleNamespace(analyze=None, refine=None, generate=None,
describe=None, frames=None)
def make(name):
def fn(*args, **kwargs):
getattr(calls, name).append((args, kwargs))
err = getattr(errors, name)
if err:
raise err
return getattr(results, name)
return fn
monkeypatch.setattr(app, "analyze_video_for_titles", make("analyze"))
monkeypatch.setattr(app, "refine_titles", make("refine"))
monkeypatch.setattr(app, "generate_thumbnail", make("generate"))
monkeypatch.setattr(app, "generate_youtube_description", make("describe"))
monkeypatch.setattr(app, "extract_face_frames", make("frames"))
return SimpleNamespace(calls=calls, results=results, errors=errors)
@pytest.fixture
def thumb_postiz(monkeypatch):
"""Minimal Postiz stub for the publish route."""
from clipwright.integrations import postiz as postiz_mod
state = SimpleNamespace(
integrations=[{"id": "yt-1", "name": "Chan", "identifier": "youtube",
"disabled": False}],
upload_result={"id": "m-1", "path": "media/p"},
create_result=[{"id": "post-1"}],
calls=SimpleNamespace(list=[], upload=[], create=[]),
)
def list_integrations(base, key, *a, **k):
state.calls.list.append((base, key))
return state.integrations
def upload_media(base, key, path, *a, **k):
state.calls.upload.append(path)
return state.upload_result
def create_post(base, key, payload, *a, **k):
state.calls.create.append(payload)
return state.create_result
monkeypatch.setattr(postiz_mod, "list_integrations", list_integrations)
monkeypatch.setattr(postiz_mod, "upload_media", upload_media)
monkeypatch.setattr(postiz_mod, "create_post", create_post)
return state
async def _wait_session(app, session_id, timeout=10.0):
"""Await the background Whisper task's completion event (bounded)."""
event = app.thumbnail_sessions[session_id].get("transcript_event")
if event is not None:
await asyncio.wait_for(event.wait(), timeout)
async def _poll_publish(client, publish_id, attempts=50):
for _ in range(attempts):
resp = await client.get(f"/api/thumbnail/publish/status/{publish_id}")
assert resp.status_code == 200
body = resp.json()
if body["status"] != "uploading":
return body
await asyncio.sleep(0)
raise AssertionError("publish background task did not finish")
def _video_file(app_state, name="video.mp4"):
path = app_state.up / name
path.write_bytes(b"fake-video-bytes")
return path
# --------------------------------------------------------------------------- #
# POST /api/thumbnail/upload
# --------------------------------------------------------------------------- #
async def test_upload_file_starts_background_transcription(client, app_state,
fake_pipeline):
resp = await client.post(
"/api/thumbnail/upload",
files={"file": ("clip.mp4", b"video-bytes", "video/mp4")})
assert resp.status_code == 200, resp.text
session_id = resp.json()["session_id"]
session = app_state.app.thumbnail_sessions[session_id]
assert session["video_path"].endswith("clip.mp4")
assert os.path.exists(session["video_path"])
await _wait_session(app_state.app, session_id)
session = app_state.app.thumbnail_sessions[session_id]
assert session["transcript_ready"] is True
assert session["video_duration"] == 2.0
assert session["language"] == "en"
assert fake_pipeline.transcribe == [session["video_path"]]
assert fake_pipeline.release == [True]
async def test_upload_url_defers_download_to_the_background_task(client, app_state,
fake_pipeline):
resp = await client.post("/api/thumbnail/upload",
data={"url": "https://youtu.be/arj7oStGLkU"})
assert resp.status_code == 200, resp.text
session_id = resp.json()["session_id"]
await _wait_session(app_state.app, session_id)
session = app_state.app.thumbnail_sessions[session_id]
assert session["video_path"].endswith("downloaded.mp4")
assert fake_pipeline.download == [
("https://youtu.be/arj7oStGLkU", app_state.app.UPLOAD_DIR)]
assert session["transcript_ready"] is True
async def test_upload_without_input_is_400(client, app_state, fake_pipeline):
resp = await client.post("/api/thumbnail/upload", data={})
assert resp.status_code == 400
assert "URL or File" in resp.json()["detail"]
async def test_upload_oversized_file_is_413(client, app_state, fake_pipeline,
monkeypatch):
monkeypatch.setattr(app_state.app, "MAX_FILE_SIZE_MB", 1)
big = b"x" * (1024 * 1024 + 64)
resp = await client.post(
"/api/thumbnail/upload",
files={"file": ("big.mp4", big, "video/mp4")})
assert resp.status_code == 413
assert "too large" in resp.json()["detail"].lower()
# Nothing was registered: the upload failed before the session existed.
assert app_state.app.thumbnail_sessions == {}
# --------------------------------------------------------------------------- #
# POST /api/thumbnail/analyze
# --------------------------------------------------------------------------- #
async def test_analyze_missing_key_is_400(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
resp = await client.post("/api/thumbnail/analyze",
files={"file": ("v.mp4", b"x", "video/mp4")})
assert resp.status_code == 400
assert "X-Gemini-Key" in resp.json()["detail"]
async def test_analyze_without_input_is_400(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
resp = await client.post("/api/thumbnail/analyze", data={})
assert resp.status_code == 400
assert "URL, File, or session_id" in resp.json()["detail"]
async def test_analyze_file_success_stores_session(client, app_state, thumb_stubs,
monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
resp = await client.post(
"/api/thumbnail/analyze",
files={"file": ("v.mp4", b"video", "video/mp4")})
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["titles"] == ["T1", "T2"]
assert body["thumbnail_texts"] == ["TT1"]
assert body["context"] == "sum"
session = app_state.app.thumbnail_sessions[body["session_id"]]
assert session["titles"] == ["T1", "T2"]
assert session["video_duration"] == 1.0
args = thumb_stubs.calls.analyze[0][0]
assert args[1].endswith("v.mp4")
assert args[2] is None # no pre-transcript on the direct-file path
async def test_analyze_reuses_a_session_transcript(client, app_state, thumb_stubs,
monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
event = asyncio.Event()
event.set()
video = _video_file(app_state, "pre.mp4")
app_state.app.thumbnail_sessions["sess-1"] = {
"video_path": str(video),
"transcript_event": event,
"transcript_ready": True,
"transcript": {"segments": [{"start": 0.0, "end": 1.0, "text": "pre"}]},
"transcript_segments": [{"start": 0.0, "end": 1.0, "text": "pre"}],
}
resp = await client.post("/api/thumbnail/analyze", data={"session_id": "sess-1"})
assert resp.status_code == 200, resp.text
# The pre-existing transcript is handed to the analyzer instead of re-Whispering.
assert thumb_stubs.calls.analyze[0][0][2] == \
{"segments": [{"start": 0.0, "end": 1.0, "text": "pre"}]}
async def test_analyze_session_without_video_is_404(client, app_state, thumb_stubs,
monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
event = asyncio.Event()
event.set()
app_state.app.thumbnail_sessions["sess-novideo"] = {
"video_path": None,
"transcript_event": event,
"transcript_ready": False,
}
resp = await client.post("/api/thumbnail/analyze",
data={"session_id": "sess-novideo"})
assert resp.status_code == 404
assert "Video file not found" in resp.json()["detail"]
async def test_analyze_session_with_transcription_error_is_500(client, app_state,
thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
event = asyncio.Event()
event.set()
app_state.app.thumbnail_sessions["sess-err"] = {
"video_path": None,
"transcript_event": event,
"transcript_error": "whisper died",
}
resp = await client.post("/api/thumbnail/analyze", data={"session_id": "sess-err"})
assert resp.status_code == 500
assert "Transcription failed" in resp.json()["detail"]
async def test_analyze_backend_error_is_500(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
thumb_stubs.errors.analyze = RuntimeError("gemini down")
resp = await client.post(
"/api/thumbnail/analyze",
files={"file": ("v.mp4", b"video", "video/mp4")})
assert resp.status_code == 500
assert "gemini down" in resp.json()["detail"]
# --------------------------------------------------------------------------- #
# POST /api/thumbnail/titles
# --------------------------------------------------------------------------- #
async def test_titles_manual_title_creates_session(client, app_state, thumb_stubs,
monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
resp = await client.post("/api/thumbnail/titles", json={"title": "Manual Title"})
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["titles"] == ["Manual Title"]
assert app_state.app.thumbnail_sessions[body["session_id"]]["titles"] == \
["Manual Title"]
async def test_titles_missing_key_is_400(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
resp = await client.post("/api/thumbnail/titles", json={"title": "T"})
assert resp.status_code == 400
async def test_titles_unknown_session_is_404(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
resp = await client.post("/api/thumbnail/titles",
json={"session_id": "nope", "message": "shorter"})
assert resp.status_code == 404
assert "Session not found" in resp.json()["detail"]
async def test_titles_without_message_is_400(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
app_state.app.thumbnail_sessions["t1"] = {
"context": "ctx", "titles": ["a"], "language": "en", "conversation": []}
resp = await client.post("/api/thumbnail/titles", json={"session_id": "t1"})
assert resp.status_code == 400
assert "message or title" in resp.json()["detail"]
async def test_titles_refinement_updates_the_session(client, app_state, thumb_stubs,
monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
app_state.app.thumbnail_sessions["t1"] = {
"context": "ctx", "titles": ["a"], "language": "en", "conversation": []}
resp = await client.post("/api/thumbnail/titles",
json={"session_id": "t1", "message": "make it shorter"})
assert resp.status_code == 200, resp.text
assert resp.json()["titles"] == ["R1"]
assert resp.json()["language"] == "es"
session = app_state.app.thumbnail_sessions["t1"]
assert session["titles"] == ["R1"]
assert session["conversation"][-1]["role"] == "assistant"
args = thumb_stubs.calls.refine[0][0]
assert args[1] == "ctx" and args[2] == "make it shorter"
async def test_titles_refinement_error_is_500(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
app_state.app.thumbnail_sessions["t1"] = {
"context": "ctx", "titles": ["a"], "language": "en", "conversation": []}
thumb_stubs.errors.refine = RuntimeError("refine failed")
resp = await client.post("/api/thumbnail/titles",
json={"session_id": "t1", "message": "x"})
assert resp.status_code == 500
assert "refine failed" in resp.json()["detail"]
# --------------------------------------------------------------------------- #
# POST /api/thumbnail/generate
# --------------------------------------------------------------------------- #
async def test_generate_missing_key_is_400(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
resp = await client.post("/api/thumbnail/generate",
data={"session_id": "s", "title": "T"})
assert resp.status_code == 400
async def test_generate_success_clamps_and_passes_session_context(client, app_state,
thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
app_state.app.thumbnail_sessions["g1"] = {
"context": "ctx", "titles": ["My Title"], "thumbnail_texts": ["HOOK"],
"language": "en", "frames": [{"url": "/videos/x/f.jpg"}]}
resp = await client.post(
"/api/thumbnail/generate",
data={"session_id": "g1", "title": "My Title", "count": "9",
"frame": "/videos/x/f.jpg"})
assert resp.status_code == 200, resp.text
assert resp.json()["thumbnails"] == [{"url": "/thumbnails/gen1.jpg"}]
args, kwargs = thumb_stubs.calls.generate[0]
assert args[1] == "My Title"
assert args[6] == 6 # count is clamped to 6
assert kwargs["thumbnail_text_hint"] == "HOOK"
assert kwargs["frame_reference"] == {"url": "/videos/x/f.jpg"}
assert kwargs["burn_text"] is True
async def test_generate_empty_result_is_500(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
thumb_stubs.results.generate = []
resp = await client.post("/api/thumbnail/generate",
data={"session_id": "g", "title": "T"})
assert resp.status_code == 500
assert "generation failed" in resp.json()["detail"].lower()
# --------------------------------------------------------------------------- #
# GET /api/thumbnail/frames/{session_id}
# --------------------------------------------------------------------------- #
async def test_frames_unknown_session_is_404(client, app_state, thumb_stubs):
resp = await client.get("/api/thumbnail/frames/nope")
assert resp.status_code == 404
assert "Session not found" in resp.json()["detail"]
async def test_frames_are_extracted_once_and_cached(client, app_state, thumb_stubs):
app_state.app.thumbnail_sessions["f1"] = {"video_path": str(_video_file(app_state))}
r1 = await client.get("/api/thumbnail/frames/f1")
assert r1.status_code == 200
assert r1.json()["frames"] == [{"url": "/videos/x/frame1.jpg", "score": 1.0}]
r2 = await client.get("/api/thumbnail/frames/f1")
assert r2.json()["frames"] == r1.json()["frames"]
assert len(thumb_stubs.calls.frames) == 1 # cached on the session
async def test_frames_without_video_are_empty(client, app_state, thumb_stubs):
app_state.app.thumbnail_sessions["f2"] = {"video_path": None}
resp = await client.get("/api/thumbnail/frames/f2")
assert resp.status_code == 200
assert resp.json()["frames"] == []
assert thumb_stubs.calls.frames == []
# --------------------------------------------------------------------------- #
# POST /api/thumbnail/describe
# --------------------------------------------------------------------------- #
async def test_describe_missing_key_is_400(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
resp = await client.post("/api/thumbnail/describe",
json={"session_id": "s", "title": "T"})
assert resp.status_code == 400
async def test_describe_unknown_session_is_404(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
resp = await client.post("/api/thumbnail/describe",
json={"session_id": "nope", "title": "T"})
assert resp.status_code == 404
async def test_describe_without_segments_is_400(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
app_state.app.thumbnail_sessions["d1"] = {"transcript_segments": []}
resp = await client.post("/api/thumbnail/describe",
json={"session_id": "d1", "title": "T"})
assert resp.status_code == 400
assert "transcript segments" in resp.json()["detail"]
async def test_describe_success(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
segments = [{"start": 0.0, "end": 5.0, "text": "hello"}]
app_state.app.thumbnail_sessions["d1"] = {
"transcript_segments": segments, "language": "en", "video_duration": 5.0}
resp = await client.post("/api/thumbnail/describe",
json={"session_id": "d1", "title": "My Title"})
assert resp.status_code == 200
assert resp.json()["description"] == "A description"
args = thumb_stubs.calls.describe[0][0]
assert args[1] == "My Title" and args[2] == segments
# --------------------------------------------------------------------------- #
# POST /api/thumbnail/publish + GET status
# --------------------------------------------------------------------------- #
async def test_publish_unknown_session_is_404(client, app_state, thumb_postiz):
resp = await client.post(
"/api/thumbnail/publish", headers=POSTIZ_HEADERS,
data={"session_id": "nope", "title": "T", "description": "D",
"thumbnail_url": "/thumbnails/t.jpg"})
assert resp.status_code == 404
async def test_publish_missing_video_is_404(client, app_state, thumb_postiz):
app_state.app.thumbnail_sessions["p1"] = {"video_path": None}
resp = await client.post(
"/api/thumbnail/publish", headers=POSTIZ_HEADERS,
data={"session_id": "p1", "title": "T", "description": "D",
"thumbnail_url": "/thumbnails/t.jpg"})
assert resp.status_code == 404
assert "video file" in resp.json()["detail"].lower()
async def test_publish_thumbnail_path_traversal_is_400(client, app_state, thumb_postiz):
_video_file(app_state, "pub.mp4")
app_state.app.thumbnail_sessions["p1"] = {
"video_path": str(app_state.up / "pub.mp4")}
resp = await client.post(
"/api/thumbnail/publish", headers=POSTIZ_HEADERS,
data={"session_id": "p1", "title": "T", "description": "D",
"thumbnail_url": "../../etc/passwd"})
assert resp.status_code == 400
assert "Invalid thumbnail path" in resp.json()["detail"]
assert thumb_postiz.calls.create == []
async def test_publish_missing_thumbnail_file_is_404(client, app_state, thumb_postiz):
_video_file(app_state, "pub.mp4")
app_state.app.thumbnail_sessions["p1"] = {
"video_path": str(app_state.up / "pub.mp4")}
resp = await client.post(
"/api/thumbnail/publish", headers=POSTIZ_HEADERS,
data={"session_id": "p1", "title": "T", "description": "D",
"thumbnail_url": "/thumbnails/missing.jpg"})
assert resp.status_code == 404
assert "Thumbnail file not found" in resp.json()["detail"]
async def test_publish_success_runs_the_background_post(client, app_state, thumb_postiz):
_video_file(app_state, "pub.mp4")
(app_state.out / "thumbnails" / "t.jpg").write_bytes(b"jpeg-bytes")
app_state.app.thumbnail_sessions["p1"] = {
"video_path": str(app_state.up / "pub.mp4")}
resp = await client.post(
"/api/thumbnail/publish", headers=POSTIZ_HEADERS,
data={"session_id": "p1", "title": "My Title", "description": "My description #tag",
"thumbnail_url": "/thumbnails/t.jpg"})
assert resp.status_code == 200, resp.text
publish_id = resp.json()["publish_id"]
status = await _poll_publish(client, publish_id)
assert status["status"] == "done"
assert status["result"] == thumb_postiz.create_result
assert thumb_postiz.calls.upload[0].endswith("pub.mp4")
payload = thumb_postiz.calls.create[0]
assert payload["type"] == "now"
assert payload["posts"][0]["integration"]["id"] == "yt-1"
settings = payload["posts"][0]["settings"]
assert settings["__type"] == "youtube"
assert settings["title"] == "My Title"
assert settings["tags"] == [{"value": "tag", "label": "tag"}]
async def test_publish_failure_marks_the_job_failed(client, app_state, thumb_postiz):
_video_file(app_state, "pub.mp4")
(app_state.out / "thumbnails" / "t.jpg").write_bytes(b"jpeg-bytes")
app_state.app.thumbnail_sessions["p1"] = {
"video_path": str(app_state.up / "pub.mp4")}
thumb_postiz.upload_result = {} # no media id -> PostizError(502)
resp = await client.post(
"/api/thumbnail/publish", headers=POSTIZ_HEADERS,
data={"session_id": "p1", "title": "T", "description": "D",
"thumbnail_url": "/thumbnails/t.jpg"})
assert resp.status_code == 200
publish_id = resp.json()["publish_id"]
status = await _poll_publish(client, publish_id)
assert status["status"] == "failed"
assert "upload failed" in status["error"].lower()
async def test_publish_status_unknown_is_404(client, app_state):
resp = await client.get("/api/thumbnail/publish/status/nope")
assert resp.status_code == 404
assert "Publish job not found" in resp.json()["detail"]