test/e2e-coverage (#5)
All checks were successful
CI / dashboard-e2e (push) Successful in 1m44s
CI / unit (push) Successful in 29s
CI / backend-e2e (push) Successful in 1m17s

Reviewed-on: #5
Co-authored-by: pedro-bento <mail@pbento.pt>
Co-committed-by: pedro-bento <mail@pbento.pt>
This commit is contained in:
pedro-bento 2026-10-04 22:28:46 +01:00 committed by pedro-bento
parent 1dec0dd1af
commit 0040aa49da
59 changed files with 7496 additions and 18 deletions

View file

@ -5,43 +5,76 @@ on:
branches: [main]
pull_request:
env:
PYTHONHASHSEED: "0"
TZ: UTC
PIP_DISABLE_PIP_VERSION_CHECK: "1"
jobs:
backend-tests:
# Fast unit suite. No ffmpeg, no ML stack, no pytest-timeout requirement.
unit:
runs-on: ubuntu-latest
timeout-minutes: 15
# The Forgejo runner cannot provision Python 3.11 via actions/setup-python
# ("Version 3.11 was not found in the local cache"), so the job runs inside
# a container that already has Python 3.11. It must also ship Node and git:
# ("Version 3.11 was not found in the local cache"), so every job runs in a
# container that already has Python 3.11. It must also ship Node and git:
# the runner executes JS actions (actions/checkout) by invoking `node`
# inside the job container, so a python-only image fails at checkout.
# inside the job container.
container: nikolaik/python-nodejs:python3.11-nodejs20
steps:
- uses: actions/checkout@v4
# Shared thin test environment (see requirements-test.txt): everything the
# collected tests import at module level, WITHOUT the heavy ML stack
# (torch/ultralytics/mediapipe/faster-whisper), which the pipeline modules
# import lazily behind their feature gates.
- name: Install test dependencies
run: pip install -r requirements-test.txt
- name: Run tests
run: pytest tests/ -v
- name: Run unit tests
# Exclude the E2E tree from *collection*: `-m "not e2e"` only filters
# execution, but pytest still imports every module to collect it, and the
# pipeline E2E modules import the pipeline (tqdm/scenedetect/ML) which is
# intentionally absent from the unit environment.
run: pytest tests/ --ignore=tests/e2e -m "not e2e" -q
frontend-build:
# Backend E2E: API + pipeline. ffmpeg/ffprobe must be installed in-job; the
# E2E requirements add pytest-asyncio/asgi-lifespan/pytest-timeout and the
# pure-Python scene engine. API and pipeline run as separate processes so the
# pipeline tests' fake `clipwright.pipeline.main` can never leak into the API
# process. No ML stack: detectors are stubbed, only ffmpeg is real.
backend-e2e:
runs-on: ubuntu-latest
# Same reason as backend-tests: the Forgejo runner cannot use
# actions/setup-node's Node download + GitHub artifact-cache service (both
# time out against the act runner: "connect ETIMEDOUT ...:41759"), and
# actions/setup-python cannot provision 3.11 either. This container already
# ships Node 20 + npm + git, so actions/checkout works and setup-node is
# dropped entirely.
timeout-minutes: 30
container: nikolaik/python-nodejs:python3.11-nodejs20
steps:
- uses: actions/checkout@v4
- name: Install ffmpeg
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg && ffmpeg -version | head -1
- name: Install E2E dependencies
run: pip install -r requirements-e2e.txt
- name: Run API E2E
run: pytest tests/e2e/api -m e2e -q --timeout=120
- name: Run pipeline E2E (non-ML)
run: pytest tests/e2e/pipeline -m "e2e and not ml" -q --timeout=120
# Dashboard E2E (Playwright). The container already ships Node 20 + npm + git,
# so actions/setup-node and actions/cache are deliberately NOT used (their
# Node download / cache endpoints time out against the act runner:
# "connect ETIMEDOUT 172.27.0.4:41759"). Playwright is retry-free by config;
# install browsers fresh each run.
dashboard-e2e:
runs-on: ubuntu-latest
timeout-minutes: 30
container: nikolaik/python-nodejs:python3.11-nodejs20
defaults:
run:
working-directory: dashboard
steps:
- uses: actions/checkout@v4
- name: Install ffmpeg (E2E media fixture)
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg
- name: Install dependencies
run: npm ci
- name: Install Playwright browsers
run: npx playwright install --with-deps chromium
- name: Lint
run: npm run lint
- name: Build
run: npm run build
- name: Browser E2E
run: npm run test:e2e

2
dashboard/e2e/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
.artifacts/
.test-results/

View file

@ -0,0 +1,389 @@
// State-machine route interception for the dashboard's backend.
//
// Every spec runs against the built dashboard with **zero unmocked network**:
// this fixture installs a catch-all that aborts anything off-origin, then the
// specific /api, /videos and /thumbnails handlers that answer with deterministic
// fixtures. The only "state" is a counter per endpoint, which is enough to model
// queued -> processing -> completed without a single timer or sleep in a spec —
// the app's own 2s poll drives it, and Playwright's auto-wait absorbs the gap.
export const BASE_ORIGIN = 'http://127.0.0.1:4173';
export const JOB_ID = '11111111-1111-4111-8111-111111111111';
// 1x1 transparent PNG, decoded by the browser at route.fulfill time.
const TINY_PNG =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC';
export function defaultClips() {
return [
{
video_url: `/videos/${JOB_ID}/clip_1.mp4`,
video_title_for_youtube_short: 'First viral clip',
video_description_for_tiktok: 'TikTok caption one #viral #shorts',
video_description_for_instagram: 'Instagram caption one #reels',
start: 0,
end: 30,
predicted_score: 91,
why: 'Opens on a strong claim the rest of the clip pays off.',
auto_hook: { text: 'Watch this' },
},
{
video_url: `/videos/${JOB_ID}/clip_2.mp4`,
video_title_for_youtube_short: 'Second viral clip',
video_description_for_tiktok: 'TikTok caption two #viral',
video_description_for_instagram: 'Instagram caption two #reels',
start: 40,
end: 70,
predicted_score: 77,
why: 'A clean story beat with a natural ending.',
auto_hook: null,
},
];
}
export function defaultResults() {
return {
clips: defaultClips(),
cost_analysis: { input_tokens: 1200, output_tokens: 400, total_cost: 0.00123 },
};
}
export function defaultEdl() {
return {
job_id: JOB_ID,
clip_index: 0,
title: 'First viral clip',
segments: [{ start: 0, end: 30 }],
framing: 'auto',
canonical_range: { start: 0, end: 30 },
duration: 30,
current_file: 'clip_1.mp4',
has_captions: false,
words: [
{ w: 'Hello', s: 0, e: 0.6 },
{ w: 'world', s: 0.6, e: 1.2 },
{ w: 'this', s: 1.2, e: 1.6 },
{ w: 'is', s: 1.6, e: 1.9 },
{ w: 'a', s: 1.9, e: 2.1 },
{ w: 'clip', s: 2.1, e: 2.7 },
],
source: { available: true, url: `/api/source/${JOB_ID}`, duration: 120, duration_estimated: false },
limits: { max_segments: 12, min_segment_seconds: 0.5, max_total_seconds: 180 },
};
}
export function defaultScenes() {
return {
job_id: JOB_ID,
clip_index: 0,
crop_width_fraction: 0.5,
preview_url: `/videos/${JOB_ID}/scenes_preview.mp4`,
saved_overrides: {},
scenes: [
{
index: 0,
start: 0,
end: 15,
suggested_center: 0.5,
suggested_center_y: 0.5,
thumbnail_url: `/thumbnails/${JOB_ID}/scene_0.png`,
},
{
index: 1,
start: 15,
end: 30,
suggested_center: 0.4,
suggested_center_y: 0.5,
thumbnail_url: `/thumbnails/${JOB_ID}/scene_1.png`,
},
],
};
}
export function defaultIntegrations() {
return [
{ id: 'int-yt', identifier: 'youtube', name: 'My YouTube', disabled: false },
{ id: 'int-tt', identifier: 'tiktok', name: 'My TikTok', disabled: false },
];
}
function json(route, data, status = 200) {
return route.fulfill({
status,
contentType: 'application/json',
body: JSON.stringify(data),
});
}
function video(route) {
return route.fulfill({ status: 200, contentType: 'video/mp4', body: '' });
}
function png(route) {
return route.fulfill({ status: 200, contentType: 'image/png', body: atob(TINY_PNG) });
}
/**
* Install all network handlers on `page`. Returns a mutable `state` object so a
* spec can assert on call counts (e.g. the quality gate resend).
*/
export async function installApiMocks(page, options = {}) {
const opts = {
config: {
youtubeUrlEnabled: true,
billingEnabled: false,
jobRetentionSeconds: 86400,
localLlm: null,
},
clips: defaultClips(),
// 'queued' | 'needs_confirmation', consumed in order.
processSequence: ['queued'],
// 'processing' | 'completed' | 'failed', consumed in order; the last
// entry repeats once exhausted.
statusSequence: ['processing', 'completed'],
transcript: { captions: [], durationSec: 30, language: 'en' },
edl: defaultEdl(),
scenes: defaultScenes(),
integrations: defaultIntegrations(),
thumbnail: {
analyze: {
session_id: 'session-e2e',
titles: ['Mock title one', 'Mock title two'],
thumbnail_texts: ['Big win', 'How to'],
context: '',
language: 'en',
recommended: [{ index: 0, reason: 'clearest promise' }],
},
generate: {
thumbnails: [
{ url: '/thumbnails/e2e/thumb_1.png', text: 'Big win', why: 'bright and readable' },
{ url: '/thumbnails/e2e/thumb_2.png', text: 'How to', why: 'strong contrast' },
],
},
describe: { description: 'A generated description with 00:00 chapters.' },
},
tools: {
transcript: {
title: 'Mock Video',
channel: 'Mock Channel',
duration: 125,
kind: 'auto',
language: 'en',
video_id: 'dQw4w9WgXcQ',
cached: false,
languages: [{ code: 'en', kind: 'auto', name: 'English', request: 'en' }],
segments: [
{ start: 0, dur: 2, text: 'Hello world' },
{ start: 2, dur: 2, text: 'Second line' },
],
},
},
...options,
};
const state = {
processCalls: 0,
statusCalls: 0,
rerenderCalls: 0,
reframeCalls: 0,
subtitleCalls: 0,
hookCalls: 0,
postCalls: 0,
thumbnailPublishCalls: 0,
thumbnailPublishStatusCalls: 0,
};
// Catch-all: allow same-origin and in-page schemes, abort everything else.
// Registered first so the specific handlers below (registered later) win.
await page.route('**/*', (route) => {
const url = new URL(route.request().url());
if (url.origin === BASE_ORIGIN || url.protocol === 'data:' || url.protocol === 'blob:') {
return route.continue();
}
return route.abort();
});
await page.route('**/api/**', async (route) => {
const req = route.request();
const method = req.method();
const path = new URL(req.url()).pathname;
if (method === 'GET' && path === '/api/config') return json(route, opts.config);
if (method === 'POST' && path === '/api/process') {
const phase = opts.processSequence[Math.min(state.processCalls, opts.processSequence.length - 1)];
state.processCalls += 1;
if (phase === 'needs_confirmation') {
return json(route, {
needs_confirmation: true,
quality_check: { max_height: 360, min_height: 720, cookies_invalid: false },
});
}
return json(route, { job_id: JOB_ID, status: 'queued', partial: null });
}
if (method === 'GET' && path.startsWith('/api/status/')) {
const phase = opts.statusSequence[Math.min(state.statusCalls, opts.statusSequence.length - 1)];
state.statusCalls += 1;
if (phase === 'failed') {
return json(route, {
status: 'failed',
logs: ['boom'],
log_times: [Date.now() / 1000],
result: null,
queue: null,
partial: null,
error: 'The video is too short to clip.',
});
}
const result = phase === 'completed'
? { clips: opts.clips, cost_analysis: defaultResults().cost_analysis }
: { clips: opts.clips.slice(0, 1), cost_analysis: null };
return json(route, {
status: phase,
logs: phase === 'completed' ? ['Done.'] : ['Rendering clip 1...'],
log_times: [Date.now() / 1000],
result,
queue: null,
partial: null,
});
}
if (method === 'GET' && path.startsWith('/api/source-url/')) {
return json(route, { url: `/videos/${JOB_ID}/source.mp4` });
}
if (method === 'GET' && path.startsWith('/api/source/')) return video(route);
if (method === 'GET' && /^\/api\/jobs\/[^/]+\/download-all$/.test(path)) {
return route.fulfill({ status: 200, contentType: 'application/zip', body: 'PK-e2e-zip' });
}
const clipMatch = path.match(/^\/api\/clip\/([^/]+)\/(\d+)\/(transcript|edl|scenes)$/);
if (method === 'GET' && clipMatch) {
const kind = clipMatch[3];
if (kind === 'transcript') return json(route, opts.transcript);
if (kind === 'edl') return json(route, opts.edl);
return json(route, opts.scenes);
}
if (method === 'POST' && path === '/api/clip/rerender') {
state.rerenderCalls += 1;
const body = req.postDataJSON();
const segments = body?.segments || [{ start: 0, end: 30 }];
return json(route, {
new_video_url: `/videos/${JOB_ID}/recut_e2e_clip_1.mp4`,
recipe: { v: 1, segments, canonical_range: { start: 0, end: 30 } },
framing: body?.framing || 'auto',
});
}
if (method === 'POST' && path === '/api/clip/reframe') {
state.reframeCalls += 1;
return json(route, {
new_video_url: `/videos/${JOB_ID}/recut_e2e_reframe_clip_1.mp4`,
recipe: { v: 1, segments: [{ start: 0, end: 30 }], canonical_range: { start: 0, end: 30 } },
framing: 'auto',
framed_scenes: [0],
});
}
if (method === 'POST' && path === '/api/subtitle/remove') {
state.subtitleCalls += 1;
return json(route, { success: true, new_video_url: `/videos/${JOB_ID}/clean_clip_1.mp4` });
}
if (method === 'POST' && path === '/api/subtitle') {
state.subtitleCalls += 1;
return json(route, { new_video_url: `/videos/${JOB_ID}/subtitled_e2e_clip_1.mp4` });
}
if (method === 'POST' && path === '/api/hook') {
state.hookCalls += 1;
const body = req.postDataJSON();
return json(route, {
new_video_url: `/videos/${JOB_ID}/hooked_e2e_clip_1.mp4`,
burned_hook: body?.remove ? null : { text: body?.text || 'Hook' },
});
}
if (method === 'POST' && path === '/api/effects/generate') {
return json(route, { effects: { segments: [{ start: 0, end: 2, zoom: 1.2 }] } });
}
if (method === 'POST' && path === '/api/edit') {
return json(route, { new_video_url: `/videos/${JOB_ID}/edited_e2e_clip_1.mp4` });
}
if (method === 'GET' && path === '/api/postiz/integrations') {
return json(route, { integrations: opts.integrations });
}
if (method === 'POST' && path === '/api/postiz/post') {
state.postCalls += 1;
return json(route, {
success: true,
results: {},
posted: [{ id: 'int-yt', name: 'My YouTube', identifier: 'youtube' }],
});
}
if (method === 'GET' && path === '/api/postiz/scheduled') {
return json(route, { scheduled_posts: [] });
}
if (method === 'POST' && path === '/api/thumbnail/upload') {
return json(route, { session_id: 'session-e2e' });
}
if (method === 'POST' && path === '/api/thumbnail/analyze') {
return json(route, opts.thumbnail.analyze);
}
if (method === 'POST' && path === '/api/thumbnail/titles') {
return json(route, {
session_id: 'session-e2e',
titles: opts.thumbnail.analyze.titles,
thumbnail_texts: opts.thumbnail.analyze.thumbnail_texts,
recommended: [],
});
}
if (method === 'POST' && path === '/api/thumbnail/generate') {
return json(route, opts.thumbnail.generate);
}
if (method === 'GET' && path.startsWith('/api/thumbnail/frames/')) {
return json(route, { frames: [] });
}
if (method === 'POST' && path === '/api/thumbnail/describe') {
return json(route, opts.thumbnail.describe);
}
if (method === 'POST' && path === '/api/thumbnail/publish') {
state.thumbnailPublishCalls += 1;
return json(route, { publish_id: 'pub-e2e', status: 'uploading' });
}
if (method === 'GET' && path.startsWith('/api/thumbnail/publish/status/')) {
state.thumbnailPublishStatusCalls += 1;
return json(route, { status: 'done', result: { id: 'post-e2e' }, error: null });
}
if (method === 'GET' && path === '/api/tools/youtube-transcript') {
return json(route, opts.tools.transcript);
}
if (method === 'POST' && path === '/api/tools/youtube-metadata') {
const body = req.postDataJSON() || {};
if (body.mode === 'titles') {
return json(route, { mode: 'titles', titles: [{ title: 'Mock title', angle: 'how-to' }] });
}
if (body.mode === 'description') {
return json(route, { mode: 'description', description: 'Mock description for the video.' });
}
return json(route, { mode: 'tags', tags: ['mock', 'tags', 'example'], characters: 17 });
}
return json(route, { detail: `no e2e mock for ${method} ${path}` }, 404);
});
await page.route('**/videos/**', (route) => video(route));
await page.route('**/thumbnails/**', (route) => png(route));
return state;
}

View file

@ -0,0 +1,63 @@
// App-level helpers shared by the specs: localStorage seeding (Gemini key,
// Postiz config, a restored session), the in-browser render seam, and a single
// `openApp` that installs mocks, seeds storage and navigates.
import { installApiMocks, JOB_ID, defaultClips, defaultResults } from './api-mocks.js';
// Mirrors SECRET_KEY in src/App.jsx (no VITE_ENCRYPTION_KEY is set by the build).
const SECRET_KEY = 'Clipwright-Static-Salt-Change-Me';
export function encryptSecret(text) {
let xor = '';
for (let i = 0; i < text.length; i += 1) {
xor += String.fromCharCode(text.charCodeAt(i) ^ SECRET_KEY.charCodeAt(i % SECRET_KEY.length));
}
return `ENC:${btoa(xor)}`;
}
export async function seedApp(page, { geminiKey = 'e2e-gemini-key', postizUrl, postizKey, session } = {}) {
await page.addInitScript((payload) => {
try {
// A stored consent decision keeps the cookie banner out of the way
// (the banner is otherwise shown to EEA timezones, which the CI
// runner's TZ would make nondeterministic).
window.localStorage.setItem('clipwright_consent', JSON.stringify({
v: 1, ts: new Date().toISOString(), necessary: true, analytics: true, marketing: false,
}));
if (payload.geminiKey) window.localStorage.setItem('gemini_key', payload.geminiKey);
if (payload.postizUrl) window.localStorage.setItem('postiz_url', payload.postizUrl);
if (payload.encryptedPostizKey) window.localStorage.setItem('postiz_key_v1', payload.encryptedPostizKey);
if (payload.session) window.localStorage.setItem('clipwright_session', JSON.stringify(payload.session));
} catch (_) { /* storage unavailable */ }
}, {
geminiKey,
postizUrl,
encryptedPostizKey: postizKey ? encryptSecret(postizKey) : null,
session,
});
// Replace the WebCodecs/Remotion render with a deterministic blob URL so the
// specs never depend on hardware encoders. See src/lib/renderInBrowser.js.
await page.addInitScript(() => {
window.__CW_E2E_RENDER__ = () => 'blob:http://127.0.0.1:4173/e2e-render';
});
}
export function completedSession({ jobId = JOB_ID, clips = defaultClips() } = {}) {
return {
jobId,
status: 'complete',
results: { clips, cost_analysis: defaultResults().cost_analysis },
processingMedia: null,
activeTab: 'dashboard',
timestamp: Date.now(),
};
}
export async function openApp(page, { hash = '#app', seed, mocks } = {}) {
const state = await installApiMocks(page, mocks);
await seedApp(page, seed);
await page.goto(`/${hash}`);
return state;
}
export { installApiMocks, JOB_ID, defaultClips, defaultResults };

View file

@ -0,0 +1,26 @@
// Builds the tiny media the specs upload. ffmpeg is required by the plan; when
// it is absent (a bare `npm test` on a machine without it) we still write a
// non-empty placeholder so the upload path is exercised rather than skipped.
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import { ARTIFACTS_DIR, SIXTY_MP4 } from './media.js';
export default function globalSetup() {
fs.mkdirSync(ARTIFACTS_DIR, { recursive: true });
try {
execFileSync('ffmpeg', [
'-y',
'-f', 'lavfi', '-i', 'testsrc=size=160x90:rate=30:duration=60',
'-f', 'lavfi', '-i', 'sine=frequency=440:duration=60',
'-c:v', 'libx264', '-pix_fmt', 'yuv420p',
'-c:a', 'aac', '-shortest',
SIXTY_MP4,
], { stdio: 'ignore' });
console.log(`[e2e] built ${SIXTY_MP4}`);
} catch (err) {
if (!fs.existsSync(SIXTY_MP4)) {
fs.writeFileSync(SIXTY_MP4, 'clipwright-e2e-placeholder');
}
console.warn(`[e2e] ffmpeg unavailable, wrote a placeholder media file: ${err.message}`);
}
}

View file

@ -0,0 +1,15 @@
// Media used by the browser E2E specs.
//
// Nothing binary is committed: global-setup builds a tiny mp4 with ffmpeg into
// e2e/.artifacts (git-ignored) and the specs read the path from here. The file
// only has to be a real, non-empty video container — the dashboard's upload
// path reads its duration from the browser and falls back gracefully when the
// browser cannot decode the codec, so an undecodable build still exercises the
// flow.
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const here = path.dirname(fileURLToPath(import.meta.url));
export const ARTIFACTS_DIR = path.join(here, '..', '.artifacts');
export const SIXTY_MP4 = path.join(ARTIFACTS_DIR, 'sixty.mp4');

View file

@ -0,0 +1,53 @@
// Browser E2E config. Two projects:
// - `mock` (default): every network edge is intercepted, no retries, one
// worker. This is the lane that must stay green in CI.
// - `real`: drives the real backend (uvicorn + stub pipeline). Kept separate
// so the mocked lane never depends on Python.
/* global process */
import { defineConfig, devices } from '@playwright/test';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const dashboardDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
export default defineConfig({
testDir: './specs',
// No retries anywhere: a flaky test is a bug, not a coin flip.
retries: 0,
// One worker keeps the shared preview server and the deterministic fixtures
// predictable.
workers: 1,
fullyParallel: false,
timeout: 30_000,
expect: { timeout: 5_000 },
reporter: [['list']],
outputDir: './.test-results',
globalSetup: './fixtures/global-setup.js',
use: {
baseURL: 'http://127.0.0.1:4173',
trace: 'retain-on-failure',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
},
projects: [
{
name: 'mock',
testIgnore: /real-backend\.spec\.js/,
use: { ...devices['Desktop Chrome'] },
},
{
name: 'real',
testMatch: /real-backend\.spec\.js/,
use: { ...devices['Desktop Chrome'] },
},
],
webServer: {
command: 'npm run build && npx vite preview --port 4173 --strictPort --host 127.0.0.1',
cwd: dashboardDir,
url: 'http://127.0.0.1:4173',
reuseExistingServer: !process.env.CI,
timeout: 120_000,
stdout: 'ignore',
stderr: 'pipe',
},
});

View file

@ -0,0 +1,35 @@
import { test, expect } from '@playwright/test';
import { openApp, completedSession, JOB_ID } from '../fixtures/app.js';
test.describe('clip editor', () => {
test('edits the recipe and re-renders through /api/clip/rerender', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() } });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await page.getByRole('button', { name: 'edit clip' }).first().click();
await expect(page.getByRole('heading', { name: 'edit clip' })).toBeVisible();
// The EDL loaded (the loading state is gone) and its segment is listed.
await expect(page.getByRole('button', { name: /add segment/i })).toBeVisible();
await expect(page.getByLabel('segment 1 start')).toHaveValue('0');
// Add a second segment so the recipe is dirty and renderable.
await page.getByRole('button', { name: /add segment/i }).click();
await expect(page.getByLabel('segment 2 start')).toBeVisible();
const requestPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/clip/rerender'),
);
await page.getByRole('button', { name: /re-render/i }).click();
const request = await requestPromise;
const body = request.postDataJSON();
expect(body.job_id).toBe(JOB_ID);
expect(body.clip_index).toBe(0);
expect(body.segments).toHaveLength(2);
expect(body.framing).toBe('auto');
expect(body.reapply_captions).toBe(true);
// The new preview URL is adopted; the editor stays open.
await expect(page.getByRole('heading', { name: 'edit clip' })).toBeVisible();
});
});

View file

@ -0,0 +1,45 @@
import { test, expect } from '@playwright/test';
import { installApiMocks } from '../fixtures/app.js';
// The free tools are static, no-React pages emitted by vite-plugin-seo. They
// talk to the same /api origin, so the same route mocks apply.
test.describe('free tools', () => {
test('youtube transcript generator renders captions', async ({ page }) => {
await installApiMocks(page);
await page.goto('/youtube-transcript-generator.html');
const requestPromise = page.waitForRequest(
(r) => r.url().includes('/api/tools/youtube-transcript'),
);
await page.fill('#yt-url', 'https://www.youtube.com/watch?v=dQw4w9WgXcQ');
await page.click('#yt-form button[type="submit"]');
const request = await requestPromise;
expect(new URL(request.url()).searchParams.get('url'))
.toBe('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
await expect(page.locator('#yt-title')).toHaveText('Mock Video');
await expect(page.locator('#yt-result')).toBeVisible();
await expect(page.locator('#yt-text')).toContainText('Hello world');
});
test('youtube tag generator returns tags', async ({ page }) => {
await installApiMocks(page);
await page.goto('/youtube-tag-generator.html');
await page.fill('#md-topic', 'A detailed topic sentence about sourdough bread for beginners.');
await page.click('#md-go');
await expect(page.locator('#md-out')).toBeVisible();
await expect(page.locator('#md-out')).toContainText('mock');
await expect(page.locator('#md-out')).toContainText('tags');
});
test('video aspect ratio converter loads its client-side tool', async ({ page }) => {
await installApiMocks(page);
await page.goto('/video-aspect-ratio-converter.html');
await expect(page.locator('#vc-file')).toBeAttached();
await expect(page.locator('#vc-drop')).toBeVisible();
});
});

View file

@ -0,0 +1,52 @@
import { test, expect } from '@playwright/test';
import { openApp } from '../fixtures/app.js';
import { SIXTY_MP4 } from '../fixtures/media.js';
test.describe('generate flow', () => {
test('uploads a file, posts it to /api/process and renders the clips', async ({ page }) => {
await openApp(page, { mocks: { statusSequence: ['processing', 'completed'] } });
await page.setInputFiles('input[type="file"][accept="video/*"]', SIXTY_MP4);
await page.locator('form input[type="checkbox"]').first().check();
const requestPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/process'),
);
await page.getByRole('button', { name: /generate clips/i }).click();
const request = await requestPromise;
expect(request.headers()['x-gemini-key']).toBe('e2e-gemini-key');
expect(request.headers()['content-type']).toContain('multipart/form-data');
// The multipart body carries the chosen file and the attestation.
const body = request.postDataBuffer().toString('latin1');
expect(body).toContain('sixty.mp4');
expect(body).toContain('acknowledged');
// Polling is driven by the app's own 2s interval; auto-wait absorbs it.
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await expect(page.getByRole('heading', { name: 'Second viral clip' })).toBeVisible();
await expect(page.getByText('2 Clips')).toBeVisible();
});
test('submits a YouTube URL as JSON with the Gemini header', async ({ page }) => {
await openApp(page);
await page.getByRole('button', { name: /video url/i }).click();
await page.getByPlaceholder(/paste a video link/i).fill('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
await page.locator('form input[type="checkbox"]').first().check();
const requestPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/process'),
);
await page.getByRole('button', { name: /generate clips/i }).click();
const request = await requestPromise;
expect(request.postDataJSON()).toMatchObject({
url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
acknowledged: true,
force_low_quality: false,
});
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
});
});

View file

@ -0,0 +1,37 @@
import { test, expect } from '@playwright/test';
import { openApp, completedSession, JOB_ID } from '../fixtures/app.js';
test.describe('postiz publish', () => {
test('publishes a clip to the connected channels through /api/postiz/post', async ({ page }) => {
await openApp(page, {
seed: {
session: completedSession(),
postizUrl: 'http://postiz.e2e.local',
postizKey: 'postiz-e2e-key',
},
});
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await page.getByRole('button', { name: 'post', exact: true }).first().click();
const dialog = page.getByRole('dialog');
await expect(dialog.getByText('PUBLISH', { exact: true })).toBeVisible();
// Connected channels load from the mocked integrations endpoint.
await expect(dialog.getByText('My YouTube')).toBeVisible();
const requestPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/postiz/post'),
);
await dialog.getByRole('button', { name: /publish now/i }).click();
const request = await requestPromise;
const body = request.postDataJSON();
expect(body.job_id).toBe(JOB_ID);
expect(body.clip_index).toBe(0);
expect(body.integration_ids).toContain('int-yt');
expect(body.title).toBe('First viral clip');
expect(request.headers()['x-postiz-url']).toBe('http://postiz.e2e.local');
await expect(page.getByText(/Posted to My YouTube/)).toBeVisible();
});
});

View file

@ -0,0 +1,38 @@
import { test, expect } from '@playwright/test';
import { openApp } from '../fixtures/app.js';
test.describe('quality gate', () => {
test('asks before processing a low-resolution source and resends with force_low_quality', async ({ page }) => {
await openApp(page, { mocks: { processSequence: ['needs_confirmation', 'queued'] } });
await page.getByRole('button', { name: /video url/i }).click();
await page.getByPlaceholder(/paste a video link/i).fill('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
await page.locator('form input[type="checkbox"]').first().check();
const firstPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/process'),
);
await page.getByRole('button', { name: /generate clips/i }).click();
const first = await firstPromise;
expect(first.postDataJSON()).toMatchObject({ force_low_quality: false });
// The gate opens instead of starting the job.
const dialog = page.getByRole('dialog');
await expect(dialog.getByText(/low source quality/i)).toBeVisible();
await expect(dialog.getByText(/360p/)).toBeVisible();
const secondPromise = page.waitForRequest(
(r) => r.method() === 'POST'
&& r.url().includes('/api/process')
&& JSON.parse(r.postData()).force_low_quality === true,
);
await page.getByRole('button', { name: /process anyway/i }).click();
const second = await secondPromise;
expect(second.postDataJSON()).toMatchObject({
url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
force_low_quality: true,
});
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
});
});

View file

@ -0,0 +1,17 @@
import { test, expect } from '@playwright/test';
// Real-backend lane.
//
// The plan calls for driving a real `uvicorn clipwright.api.app:app` with the
// pipeline's stub_env (tests/e2e/pipeline/stub_env) so the browser talks to the
// actual API instead of route mocks. That pipeline/stub environment is owned by
// the backend E2E lanes, and the dashboard CI job provisions Node + Chromium
// only (no Python deps, no ffmpeg), so this stays fixme until the backend lane
// exposes a server the dashboard job can launch. The same routes are covered
// end-to-end over HTTP by tests/e2e/api.
test.describe('real backend', () => {
test.fixme('generates clips against a real uvicorn + stub_env server', async ({ page }) => {
await page.goto('/');
await expect(page).toHaveTitle(/Clipwright/);
});
});

View file

@ -0,0 +1,35 @@
import { test, expect } from '@playwright/test';
import { openApp, completedSession, JOB_ID } from '../fixtures/app.js';
test.describe('reframe editor', () => {
test('splits a scene and applies reframing through /api/clip/reframe', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() } });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await page.getByRole('button', { name: 'reframing' }).first().click();
await expect(page.getByRole('heading', { name: 'reframing' })).toBeVisible();
// Scenes came back from the mocked /scenes endpoint.
await expect(page.getByText(/scene 1 ·/)).toBeVisible();
await expect(page.getByText(/nothing adjusted yet/i)).toBeVisible();
await page.getByTitle('stack two regions instead of one window').first().click();
await expect(page.getByText(/1 scene reframed by hand/i)).toBeVisible();
const requestPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/clip/reframe'),
);
await page.getByRole('button', { name: /apply reframing/i }).click();
const request = await requestPromise;
const body = request.postDataJSON();
expect(body.job_id).toBe(JOB_ID);
expect(body.clip_index).toBe(0);
expect(body.crop_overrides['0']).toBeTruthy();
expect(body.crop_overrides['0'].top).toBeTruthy();
expect(body.crop_overrides['0'].bottom).toBeTruthy();
// A successful save closes the editor.
await expect(page.getByRole('heading', { name: 'reframing' })).toHaveCount(0);
});
});

View file

@ -0,0 +1,38 @@
import { test, expect } from '@playwright/test';
import { openApp, completedSession, JOB_ID } from '../fixtures/app.js';
test.describe('results actions', () => {
test('downloads all clips as a zip', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() } });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
const requestPromise = page.waitForRequest(
(r) => r.method() === 'GET' && r.url().includes(`/api/jobs/${JOB_ID}/download-all`),
);
const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: /download all/i }).click();
await requestPromise;
const download = await downloadPromise;
expect(download.suggestedFilename()).toContain('clipwright_clips_');
});
test('opens the generated descriptions', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() } });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await page.getByRole('button', { name: /view descriptions/i }).first().click();
const dialog = page.getByRole('dialog');
await expect(dialog.getByText('GENERATED COPY')).toBeVisible();
await expect(dialog.getByText('TikTok caption one #viral #shorts')).toBeVisible();
await expect(dialog.getByText('First viral clip')).toBeVisible();
});
test('removes a generated clip and resets the workspace', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() } });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await page.getByRole('button', { name: /new project/i }).click();
await expect(page.getByRole('heading', { name: /create viral shorts/i })).toBeVisible();
});
});

View file

@ -0,0 +1,23 @@
import { test, expect } from '@playwright/test';
import { openApp, completedSession } from '../fixtures/app.js';
test.describe('session restore', () => {
test('restores a completed job from localStorage and shows its clips', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() } });
await expect(page.getByText('Session recovered')).toBeVisible();
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await expect(page.getByRole('heading', { name: 'Second viral clip' })).toBeVisible();
await expect(page.getByText('2 Clips')).toBeVisible();
});
test('discards a session older than the retention window', async ({ page }) => {
const stale = completedSession();
stale.timestamp = Date.now() - 25 * 60 * 60 * 1000; // 25h > 24h
await openApp(page, { seed: { session: stale } });
await expect(page.getByRole('heading', { name: /create viral shorts/i })).toBeVisible();
await expect(page.getByText('Session recovered')).toHaveCount(0);
await expect(page.getByRole('heading', { name: 'First viral clip' })).toHaveCount(0);
});
});

View file

@ -0,0 +1,28 @@
import { test, expect } from '@playwright/test';
import { openApp } from '../fixtures/app.js';
test.describe('smoke', () => {
test('boots the app, renders the generator and reaches Settings', async ({ page }) => {
const pageErrors = [];
page.on('pageerror', (err) => pageErrors.push(err.message));
await openApp(page, { hash: '#app' });
await expect(page.getByRole('heading', { name: /create viral shorts/i })).toBeVisible();
// The Gemini key is seeded, so the "keys missing" banners must not show.
await expect(page.getByText(/Required API keys missing/i)).toHaveCount(0);
await expect(page.getByText(/Gemini API Key Missing/i)).toHaveCount(0);
// Settings is a full view reachable from the rail.
await page.getByRole('button', { name: /settings/i }).first().click();
await expect(page.getByRole('heading', { name: 'Settings' })).toBeVisible();
await expect(page.getByText(/Publishing \(Postiz\)/i)).toBeVisible();
expect(pageErrors).toEqual([]);
});
test('asks for the Gemini key when none is stored', async ({ page }) => {
await openApp(page, { seed: { geminiKey: '' } });
await expect(page.getByText(/Required API keys missing/i)).toBeVisible();
});
});

View file

@ -0,0 +1,46 @@
import { test, expect } from '@playwright/test';
import { openApp, completedSession, JOB_ID } from '../fixtures/app.js';
test.describe('subtitle modal', () => {
test('applies a caption style to one clip and posts the style to /api/subtitle', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() } });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await page.getByRole('button', { name: 'subtitles' }).first().click();
const dialog = page.getByRole('dialog');
await expect(dialog.getByText('EDITOR · SUBTITLES')).toBeVisible();
const requestPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/subtitle'),
);
await dialog.getByRole('button', { name: /apply to this clip/i }).click();
const request = await requestPromise;
expect(request.postDataJSON()).toMatchObject({
job_id: JOB_ID,
clip_index: 0,
style: 'karaoke',
input_filename: 'clip_1.mp4',
});
// Success closes the editor.
await expect(page.getByText('EDITOR · SUBTITLES')).toHaveCount(0);
});
test('applies one style to every clip', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() }, mocks: { statusSequence: ['completed'] } });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
const bodies = [];
page.on('request', (r) => {
if (r.method() === 'POST' && r.url().includes('/api/subtitle')) bodies.push(r.postDataJSON());
});
await page.getByRole('button', { name: 'subtitles' }).first().click();
const dialog = page.getByRole('dialog');
await dialog.getByRole('button', { name: /apply this style to all 2 clips/i }).click();
await expect.poll(() => bodies.length).toBe(2);
expect(bodies.map((b) => b.clip_index).sort()).toEqual([0, 1]);
});
});

View file

@ -0,0 +1,43 @@
import { test, expect } from '@playwright/test';
import { openApp } from '../fixtures/app.js';
test.describe('thumbnail studio', () => {
test('manual title -> generate -> describe -> publish to YouTube', async ({ page }) => {
await openApp(page, {
hash: '#app?tab=thumbnails',
seed: { postizUrl: 'http://postiz.e2e.local', postizKey: 'postiz-e2e-key' },
});
await expect(page.getByRole('heading', { name: /youtube studio/i })).toBeVisible();
// Mode B: write a title by hand.
await page.getByPlaceholder(/Enter your YouTube title/i).fill('My manual e2e title');
await page.getByRole('button', { name: /use this title/i }).click();
await page.getByRole('button', { name: /continue to thumbnails/i }).click();
// Step 2: generate thumbnails.
const generatePromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/thumbnail/generate'),
);
await page.getByRole('button', { name: /generate thumbnails/i }).click();
await generatePromise;
await expect(page.getByAltText('Thumbnail 1')).toBeVisible();
await page.getByAltText('Thumbnail 1').click({ force: true });
await page.getByRole('button', { name: /next: description/i }).click();
// Step 3: write a description and continue.
await page.locator('textarea').first().fill('A hand written e2e description.');
await page.getByRole('button', { name: /next: publish/i }).click();
// Step 4: publish (Postiz is configured).
const publishPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/thumbnail/publish'),
);
await page.getByRole('button', { name: /publish to youtube/i }).click();
const publish = await publishPromise;
expect(publish.postDataBuffer().toString('latin1')).toContain('My manual e2e title');
await expect(page.getByText(/published successfully/i)).toBeVisible();
});
});

View file

@ -19,6 +19,7 @@
},
"devDependencies": {
"@eslint/js": "^9.39.5",
"@playwright/test": "^1.63.0",
"@types/react": "^18.2.64",
"@types/react-dom": "^18.2.21",
"@vitejs/plugin-react": "^4.2.1",
@ -986,6 +987,22 @@
"node": ">= 8"
}
},
"node_modules/@playwright/test": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",
"integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.63.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@remotion/licensing": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
@ -3895,6 +3912,35 @@
"node": ">= 6"
}
},
"node_modules/playwright": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.63.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright-core": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/possible-typed-array-names": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
@ -5785,6 +5831,15 @@
"fastq": "^1.6.0"
}
},
"@playwright/test": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",
"integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",
"dev": true,
"requires": {
"playwright": "1.63.0"
}
},
"@remotion/licensing": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
@ -7742,6 +7797,21 @@
"integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
"dev": true
},
"playwright": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
"dev": true,
"requires": {
"playwright-core": "1.63.0"
}
},
"playwright-core": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
"dev": true
},
"possible-typed-array-names": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",

View file

@ -7,7 +7,8 @@
"dev": "vite",
"build": "vite build",
"lint": "eslint . --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
"preview": "vite preview",
"test:e2e": "playwright test --config e2e/playwright.config.js"
},
"dependencies": {
"@remotion/media": "^4.0.447",
@ -21,6 +22,7 @@
},
"devDependencies": {
"@eslint/js": "^9.39.5",
"@playwright/test": "^1.63.0",
"@types/react": "^18.2.64",
"@types/react-dom": "^18.2.21",
"@vitejs/plugin-react": "^4.2.1",

View file

@ -24,6 +24,7 @@ export async function renderInBrowser({
onProgress,
signal,
}) {
if (window.__CW_E2E_RENDER__) return window.__CW_E2E_RENDER__();
const fps = 30;
const durationInFrames = Math.max(1, Math.round(durationInSeconds * fps));

View file

@ -11,6 +11,19 @@ testpaths = ["tests"]
# Makes the repo-root `clipwright/` package importable without a sys.path hack
# in tests/conftest.py.
pythonpath = ["."]
# E2E taxonomy. The fast unit suite (`tests/test_*.py`) is selected with
# `-m "not e2e"`; the E2E lanes live under `tests/e2e/` and mark themselves.
# `ml` gates the heavy ML stack (torch/ultralytics/mediapipe/faster-whisper).
markers = [
"e2e: end-to-end tests, run separately from the fast unit suite",
"pipeline: end-to-end tests that exercise the pipeline stages",
"ml: tests that need the heavy ML stack (see requirements-ml-e2e.txt)",
]
# Safe: `grep -rn "async def test_" tests/` found no existing async tests, so
# auto mode does not change the behaviour of the unit suite. pytest-timeout is
# passed on the CI command line (`--timeout=120`) instead of an ini key so the
# thin unit environment (which may lack pytest-timeout) still collects.
asyncio_mode = "auto"
[tool.ruff]
line-length = 100

11
requirements-e2e.txt Normal file
View file

@ -0,0 +1,11 @@
-r requirements-test.txt
# Thin E2E environment: the unit-test stack plus the async HTTP client, the
# ASGI lifespan helper and the ffmpeg-driven media/scene helpers. No heavy ML
# here — the `ml`-marked pipeline tests add requirements-ml-e2e.txt on top.
pytest-asyncio==1.4.0
asgi-lifespan==2.1.0
pytest-timeout==2.4.0
scenedetect==0.7
tqdm==4.67.3
yt-dlp==2026.8.19

6
requirements-ml-e2e.txt Normal file
View file

@ -0,0 +1,6 @@
# Heavy ML stack for the `ml`-marked pipeline E2E tests. Mirrors the runtime
# image's requirements.txt (torch / ultralytics / mediapipe / faster-whisper)
# on top of the thin E2E environment. Non-ML pipeline tests run against the
# stub_env fakes and never need this file.
-r requirements-e2e.txt
-r requirements.txt

1
tests/e2e/__init__.py Normal file
View file

@ -0,0 +1 @@
"""End-to-end tests (API, pipeline, browser). See tests/e2e/conftest.py."""

View file

@ -0,0 +1 @@
"""API-level end-to-end tests (one module per route family)."""

152
tests/e2e/api/conftest.py Normal file
View file

@ -0,0 +1,152 @@
"""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

View file

@ -0,0 +1,46 @@
"""L1 API core: the per-job "download all clips" ZIP bundle."""
import io
import json
import zipfile
import pytest
pytestmark = pytest.mark.e2e
async def test_download_all_returns_a_zip_of_every_clip(client, app_state, seeded_job):
job_id = seeded_job(job_id="job-zip", base="bundle", clips=2)
resp = await client.get(f"/api/jobs/{job_id}/download-all")
assert resp.status_code == 200
assert resp.headers["content-type"] == "application/zip"
with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
names = sorted(zf.namelist())
assert names == [
"clip_01_bundle_clip_1.mp4",
"clip_02_bundle_clip_2.mp4",
]
for name in names:
assert zf.read(name)
async def test_download_all_without_metadata_is_404(client):
resp = await client.get("/api/jobs/nobody-home/download-all")
assert resp.status_code == 404
assert resp.json()["detail"] == "Job not found"
async def test_download_all_without_clip_files_is_404(client, app_state):
job_id = "job-empty"
job_dir = app_state.out / job_id
job_dir.mkdir()
# Metadata promises a clip; the file itself was never rendered.
(job_dir / "empty_metadata.json").write_text(json.dumps({
"shorts": [{"start": 0.0, "end": 5.0, "video_title_for_youtube_short": "x"}],
}))
resp = await client.get(f"/api/jobs/{job_id}/download-all")
assert resp.status_code == 404
assert resp.json()["detail"] == "No clip files found for this job"

View file

@ -0,0 +1,263 @@
"""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

View file

@ -0,0 +1,82 @@
"""Phase-0 foundation smoke test.
Proves the shared E2E scaffolding works before the per-route lanes are built:
1. ``/health`` answers through the in-process ASGI client.
2. ``app_state`` gives each test a private ``jobs`` dict (isolation).
3. A disk-seeded completed job is recoverable the same way a restart recovers.
4. The session ``media_factory`` produces ffprobe-able fixture videos.
"""
import json
import subprocess
import pytest
pytestmark = pytest.mark.e2e
async def test_health_ok(client):
resp = await client.get("/health")
assert resp.status_code == 200
assert resp.json() == {"status": "ok"}
async def test_app_state_isolation_a(app_state):
# Fresh per test: nothing seeded this dict.
assert app_state.app.jobs == {}
app_state.app.jobs["isolation-a"] = {"status": "sentinel"}
async def test_app_state_isolation_b(app_state):
# If the previous test's write leaked, this dict would not be empty.
assert app_state.app.jobs == {}
app_state.app.jobs["isolation-b"] = {"status": "sentinel"}
async def test_disk_seeded_job_is_recoverable(app_state, seeded_job, client):
job_id = seeded_job(job_id="job-smoke", base="smoke", clips=1)
job = app_state.app.jobs[job_id]
assert job["status"] == "completed"
assert job["output_dir"] == str(app_state.out / job_id)
clips = job["result"]["clips"]
assert len(clips) == 1
assert clips[0]["video_url"].endswith("/smoke_clip_1.mp4")
clip_path = app_state.out / job_id / "smoke_clip_1.mp4"
assert clip_path.is_file() and clip_path.stat().st_size > 0
# The recovered clip is actually servable: this proves the /videos mount was
# repointed at the per-test output tree (it captures its directory at
# import time, so the app_state rebind has to move it explicitly).
resp = await client.get(clips[0]["video_url"])
assert resp.status_code == 200
assert resp.content
def _probe(path):
out = subprocess.run(
["ffprobe", "-v", "error", "-show_entries",
"format=duration:stream=codec_type", "-of", "json", str(path)],
capture_output=True, text=True, check=True,
)
return json.loads(out.stdout)
def test_media_factory_files_are_probeable(media_factory):
sixty = _probe(media_factory.sixty)
assert float(sixty["format"]["duration"]) == pytest.approx(60.0, abs=1.0)
assert {"video", "audio"} <= {s["codec_type"] for s in sixty["streams"]}
six = _probe(media_factory.six)
assert float(six["format"]["duration"]) == pytest.approx(6.0, abs=1.0)
assert {"video", "audio"} <= {s["codec_type"] for s in six["streams"]}
silent = _probe(media_factory.silent)
assert {s["codec_type"] for s in silent["streams"]} == {"video"}
cuts = _probe(media_factory.cuts)
assert float(cuts["format"]["duration"]) == pytest.approx(6.0, abs=1.0)
assert {"video"} <= {s["codec_type"] for s in cuts["streams"]}

View file

@ -0,0 +1,65 @@
"""L1 API core: liveness/readiness probes and the dashboard bootstrap config.
Drives the real app through ``httpx.ASGITransport`` (no lifespan), so the
``_stopping`` flag is flipped by hand the same way SIGTERM does at runtime.
"""
import pytest
pytestmark = pytest.mark.e2e
async def test_health_is_ok(client):
resp = await client.get("/health")
assert resp.status_code == 200
assert resp.json() == {"status": "ok"}
async def test_health_ready_when_running(client, app_state):
app_state.app._stopping = False
resp = await client.get("/health/ready")
assert resp.status_code == 200
assert resp.json() == {"status": "ready"}
async def test_health_ready_is_503_while_stopping(client, app_state, monkeypatch):
monkeypatch.setattr(app_state.app, "_stopping", True)
resp = await client.get("/health/ready")
assert resp.status_code == 503
assert resp.json() == {"status": "stopping"}
async def test_config_youtube_enabled(client, app_state, monkeypatch):
monkeypatch.setattr(app_state.app, "DISABLE_YOUTUBE_URL", False)
monkeypatch.delenv("LLM_BASE_URL", raising=False)
monkeypatch.delenv("LLM_PROVIDER", raising=False)
resp = await client.get("/api/config")
assert resp.status_code == 200
body = resp.json()
assert body["youtubeUrlEnabled"] is True
assert body["billingEnabled"] is False
assert body["jobRetentionSeconds"] == app_state.app.JOB_RETENTION_SECONDS
# No OpenAI-compatible server configured -> the dashboard is told nothing.
assert body["localLlm"] is None
async def test_config_youtube_disabled(client, app_state, monkeypatch):
monkeypatch.setattr(app_state.app, "DISABLE_YOUTUBE_URL", True)
resp = await client.get("/api/config")
assert resp.status_code == 200
assert resp.json()["youtubeUrlEnabled"] is False
async def test_config_describes_local_llm(client, app_state, monkeypatch):
monkeypatch.setenv("LLM_PROVIDER", "openai")
monkeypatch.setenv("LLM_BASE_URL", "http://127.0.0.1:11434")
monkeypatch.delenv("LLM_MODEL", raising=False)
resp = await client.get("/api/config")
assert resp.status_code == 200
assert resp.json()["localLlm"] == {
"provider": "openai",
"model": "llama3.1:8b",
"baseUrl": "http://127.0.0.1:11434",
}

150
tests/e2e/api/test_hook.py Normal file
View file

@ -0,0 +1,150 @@
"""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

View file

@ -0,0 +1,423 @@
"""L3 E2E: the Postiz integration routes.
Everything outbound is stubbed at the ``clipwright.integrations.postiz`` seam
(``app.py`` calls the module functions through ``asyncio.to_thread``), so the
tests exercise the real route logic: credential resolution, channel selection
by id vs the legacy ``platforms`` fallback, the per-provider ``settings``
mapping, the schedule window and the error translation.
The unit suite (``tests/test_postiz.py``) already pins the helper functions;
these are the ASGI-level contracts through the shared ``client`` fixture.
"""
import functools
from datetime import datetime, timedelta, timezone
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 postiz_stub(monkeypatch):
"""Capture every Postiz call and return scripted responses.
Mutate ``stub.integrations`` / ``stub.*_result`` / ``stub.errors`` per test.
"""
from clipwright.integrations import postiz as postiz_mod
class Stub:
def __init__(self):
self.calls = {}
self.integrations = [
{"id": "yt-1", "name": "Main", "identifier": "youtube", "disabled": False},
{"id": "yt-2", "name": "Second", "identifier": "youtube", "disabled": False},
{"id": "ig-1", "name": "IG", "identifier": "instagram-standalone",
"disabled": False},
{"id": "tt-1", "name": "TT", "identifier": "tiktok-business",
"disabled": False},
]
self.upload_result = {"id": "media-1", "path": "media/path"}
self.create_result = [{"postId": "p1", "integration": "yt-1"}]
self.posts_result = [
{"id": "sched-1", "date": "2030-01-01T00:00:00.000Z",
"integration": {"id": "yt-1"}},
]
self.delete_result = None
self.analytics_result = {"views": 5, "likes": 1}
self.analytics_post_result = {"likes": 3}
self.errors = {}
def _record(self, name, *args, **kwargs):
self.calls.setdefault(name, []).append((args, kwargs))
if name in self.errors:
raise self.errors[name]
return {
"list_integrations": self.integrations,
"upload_media": self.upload_result,
"create_post": self.create_result,
"list_posts": self.posts_result,
"delete_post": self.delete_result,
"analytics": self.analytics_result,
"analytics_post": self.analytics_post_result,
}[name]
stub = Stub()
for name in ("list_integrations", "upload_media", "create_post",
"list_posts", "delete_post", "analytics", "analytics_post"):
monkeypatch.setattr(postiz_mod, name, functools.partial(stub._record, name))
return stub
def _payload(stub):
"""The payload handed to ``create_post`` (base, key, payload)."""
return stub.calls["create_post"][0][0][2]
# --------------------------------------------------------------------------- #
# POST /api/postiz/post
# --------------------------------------------------------------------------- #
async def test_post_success_by_integration_id(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-post", base="pw", clips=1)
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0,
"integration_ids": ["ig-1", "tt-1"],
"title": "My Title", "description": "Watch this #fun #clips"},
)
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["success"] is True
assert body["results"] == postiz_stub.create_result
assert [p["platform"] for p in body["posted"]] == ["instagram", "tiktok"]
assert [p["name"] for p in body["posted"]] == ["IG", "TT"]
payload = _payload(postiz_stub)
assert payload["type"] == "now"
assert payload["shortLink"] is False
posts = payload["posts"]
assert [p["integration"]["id"] for p in posts] == ["ig-1", "tt-1"]
# __type echoes the real identifier, not the mapped platform.
assert [p["settings"]["__type"] for p in posts] == \
["instagram-standalone", "tiktok-business"]
assert posts[0]["settings"] == {"__type": "instagram-standalone", "post_type": "post"}
assert posts[1]["settings"]["content_posting_method"] == "DIRECT_POST"
assert posts[0]["value"][0]["content"] == "Watch this #fun #clips"
assert posts[0]["value"][0]["image"][0] == {"id": "media-1", "path": "media/path"}
# The local clip was re-uploaded to Postiz first.
assert postiz_stub.calls["upload_media"][0][0][2].endswith("pw_clip_1.mp4")
async def test_post_legacy_platforms_use_the_identifier_map(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-legacy", base="pw")
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0,
"platforms": ["instagram", "tiktok"]},
)
assert resp.status_code == 200, resp.text
posts = _payload(postiz_stub)["posts"]
assert [p["integration"]["id"] for p in posts] == ["ig-1", "tt-1"]
assert [p["settings"]["__type"] for p in posts] == \
["instagram-standalone", "tiktok-business"]
assert [e["platform"] for e in resp.json()["posted"]] == ["instagram", "tiktok"]
async def test_post_future_schedule_sets_schedule_type(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-sched", base="pw")
future = datetime.now(timezone.utc) + timedelta(days=2)
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"],
"scheduled_date": future.isoformat()},
)
assert resp.status_code == 200, resp.text
payload = _payload(postiz_stub)
assert payload["type"] == "schedule"
assert payload["date"] == future.astimezone(timezone.utc).strftime(
"%Y-%m-%dT%H:%M:%S.000Z")
async def test_post_schedule_accepts_an_iso_offset(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-tz", base="pw")
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"],
"scheduled_date": "2030-06-01T12:00:00+02:00"},
)
assert resp.status_code == 200, resp.text
# The offset is normalised to UTC.
assert _payload(postiz_stub)["date"] == "2030-06-01T10:00:00.000Z"
async def test_post_past_schedule_is_400_before_upload(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-past", base="pw")
past = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"],
"scheduled_date": past},
)
assert resp.status_code == 400
assert "past" in resp.json()["detail"].lower()
assert "upload_media" not in postiz_stub.calls
assert "create_post" not in postiz_stub.calls
async def test_post_unparseable_schedule_is_400(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-bad-date", base="pw")
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"],
"scheduled_date": "tomorrow"},
)
assert resp.status_code == 400
async def test_post_unknown_integration_id_is_400(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-unknown", base="pw")
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["nope"]},
)
assert resp.status_code == 400
assert "nope" in resp.json()["detail"]
assert "upload_media" not in postiz_stub.calls
async def test_post_disabled_integration_id_is_400(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-disabled", base="pw")
postiz_stub.integrations = [
{"id": "ig-1", "name": "IG", "identifier": "instagram-standalone",
"disabled": True},
]
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["ig-1"]},
)
assert resp.status_code == 400
assert "Disabled" in resp.json()["detail"]
assert "upload_media" not in postiz_stub.calls
async def test_post_not_connected_platform_is_400(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-notconn", base="pw")
postiz_stub.integrations = [
{"id": "yt-1", "name": "Main", "identifier": "youtube", "disabled": False},
]
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "platforms": ["instagram"]},
)
assert resp.status_code == 400
assert "Not connected" in resp.json()["detail"]
assert "upload_media" not in postiz_stub.calls
async def test_post_missing_credentials_is_400(client, seeded_job, postiz_stub,
monkeypatch):
monkeypatch.delenv("POSTIZ_URL", raising=False)
monkeypatch.delenv("POSTIZ_API_KEY", raising=False)
job_id = seeded_job(job_id="job-creds", base="pw")
body = {"job_id": job_id, "clip_index": 0, "platforms": ["youtube"]}
r = await client.post("/api/postiz/post", headers={"X-Postiz-Key": "k"}, json=body)
assert r.status_code == 400 and "URL" in r.json()["detail"]
r = await client.post("/api/postiz/post",
headers={"X-Postiz-Url": "https://p.example"}, json=body)
assert r.status_code == 400 and "key" in r.json()["detail"].lower()
async def test_post_no_channels_is_400(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-nochan", base="pw")
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0},
)
assert resp.status_code == 400
assert "No channels" in resp.json()["detail"]
assert "upload_media" not in postiz_stub.calls
async def test_post_unknown_job_is_404(client, postiz_stub):
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": "nobody-home", "clip_index": 0, "integration_ids": ["yt-1"]},
)
assert resp.status_code == 404
assert resp.json()["detail"] == "Job not found"
assert postiz_stub.calls == {}
async def test_post_missing_clip_file_is_404(client, app_state, postiz_stub):
app_state.app.jobs["job-nofile"] = {
"result": {"clips": [{"video_url": "/videos/job-nofile/missing.mp4"}]},
}
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": "job-nofile", "clip_index": 0, "integration_ids": ["yt-1"]},
)
assert resp.status_code == 404
assert "not found" in resp.json()["detail"].lower()
assert "upload_media" not in postiz_stub.calls
async def test_post_clip_index_out_of_range_is_400(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-index", base="pw")
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 9, "integration_ids": ["yt-1"]},
)
assert resp.status_code == 400
assert "range" in resp.json()["detail"].lower()
async def test_post_upload_failure_is_502(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-upfail", base="pw")
postiz_stub.upload_result = {}
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"]},
)
assert resp.status_code == 502
assert "upload failed" in resp.json()["detail"].lower()
assert "create_post" not in postiz_stub.calls
async def test_post_postiz_error_is_translated(client, seeded_job, postiz_stub):
from clipwright.integrations import postiz
job_id = seeded_job(job_id="job-err", base="pw")
postiz_stub.errors["create_post"] = postiz.PostizError(
429, "Postiz API Error: slow down")
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"]},
)
assert resp.status_code == 429
assert resp.json()["detail"] == "Postiz API Error: slow down"
# --------------------------------------------------------------------------- #
# Other Postiz routes
# --------------------------------------------------------------------------- #
async def test_integrations_route_normalises_disabled(client, postiz_stub):
postiz_stub.integrations = [
{"id": "a", "identifier": "youtube", "disabled": 1},
{"id": "b", "identifier": "youtube", "disabled": 0},
{"id": "c", "identifier": "youtube"},
]
resp = await client.get("/api/postiz/integrations", headers=POSTIZ_HEADERS)
assert resp.status_code == 200
integrations = resp.json()["integrations"]
assert [i["disabled"] for i in integrations] == [True, False, False]
async def test_integrations_route_translates_postiz_error(client, postiz_stub):
from clipwright.integrations import postiz
postiz_stub.errors["list_integrations"] = postiz.PostizError(
401, "Postiz API Error: bad key")
resp = await client.get("/api/postiz/integrations", headers=POSTIZ_HEADERS)
assert resp.status_code == 401
assert "bad key" in resp.json()["detail"]
async def test_scheduled_route_backfills_and_widens_window(client, postiz_stub):
resp = await client.get("/api/postiz/scheduled", headers=POSTIZ_HEADERS,
params={"days": 30})
assert resp.status_code == 200
posts = resp.json()["scheduled_posts"]
# Postiz calls it ``date``; the consumer reads ``scheduled_date``.
assert posts[0]["scheduled_date"] == "2030-01-01T00:00:00.000Z"
assert posts[0]["date"] == "2030-01-01T00:00:00.000Z"
args = postiz_stub.calls["list_posts"][0][0]
start = datetime.fromisoformat(args[2].replace("Z", "+00:00"))
end = datetime.fromisoformat(args[3].replace("Z", "+00:00"))
# The default window is widened to at least POSTIZ_SCHEDULED_MIN_DAYS (90).
assert (end - start) >= timedelta(days=89)
async def test_scheduled_route_forwards_explicit_dates(client, postiz_stub):
resp = await client.get(
"/api/postiz/scheduled", headers=POSTIZ_HEADERS,
params={"start_date": "2030-01-01T00:00:00.000Z",
"end_date": "2030-02-01T00:00:00.000Z"})
assert resp.status_code == 200
args = postiz_stub.calls["list_posts"][0][0]
assert args[2] == "2030-01-01T00:00:00.000Z"
assert args[3] == "2030-02-01T00:00:00.000Z"
async def test_scheduled_route_translates_postiz_error(client, postiz_stub):
from clipwright.integrations import postiz
postiz_stub.errors["list_posts"] = postiz.PostizError(500, "Postiz API Error: boom")
resp = await client.get("/api/postiz/scheduled", headers=POSTIZ_HEADERS)
assert resp.status_code == 500
assert "boom" in resp.json()["detail"]
async def test_cancel_scheduled_deletes_and_reports(client, postiz_stub):
resp = await client.delete("/api/postiz/scheduled/sched-9",
headers=POSTIZ_HEADERS)
assert resp.status_code == 200
assert resp.json() == {"success": True, "id": "sched-9"}
assert postiz_stub.calls["delete_post"][0][0][2] == "sched-9"
async def test_analytics_route_forwards_channel_and_days(client, postiz_stub):
resp = await client.get("/api/postiz/analytics", headers=POSTIZ_HEADERS,
params={"integration": "yt-1", "days": 7})
assert resp.status_code == 200
assert resp.json() == postiz_stub.analytics_result
args = postiz_stub.calls["analytics"][0][0]
assert args[2] == "yt-1" and args[3] == 7
async def test_analytics_posts_route_forwards_post_id(client, postiz_stub):
resp = await client.get("/api/postiz/analytics/posts", headers=POSTIZ_HEADERS,
params={"post_id": "post-9", "days": 3})
assert resp.status_code == 200
assert resp.json() == postiz_stub.analytics_post_result
args = postiz_stub.calls["analytics_post"][0][0]
assert args[2] == "post-9" and args[3] == 3
# --------------------------------------------------------------------------- #
# The identifier -> platform map that drives settings.__type
# --------------------------------------------------------------------------- #
def test_settings_echo_the_real_identifier(app_state):
app = app_state.app
assert app._identifier_platform("instagram-standalone") == "instagram"
assert app._identifier_platform("tiktok-business") == "tiktok"
assert app._identifier_platform("youtube") == "youtube"
ig = app._postiz_settings("instagram-standalone", "T", "caption", [])
assert ig == {"__type": "instagram-standalone", "post_type": "post"}
tt = app._postiz_settings("tiktok-business", "T", "caption", [])
assert tt["__type"] == "tiktok-business"
assert tt["content_posting_method"] == "DIRECT_POST"

View file

@ -0,0 +1,340 @@
"""L1 API core: the /api/process submit matrix.
The worker never runs here (ASGITransport skips lifespan), so every assertion is
about the QUEUED record: validation branches, the chosen ingest path, the env
overrides handed to the child, the attestation, and the on-disk resume manifest.
URL tests stub ``assert_public_url`` (the autouse no-network guard would abort a
real DNS lookup) and/or ``_probe_youtube_quality``; IP-literal URLs exercise the
real SSRF guard without touching DNS.
"""
import json
import os
import pytest
pytestmark = pytest.mark.e2e
WATCH = "https://www.youtube.com/watch?v=abcdefghijk"
KEY = {"X-Gemini-Key": "test-key"}
@pytest.fixture
def allow_urls(monkeypatch):
"""Let hostname URLs pass the SSRF guard without a DNS lookup."""
import clipwright.core.security_utils as security_utils
monkeypatch.setattr(security_utils, "assert_public_url", lambda url: url)
def _job(client, resp):
assert resp.status_code == 200, resp.text
body = resp.json()
assert "job_id" in body
return body["job_id"]
async def _submit_json(client, body):
return await client.post("/api/process", json=body, headers=KEY)
async def _submit_file(client, data, files, headers=KEY):
return await client.post("/api/process", data=data, files=files, headers=headers)
# --------------------------------------------------------------------------- #
# Happy paths: one per ingest source
# --------------------------------------------------------------------------- #
async def test_submit_url_queues_with_attestation_and_manifest(
client, app_state, allow_urls, monkeypatch):
monkeypatch.delenv("PUBLIC_API_URL", raising=False)
resp = await _submit_json(client, {"url": WATCH, "acknowledged": True})
job_id = _job(client, resp)
job = app_state.app.jobs[job_id]
assert job["status"] == "queued"
assert WATCH in job["cmd"] and "--keep-original" in job["cmd"]
assert job["env"]["GEMINI_API_KEY"] == "test-key"
assert job["attestation"]["acknowledged"] is True
assert job["attestation"]["source"] == "url"
assert job["attestation"]["ip"] # client host (testserver / 127.0.0.1)
manifest = json.loads((app_state.out / job_id / ".resume.json").read_text())
assert manifest["cmd"] == job["cmd"]
assert manifest["priority"] == 2
# Queued, not run: the queue holds exactly this one entry.
assert app_state.app.job_queue.qsize() == 1
async def test_submit_multipart_file(client, app_state, media_factory):
resp = await _submit_file(
client,
{"acknowledged": "true"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
job_id = _job(client, resp)
job = app_state.app.jobs[job_id]
input_path = job["cmd"][job["cmd"].index("-i") + 1]
assert os.path.dirname(input_path) == str(app_state.up)
assert os.path.basename(input_path).startswith(job_id)
assert os.path.basename(input_path).endswith("clip.mp4")
assert os.path.exists(input_path)
assert job["attestation"]["source"] == "file"
async def test_submit_completed_upload_id(client, app_state, media_factory):
reserved = await client.post("/api/uploads", json={"filename": "clip.mp4"})
uid = reserved.json()["upload_id"]
assert (await client.put(f"/api/uploads/{uid}",
content=media_factory.six.read_bytes())).status_code == 200
resp = await _submit_json(client, {"upload_id": uid, "acknowledged": True})
job_id = _job(client, resp)
job = app_state.app.jobs[job_id]
input_path = job["cmd"][job["cmd"].index("-i") + 1]
assert os.path.exists(input_path)
assert os.path.basename(input_path) == f"{job_id}_clip.mp4"
assert uid not in app_state.app.pending_uploads
assert job["attestation"]["source"] == "upload_id"
async def test_submit_thumbnail_session_id(client, app_state, media_factory, monkeypatch):
sid = "sess-e2e"
app_state.app.thumbnail_sessions[sid] = {
"user_id": None,
"video_path": str(media_factory.six),
"transcript_ready": False,
"transcript": None,
}
resp = await _submit_json(client, {"thumbnail_session_id": sid, "acknowledged": True})
job_id = _job(client, resp)
job = app_state.app.jobs[job_id]
assert "-i" in job["cmd"]
assert os.path.exists(job["cmd"][job["cmd"].index("-i") + 1])
assert job["attestation"]["source"] == "thumbnail_session"
async def test_submit_thumbnail_session_missing_404(client, app_state):
resp = await _submit_json(client, {"thumbnail_session_id": "nope", "acknowledged": True})
assert resp.status_code == 404
# --------------------------------------------------------------------------- #
# Validation branches
# --------------------------------------------------------------------------- #
async def test_submit_without_input_is_400(client):
resp = await _submit_json(client, {"acknowledged": True})
assert resp.status_code == 400
assert "Must provide URL, File or upload_id" in resp.json()["detail"]
async def test_submit_without_ack_is_400(client, allow_urls):
resp = await _submit_json(client, {"url": WATCH})
assert resp.status_code == 400
assert "confirm you own the content" in resp.json()["detail"]
async def test_submit_without_key_is_400(client, media_factory, monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
monkeypatch.delenv("LLM_BASE_URL", raising=False)
monkeypatch.delenv("LLM_PROVIDER", raising=False)
resp = await _submit_file(
client,
{"acknowledged": "true"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
headers={},
)
assert resp.status_code == 400
assert resp.json()["detail"] == "Missing X-Gemini-Key header"
async def test_submit_without_key_but_local_llm_queues(
client, app_state, media_factory, monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
monkeypatch.setenv("LLM_PROVIDER", "openai")
monkeypatch.setenv("LLM_BASE_URL", "http://127.0.0.1:9")
resp = await _submit_file(
client,
{"acknowledged": "true"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
headers={},
)
job_id = _job(client, resp)
# A local-LLM job must not leak a stale Google key into the child env.
assert "GEMINI_API_KEY" not in app_state.app.jobs[job_id]["env"]
async def test_submit_youtube_disabled_is_403(client, app_state, allow_urls, monkeypatch):
monkeypatch.setattr(app_state.app, "DISABLE_YOUTUBE_URL", True)
resp = await _submit_json(client, {"url": WATCH, "acknowledged": True})
assert resp.status_code == 403
assert "disabled on this deployment" in resp.json()["detail"]
async def test_submit_playlist_is_400(client, allow_urls):
resp = await _submit_json(client, {
"url": "https://www.youtube.com/playlist?list=PLabc",
"acknowledged": True,
})
assert resp.status_code == 400
assert "playlist" in resp.json()["detail"]
async def test_submit_ssrf_url_is_400(client):
# Real guard, IP literal -> no DNS, rejected as non-public.
resp = await _submit_json(client, {
"url": "http://169.254.169.254/latest/meta-data",
"acknowledged": True,
})
assert resp.status_code == 400
assert "can't be processed" in resp.json()["detail"]
async def test_submit_short_source_is_400(client, app_state, allow_urls, monkeypatch):
monkeypatch.setattr(app_state.app, "MIN_SOURCE_SECONDS", 45)
monkeypatch.setattr(app_state.app, "QUALITY_GATE_MIN_HEIGHT", 0)
async def probe(url):
return {"duration": 10, "max_height": 1080}
monkeypatch.setattr(app_state.app, "_probe_youtube_quality", probe)
resp = await _submit_json(client, {"url": WATCH, "acknowledged": True})
assert resp.status_code == 400
assert "10s" in resp.json()["detail"]
# The aborted job dir must not linger (only the thumbnails mount remains).
assert [p.name for p in app_state.out.iterdir()] == ["thumbnails"]
async def test_quality_gate_needs_confirmation_then_force_low_quality(
client, app_state, allow_urls, monkeypatch):
monkeypatch.setattr(app_state.app, "QUALITY_GATE_MIN_HEIGHT", 720)
monkeypatch.setattr(app_state.app, "MIN_SOURCE_SECONDS", 0)
async def probe(url):
return {"duration": 600, "max_height": 480}
monkeypatch.setattr(app_state.app, "_probe_youtube_quality", probe)
first = await _submit_json(client, {"url": WATCH, "acknowledged": True})
assert first.status_code == 200
assert first.json()["needs_confirmation"] is True
assert first.json()["quality_check"]["max_height"] == 480
assert first.json()["quality_check"]["min_height"] == 720
assert app_state.app.jobs == {}
forced = await _submit_json(client, {
"url": WATCH, "acknowledged": True, "force_low_quality": True,
})
job_id = _job(client, forced)
assert app_state.app.jobs[job_id]["status"] == "queued"
async def test_submit_bad_webhook_is_400(client, media_factory):
resp = await _submit_file(
client,
{"acknowledged": "true", "webhook_url": "http://127.0.0.1/hook"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
assert resp.status_code == 400
assert "Invalid webhook_url" in resp.json()["detail"]
async def test_target_clips_validation(client, media_factory):
bad_type = await _submit_file(
client,
{"acknowledged": "true", "target_clips": "lots"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
assert bad_type.status_code == 400
assert "target_clips must be a number" in bad_type.json()["detail"]
out_of_range = await _submit_file(
client,
{"acknowledged": "true", "target_clips": "0"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
assert out_of_range.status_code == 400
assert "target_clips must be between 1 and 15" in out_of_range.json()["detail"]
async def test_clip_range_validation(client, media_factory):
too_short = await _submit_file(
client,
{"acknowledged": "true", "clip_min_seconds": "2"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
assert too_short.status_code == 400
assert "clip_min_seconds must be between 5 and 175" in too_short.json()["detail"]
inverted = await _submit_file(
client,
{"acknowledged": "true", "clip_min_seconds": "10", "clip_max_seconds": "12"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
assert inverted.status_code == 400
assert "at least 5s above" in inverted.json()["detail"]
# --------------------------------------------------------------------------- #
# Env mapping: layouts, hooks, captions, format, generation controls
# --------------------------------------------------------------------------- #
async def test_env_mapping_for_layouts_hooks_captions_and_format(
client, app_state, media_factory):
resp = await _submit_file(
client,
{
"acknowledged": "true",
"layouts": "split,auto",
"auto_hook": "true",
"auto_hook_style": "classic",
"captions": "false",
"output_format": "vertical",
"target_clips": "3",
"clip_min_seconds": "10",
"clip_max_seconds": "30",
},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
job_id = _job(client, resp)
env = app_state.app.jobs[job_id]["env"]
assert env["SPLIT_LAYOUT"] == "1"
assert env["SPEAKER_SIGNAL"] == "1" # implied by split
assert env["AUTO_LAYOUT"] == "1"
assert env["AUTO_HOOK"] == "1"
assert env["AUTO_HOOK_STYLE"] == "classic"
assert env["AUTO_CAPTIONS"] == "0"
assert env["CLIP_TARGET_MIN"] == "3" and env["CLIP_TARGET_MAX"] == "3"
assert env["CLIP_MIN_SECONDS"] == "10.0"
assert env["CLIP_MAX_SECONDS"] == "30.0"
assert "--format" in app_state.app.jobs[job_id]["cmd"]
assert app_state.app.jobs[job_id]["cmd"][
app_state.app.jobs[job_id]["cmd"].index("--format") + 1] == "vertical"
async def test_layout_none_switches_picker_off(client, app_state, media_factory):
resp = await _submit_file(
client,
{"acknowledged": "true", "layouts": "none"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
job_id = _job(client, resp)
assert app_state.app.jobs[job_id]["env"]["AUTO_LAYOUT"] == "0"
async def test_unknown_output_format_is_normalised_to_auto(client, app_state, media_factory):
resp = await _submit_file(
client,
{"acknowledged": "true", "output_format": "widescreen"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
job_id = _job(client, resp)
assert "--format" not in app_state.app.jobs[job_id]["cmd"]

View file

@ -0,0 +1,188 @@
"""L1 API core: the real worker path.
``fake_popen`` replaces ``subprocess.Popen`` so ``run_job`` sees a finished
child that already wrote a canonical clip + metadata; ``job_done`` runs
``process_queue`` as a task and waits on an event set by a wrapper around
``run_job_wrapper`` (no sleeps, bounded wait). Webhook delivery, transient
auto-retry, and resume-from-manifest are covered here too.
"""
import asyncio
import json
import os
import sys
import pytest
pytestmark = pytest.mark.e2e
KEY = {"X-Gemini-Key": "test-key"}
async def _submit_file(client, media_factory, **form):
data = {"acknowledged": "true", **form}
return await client.post(
"/api/process",
data=data,
files={"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
headers=KEY,
)
async def test_queued_job_runs_to_completion(client, app_state, media_factory,
fake_popen, job_done):
resp = await _submit_file(client, media_factory)
assert resp.status_code == 200, resp.text
job_id = resp.json()["job_id"]
assert app_state.app.jobs[job_id]["status"] == "queued"
await job_done(job_id)
job = app_state.app.jobs[job_id]
assert job["status"] == "completed"
clips = job["result"]["clips"]
assert len(clips) == 1
assert clips[0]["video_url"] == f"/videos/{job_id}/clipwright_clip_1.mp4"
assert (app_state.out / job_id / "clipwright_clip_1.mp4").stat().st_size > 0
# Terminal state drops the resume manifest.
assert not (app_state.out / job_id / ".resume.json").exists()
# The fake was actually invoked with the queued command (other FakePopen
# instances are the ffprobe duration probes, which share the module Popen).
workers = [i for i in fake_popen.instances if "clipwright.pipeline.main" in i.cmd]
assert workers and workers[0].cmd[0] == sys.executable
async def test_webhook_delivered_with_signature(client, app_state, media_factory,
fake_popen, job_done, monkeypatch):
captured = {}
class FakeAsyncClient:
def __init__(self, *a, **k):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
async def post(self, url, content=None, headers=None):
captured["url"] = url
captured["body"] = content
captured["headers"] = headers
delivered.set()
class _Resp:
status_code = 200
return _Resp()
delivered = asyncio.Event()
monkeypatch.setattr(app_state.app.httpx, "AsyncClient", FakeAsyncClient)
monkeypatch.delenv("PUBLIC_API_URL", raising=False)
resp = await _submit_file(
client, media_factory,
webhook_url="http://8.8.8.8/hook",
webhook_secret="s3cret",
)
assert resp.status_code == 200, resp.text
job_id = resp.json()["job_id"]
await job_done(job_id)
await asyncio.wait_for(delivered.wait(), 5)
payload = json.loads(captured["body"].decode())
assert payload["event"] == "job.completed"
assert payload["job_id"] == job_id
assert payload["status"] == "completed"
assert payload["clips"][0]["index"] == 0
assert payload["clips"][0]["title"] == "Fake clip 1"
assert payload["clips"][0]["video_url"] == (
f"http://testserver/videos/{job_id}/clipwright_clip_1.mp4")
expected = app_state.app._sign_webhook(captured["body"], "s3cret")
assert captured["headers"]["X-Clipwright-Signature"] == expected
async def test_transient_failure_is_auto_retried(app_state, media_factory,
fake_popen, monkeypatch):
app = app_state.app
monkeypatch.setattr(app, "AUTO_RETRY_DELAY_SECONDS", 0)
fake_popen.returncode = 1
fake_popen.lines = ["CUDA out of memory while starting"]
job_id = "job-retry"
out_dir = app_state.out / job_id
out_dir.mkdir()
app.jobs[job_id] = {
"status": "queued",
"logs": app._TimedLog(["❌ CUDA out of memory while starting"]),
"cmd": [sys.executable, "-m", "clipwright.pipeline.main",
"-i", "x", "-o", str(out_dir)],
"env": {},
"output_dir": str(out_dir),
"webhook_url": None,
"webhook_secret": None,
"user_id": None,
}
enqueued = []
retried = asyncio.Event()
original_enqueue = app._enqueue_job
def capture(jid, priority=2):
original_enqueue(jid, priority)
enqueued.append((jid, priority))
retried.set()
monkeypatch.setattr(app, "_enqueue_job", capture)
# Balance the queue's task_done() and the semaphore's release().
await app.concurrency_semaphore.acquire()
app.job_queue.put_nowait((2, 0, job_id))
await app.job_queue.get()
await app.run_job_wrapper(job_id)
await asyncio.wait_for(retried.wait(), 5)
job = app.jobs[job_id]
assert job["status"] == "queued"
assert job["auto_retries"] == 1
assert enqueued == [(job_id, 1)]
# Half-made outputs are cleared; the source survives for the retry.
assert not (out_dir / "clipwright_clip_1.mp4").exists()
assert not (out_dir / "clipwright_metadata.json").exists()
async def test_manifest_resumes_an_interrupted_job(app_state):
app = app_state.app
job_id = "job-resume"
job_dir = app_state.out / job_id
job_dir.mkdir()
app._write_resume_manifest(job_id, ["python", "-m", "clipwright.pipeline.main"],
priority=2, user_id=None, reservation_id=None)
keep = app._resume_interrupted_jobs()
assert keep == set()
job = app.jobs[job_id]
assert job["status"] == "queued"
assert any("Resuming" in line for line in job["logs"])
assert app.job_queue.qsize() == 1
assert app._read_manifest(job_id)["attempts"] == 1
async def test_manifest_gives_up_after_max_attempts(app_state):
app = app_state.app
job_id = "job-poison"
job_dir = app_state.out / job_id
job_dir.mkdir()
(job_dir / ".resume.json").write_text(json.dumps({
"cmd": ["python"], "priority": 2, "attempts": app.MAX_RESUME_ATTEMPTS,
}))
app._resume_interrupted_jobs()
assert job_id not in app.jobs
assert app.job_queue.qsize() == 0
assert not (job_dir / ".resume.json").exists()

View file

@ -0,0 +1,256 @@
"""L2 API editing E2E: GET .../scenes and POST /api/clip/reframe.
``/scenes`` cuts the clip from source with real ffmpeg and encodes a preview,
but the ML detectors it calls live in the heavy ``clipwright.pipeline.main``
module (absent in the thin E2E env). A fake module is injected into
``sys.modules`` returning deterministic scene/face data — the real module is
never imported. The re-render path is stubbed at ``recut.perform_recut``.
"""
import json
import os
import shutil
import sys
import types
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": 6.0, "text": "hello there",
"words": [{"word": "hello", "start": 1.0, "end": 1.4},
{"word": "there", "start": 3.0, "end": 3.4}],
}],
}
class _Frames:
def __init__(self, n):
self._n = n
def get_frames(self):
return self._n
def _fake_main():
"""The three functions app.py's scenes builder actually calls."""
fake = types.ModuleType("clipwright.pipeline.main")
def detect_scenes(path):
return [(_Frames(0), _Frames(30)), (_Frames(30), _Frames(60))], 10.0
def get_video_resolution(path):
return 320, 180
def detect_face_candidates(frame):
return [{"box": [100, 40, 60, 60]}]
fake.detect_scenes = detect_scenes
fake.get_video_resolution = get_video_resolution
fake.detect_face_candidates = detect_face_candidates
return fake
@pytest.fixture
def fake_pipeline_main(monkeypatch):
import clipwright.pipeline as pipeline_pkg
fake = _fake_main()
monkeypatch.setitem(sys.modules, "clipwright.pipeline.main", fake)
# Belt and braces: `from clipwright.pipeline import main` resolves the
# parent attribute before falling back to the sys.modules entry.
monkeypatch.setattr(pipeline_pkg, "main", fake, raising=False)
return fake
def _make_job(app_state, media_factory, job_id="job-scenes", base="scenes",
output_format="auto", crop_overrides=None):
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")
# Source lives in uploads/<job_id>_*, which is where _locate_source looks
# first for an upload job.
shutil.copy(media_factory.six, app_state.up / f"{job_id}_source.mp4")
clip = {
"start": 0.0,
"end": 6.0,
"video_title_for_youtube_short": "Scenes clip",
"video_url": f"/videos/{job_id}/{base}_clip_1.mp4",
}
if crop_overrides is not None:
clip["crop_overrides"] = crop_overrides
(job_dir / f"{base}_metadata.json").write_text(json.dumps({
"shorts": [clip],
"transcript": TRANSCRIPT,
"output_format": output_format,
"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",
"source": app_state.up / f"{job_id}_source.mp4"}
@pytest.fixture
def scenes_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}/scenes --------------------------------------
class TestScenes:
async def test_success_lists_scenes_and_preview(self, client, scenes_job,
fake_pipeline_main):
resp = await client.get(f"/api/clip/{scenes_job['job_id']}/0/scenes")
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["source_width"] == 320
assert data["source_height"] == 180
# 9:16 crop of a 320x180 source: min(320, 180*9/16) / 320.
assert data["crop_width_fraction"] == pytest.approx(
(180 * 9 / 16) / 320, abs=1e-3)
assert data["saved_overrides"] == {}
assert len(data["scenes"]) == 2
first = data["scenes"][0]
assert first["index"] == 0
assert (first["start"], first["end"]) == (0.0, 3.0)
# The face box [100,40,60,60] centres at x=130/320, y=70/180.
assert first["suggested_center"] == pytest.approx(130 / 320, abs=1e-3)
assert first["suggested_center_y"] == pytest.approx(70 / 180, abs=1e-3)
# The preview and the per-scene thumbnails were really written.
assert data["preview_url"] == (
f"/videos/{scenes_job['job_id']}/temp_preview_0.mp4")
assert (scenes_job["dir"] / "temp_preview_0.mp4").is_file()
assert first["thumbnail_url"].endswith("temp_scene_0_000.jpg")
assert (scenes_job["dir"] / "temp_scene_0_000.jpg").is_file()
# The temp cut was cleaned up (the canonical clip is scenes_clip_1.mp4,
# so scope the glob to the per-call work token).
assert not list(scenes_job["dir"].glob("scenes_0_*.mp4"))
async def test_serves_saved_overrides(self, client, app_state,
media_factory, fake_pipeline_main):
job = _make_job(app_state, media_factory, job_id="job-scenes-ov",
base="ov", crop_overrides={"0": 0.25})
data = (await client.get(f"/api/clip/{job['job_id']}/0/scenes")).json()
assert data["saved_overrides"] == {"0": 0.25}
async def test_horizontal_400(self, client, app_state, media_factory,
fake_pipeline_main):
job = _make_job(app_state, media_factory, job_id="job-scenes-h",
base="h", output_format="horizontal")
resp = await client.get(f"/api/clip/{job['job_id']}/0/scenes")
assert resp.status_code == 400
async def test_no_source_409(self, client, scenes_job, fake_pipeline_main):
os.remove(scenes_job["source"])
resp = await client.get(f"/api/clip/{scenes_job['job_id']}/0/scenes")
assert resp.status_code == 409
async def test_404_unknown_job(self, client, fake_pipeline_main):
assert (await client.get(
"/api/clip/nope/0/scenes")).status_code == 404
async def test_404_missing_metadata(self, client, scenes_job,
fake_pipeline_main):
os.remove(scenes_job["meta"])
assert (await client.get(
f"/api/clip/{scenes_job['job_id']}/0/scenes")).status_code == 404
async def test_404_clip_out_of_range(self, client, scenes_job,
fake_pipeline_main):
assert (await client.get(
f"/api/clip/{scenes_job['job_id']}/4/scenes")).status_code == 404
# --- POST /api/clip/reframe -------------------------------------------------
class TestReframe:
async def test_success_persists_overrides(self, client, scenes_job,
fake_recut):
resp = await client.post("/api/clip/reframe", json={
"job_id": scenes_job["job_id"], "clip_index": 0,
"crop_overrides": {
"0": 0.2,
"1": {"top": 0.6, "bottom": {"x": 0.3, "y": 0.4}},
}})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["framed_scenes"] == [0, 1]
call = fake_recut[0]
assert call["input_path"].endswith(f"{scenes_job['job_id']}_source.mp4")
assert call["reframe"] is True
assert call["crop_overrides"][0] == 0.2
assert call["crop_overrides"][1]["top"] == {"x": 0.6, "y": 0.5}
assert call["crop_overrides"][1]["bottom"] == {"x": 0.3, "y": 0.4}
assert call["captions_transcript"]["segments"][0]["words"]
meta = json.loads(scenes_job["meta"].read_text())
stored = meta["shorts"][0]
assert stored["crop_overrides"]["0"] == 0.2
assert stored["video_url"] == data["new_video_url"]
mem = app_module.jobs[scenes_job["job_id"]]["result"]["clips"][0]
assert mem["crop_overrides"]["0"] == 0.2
async def test_400_no_usable_overrides(self, client, scenes_job,
fake_recut):
for overrides in ({}, {"nope": "x"}, {"0": "garbage"}):
resp = await client.post("/api/clip/reframe", json={
"job_id": scenes_job["job_id"], "clip_index": 0,
"crop_overrides": overrides})
assert resp.status_code == 400, overrides
assert fake_recut == []
async def test_horizontal_400(self, client, app_state, media_factory,
fake_recut):
job = _make_job(app_state, media_factory, job_id="job-reframe-h",
base="rh", output_format="horizontal")
resp = await client.post("/api/clip/reframe", json={
"job_id": job["job_id"], "clip_index": 0,
"crop_overrides": {"0": 0.5}})
assert resp.status_code == 400
assert fake_recut == []
async def test_409_no_source(self, client, scenes_job, fake_recut):
os.remove(scenes_job["source"])
resp = await client.post("/api/clip/reframe", json={
"job_id": scenes_job["job_id"], "clip_index": 0,
"crop_overrides": {"0": 0.5}})
assert resp.status_code == 409
assert fake_recut == []
async def test_404_unknown_job(self, client, fake_recut):
assert (await client.post("/api/clip/reframe", json={
"job_id": "nope", "clip_index": 0,
"crop_overrides": {"0": 0.5}})).status_code == 404
async def test_404_clip_out_of_range(self, client, scenes_job, fake_recut):
assert (await client.post("/api/clip/reframe", json={
"job_id": scenes_job["job_id"], "clip_index": 4,
"crop_overrides": {"0": 0.5}})).status_code == 404

View file

@ -0,0 +1,125 @@
"""L3 E2E: security cross-cuts shared by the API surface.
Pins the path allowlist on the ``/videos`` mount, the traversal refusal on the
``/thumbnails`` mount, the basename sanitisation of client-supplied filenames,
the credential scrubbing of logs, and the deliberate absence of an auth gate in
this single-tenant fork (so a future accidental gate fails loudly here).
"""
import os
import pytest
pytestmark = pytest.mark.e2e
# --------------------------------------------------------------------------- #
# /videos allowlist
# --------------------------------------------------------------------------- #
async def test_videos_serves_clips_but_refuses_sidecars(client, app_state, seeded_job):
job_id = seeded_job(job_id="job-sec", base="pw", clips=1)
job_dir = app_state.out / job_id
# The sensitive sidecars the old plain-StaticFiles mount handed out.
(job_dir / ".owner").write_text("user-uuid")
(job_dir / ".resume.json").write_text('{"webhook_secret": "s"}')
(job_dir / ".instance").write_text("instance-id")
(job_dir / ".transcript_checkpoint.json").write_text("{}")
(job_dir / "notes.json").write_text("{}")
served = await client.get(f"/videos/{job_id}/pw_clip_1.mp4")
assert served.status_code == 200
assert served.content
for name in (".owner", ".resume.json", ".instance",
".transcript_checkpoint.json", "pw_metadata.json", "notes.json"):
resp = await client.get(f"/videos/{job_id}/{name}")
assert resp.status_code == 404, f"{name} leaked from /videos"
async def test_media_guard_rejects_traversal_and_hidden_paths(app_state):
app = app_state.app
assert app._media_guard("job/pw_clip_1.mp4")
for bad in ("../app.py", "job/../../app.py", "job/../.resume.json",
"job/.owner", "job/pw_metadata.json", "/etc/passwd"):
assert not app._media_guard(bad), bad
async def test_videos_encoded_traversal_is_404(client, app_state, seeded_job):
seeded_job(job_id="job-trav", base="pw")
for path in ("/videos/%2e%2e/%2e%2e/etc/passwd",
"/videos/job-trav/..%2f..%2fetc%2fpasswd.mp4",
"/videos/job-trav/%2e%2e/%2e%2e/etc/passwd.mp4"):
resp = await client.get(path)
assert resp.status_code == 404, path
# --------------------------------------------------------------------------- #
# /thumbnails mount
# --------------------------------------------------------------------------- #
async def test_thumbnails_serves_files_but_blocks_traversal(client, app_state):
(app_state.out / "thumbnails" / "ok.jpg").write_bytes(b"jpeg")
ok = await client.get("/thumbnails/ok.jpg")
assert ok.status_code == 200
assert ok.content == b"jpeg"
for path in ("/thumbnails/%2e%2e/%2e%2e/etc/passwd",
"/thumbnails/..%2f..%2fetc%2fpasswd",
"/thumbnails/%2e%2e/secret.txt"):
resp = await client.get(path)
assert resp.status_code == 404, path
# --------------------------------------------------------------------------- #
# Client-supplied filenames are basenamed
# --------------------------------------------------------------------------- #
async def test_edit_input_filename_traversal_is_basenamed(client, app_state, seeded_job):
job_id = seeded_job(job_id="job-edit", base="pw", clips=1)
# A traversal name must resolve under OUTPUT_DIR/<job>/ after basename().
resp = await client.post(
"/api/edit",
json={"job_id": job_id, "clip_index": 0, "api_key": "k",
"input_filename": "../../outside.mp4"},
)
# The route's broad except turns the missing-file 404 into a 500, but the
# detail still shows which path it resolved: the basenamed one.
detail = resp.json()["detail"]
assert detail.endswith(os.path.join(job_id, "outside.mp4"))
assert ".." not in detail
# --------------------------------------------------------------------------- #
# Log credential scrubbing
# --------------------------------------------------------------------------- #
def test_scrub_secrets_masks_embedded_credentials(app_state):
scrub = app_state.app._scrub_secrets
assert scrub("proxy http://user:pass@host:8080/x") == \
"proxy http://***:***@host:8080/x"
assert scrub("socks5://alice:s3cr3t@proxy.example:1080") == \
"socks5://***:***@proxy.example:1080"
assert scrub("no credentials here") == "no credentials here"
assert scrub("https://host/path") == "https://host/path"
# --------------------------------------------------------------------------- #
# No auth gate (single-tenant fork) — pin the intentional openness
# --------------------------------------------------------------------------- #
async def test_public_endpoints_need_no_auth(client, app_state, seeded_job):
# No Authorization / API-key header on any of these.
cfg = await client.get("/api/config")
assert cfg.status_code == 200
job_id = seeded_job(job_id="job-open", base="pw", clips=1)
status = await client.get(f"/api/status/{job_id}")
assert status.status_code == 200
clip = await client.get(f"/videos/{job_id}/pw_clip_1.mp4")
assert clip.status_code == 200
bundle = await client.get(f"/api/jobs/{job_id}/download-all")
assert bundle.status_code == 200
assert bundle.headers["content-type"] == "application/zip"

View file

@ -0,0 +1,66 @@
"""L1 API core: job status polling and source-video streaming."""
import pytest
pytestmark = pytest.mark.e2e
async def test_status_of_a_queued_job(client, app_state):
job_id = "job-status"
app_state.app.jobs[job_id] = {
"status": "queued",
"logs": app_state.app._TimedLog(["Job queued."]),
"result": None,
"partial": None,
}
app_state.app._enqueue_job(job_id)
resp = await client.get(f"/api/status/{job_id}")
assert resp.status_code == 200
body = resp.json()
assert body["status"] == "queued"
assert body["logs"] == ["Job queued."]
assert body["log_times"] is not None and len(body["log_times"]) == 1
assert body["queue"]["position"] == 1
assert body["result"] is None
async def test_status_of_a_disk_recovered_job(client, app_state, seeded_job):
job_id = seeded_job(job_id="job-status-disk", base="status", clips=1)
resp = await client.get(f"/api/status/{job_id}")
assert resp.status_code == 200
body = resp.json()
assert body["status"] == "completed"
assert body["result"]["clips"][0]["video_url"].endswith("/status_clip_1.mp4")
# A completed job is not on the queue.
assert body["queue"] is None
async def test_status_unknown_job_is_404(client):
resp = await client.get("/api/status/nobody-home")
assert resp.status_code == 404
assert resp.json()["detail"] == "Job not found"
async def test_source_url_returns_the_plain_path(client):
resp = await client.get("/api/source-url/any-job")
assert resp.status_code == 200
assert resp.json() == {"url": "/api/source/any-job"}
async def test_source_without_a_file_is_404(client):
resp = await client.get("/api/source/nobody-home")
assert resp.status_code == 404
assert resp.json()["detail"] == "Source not found"
async def test_source_streams_an_upload(client, app_state):
job_id = "job-source"
payload = b"pretend this is a video"
(app_state.up / f"{job_id}_source.mp4").write_bytes(payload)
resp = await client.get(f"/api/source/{job_id}")
assert resp.status_code == 200
assert resp.content == payload
assert resp.headers["content-type"] == "video/mp4"

View file

@ -0,0 +1,209 @@
"""L2 API editing E2E: POST /api/subtitle and POST /api/subtitle/remove.
The burn is REAL ffmpeg over a real fixture video (the whole point of this
lane): the endpoint's SRT/ASS generation, the burn filter and the persistence
all run for real. Only the clip itself is supplied by the media factory.
"""
import json
import os
import shutil
import subprocess
import pytest
pytestmark = pytest.mark.e2e
app_module = pytest.importorskip("clipwright.api.app")
TRANSCRIPT = {
"language": "en",
"segments": [{
"start": 0.0, "end": 6.0, "text": "hello world",
"words": [{"word": "hello", "start": 1.0, "end": 1.4},
{"word": "world", "start": 2.0, "end": 2.4}],
}],
}
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-sub", base="sub",
transcript=TRANSCRIPT):
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": "Sub clip",
"video_url": f"/videos/{job_id}/{base}_clip_1.mp4",
}
meta = {"shorts": [clip], "output_format": "auto", "cost_analysis": {}}
if transcript is not None:
meta["transcript"] = transcript
(job_dir / f"{base}_metadata.json").write_text(json.dumps(meta))
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 sub_job(app_state, media_factory):
return _make_job(app_state, media_factory)
def _output_file(job):
matches = list(job["dir"].glob("subtitled_*_sub_clip_1.mp4"))
assert len(matches) == 1, matches
return matches[0]
# --- POST /api/subtitle -----------------------------------------------------
class TestSubtitle:
async def test_preset_unknown_400(self, client, sub_job):
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0, "preset": "nope"})
assert resp.status_code == 400
assert "preset" in resp.json()["detail"].lower()
async def test_classic_burn_is_playable(self, client, sub_job):
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0, "style": "classic"})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["success"] is True
assert data["new_video_url"].startswith(
f"/videos/{sub_job['job_id']}/subtitled_")
assert data["new_video_url"].endswith("_sub_clip_1.mp4")
out = _output_file(sub_job)
assert out.stat().st_size > 0
assert "video" in {s["codec_type"] for s in _probe(out)["streams"]}
# The SRT sidecar was generated too.
assert list(sub_job["dir"].glob("subs_0_*.srt"))
meta = json.loads(sub_job["meta"].read_text())
assert meta["shorts"][0]["video_url"] == data["new_video_url"]
mem = app_module.jobs[sub_job["job_id"]]["result"]["clips"][0]
assert mem["video_url"] == data["new_video_url"]
async def test_karaoke_preset_burns_ass(self, client, sub_job):
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0, "preset": "default"})
assert resp.status_code == 200, resp.text
assert _output_file(sub_job).is_file()
# Karaoke renders an ASS sidecar (its own per-word styles).
assert list(sub_job["dir"].glob("subs_0_*.ass"))
async def test_words_path_burns_edited_captions(self, client, sub_job):
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0, "style": "classic",
"words": [
{"text": "edited", "startMs": 500, "endMs": 900},
{"text": "captions", "startMs": 1200, "endMs": 1800},
]})
assert resp.status_code == 200, resp.text
assert _output_file(sub_job).is_file()
srt = list(sub_job["dir"].glob("subs_0_*.srt"))[0]
assert "edited" in srt.read_text(encoding="utf-8-sig").lower()
async def test_too_many_words_400(self, client, sub_job):
words = [{"text": "w", "startMs": i, "endMs": i + 1}
for i in range(2001)]
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0, "words": words})
assert resp.status_code == 400
assert "Too many" in resp.json()["detail"]
async def test_no_words_in_range_is_wrapped_as_500(self, client, app_state,
media_factory):
# generate_srt() returns False and the route raises its 400 INSIDE the
# try whose catch-all turns it into a 500 (documented deviation from
# the 400 the spec expected).
job = _make_job(app_state, media_factory, job_id="job-sub-nowords",
base="nw", transcript={
"language": "en",
"segments": [{
"start": 100.0, "end": 106.0, "text": "late",
"words": [{"word": "late", "start": 100.0,
"end": 100.4}],
}],
})
resp = await client.post("/api/subtitle", json={
"job_id": job["job_id"], "clip_index": 0, "style": "classic"})
assert resp.status_code == 500
assert "words" in resp.json()["detail"].lower()
async def test_missing_transcript_400(self, client, app_state,
media_factory):
job = _make_job(app_state, media_factory, job_id="job-sub-notx",
base="nt", transcript=None)
resp = await client.post("/api/subtitle", json={
"job_id": job["job_id"], "clip_index": 0})
assert resp.status_code == 400
async def test_404_unknown_job(self, client):
resp = await client.post("/api/subtitle", json={
"job_id": "nope", "clip_index": 0})
assert resp.status_code == 404
async def test_404_missing_metadata(self, client, sub_job):
os.remove(sub_job["meta"])
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0})
assert resp.status_code == 404
async def test_404_clip_out_of_range(self, client, sub_job):
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 5})
assert resp.status_code == 404
async def test_404_missing_file(self, client, sub_job):
os.remove(sub_job["dir"] / "sub_clip_1.mp4")
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0})
assert resp.status_code == 404
# --- POST /api/subtitle/remove ----------------------------------------------
class TestRemoveSubtitles:
async def test_points_back_at_clean_file(self, client, sub_job):
burn = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0, "style": "classic"})
assert burn.status_code == 200
resp = await client.post("/api/subtitle/remove", json={
"job_id": sub_job["job_id"], "clip_index": 0})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["new_video_url"] == (
f"/videos/{sub_job['job_id']}/sub_clip_1.mp4")
meta = json.loads(sub_job["meta"].read_text())
assert meta["shorts"][0]["video_url"] == data["new_video_url"]
mem = app_module.jobs[sub_job["job_id"]]["result"]["clips"][0]
assert mem["video_url"] == data["new_video_url"]
async def test_404_original_gone(self, client, sub_job):
resp = await client.post("/api/subtitle/remove", json={
"job_id": sub_job["job_id"], "clip_index": 0,
"input_filename": "gone.mp4"})
assert resp.status_code == 404
async def test_404_unknown_job(self, client):
resp = await client.post("/api/subtitle/remove", json={
"job_id": "nope", "clip_index": 0})
assert resp.status_code == 404

View file

@ -0,0 +1,585 @@
"""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"]

View file

@ -0,0 +1,242 @@
"""L3 E2E: the anonymous free tools (``clipwright.api.free_tools``).
The network seams are stubbed (``_fetch_with_slot`` for the transcript, the
``_generate`` Gemini call for metadata), so the real route logic runs: URL
validation, caption/error mapping, the 24 h cache, the in-process rate limiter
and the metadata mode/shape handling.
"""
import asyncio
from collections import OrderedDict
from types import SimpleNamespace
import pytest
pytestmark = pytest.mark.e2e
VIDEO_A = "arj7oStGLkU"
VIDEO_B = "dQw4w9WgXcQ"
@pytest.fixture
def ft(monkeypatch):
"""A clean free_tools module: fresh cache and a fresh limiter per test."""
from clipwright.api import free_tools
monkeypatch.setattr(free_tools, "_TRANSCRIPT_CACHE", OrderedDict())
monkeypatch.setattr(free_tools, "_limiter", free_tools.RateLimiter(free_tools.LIMITS))
return free_tools
@pytest.fixture
def transcript_stub(monkeypatch, ft):
"""Stub ``_fetch_with_slot`` (what the route hands to ``to_thread``)."""
state = SimpleNamespace(
calls=[],
error=None,
result={"video_id": "x", "title": "A video", "channel": "Chan",
"duration": 12, "languages": [], "language": "en", "kind": "manual",
"segments": [{"start": 0.0, "dur": 1.0, "text": "hello"}]},
)
def fake(video_id, lang):
state.calls.append((video_id, lang))
if state.error:
raise state.error
return state.result
monkeypatch.setattr(ft, "_fetch_with_slot", fake)
return state
@pytest.fixture
def generate_stub(monkeypatch, ft):
"""Stub the Gemini ``_generate`` seam used by the metadata route."""
state = SimpleNamespace(calls=[], result={"titles": [{"title": "A", "angle": "x"}]},
error=None)
def fake(prompt):
state.calls.append(prompt)
if state.error:
raise state.error
return state.result
monkeypatch.setattr(ft, "_generate", fake)
return state
# --------------------------------------------------------------------------- #
# GET /api/tools/youtube-transcript
# --------------------------------------------------------------------------- #
async def test_transcript_success_then_served_from_cache(client, ft, transcript_stub):
r1 = await client.get("/api/tools/youtube-transcript",
params={"url": f"https://youtu.be/{VIDEO_A}"})
assert r1.status_code == 200, r1.text
assert r1.json()["cached"] is False
assert r1.json()["segments"] == [{"start": 0.0, "dur": 1.0, "text": "hello"}]
# A bare id resolves to the same video id -> cache hit, no second fetch.
r2 = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r2.status_code == 200
assert r2.json()["cached"] is True
assert len(transcript_stub.calls) == 1
assert transcript_stub.calls[0][0] == VIDEO_A
async def test_transcript_bad_url_is_400_without_work(client, ft, transcript_stub):
r = await client.get("/api/tools/youtube-transcript",
params={"url": "https://youtube.com/@ted"})
assert r.status_code == 400
assert r.json()["detail"]["code"] == "bad_url"
assert transcript_stub.calls == []
async def test_transcript_no_captions_is_404_and_cached(client, ft, transcript_stub):
transcript_stub.error = ft.TranscriptError("no_captions", "none", 404)
r1 = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r1.status_code == 404
assert r1.json()["detail"]["code"] == "no_captions"
# The verdict about the video is cached: no second fetch, same 404.
r2 = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r2.status_code == 404
assert r2.json()["detail"]["code"] == "no_captions"
assert len(transcript_stub.calls) == 1
async def test_transcript_unavailable_is_422(client, ft, transcript_stub):
transcript_stub.error = ft.TranscriptError("unavailable", "private", 422)
r = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r.status_code == 422
assert r.json()["detail"]["code"] == "unavailable"
async def test_transcript_blocked_is_503(client, ft, transcript_stub):
transcript_stub.error = ft.TranscriptError("youtube_blocked", "blocked", 503)
r = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r.status_code == 503
assert r.json()["detail"]["code"] == "youtube_blocked"
async def test_transcript_busy_is_503(client, ft, transcript_stub):
transcript_stub.error = ft.TranscriptError("busy", "busy", 503)
r = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r.status_code == 503
assert r.json()["detail"]["code"] == "busy"
async def test_transcript_timeout_is_504(client, ft, transcript_stub):
transcript_stub.error = asyncio.TimeoutError()
r = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r.status_code == 504
assert r.json()["detail"]["code"] == "timeout"
async def test_transcript_per_ip_rate_limit_is_429(client, ft, transcript_stub, monkeypatch):
monkeypatch.setattr(
ft, "_limiter",
ft.RateLimiter({"transcript": {"per_ip": [(600, 1)], "global_day": 1000}}))
r1 = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r1.status_code == 200
r2 = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_B})
assert r2.status_code == 429
assert r2.json()["detail"]["code"] == "rate_limited"
async def test_transcript_global_rate_limit_is_429_busy(client, ft, transcript_stub,
monkeypatch):
monkeypatch.setattr(
ft, "_limiter",
ft.RateLimiter({"transcript": {"per_ip": [(600, 100)], "global_day": 1}}))
r1 = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r1.status_code == 200
r2 = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_B})
assert r2.status_code == 429
assert r2.json()["detail"]["code"] == "busy"
# --------------------------------------------------------------------------- #
# POST /api/tools/youtube-metadata
# --------------------------------------------------------------------------- #
async def test_metadata_bad_mode_is_400(client, ft, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
r = await client.post("/api/tools/youtube-metadata",
json={"mode": "bogus", "topic": "a" * 40})
assert r.status_code == 400
assert r.json()["detail"]["code"] == "bad_mode"
async def test_metadata_too_short_topic_is_400(client, ft, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
r = await client.post("/api/tools/youtube-metadata",
json={"mode": "titles", "topic": "short"})
assert r.status_code == 400
assert r.json()["detail"]["code"] == "too_short"
async def test_metadata_not_configured_is_503(client, ft, monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
r = await client.post("/api/tools/youtube-metadata",
json={"mode": "titles", "topic": "A video about sourdough bread"})
assert r.status_code == 503
assert r.json()["detail"]["code"] == "not_configured"
async def test_metadata_titles_mode(client, ft, generate_stub, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
generate_stub.result = {"titles": [{"title": "How to bake", "angle": "how-to"}]}
r = await client.post("/api/tools/youtube-metadata",
json={"mode": "titles", "topic": "A video about sourdough bread",
"keyword": "sourdough"})
assert r.status_code == 200, r.text
assert r.json()["mode"] == "titles"
assert r.json()["titles"] == [{"title": "How to bake", "angle": "how-to"}]
# The keyword rides into the prompt.
assert "sourdough" in generate_stub.calls[0]
async def test_metadata_description_mode(client, ft, generate_stub, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
generate_stub.result = {"description": "A long enough description."}
r = await client.post("/api/tools/youtube-metadata",
json={"mode": "description",
"topic": "A video about sourdough bread"})
assert r.status_code == 200
assert r.json()["description"] == "A long enough description."
async def test_metadata_tags_mode(client, ft, generate_stub, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
generate_stub.result = {"tags": ["sourdough", "baking"]}
r = await client.post("/api/tools/youtube-metadata",
json={"mode": "tags", "topic": "A video about sourdough bread"})
assert r.status_code == 200
assert r.json()["tags"] == ["sourdough", "baking"]
assert r.json()["characters"] == len("sourdough,baking")
async def test_metadata_generation_failure_is_502_after_retry(client, ft, generate_stub,
monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
generate_stub.error = RuntimeError("model exploded")
r = await client.post("/api/tools/youtube-metadata",
json={"mode": "titles", "topic": "A video about sourdough bread"})
assert r.status_code == 502
assert r.json()["detail"]["code"] == "generation_failed"
assert len(generate_stub.calls) == 2 # one retry
async def test_metadata_rate_limit_is_429(client, ft, generate_stub, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
monkeypatch.setattr(
ft, "_limiter",
ft.RateLimiter({"metadata": {"per_ip": [(600, 1)], "global_day": 1000}}))
generate_stub.result = {"titles": [{"title": "A", "angle": "x"}]}
body = {"mode": "titles", "topic": "A video about sourdough bread"}
r1 = await client.post("/api/tools/youtube-metadata", json=body)
assert r1.status_code == 200
r2 = await client.post("/api/tools/youtube-metadata", json=body)
assert r2.status_code == 429
assert r2.json()["detail"]["code"] == "rate_limited"

View file

@ -0,0 +1,288 @@
"""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"]

View file

@ -0,0 +1,130 @@
"""L1 API core: the two-step agent upload path (POST reserve, PUT bytes,
DELETE drop).
The PUT is capped at ``MAX_FILE_SIZE_MB`` (0 = unlimited) and probes the body
with ffprobe, so a non-video is refused with 400 rather than queued.
"""
import os
import pytest
pytestmark = pytest.mark.e2e
async def _reserve(client, filename=None):
body = {} if filename is None else {"filename": filename}
resp = await client.post("/api/uploads", json=body)
assert resp.status_code == 200, resp.text
return resp.json()
async def test_reserve_returns_slot_shape_and_sanitises_basename(client, app_state):
data = await _reserve(client, "../../etc/evil.mp4")
uid = data["upload_id"]
slot = app_state.app.pending_uploads[uid]
# basename() strips every path component the client tried to smuggle in.
assert slot["filename"] == "evil.mp4"
assert os.path.basename(slot["path"]).startswith(f"pending_{uid}_")
assert os.path.basename(slot["path"]).endswith("evil.mp4")
assert slot["complete"] is False and slot["bytes"] == 0
assert data["upload_url"].endswith(f"/api/uploads/{uid}")
assert data["method"] == "PUT"
assert data["max_mb"] == app_state.app.MAX_FILE_SIZE_MB
assert data["expires_in"] == app_state.app.UPLOAD_TTL_SECONDS
assert "PUT the raw video bytes" in data["hint"]
async def test_reserve_defaults_filename_when_body_absent(client, app_state):
resp = await client.post("/api/uploads")
assert resp.status_code == 200
uid = resp.json()["upload_id"]
assert app_state.app.pending_uploads[uid]["filename"] == "video.mp4"
async def test_put_unknown_id_is_404(client, app_state):
resp = await client.put("/api/uploads/does-not-exist", content=b"x")
assert resp.status_code == 404
assert "Unknown or expired" in resp.json()["detail"]
async def test_put_expired_slot_is_404_and_dropped(client, app_state):
uid = (await _reserve(client))["upload_id"]
slot = app_state.app.pending_uploads[uid]
slot["created"] -= app_state.app.UPLOAD_TTL_SECONDS + 10
resp = await client.put(f"/api/uploads/{uid}", content=b"anything")
assert resp.status_code == 404
assert uid not in app_state.app.pending_uploads
async def test_put_empty_body_is_400_and_removes_file(client, app_state):
uid = (await _reserve(client))["upload_id"]
path = app_state.app.pending_uploads[uid]["path"]
resp = await client.put(f"/api/uploads/{uid}", content=b"")
assert resp.status_code == 400
assert resp.json()["detail"] == "Empty body"
assert not os.path.exists(path)
assert app_state.app.pending_uploads[uid]["complete"] is False
async def test_put_unreadable_body_is_400_and_removes_file(client, app_state):
uid = (await _reserve(client))["upload_id"]
path = app_state.app.pending_uploads[uid]["path"]
resp = await client.put(f"/api/uploads/{uid}", content=b"this is not a video")
assert resp.status_code == 400
assert "not a readable video file" in resp.json()["detail"]
assert not os.path.exists(path)
assert app_state.app.pending_uploads[uid]["complete"] is False
async def test_put_oversized_body_is_413_and_removes_file(client, app_state, monkeypatch):
monkeypatch.setattr(app_state.app, "MAX_FILE_SIZE_MB", 1)
uid = (await _reserve(client))["upload_id"]
path = app_state.app.pending_uploads[uid]["path"]
oversized = b"x" * (1024 * 1024 + 1)
resp = await client.put(f"/api/uploads/{uid}", content=oversized)
assert resp.status_code == 413
assert "File too large" in resp.json()["detail"]
assert not os.path.exists(path)
async def test_second_put_replaces_the_first(client, app_state, media_factory):
uid = (await _reserve(client))["upload_id"]
path = app_state.app.pending_uploads[uid]["path"]
first = media_factory.six.read_bytes()
resp = await client.put(f"/api/uploads/{uid}", content=first)
assert resp.status_code == 200
assert resp.json()["bytes"] == len(first)
assert resp.json()["duration_seconds"] == pytest.approx(6.0, abs=1.0)
second = media_factory.silent.read_bytes()
resp = await client.put(f"/api/uploads/{uid}", content=second)
assert resp.status_code == 200
assert resp.json()["bytes"] == len(second)
# The slot now points at the replacement, not the first body.
assert open(path, "rb").read() == second
async def test_delete_removes_slot_and_file(client, app_state, media_factory):
uid = (await _reserve(client))["upload_id"]
path = app_state.app.pending_uploads[uid]["path"]
assert (await client.put(f"/api/uploads/{uid}",
content=media_factory.six.read_bytes())).status_code == 200
resp = await client.delete(f"/api/uploads/{uid}")
assert resp.status_code == 200
assert resp.json() == {"deleted": uid}
assert uid not in app_state.app.pending_uploads
assert not os.path.exists(path)
async def test_delete_unknown_id_is_404(client, app_state):
resp = await client.delete("/api/uploads/nope")
assert resp.status_code == 404

199
tests/e2e/conftest.py Normal file
View file

@ -0,0 +1,199 @@
"""Shared E2E fixtures: state isolation, a no-network guard, ffmpeg media, and
disk-seeded jobs.
Design notes
------------
* ``no_network`` (autouse) makes any unmocked DNS lookup fail loudly. The API
tests drive the app through ``httpx.ASGITransport``, which never touches a
socket; the pipeline tests run the real CLI with the stub_env fakes.
* ``app_state`` rebinds the module globals in ``clipwright.api.app`` per test so
two tests never share a ``jobs`` dict, a queue, or a semaphore. All names were
verified against ``clipwright/api/app.py`` (see the note in the report).
* ``media_factory`` is session-scoped and generates the fixture videos with
ffmpeg ``lavfi`` sources, so no binaries live in git. Tests assert on
globs/ffprobe values, never on exact ``<timestamp>`` filenames.
"""
import asyncio
import json
import socket
import subprocess
from types import SimpleNamespace
import pytest
@pytest.fixture(autouse=True)
def no_network(monkeypatch):
"""Fail on any unmocked outbound DNS lookup.
Loopback is allowed so local servers (an OpenAI-compatible LLM, a test
Postiz) can be reached; everything else must be mocked explicitly.
"""
real = socket.getaddrinfo
def guard(host, *args, **kwargs):
if host in ("127.0.0.1", "localhost", "::1", None, "", b"127.0.0.1"):
return real(host, *args, **kwargs)
raise AssertionError(f"unmocked network access to {host!r}")
monkeypatch.setattr(socket, "getaddrinfo", guard)
@pytest.fixture
def app_state(tmp_path, monkeypatch):
"""Point ``clipwright.api.app`` at a per-test output/upload tree.
Rebind the module globals the routes read at call time. ``job_queue`` and
``concurrency_semaphore`` are recreated because asyncio primitives latch
onto the first event loop they touch, and each test gets a fresh loop.
"""
import clipwright.api.app as app
out = tmp_path / "output"
up = tmp_path / "uploads"
out.mkdir()
up.mkdir()
(out / "thumbnails").mkdir()
monkeypatch.setattr(app, "OUTPUT_DIR", str(out))
monkeypatch.setattr(app, "UPLOAD_DIR", str(up))
monkeypatch.setattr(app, "THUMBNAILS_DIR", str(out / "thumbnails"))
# The /videos and /thumbnails mounts captured their directory at import
# time (`app.mount(..., directory=OUTPUT_DIR)`), so rebinding the module
# globals is not enough: repoint the mounted StaticFiles instances too or
# route tests would read the real `output/` tree. Both `.directory` (used
# for the directory-redirect check) and `.all_directories` (used by
# lookup_path) must move together.
def _repoint(name, directory):
for route in getattr(app.app, "routes", []):
if getattr(route, "name", None) == name:
sub = getattr(route, "app", None)
if sub is not None and hasattr(sub, "all_directories"):
sub.directory = str(directory)
sub.all_directories = [str(directory)]
_repoint("videos", out)
_repoint("thumbnails", out / "thumbnails")
for name, empty in (
("jobs", {}),
("thumbnail_sessions", {}),
("publish_jobs", {}),
("pending_uploads", {}),
("_rerender_locks", {}),
("_scenes_locks", {}),
("_recent_job_seconds", []),
("_admitting", set()),
("_running_jobs", set()),
):
monkeypatch.setattr(app, name, empty)
# Rebind loop-bound primitives (see docstring).
monkeypatch.setattr(app, "job_queue", asyncio.PriorityQueue())
monkeypatch.setattr(app, "concurrency_semaphore", asyncio.Semaphore(5))
monkeypatch.setattr(app, "_draining", False)
monkeypatch.setattr(app, "_stopping", False)
# Hermetic defaults: never gate on source height/length/size in tests.
monkeypatch.setattr(app, "QUALITY_GATE_MIN_HEIGHT", 0)
monkeypatch.setattr(app, "MIN_SOURCE_SECONDS", 0)
monkeypatch.setattr(app, "MAX_FILE_SIZE_MB", 0)
return SimpleNamespace(out=out, up=up, app=app)
@pytest.fixture(scope="session")
def media_factory(tmp_path_factory):
"""Generate the shared E2E fixture videos once per session.
Returns a ``SimpleNamespace`` whose attributes are ``pathlib.Path``s:
* ``sixty`` — 160x90, 60 s, with audio (uploads / process)
* ``six`` — 320x180, 6 s, with audio (fast stage tests)
* ``cuts`` — 320x180, 4 hard-colour segments (scene detection)
* ``silent`` — 320x180, 6 s, no audio (vision / no-audio paths)
"""
root = tmp_path_factory.mktemp("media")
def _run(args):
subprocess.run(
["ffmpeg", "-y", "-hide_banner", "-loglevel", "error", *args],
check=True,
)
sixty = root / "sixty.mp4"
six = root / "six.mp4"
cuts = root / "cuts.mp4"
silent = root / "silent.mp4"
if not sixty.exists():
_run([
"-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=60",
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=60",
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-shortest", str(sixty),
])
if not six.exists():
_run([
"-f", "lavfi", "-i", "testsrc=size=320x180:rate=10:duration=6",
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=6",
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-shortest", str(six),
])
if not cuts.exists():
_run([
"-f", "lavfi", "-i", "color=c=red:s=320x180:d=1.5",
"-f", "lavfi", "-i", "color=c=green:s=320x180:d=1.5",
"-f", "lavfi", "-i", "color=c=blue:s=320x180:d=1.5",
"-f", "lavfi", "-i", "color=c=yellow:s=320x180:d=1.5",
"-filter_complex", "[0:v][1:v][2:v][3:v]concat=n=4:v=1:a=0[v]",
"-map", "[v]", "-c:v", "libx264", "-preset", "ultrafast",
"-pix_fmt", "yuv420p", str(cuts),
])
if not silent.exists():
_run([
"-f", "lavfi", "-i", "testsrc=size=320x180:rate=10:duration=6",
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
str(silent),
])
return SimpleNamespace(sixty=sixty, six=six, cuts=cuts, silent=silent)
@pytest.fixture
def seeded_job(app_state):
"""Factory: write a completed job to disk and recover it into ``jobs``.
Mirrors the restart path: ``output/<job_id>/<base>_metadata.json`` plus a
non-empty ``<base>_clip_<n>.mp4`` per clip, then
``app._recover_jobs_from_disk()``. Returns the ``job_id`` (the recovered
record is available as ``app_state.app.jobs[job_id]``).
"""
def _seed(job_id="job-seeded", base="clipwright", clips=1):
import clipwright.api.app as app
job_dir = app_state.out / job_id
job_dir.mkdir(parents=True, exist_ok=True)
shorts = []
for i in range(clips):
shorts.append({
"start": float(i * 10),
"end": float(i * 10 + 8),
"predicted_score": 80 - i,
"video_title_for_youtube_short": f"Seeded clip {i + 1}",
"viral_hook_text": f"Hook {i + 1}",
"video_description_for_tiktok": "Seeded #test",
"video_description_for_instagram": "Seeded #test",
})
(job_dir / f"{base}_clip_{i + 1}.mp4").write_bytes(b"\x00" * 2048)
(job_dir / f"{base}_metadata.json").write_text(json.dumps({
"shorts": shorts,
"cost_analysis": {"total_cost": 0.0, "model": "seeded"},
}))
app._recover_jobs_from_disk()
return job_id
return _seed

View file

@ -0,0 +1 @@
"""Pipeline-stage end-to-end tests (real CLI, real ffmpeg, stubbed ML/LLM)."""

View file

@ -0,0 +1,69 @@
"""Pipeline E2E fixtures.
The tests here run the REAL CLI (``python -m clipwright.pipeline.main``) with
real ffmpeg, but the child interpreter is started with ``stub_env`` on
``PYTHONPATH``. ``stub_env/sitecustomize.py`` swaps the ML and network edges
(ultralytics/mediapipe, ASR, Gemini) for deterministic fakes, so no model is
downloaded and no request leaves the process. Mark ML-backed variants with
``pytest.mark.ml``; those run against ``requirements-ml-e2e.txt`` instead.
"""
import os
import subprocess
import sys
from pathlib import Path
import pytest
pytestmark = pytest.mark.pipeline
REPO_ROOT = Path(__file__).resolve().parents[3]
STUB_ENV = Path(__file__).resolve().parent / "stub_env"
@pytest.fixture(scope="session")
def stub_env_dir():
"""Directory holding ``sitecustomize.py`` for the pipeline child."""
assert (STUB_ENV / "sitecustomize.py").is_file()
return STUB_ENV
@pytest.fixture
def pipeline_env(stub_env_dir, tmp_path):
"""Environment for a pipeline subprocess: stub env on PYTHONPATH, no LLM."""
env = dict(os.environ)
env.pop("LLM_BASE_URL", None)
env.pop("LLM_MODEL", None)
env["GEMINI_API_KEY"] = "stub-gemini-key"
env["PYTHONPATH"] = os.pathsep.join(
[str(stub_env_dir), str(REPO_ROOT), env.get("PYTHONPATH", "")]
).strip(os.pathsep)
env["PYTHONHASHSEED"] = "0"
env["TZ"] = "UTC"
# Keep output inside the test's tmp tree unless the caller overrides it.
env.setdefault("TRANSCRIBE_BACKEND", "whisper")
return env
@pytest.fixture
def run_pipeline(pipeline_env):
"""Run the real CLI; returns the CompletedProcess.
Usage: ``run_pipeline(media.six, "-o", str(out))``.
"""
def _run(input_path, *extra, timeout=180):
cmd = [
sys.executable, "-u", "-m", "clipwright.pipeline.main",
"-i", str(input_path), *extra,
]
return subprocess.run(
cmd,
cwd=str(REPO_ROOT),
env=pipeline_env,
capture_output=True,
text=True,
timeout=timeout,
)
return _run

View file

@ -0,0 +1,281 @@
"""Interpreter-startup stubs injected into the pipeline CLI child via PYTHONPATH.
This file is named ``sitecustomize`` so CPython imports it automatically at
startup, *before* the ``-m clipwright.pipeline.main`` module body runs. That
lets us satisfy the heavy imports at the top of ``main.py`` (``ultralytics``,
``mediapipe``) and replace the two network/ML edges — ASR and Gemini — with
deterministic fakes. The real CLI then runs the real pipeline with real ffmpeg
and zero network / zero ML.
Kept intentionally dependency-free (stdlib only) so it imports cleanly in the
thin ``requirements-e2e.txt`` environment.
"""
import json
import sys
import types
from types import SimpleNamespace
# ---------------------------------------------------------------------------
# Fake ultralytics / mediapipe: main.py imports these at module level.
# ---------------------------------------------------------------------------
class _FakeYOLO:
def __init__(self, *args, **kwargs):
self.args = args
def __call__(self, *args, **kwargs):
return []
def predict(self, *args, **kwargs):
return []
def track(self, *args, **kwargs):
return []
class _FakeFaceDetection:
def __init__(self, *args, **kwargs):
pass
def process(self, *args, **kwargs):
return SimpleNamespace(detections=None)
def close(self):
pass
def _install_module(name, module):
sys.modules[name] = module
def _fake_ultralytics():
mod = types.ModuleType("ultralytics")
mod.YOLO = _FakeYOLO
return mod
def _fake_mediapipe():
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
face_detection = types.ModuleType("mediapipe.solutions.face_detection")
face_detection.FaceDetection = _FakeFaceDetection
solutions.face_detection = face_detection
mp.solutions = solutions
return mp
_install_module("ultralytics", _fake_ultralytics())
_install_module("mediapipe", _fake_mediapipe())
_install_module("mediapipe.solutions", sys.modules["mediapipe"].solutions)
_install_module("mediapipe.solutions.face_detection",
sys.modules["mediapipe"].solutions.face_detection)
# ---------------------------------------------------------------------------
# Canned transcript: patch transcribe_backends so no ASR model is loaded.
# ---------------------------------------------------------------------------
_CANNED_TRANSCRIPT = {
"text": "This is a canned transcript for the end-to-end pipeline tests.",
"language": "en",
"segments": [
{
"start": 0.0,
"end": 3.0,
"text": " This is a canned transcript",
"words": [
{"word": " This", "start": 0.0, "end": 0.4},
{"word": " is", "start": 0.4, "end": 0.7},
{"word": " a", "start": 0.7, "end": 0.9},
{"word": " canned", "start": 0.9, "end": 1.4},
{"word": " transcript", "start": 1.4, "end": 2.2},
],
},
{
"start": 3.0,
"end": 6.0,
"text": " for the end-to-end pipeline tests.",
"words": [
{"word": " for", "start": 3.0, "end": 3.3},
{"word": " the", "start": 3.3, "end": 3.5},
{"word": " end-to-end", "start": 3.5, "end": 4.4},
{"word": " pipeline", "start": 4.4, "end": 5.1},
{"word": " tests.", "start": 5.1, "end": 5.9},
],
},
],
}
def _fake_transcribe_media(media_path):
return json.loads(json.dumps(_CANNED_TRANSCRIPT))
def _fake_release_models():
return None
try:
from clipwright.pipeline import transcribe_backends as _tb
_tb.transcribe_media = _fake_transcribe_media
_tb.release_models = _fake_release_models
except Exception as _exc: # pragma: no cover - surfaced in the child's stderr
print(f"[stub_env] could not patch transcribe_backends: {_exc}", file=sys.stderr)
# ---------------------------------------------------------------------------
# Scripted Gemini client. The real SDK is imported by main.py and the stage
# modules; we replace only ``genai.Client`` (they all call ``genai.Client(...)``
# on the module object, so the patch reaches every caller).
# ---------------------------------------------------------------------------
class _FakeResponse:
"""Surface consumed by gemini_worker / main._run_gemini_stage.
``parsed`` is None so the real JSON parser runs against ``.text`` — this
exercises the production parse path instead of bypassing it.
"""
def __init__(self, text):
self.text = text
self.parsed = None
self.prompt_feedback = None
self.candidates = []
self.usage_metadata = None
def _prompt_text(contents):
if isinstance(contents, str):
return contents
parts = []
for item in contents or []:
text = getattr(item, "text", None)
if isinstance(item, str):
parts.append(item)
elif text:
parts.append(text)
return "\n".join(parts)
def _extract_windows(prompt):
"""Parse the JSON array embedded after ``WINDOWS_JSON:`` / ``..._WINDOWS_JSON:``."""
for marker in ("WINDOWS_JSON:", "CANDIDATE_WINDOWS_JSON:"):
if marker not in prompt:
continue
tail = prompt.split(marker, 1)[1]
for stop in ("\n\nReturn only:", "\n\nReturn only"):
if stop in tail:
tail = tail.split(stop, 1)[0]
try:
return json.loads(tail.strip())
except Exception:
return []
return []
def _score_response(prompt):
windows = _extract_windows(prompt)
return json.dumps({
"windows": [
{
"id": w.get("id"),
"start": float(w.get("start", 0)),
"end": float(w.get("end", 1)),
"score": 85,
"reason": "stub score",
}
for w in windows
]
})
def _detail_response(prompt):
windows = _extract_windows(prompt)
if not windows:
windows = [{"start": 0, "end": 6, "id": "w0"}]
return json.dumps({
"shorts": [
{
"start": float(w.get("start", 0)),
"end": float(w.get("end", 1)),
"source_window_id": w.get("id") or "w0",
"predicted_score": 85,
"video_description_for_tiktok": "Stub #test #clip",
"video_description_for_instagram": "Stub #test #clip",
"video_title_for_youtube_short": "Stub clip",
"viral_hook_text": "Stub hook",
"why": "stub moment",
}
for w in windows
]
})
def _visual_response(prompt):
return json.dumps({
"shorts": [
{
"start": 0.0,
"end": 5.0,
"predicted_score": 80,
"video_description_for_tiktok": "Stub #test #clip",
"video_description_for_instagram": "Stub #test #clip",
"video_title_for_youtube_short": "Stub visual clip",
"viral_hook_text": "Stub visual hook",
}
]
})
def _response_for(prompt):
if "RANK these candidate windows" in prompt:
return _score_response(prompt)
if "Choose the BEST short clips" in prompt:
return _detail_response(prompt)
if "This video has NO speech/audio" in prompt:
return _visual_response(prompt)
if "These frames come from ONE short clip" in prompt:
return json.dumps({
"on_screen": "a screen",
"viral_hook_text": "Stub grounded hook",
"video_title_for_youtube_short": "Stub grounded title",
})
if "You are choosing how to re-frame" in prompt:
return json.dumps({"layout": "none", "confidence": 0.95, "why": "talking head"})
if "preparing a landscape video" in prompt:
return json.dumps({"ranges": []})
return "{}"
class _FakeModels:
def generate_content(self, model=None, contents=None, config=None):
return _FakeResponse(_response_for(_prompt_text(contents)))
class _FakeFiles:
def upload(self, file=None, config=None):
return SimpleNamespace(name="files/stub-video")
def get(self, name=None):
return SimpleNamespace(state=SimpleNamespace(name="ACTIVE"))
def delete(self, name=None):
return None
class _FakeClient:
def __init__(self, api_key=None, **kwargs):
self.models = _FakeModels()
self.files = _FakeFiles()
try:
from google import genai as _genai
_genai.Client = _FakeClient
except Exception as _exc: # pragma: no cover - surfaced in the child's stderr
print(f"[stub_env] could not patch google.genai.Client: {_exc}", file=sys.stderr)

View file

@ -0,0 +1,119 @@
"""L4 — full CLI pipeline (the keystone test).
Runs the REAL ``python -m clipwright.pipeline.main`` end to end with real
ffmpeg. The child interpreter is started with ``stub_env`` first on
``PYTHONPATH``, so ``sitecustomize.py`` injects the fake ultralytics/mediapipe
modules, stubs ASR, and patches the Gemini client. The test asserts on exit
code, metadata JSON, real clip files (ffprobe, never bytes) and the
``CLIP_READY`` markers — plus a failure variant that must write no metadata.
"""
import json
import subprocess
from pathlib import Path
import pytest
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
def _cli_env(pipeline_env, **overrides):
"""Pin the deterministic, no-ML pipeline environment for the child."""
pipeline_env.update({
"GEMINI_API_KEY": "test",
"AUTO_LAYOUT": "0",
"SCENE_ENGINE": "pyscenedetect",
"FFMPEG_ENCODER": "x264",
"ASR_HOST_SLOTS": "0",
"CLIP_WORKERS": "2",
})
for var in ("AUTO_HOOK", "WATERMARK", "MAX_SOURCE_MINUTES",
"SOURCE_CAP_MINUTES", "DOWNLOAD_SKIP_STATICS"):
pipeline_env.pop(var, None)
pipeline_env.update(overrides)
return pipeline_env
def _probe(path):
out = subprocess.run(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", str(path)],
capture_output=True, text=True, check=True)
width, height = out.stdout.strip().split("x")
return int(width), int(height)
def _ready_lines(stdout):
return [line for line in stdout.splitlines() if line.startswith("CLIP_READY ")]
def _assert_success(result, out, media, fmt):
assert result.returncode == 0, (
f"CLI failed ({result.returncode})\nSTDOUT:\n{result.stdout[-4000:]}\n"
f"STDERR:\n{result.stderr[-4000:]}")
metadata_files = list(out.glob("*_metadata.json"))
assert len(metadata_files) == 1
meta = json.loads(metadata_files[0].read_text())
assert meta["shorts"], "expected at least one clip"
assert meta["transcript"]["segments"], "expected the transcript in metadata"
assert meta["source_video"] == media.name
assert meta["output_format"] == fmt
base = media.stem
clips = sorted(out.glob(f"{base}_clip_*.mp4"))
assert len(clips) == len(meta["shorts"])
for clip in clips:
assert clip.stat().st_size > 1024
assert _probe(clip)[0] > 0
ready = _ready_lines(result.stdout)
assert len(ready) == len(meta["shorts"])
return meta, clips
def test_cli_full_pipeline_vertical(run_pipeline, pipeline_env, media_factory, tmp_path):
_cli_env(pipeline_env)
out = tmp_path / "out"
result = run_pipeline(media_factory.six, "-o", str(out), "--format", "vertical")
meta, clips = _assert_success(result, out, media_factory.six, "vertical")
width, height = _probe(clips[0])
assert height > width, f"vertical clip should be portrait, got {width}x{height}"
def test_cli_full_pipeline_horizontal(run_pipeline, pipeline_env, media_factory, tmp_path):
_cli_env(pipeline_env)
out = tmp_path / "out"
result = run_pipeline(media_factory.six, "-o", str(out), "--format", "horizontal")
meta, clips = _assert_success(result, out, media_factory.six, "horizontal")
width, height = _probe(clips[0])
assert width > height, f"horizontal clip should be landscape, got {width}x{height}"
def test_cli_failure_writes_no_metadata(run_pipeline, pipeline_env, media_factory, tmp_path):
# No Gemini key + no clips available -> the pipeline raises instead of
# shipping a silent render; nothing must be written to the output dir.
_cli_env(pipeline_env, GEMINI_API_KEY="")
out = tmp_path / "out"
result = run_pipeline(media_factory.silent, "-o", str(out), "--format", "vertical")
assert result.returncode != 0
assert not list(out.glob("*_metadata.json"))
assert not list(out.glob("*_clip_*.mp4"))
def test_cli_missing_input_exits_nonzero(run_pipeline, pipeline_env, tmp_path):
_cli_env(pipeline_env)
out = tmp_path / "out"
result = run_pipeline(tmp_path / "does-not-exist.mp4", "-o", str(out))
assert result.returncode != 0
assert not list(out.glob("*_metadata.json"))

View file

@ -0,0 +1,347 @@
"""L4 — download stage.
Covers the pure attempt planner, the real-ffmpeg duration cap, and the
``download_youtube_video`` orchestration with a fake ``yt_dlp.YoutubeDL`` (no
network, no real yt-dlp download). The download path imports ``main`` lazily,
so ``heavy_stubs`` injects the fake ``ultralytics``/``mediapipe`` modules first
(the heavy deps are not installed in the thin E2E environment).
"""
import json
import os
import shutil
import subprocess
from types import SimpleNamespace
import pytest
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
# A public, literal IP so ``assert_public_url`` passes without a DNS lookup
# (the shared ``no_network`` guard blocks hostname resolution).
_DIRECT_URL = "http://93.184.216.34/video.mp4"
@pytest.fixture(scope="session")
def heavy_stubs():
"""Inject fake ``ultralytics``/``mediapipe`` then import ``main`` lazily."""
import sys
import types
if "ultralytics" not in sys.modules:
ul = types.ModuleType("ultralytics")
class _YOLO:
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return []
def predict(self, *args, **kwargs):
return []
ul.YOLO = _YOLO
sys.modules["ultralytics"] = ul
if "mediapipe" not in sys.modules:
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
face_detection = types.ModuleType("mediapipe.solutions.face_detection")
class _FaceDetection:
def __init__(self, *args, **kwargs):
pass
def process(self, *args, **kwargs):
return SimpleNamespace(detections=None)
def close(self):
pass
face_detection.FaceDetection = _FaceDetection
solutions.face_detection = face_detection
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = face_detection
import clipwright.pipeline.main as main
return main
# ---------------------------------------------------------------------------
# plan_download_attempts — pure
# ---------------------------------------------------------------------------
def test_plan_direct_file_url(heavy_stubs):
plan = heavy_stubs.plan_download_attempts(False, [], None, False, youtube=False)
assert plan == [("direct", False, None)]
def test_plan_direct_file_url_with_static_fallback(heavy_stubs):
plan = heavy_stubs.plan_download_attempts(
False, ["http://s1", "http://s2"], "http://paid", True, youtube=False)
assert plan == [("direct", False, None),
("static-fallback", False, "http://s1")]
def test_plan_youtube_full_ladder(heavy_stubs):
plan = heavy_stubs.plan_download_attempts(
True, ["s1", "s2"], "P", True, youtube=True)
assert plan == [
("HD-direct", False, None),
("HD-static1", False, "s1"),
("HD-static2", False, "s2"),
("fallback-static", False, "s1"),
("HD", True, "P"),
("fallback", True, "P"),
]
def test_plan_youtube_paid_only_no_hd(heavy_stubs):
plan = heavy_stubs.plan_download_attempts(
False, [], "P", False, youtube=True)
assert plan == [("fallback", True, "P")]
def test_plan_youtube_static_only_hd(heavy_stubs):
plan = heavy_stubs.plan_download_attempts(
False, ["s1"], None, True, youtube=True)
assert plan == [
("HD-static1", False, "s1"),
("HD", False, None),
("fallback", False, "s1"),
]
def test_plan_skip_statics_goes_straight_to_paid(heavy_stubs):
plan = heavy_stubs.plan_download_attempts(
True, ["s1"], "P", True, youtube=True, skip_statics=True)
assert plan == [("HD", True, "P"), ("fallback", True, "P")]
def test_plan_skip_statics_ignored_without_paid(heavy_stubs):
plan = heavy_stubs.plan_download_attempts(
False, ["s1"], None, True, youtube=True, skip_statics=True)
assert plan == [
("HD-static1", False, "s1"),
("HD", False, None),
("fallback", False, "s1"),
]
# ---------------------------------------------------------------------------
# cap_source_duration — real ffmpeg
# ---------------------------------------------------------------------------
def _duration_seconds(path):
out = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=nw=1:nk=1", str(path)],
capture_output=True, text=True, check=True)
return float(out.stdout.strip())
def test_cap_source_duration_leaves_short_source_untouched(heavy_stubs, media_factory, tmp_path):
src = tmp_path / "six.mp4"
shutil.copy(media_factory.six, src)
before = (src.stat().st_size, src.stat().st_mtime_ns)
result = heavy_stubs.cap_source_duration(str(src), 10)
assert result == str(src)
assert (src.stat().st_size, src.stat().st_mtime_ns) == before
def test_cap_source_duration_cuts_long_source(heavy_stubs, media_factory, tmp_path):
src = tmp_path / "sixty.mp4"
shutil.copy(media_factory.sixty, src)
assert _duration_seconds(src) > 55
result = heavy_stubs.cap_source_duration(str(src), 0.5)
assert result == str(src)
# Stream-copy lands on a packet boundary a fraction past the cap.
assert _duration_seconds(src) <= 32.0
def test_cap_source_duration_safety_within_margin_untouched(heavy_stubs, media_factory, tmp_path):
src = tmp_path / "sixty.mp4"
shutil.copy(media_factory.sixty, src)
before = src.stat().st_size
result = heavy_stubs.cap_source_duration(str(src), 0.5, safety=True)
# 60s is within the 30s safety margin of a 30s cap: left alone.
assert result == str(src)
assert src.stat().st_size == before
def test_cap_source_duration_degenerate_inputs(heavy_stubs, tmp_path):
src = tmp_path / "x.mp4"
src.write_bytes(b"not a video")
assert heavy_stubs.cap_source_duration(str(src), 0) == str(src)
assert heavy_stubs.cap_source_duration(str(src), "abc") == str(src)
# ---------------------------------------------------------------------------
# _content_block — user-facing reasons
# ---------------------------------------------------------------------------
def test_content_block_private(heavy_stubs):
msg = heavy_stubs._content_block("ERROR: Private video. Sign in if you've been granted access")
assert "private on YouTube" in msg
assert "Unlisted" in msg
def test_content_block_members_only(heavy_stubs):
assert "members only" in heavy_stubs._content_block("Join this channel to get access")
assert "members only" in heavy_stubs._content_block("This video is members-only")
def test_content_block_none_for_network_error(heavy_stubs):
assert heavy_stubs._content_block("Video unavailable") is None
assert heavy_stubs._content_block("HTTP Error 429") is None
# ---------------------------------------------------------------------------
# download_youtube_video — fake yt-dlp
# ---------------------------------------------------------------------------
class _FakeYoutubeDL:
"""Minimal YoutubeDL double: ``process_ie_result`` writes the merged mp4."""
mode = "success"
title = "My Video"
def __init__(self, opts):
self.opts = opts
def __enter__(self):
return self
def __exit__(self, *exc):
return False
def extract_info(self, url, download=False, process=False):
if _FakeYoutubeDL.mode == "private":
raise Exception(
"ERROR: Private video. Sign in if you've been granted access to this video")
if _FakeYoutubeDL.mode == "unavailable":
raise Exception("ERROR: Video unavailable")
return {
"title": _FakeYoutubeDL.title,
"formats": [{"format_id": "18"}],
"duration": 60,
"_type": "video",
}
def _write(self):
outtmpl = self.opts.get("outtmpl") or ""
path = outtmpl.replace("%(ext)s", "mp4")
if path:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as fh:
fh.write(b"\x00" * 4096)
return path
def process_ie_result(self, info, download=True):
path = self._write()
return {"requested_downloads": [{"filepath": path}]}
def download(self, urls):
self._write()
return 0
@pytest.fixture
def fake_ytdlp(monkeypatch, heavy_stubs):
_FakeYoutubeDL.mode = "success"
_FakeYoutubeDL.title = "My Video"
monkeypatch.setattr(heavy_stubs.yt_dlp, "YoutubeDL", _FakeYoutubeDL)
for var in ("PROXY_URL", "STATIC_PROXY_URLS", "DIRECT_FIRST",
"DOWNLOAD_SKIP_STATICS", "YOUTUBE_COOKIES",
"MAX_SOURCE_MINUTES", "SOURCE_CAP_MINUTES", "BGUTIL_BASE_URL",
"BGUTIL_SCRIPT_PATH"):
monkeypatch.delenv(var, raising=False)
return _FakeYoutubeDL
def _route_from_stdout(text):
line = next(l for l in text.splitlines() if l.startswith("PROXY_ROUTE="))
return json.loads(line.split("=", 1)[1])
def test_download_direct_success(heavy_stubs, fake_ytdlp, tmp_path, capsys):
path, title = heavy_stubs.download_youtube_video(_DIRECT_URL, str(tmp_path))
assert title == "My_Video"
assert path == str(tmp_path / "My_Video.mp4")
assert os.path.getsize(path) > 0
route = _route_from_stdout(capsys.readouterr().out)
assert route["winner"] == "direct"
assert route["paid_bytes"] == 0
def test_download_static_proxy_wins_before_paid(heavy_stubs, fake_ytdlp, monkeypatch,
tmp_path, capsys):
import clipwright.core.security_utils as security
# Avoid DNS for the youtube hostname; the guard itself is unit-tested elsewhere.
monkeypatch.setattr(security, "assert_public_url", lambda url: url)
monkeypatch.setenv("STATIC_PROXY_URLS", "http://static-1:8080")
monkeypatch.setenv("PROXY_URL", "http://paid-proxy:8080")
path, title = heavy_stubs.download_youtube_video(
"https://www.youtube.com/watch?v=abc123", str(tmp_path))
assert title == "My_Video"
assert os.path.exists(path)
out = capsys.readouterr().out
route = _route_from_stdout(out)
assert route["winner"] == "fallback-static"
assert route["attempts"][0]["paid"] is False
assert "PROXY_BYTES=" not in out
def test_download_paid_proxy_used_without_statics(heavy_stubs, fake_ytdlp, monkeypatch,
tmp_path, capsys):
import clipwright.core.security_utils as security
monkeypatch.setattr(security, "assert_public_url", lambda url: url)
monkeypatch.setenv("PROXY_URL", "http://paid-proxy:8080")
heavy_stubs.download_youtube_video(
"https://www.youtube.com/watch?v=abc123", str(tmp_path))
route = _route_from_stdout(capsys.readouterr().out)
assert route["winner"] == "fallback"
assert route["attempts"][0]["paid"] is True
def test_download_private_video_raises_with_message(heavy_stubs, fake_ytdlp,
tmp_path, capsys):
_FakeYoutubeDL.mode = "private"
with pytest.raises(Exception) as excinfo:
heavy_stubs.download_youtube_video(_DIRECT_URL, str(tmp_path))
assert "Private video" in str(excinfo.value)
out = capsys.readouterr().out
assert "private on YouTube" in out
assert not (tmp_path / "My_Video.mp4").exists()
def test_download_all_attempts_failed_raises(heavy_stubs, fake_ytdlp, tmp_path, capsys):
_FakeYoutubeDL.mode = "unavailable"
with pytest.raises(Exception):
heavy_stubs.download_youtube_video(_DIRECT_URL, str(tmp_path))
out = capsys.readouterr().out
assert "YOUTUBE DOWNLOAD FAILED" in out
assert not (tmp_path / "My_Video.mp4").exists()

View file

@ -0,0 +1,150 @@
"""L5 Pipeline media — HOOK stage.
The overlay image is drawn from the repo's bundled fonts (never downloaded), the
real ffmpeg overlay must land next to the clip under the ``hooked_<ts>_`` name,
the combined hook+captions pass writes both files from one decode, and a bad
hook fails open (returns None) instead of costing the clip.
"""
import os
import shutil
import subprocess
import sys
import types
from types import SimpleNamespace
import pytest
from PIL import Image
from clipwright.media import hooks
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
def _install_ml_stubs():
if "ultralytics" in sys.modules and "mediapipe" in sys.modules:
return
class _FakeYOLO:
def __init__(self, *a, **k):
pass
def __call__(self, *a, **k):
return []
def predict(self, *a, **k):
return []
def track(self, *a, **k):
return []
class _FakeFaceDetection:
def __init__(self, *a, **k):
pass
def process(self, *a, **k):
return SimpleNamespace(detections=None)
def close(self):
pass
ul = types.ModuleType("ultralytics")
ul.YOLO = _FakeYOLO
sys.modules["ultralytics"] = ul
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
fd = types.ModuleType("mediapipe.solutions.face_detection")
fd.FaceDetection = _FakeFaceDetection
solutions.face_detection = fd
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = fd
_install_ml_stubs()
from clipwright.pipeline import main # noqa: E402
TRANSCRIPT = {
"language": "en",
"segments": [{
"start": 0.0, "end": 3.0, "text": " hello world",
"words": [
{"word": " hello", "start": 0.0, "end": 0.6},
{"word": " world", "start": 0.7, "end": 1.4},
],
}],
}
def _probe_dims(path):
out = subprocess.check_output(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", str(path)],
text=True).strip()
w, h = out.split("x")
return int(w), int(h)
@pytest.fixture
def clip(tmp_path, media_factory):
dest = tmp_path / "clip.mp4"
shutil.copyfile(media_factory.six, dest)
return dest
class TestCreateHookImage:
def test_repo_font_draws_a_nonempty_png(self, tmp_path):
out = tmp_path / "hook.png"
path, w, h = hooks.create_hook_image("Big news today", 1080, str(out))
assert os.path.exists(path) and w > 0 and h > 0
with Image.open(out) as img:
assert img.size == (w, h)
def test_classic_style_also_renders(self, tmp_path):
out = tmp_path / "classic.png"
path, _w, _h = hooks.create_hook_image("Hello", 720, str(out), style="classic")
assert os.path.exists(path)
class TestAddHookToVideo:
def test_overlay_writes_a_playable_file(self, clip, tmp_path):
out = tmp_path / "hooked.mp4"
assert hooks.add_hook_to_video(str(clip), "Watch this", str(out)) is True
assert out.exists() and out.stat().st_size > 0
assert _probe_dims(out) == (320, 180)
class TestAutoHookClip:
def test_writes_a_hooked_derivative_next_to_the_clip(self, clip, tmp_path):
result = main.auto_hook_clip(str(clip), {"viral_hook_text": "Must see this"})
assert result is not None
out_path, config = result
assert os.path.basename(out_path).startswith("hooked_")
assert os.path.basename(out_path).endswith("_clip.mp4")
assert os.path.exists(out_path)
assert config["text"] == "Must see this"
def test_combined_hook_and_captions_write_both_files(self, clip, tmp_path):
plan = main.auto_caption_clip(str(clip), TRANSCRIPT, 0.0, 3.0, plan_only=True)
assert plan is not None
vf, generation_id = plan
result = main.auto_hook_clip(str(clip), {"viral_hook_text": "Combined"},
captions=(vf, generation_id))
assert result is not None
out_path, config = result
assert "_captioned" in config
captioned = config["_captioned"]
assert os.path.exists(out_path)
assert os.path.exists(captioned)
assert os.path.basename(captioned).startswith("subtitled_")
assert os.path.basename(captioned).endswith(os.path.basename(out_path))
def test_empty_text_is_skipped(self, clip):
assert main.auto_hook_clip(str(clip), {"viral_hook_text": " "}) is None
def test_missing_clip_fails_open(self, tmp_path):
missing = tmp_path / "nope.mp4"
assert main.auto_hook_clip(str(missing), {"viral_hook_text": "hi"}) is None

View file

@ -0,0 +1,245 @@
"""L5 Pipeline media — LAYOUT stage.
Covers the layout picker's flag mapping (``layout_picker.apply`` / the API's
``layout_env``), the pure geometry every layout engine hands to ffmpeg
(``reframe_v2``, ``split_layout``, ``screencast_layout``, ``punch_in``) and the
``layout_ranges`` sidecar round-trip. No ML: ``apply`` is exercised with stand-in
modules so a real ``ENABLED`` flag is never flipped for a later test.
"""
import sys
import types
import pytest
from clipwright.layouts import layout_ranges
from clipwright.layouts import layout_picker
from clipwright.layouts import punch_in
from clipwright.layouts import screencast_layout
from clipwright.layouts import split_layout
from clipwright.layouts import reframe_v2
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
VERTICAL = 9 / 16
_FAKE_LAYOUT_MODULES = {
"split_layout": "clipwright.layouts.split_layout",
"screencast_layout": "clipwright.layouts.screencast_layout",
"active_speaker": "clipwright.layouts.active_speaker",
}
def fake_modules(monkeypatch, **initial):
"""Install stand-in layout modules so ``apply`` never mutates real globals."""
from clipwright import layouts
made = {}
for label, dotted in _FAKE_LAYOUT_MODULES.items():
module = types.ModuleType(dotted)
module.ENABLED = initial.get(label, False)
monkeypatch.setitem(sys.modules, dotted, module)
monkeypatch.setattr(layouts, label, module, raising=False)
made[dotted] = module
return made
# --- layout_picker.apply ----------------------------------------------------
class TestPickerFlagMapping:
def test_split_enables_both_modules(self, monkeypatch):
mods = fake_modules(monkeypatch)
assert set(layout_picker.apply("split")) == {"split_layout", "active_speaker"}
assert mods["clipwright.layouts.split_layout"].ENABLED is True
assert mods["clipwright.layouts.active_speaker"].ENABLED is True
def test_screencast_enables_only_its_module(self, monkeypatch):
mods = fake_modules(monkeypatch)
assert layout_picker.apply("screencast") == ["screencast_layout"]
assert mods["clipwright.layouts.screencast_layout"].ENABLED is True
assert mods["clipwright.layouts.split_layout"].ENABLED is False
def test_none_is_inert(self, monkeypatch):
mods = fake_modules(monkeypatch)
assert layout_picker.apply("none") == []
assert not any(m.ENABLED for m in mods.values())
def test_unknown_decision_is_inert(self, monkeypatch):
fake_modules(monkeypatch)
assert layout_picker.apply("gameplay") == []
def test_already_enabled_is_not_reported(self, monkeypatch):
fake_modules(monkeypatch, screencast_layout=True)
assert layout_picker.apply("screencast") == []
def test_pick_and_apply_uses_the_stubbed_pick(self, monkeypatch):
mods = fake_modules(monkeypatch)
monkeypatch.setattr(layout_picker, "ENABLED", True)
monkeypatch.setattr(layout_picker, "SHADOW", False)
monkeypatch.setattr(layout_picker, "pick", lambda *a, **k: "screencast")
assert layout_picker.pick_and_apply("v.mp4", 60) == "screencast"
assert mods["clipwright.layouts.screencast_layout"].ENABLED is True
def test_shadow_mode_decides_but_applies_nothing(self, monkeypatch):
mods = fake_modules(monkeypatch)
monkeypatch.setattr(layout_picker, "ENABLED", True)
monkeypatch.setattr(layout_picker, "SHADOW", True)
monkeypatch.setattr(layout_picker, "pick", lambda *a, **k: "split")
assert layout_picker.pick_and_apply("v.mp4", 90) == "split"
assert not any(m.ENABLED for m in mods.values())
@pytest.fixture
def layout_env():
"""``layout_env`` is the request -> env-flag bridge the API hands the job."""
app = pytest.importorskip("clipwright.api.app")
return app.layout_env
class TestApiLayoutEnv:
def test_none_and_auto_toggle_the_picker(self, layout_env):
assert layout_env(["none"]) == {"AUTO_LAYOUT": "0"}
assert layout_env(["auto"]) == {"AUTO_LAYOUT": "1"}
def test_explicit_picks_map_to_their_env_vars(self, layout_env):
assert layout_env(["split"])["SPLIT_LAYOUT"] == "1"
assert layout_env(["screencast"])["SCREENCAST_LAYOUT"] == "1"
assert layout_env(["punch_in"])["PUNCH_IN"] == "1"
def test_split_implies_the_speaker_signal(self, layout_env):
assert layout_env(["split"]).get("SPEAKER_SIGNAL") == "1"
def test_unknown_names_are_ignored(self, layout_env):
assert layout_env(["teleport", ""]) == {}
def test_auto_composes_with_explicit_picks(self, layout_env):
env = layout_env(["auto", "punch_in"])
assert env["AUTO_LAYOUT"] == "1" and env["PUNCH_IN"] == "1"
# --- reframe_v2 pure geometry ----------------------------------------------
class TestReframeGeometry:
def test_delivery_size_upscales_a_720p_source_to_the_floor(self):
assert reframe_v2.delivery_size(1280, 720, VERTICAL) == (1080, 1920)
def test_delivery_size_never_downscales_a_4k_source(self):
assert reframe_v2.delivery_size(3840, 2160, VERTICAL) == (1216, 2160)
def test_delivery_size_always_even(self):
for w, h in [(320, 180), (854, 480), (641, 361)]:
out_w, out_h = reframe_v2.delivery_size(w, h, VERTICAL)
assert out_w % 2 == 0 and out_h % 2 == 0
def test_general_filtergraph_blurs_background_and_centres(self):
graph = reframe_v2.general_filtergraph(1080, 1920, orig_w=1920, orig_h=1080)
assert "gblur" in graph
assert "overlay=x=(W-w)/2:y=(H-h)/2" in graph
def test_scene_ranges_clamp_and_keep_strategy(self):
ranges = reframe_v2.scene_frame_ranges(
[(0, 100), (100, 250), (250, 400)],
["TRACK", "GENERAL", "TRACK"], total_frames=200)
assert ranges == [(0, 100, "TRACK"), (100, 200, "GENERAL")]
def test_source_already_fits_vertical(self):
assert reframe_v2.source_already_fits(1080, 1920, VERTICAL)
assert not reframe_v2.source_already_fits(1920, 1080, VERTICAL)
def test_sendcmd_lines_dedupe_to_change_points(self):
assert reframe_v2.dedupe_sendcmd_lines([100, 100, 104], fps=30.0) == [
"0.0000 crop@c x 100;",
"0.0667 crop@c x 104;",
]
# --- split_layout pure geometry --------------------------------------------
class TestSplitGeometry:
def test_two_shot_qualifies_and_is_ordered(self):
frames = [[{"box": [500, 300, 200, 200], "score": 40000},
{"box": [1300, 300, 200, 200], "score": 40000}] for _ in range(10)]
left, right = split_layout.analyze_scene(frames, frame_w=1920)
assert left[0] < right[0]
def test_single_speaker_is_rejected(self):
frames = [[{"box": [800, 300, 200, 200], "score": 40000}] for _ in range(10)]
assert split_layout.analyze_scene(frames, frame_w=1920) is None
def test_split_geometry_stays_inside_the_source(self):
w, h, x, y, half_h = split_layout.split_geometry(1920, 1080, 1080, 1920, (600, 400))
assert w <= 1920 and h <= 1080
assert 0 <= x <= 1920 - w and 0 <= y <= 1080 - h
assert w % 2 == 0 and h % 2 == 0 and half_h == 960
def test_split_filtergraph_stacks_into_the_output(self):
graph = split_layout.split_filtergraph(1920, 1080, 1080, 1920,
(600, 400), (1400, 400))
assert "vstack=inputs=2" in graph
assert "pad=1080:1920" in graph
# --- screencast_layout pure geometry ---------------------------------------
class TestScreencastGeometry:
def test_content_bands_keep_full_width(self):
content_h, speaker_h = screencast_layout.content_bands(1920, 1080, 1080, 1920)
assert content_h == 608 and speaker_h == 1312
assert content_h % 2 == 0
def test_speaker_crop_is_inside_the_frame(self):
w, h, x, y = screencast_layout.speaker_crop(1920, 1080, 1080, 1312, (600, 400))
assert w <= 1920 and h <= 1080
assert 0 <= x <= 1920 - w and 0 <= y <= 1080 - h
def test_screencast_filtergraph_stacks_content_over_speaker(self):
graph = screencast_layout.screencast_filtergraph(1920, 1080, 1080, 1920, (600, 400))
assert "[ca]scale=1080:608" in graph
assert "vstack=inputs=2" in graph
# --- punch_in pure geometry -------------------------------------------------
class TestPunchIn:
def test_zoom_curve_is_flat_without_beats(self):
assert punch_in.zoom_curve(10, 30.0, []) == [1.0] * 10
def test_zoom_curve_peaks_on_a_beat_and_returns(self):
zooms = punch_in.zoom_curve(300, 30.0, [2.0], max_zoom=1.2)
assert max(zooms) > 1.0
# The push starts at 1.0 and has fully relaxed long before the end.
assert zooms[0] == 1.0 and zooms[-1] == 1.0
def test_crop_boxes_zoom_about_the_crop_centre(self):
boxes = punch_in.crop_boxes([100, 100], [1.0, 1.25], 320, 180, 640, 360)
assert boxes[0][0] == 320 and boxes[1][0] < 320
assert all(b[0] % 2 == 0 and b[1] % 2 == 0 for b in boxes)
def test_sendcmd_lines_emit_only_changes(self):
boxes = [(320, 180, 0, 0), (320, 180, 0, 0), (256, 144, 32, 18)]
lines = punch_in.sendcmd_lines(boxes, fps=30.0)
assert lines[0] == "0.0000 crop@c w 320;"
assert any("crop@c x 32;" in line for line in lines)
# The unchanged middle frame adds nothing.
assert not any(line.startswith("0.0333") for line in lines)
# --- layout_ranges sidecar round-trip --------------------------------------
class TestLayoutRangesRoundTrip:
def test_write_read_and_split_ranges(self, tmp_path):
clip = str(tmp_path / "clip_1.mp4")
layout_ranges.write(clip, [(0, 4.5, "TRACK"), (4.5, 10, "SPLIT")])
got = layout_ranges.read(clip)
assert got == [{"start": 0.0, "end": 4.5, "layout": "track"},
{"start": 4.5, "end": 10.0, "layout": "split"}]
assert layout_ranges.split_ranges(got) == [(4.5, 10.0)]
def test_missing_sidecar_reads_empty(self, tmp_path):
assert layout_ranges.read(str(tmp_path / "nope.mp4")) == []
def test_remap_across_a_cut(self):
ranges = [(0, 10, "split"), (10, 20, "track")]
got = layout_ranges.remap(ranges, [{"start": 5, "end": 12}])
assert got == [{"start": 0.0, "end": 5.0, "layout": "split"},
{"start": 5.0, "end": 7.0, "layout": "track"}]

View file

@ -0,0 +1,181 @@
"""L5 Pipeline media — RENDER / REFRAME stage.
Real ffmpeg throughout. ``clipwright.pipeline.main`` imports ``ultralytics`` and
``mediapipe`` at module level (heavy deps absent in this thin env), so fake
modules are injected into ``sys.modules`` *before* importing it. With the fakes
in place no detector finds a face, so every scene classifies GENERAL and the
reframe runs the blurred-background layout — exactly the path we probe.
"""
import os
import shutil
import subprocess
import sys
import types
from types import SimpleNamespace
import pytest
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
def _install_ml_stubs():
"""Mirror stub_env/sitecustomize.py for in-process imports of main.py."""
if "ultralytics" in sys.modules and "mediapipe" in sys.modules:
return
class _FakeYOLO:
def __init__(self, *a, **k):
pass
def __call__(self, *a, **k):
return []
def predict(self, *a, **k):
return []
def track(self, *a, **k):
return []
class _FakeFaceDetection:
def __init__(self, *a, **k):
pass
def process(self, *a, **k):
return SimpleNamespace(detections=None)
def close(self):
pass
ul = types.ModuleType("ultralytics")
ul.YOLO = _FakeYOLO
sys.modules["ultralytics"] = ul
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
fd = types.ModuleType("mediapipe.solutions.face_detection")
fd.FaceDetection = _FakeFaceDetection
solutions.face_detection = fd
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = fd
_install_ml_stubs()
from clipwright.layouts import layout_ranges # noqa: E402
from clipwright.layouts import reframe_v2 # noqa: E402
from clipwright.media import recut # noqa: E402
from clipwright.pipeline import main # noqa: E402
def _probe_dims(path):
out = subprocess.check_output(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", str(path)],
text=True).strip()
w, h = out.split("x")
return int(w), int(h)
@pytest.fixture(autouse=True)
def _pyscenedetect(monkeypatch):
"""TransNetV2 is ML; use the installed PySceneDetect fallback."""
monkeypatch.setenv("SCENE_ENGINE", "pyscenedetect")
@pytest.fixture
def clip(tmp_path, media_factory):
"""A real, playable 320x180 6s clip with audio in the test's tmp tree."""
dest = tmp_path / "clip.mp4"
shutil.copyfile(media_factory.six, dest)
return dest
class TestReframeRender:
def test_render_produces_a_vertical_delivery_and_sidecar(self, clip, tmp_path):
out = tmp_path / "out.mp4"
assert reframe_v2.render(str(clip), str(out), 9 / 16) is True
assert out.exists() and out.stat().st_size > 0
assert _probe_dims(out) == (1080, 1920)
# The render records which stretches used which layout for the
# caption pass.
ranges = layout_ranges.read(str(out))
assert ranges and all(r["layout"] == "general" for r in ranges)
def test_render_force_strategy_track_uses_the_crop_path(self, clip, tmp_path):
out = tmp_path / "track.mp4"
assert reframe_v2.render(str(clip), str(out), 9 / 16,
force_strategy="TRACK") is True
assert _probe_dims(out) == (1080, 1920)
class TestRecut:
def test_fast_path_real_ffmpeg_keeps_source_dimensions(self, clip, tmp_path):
served, clean = recut.perform_recut(
input_path=str(clip), segments=[{"start": 0, "end": 3}],
output_dir=str(tmp_path), clean_name="clip_1.mp4")
assert served == clean
assert served.startswith("recut_") and served.endswith("_clip_1.mp4")
assert _probe_dims(tmp_path / served) == (320, 180)
def test_source_path_wires_renderer_and_watermarker(self, tmp_path):
events = []
def fake_runner(cmd):
with open(cmd[-1], "wb") as f:
f.write(b"x")
def fake_renderer(work, out, output_format):
events.append(("reframe", output_format))
with open(out, "wb") as f:
f.write(b"x")
return True
served, clean = recut.perform_recut(
input_path="source.mp4", segments=[{"start": 5, "end": 15}],
output_dir=str(tmp_path), clean_name="clip_1.mp4",
reframe=True, output_format="vertical", watermark=True,
runner=fake_runner, renderer=fake_renderer,
watermarker=lambda path: events.append(("watermark",)))
assert events == [("reframe", "vertical"), ("watermark",)]
assert served == clean
def test_captioner_is_invoked_last_and_wins_the_served_name(self, tmp_path):
seen = []
def fake_runner(cmd):
with open(cmd[-1], "wb") as f:
f.write(b"x")
def fake_captioner(path, transcript, start, end):
seen.append((os.path.basename(path), start, end))
out = os.path.join(os.path.dirname(path),
f"subtitled_1_{os.path.basename(path)}")
with open(out, "wb") as f:
f.write(b"x")
return out
transcript = {"segments": [{"words": [{"word": " a", "start": 0, "end": 1}]}]}
served, clean = recut.perform_recut(
input_path="clip.mp4", segments=[{"start": 0, "end": 10}],
output_dir=str(tmp_path), clean_name="clip_1.mp4",
captions_transcript=transcript,
runner=fake_runner, captioner=fake_captioner)
assert served == f"subtitled_1_{clean}"
assert seen == [(clean, 0.0, 10.0)]
class TestMainClipHelpers:
def test_cut_clip_writes_a_playable_slice(self, clip, tmp_path):
out = tmp_path / "cut.mp4"
main.cut_clip(str(clip), str(out), 1.0, 3.0, 1)
assert out.exists() and out.stat().st_size > 1024
assert _probe_dims(out) == (320, 180)
def test_finalize_passthrough_stream_copies_native_framing(self, clip, tmp_path):
out = tmp_path / "horizontal.mp4"
assert main.finalize_clip_passthrough(str(clip), str(out)) is True
assert out.exists()
assert _probe_dims(out) == _probe_dims(clip)

View file

@ -0,0 +1,115 @@
"""L4 — scene stage.
Covers PySceneDetect on a clip with three hard cuts, the TransNetV2 ->
PySceneDetect fallback, and ``main.detect_scenes`` delegation. No torch / no
TransNetV2 model is loaded: the engine is either selected via env or stubbed.
"""
from types import SimpleNamespace
import pytest
from clipwright.media import scene_detection
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
@pytest.fixture(scope="session")
def heavy_stubs():
"""Inject fake ``ultralytics``/``mediapipe`` then import ``main`` lazily."""
import sys
import types
if "ultralytics" not in sys.modules:
ul = types.ModuleType("ultralytics")
class _YOLO:
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return []
ul.YOLO = _YOLO
sys.modules["ultralytics"] = ul
if "mediapipe" not in sys.modules:
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
face_detection = types.ModuleType("mediapipe.solutions.face_detection")
class _FaceDetection:
def __init__(self, *args, **kwargs):
pass
def process(self, *args, **kwargs):
return SimpleNamespace(detections=None)
def close(self):
pass
face_detection.FaceDetection = _FaceDetection
solutions.face_detection = face_detection
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = face_detection
import clipwright.pipeline.main as main
return main
def test_pyscenedetect_finds_three_hard_cuts(media_factory, monkeypatch):
monkeypatch.setenv("SCENE_ENGINE", "pyscenedetect")
scenes, fps = scene_detection.detect_scenes(str(media_factory.cuts))
# Four colour segments -> three cuts -> four scenes.
assert len(scenes) == 4
assert float(fps) == pytest.approx(25.0, abs=1.0)
# Scene boundaries are ordered, non-empty and cover the clip.
for (start, end) in scenes:
assert end.frame_num > start.frame_num
assert scenes[0][0].frame_num == 0
assert scenes[-1][1].frame_num == sum(
end.frame_num - start.frame_num for start, end in scenes)
def test_transnetv2_failure_falls_back_to_pyscenedetect(media_factory, monkeypatch, capsys):
monkeypatch.setenv("SCENE_ENGINE", "transnetv2")
def _boom(path):
raise RuntimeError("torch unavailable")
monkeypatch.setattr(scene_detection, "_detect_transnetv2", _boom)
scenes, fps = scene_detection.detect_scenes(str(media_factory.cuts))
assert len(scenes) == 4
assert float(fps) == pytest.approx(25.0, abs=1.0)
assert "falling back to PySceneDetect" in capsys.readouterr().out
def test_transnetv2_success_is_used_when_available(media_factory, monkeypatch):
monkeypatch.setenv("SCENE_ENGINE", "transnetv2")
sentinel = ([("a", "b")], 30.0)
monkeypatch.setattr(scene_detection, "_detect_transnetv2", lambda path: sentinel)
assert scene_detection.detect_scenes(str(media_factory.cuts)) == sentinel
def test_merge_short_scenes_absorbs_short_neighbours():
# fps 10, min_sec 0.5 -> min_frames 5. The 2-frame scene folds into its
# predecessor; the long neighbours stay put.
merged = scene_detection._merge_short_scenes(
[(0, 20), (20, 22), (22, 40)], fps=10.0, min_sec=0.5)
assert merged == [(0, 22), (22, 40)]
def test_main_detect_scenes_delegates(heavy_stubs, monkeypatch):
sentinel = (["scene"], 29.97)
monkeypatch.setattr(scene_detection, "detect_scenes", lambda path: sentinel)
assert heavy_stubs.detect_scenes("/tmp/whatever.mp4") == sentinel

View file

@ -0,0 +1,320 @@
"""L4 — selection stage.
Pure ``clip_selection`` helpers plus ``main.get_viral_clips`` driven by a
stubbed ``main._run_gemini_stage`` (score -> detail -> floor recovery -> empty)
and ``main.speech_is_sparse``. No Gemini call, no network.
"""
import json
from types import SimpleNamespace
import pytest
from clipwright.pipeline import clip_selection as cs
from clipwright.pipeline import gemini_worker
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
@pytest.fixture(scope="session")
def heavy_stubs():
"""Inject fake ``ultralytics``/``mediapipe`` then import ``main`` lazily."""
import sys
import types
if "ultralytics" not in sys.modules:
ul = types.ModuleType("ultralytics")
class _YOLO:
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return []
ul.YOLO = _YOLO
sys.modules["ultralytics"] = ul
if "mediapipe" not in sys.modules:
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
face_detection = types.ModuleType("mediapipe.solutions.face_detection")
class _FaceDetection:
def __init__(self, *args, **kwargs):
pass
def process(self, *args, **kwargs):
return SimpleNamespace(detections=None)
def close(self):
pass
face_detection.FaceDetection = _FaceDetection
solutions.face_detection = face_detection
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = face_detection
import clipwright.pipeline.main as main
return main
# ---------------------------------------------------------------------------
# Pure helpers
# ---------------------------------------------------------------------------
def test_lookup_model_prices_longest_prefix():
assert cs.lookup_model_prices("gemini-3.1-flash-lite") == (0.25, 1.50)
assert cs.lookup_model_prices("gemini-3.1-flash-lite-002") == (0.25, 1.50)
assert cs.lookup_model_prices("GEMINI-2.5-FLASH") == (0.30, 2.50)
assert cs.lookup_model_prices("unknown-model") is None
assert cs.lookup_model_prices(None) is None
def test_clip_count_targets_floor_and_ceiling():
assert cs.clip_count_targets(1) == (2, 4)
assert cs.clip_count_targets(3) == (3, 6)
assert cs.clip_count_targets(10) == (6, 12)
def test_clip_count_targets_env_override(monkeypatch):
monkeypatch.setenv("CLIP_TARGET_MIN", "5")
monkeypatch.setenv("CLIP_TARGET_MAX", "7")
assert cs.clip_count_targets(3) == (5, 7)
def test_shortlist_target_scales_and_is_bounded():
assert cs.shortlist_target(0) == 3
assert cs.shortlist_target(90) == 3
assert cs.shortlist_target(180) == 4
assert cs.shortlist_target(9000) == 10
def test_score_batches_near_equal_and_remainder():
assert cs.score_batches([], 8) == []
assert cs.score_batches(list(range(8)), 8) == [list(range(8))]
batches = cs.score_batches(list(range(9)), 8)
assert [len(b) for b in batches] == [5, 4]
assert sum(batches, []) == list(range(9))
def test_trim_to_best_keeps_top_scores_in_transcript_order():
shorts = [
{"start": 0, "predicted_score": 10},
{"start": 10, "predicted_score": 90},
{"start": 20, "predicted_score": 80},
{"start": 30, "predicted_score": 70},
]
kept = cs.trim_to_best(shorts, 2)
assert [s["predicted_score"] for s in kept] == [90, 80]
assert [s["start"] for s in kept] == [10, 20]
# Under the cap: unchanged.
assert cs.trim_to_best(shorts[:2], 5) == shorts[:2]
def test_clip_duration_bounds_defaults_and_overrides(monkeypatch):
for var in ("CLIP_MIN_SECONDS", "CLIP_MAX_SECONDS"):
monkeypatch.delenv(var, raising=False)
assert cs.clip_duration_bounds() == (15.0, 60.0)
monkeypatch.setenv("CLIP_MIN_SECONDS", "5")
monkeypatch.setenv("CLIP_MAX_SECONDS", "10")
assert cs.clip_duration_bounds() == (5.0, 10.0)
# Degenerate band widens to the minimum 5s spread.
monkeypatch.setenv("CLIP_MIN_SECONDS", "100")
monkeypatch.setenv("CLIP_MAX_SECONDS", "10")
assert cs.clip_duration_bounds() == (100.0, 105.0)
def test_build_transcript_windows_aligns_to_segments():
transcript = {
"text": "a b c d",
"segments": [
{"start": 0, "end": 30, "text": "a"},
{"start": 30, "end": 60, "text": "b"},
{"start": 60, "end": 90, "text": "c"},
{"start": 90, "end": 120, "text": "d"},
],
}
windows = cs.build_transcript_windows(transcript, 120, window_seconds=90,
overlap_seconds=30)
assert [w["id"] for w in windows] == ["window_001", "window_002"]
assert windows[0]["start"] == 0 and windows[0]["end"] == 90
assert windows[1]["start"] == 60 and windows[1]["end"] == 120
def test_build_transcript_windows_empty_falls_back_to_full_video():
windows = cs.build_transcript_windows({"text": "hi", "segments": []}, 42)
assert len(windows) == 1
assert windows[0]["end"] == 42.0
def test_dedupe_overlapping_keeps_higher_score():
a = {"start": 0, "end": 30, "predicted_score": 50}
b = {"start": 10, "end": 40, "predicted_score": 80}
assert cs.dedupe_overlapping([a, b]) == [b]
# Non-overlapping clips both survive, in transcript order.
c = {"start": 100, "end": 130, "predicted_score": 10}
assert cs.dedupe_overlapping([a, c]) == [a, c]
def test_snap_clip_to_words_no_words_returns_original():
assert cs.snap_clip_to_words(4.8, 21.2, [], 60) == (4.8, 21.2)
def test_snap_clip_to_words_snaps_and_repairs_duration():
words = [{"s": 0, "e": 1}, {"s": 5, "e": 6},
{"s": 20, "e": 21}, {"s": 40, "e": 41}]
# Snap start to 5 (lead 0.35) and end to 21 (trail 0.45).
assert cs.snap_clip_to_words(4.8, 21.2, words, 60) == (4.65, 21.45)
# Too short after snapping -> extended to the next word end + 0.2.
assert cs.snap_clip_to_words(0.0, 5.0, words, 60) == (0.0, 21.2)
# ---------------------------------------------------------------------------
# speech_is_sparse — pure
# ---------------------------------------------------------------------------
def test_speech_is_sparse_thin_transcript(heavy_stubs):
thin = {"segments": [{"text": "uh uh"}]}
assert heavy_stubs.speech_is_sparse(thin, 60) is True
def test_speech_is_sparse_dense_transcript(heavy_stubs):
dense = {"segments": [{"text": " ".join(["word"] * 200)}]}
assert heavy_stubs.speech_is_sparse(dense, 60) is False
def test_speech_is_sparse_none_transcript(heavy_stubs):
assert heavy_stubs.speech_is_sparse(None, 60) is True
# ---------------------------------------------------------------------------
# get_viral_clips — stub _run_gemini_stage
# ---------------------------------------------------------------------------
def _dense_transcript():
return {
"text": "alpha beta gamma delta",
"language": "en",
"segments": [
{"start": 0, "end": 30, "text": "alpha",
"words": [{"word": " alpha", "start": 0.0, "end": 1.0}]},
{"start": 30, "end": 60, "text": "beta",
"words": [{"word": " beta", "start": 30.0, "end": 31.0}]},
{"start": 60, "end": 90, "text": "gamma",
"words": [{"word": " gamma", "start": 60.0, "end": 61.0}]},
{"start": 90, "end": 120, "text": "delta",
"words": [{"word": " delta", "start": 90.0, "end": 91.0}]},
],
}
def _short(start, end, score, window):
return {
"start": start, "end": end, "source_window_id": window,
"predicted_score": score,
"video_description_for_tiktok": "t #x",
"video_description_for_instagram": "i #x",
"video_title_for_youtube_short": "title",
"viral_hook_text": "hook",
"why": "why",
}
def _prompt_windows(prompt, marker):
tail = prompt.split(marker, 1)[1]
tail = tail.split("\n\nReturn only", 1)[0]
return json.loads(tail.strip())
def _prepare_gemini(monkeypatch, main):
monkeypatch.setenv("GEMINI_API_KEY", "test")
monkeypatch.setattr(main.llm_backend, "active", lambda: False)
monkeypatch.setattr(main.genai, "Client", lambda **kwargs: object())
def _stub_gemini(monkeypatch, main, detail_plan, score_plan=None):
calls = []
def fake(client, model_name, prompt, schema):
calls.append(schema)
if schema is gemini_worker.ScoreResponse:
windows = _prompt_windows(prompt, "WINDOWS_JSON:")
return {"windows": score_plan(windows) if score_plan
else [{"id": w["id"], "start": w["start"], "end": w["end"],
"score": 85, "reason": "r"} for w in windows]}, None
if schema is gemini_worker.DetailResponse:
windows = _prompt_windows(prompt, "CANDIDATE_WINDOWS_JSON:")
return {"shorts": detail_plan(windows)}, None
raise AssertionError(f"unexpected schema {schema}")
monkeypatch.setattr(main, "_run_gemini_stage", fake)
return calls
def test_get_viral_clips_score_then_detail(heavy_stubs, monkeypatch):
main = heavy_stubs
_prepare_gemini(monkeypatch, main)
def plan(windows):
# One clip per shortlisted window plus one extra non-overlapping clip.
return [_short(0, 30, 90, "window_001"),
_short(60, 90, 80, "window_002"),
_short(90, 120, 70, "window_002")]
_stub_gemini(monkeypatch, main, plan)
result = main.get_viral_clips(_dense_transcript(), 120)
assert result is not None
assert len(result["shorts"]) == 3
assert all("proposed" in s for s in result["shorts"])
def test_get_viral_clips_floor_recovery(heavy_stubs, monkeypatch, capsys):
main = heavy_stubs
_prepare_gemini(monkeypatch, main)
def plan(windows):
if len(windows) == 2: # first detail call over the full shortlist
return [_short(0, 30, 90, "window_001")]
return [_short(60, 90, 80, "window_002"),
_short(90, 120, 70, "window_002")]
_stub_gemini(monkeypatch, main, plan)
result = main.get_viral_clips(_dense_transcript(), 120)
assert result is not None
assert len(result["shorts"]) == 3
assert "Recovered 2 clip(s)" in capsys.readouterr().out
def test_get_viral_clips_empty_returns_none(heavy_stubs, monkeypatch):
main = heavy_stubs
_prepare_gemini(monkeypatch, main)
_stub_gemini(monkeypatch, main, lambda windows: [])
assert main.get_viral_clips(_dense_transcript(), 120) is None
def test_get_viral_clips_score_empty_shortlists_all_windows(heavy_stubs, monkeypatch):
main = heavy_stubs
_prepare_gemini(monkeypatch, main)
# Score returns nothing usable -> shortlist falls back to the windows themselves.
_stub_gemini(monkeypatch, main,
lambda windows: [_short(0, 30, 90, "window_001"),
_short(60, 90, 80, "window_002"),
_short(90, 120, 70, "window_002")],
score_plan=lambda windows: [])
result = main.get_viral_clips(_dense_transcript(), 120)
assert result is not None
assert len(result["shorts"]) == 3

View file

@ -0,0 +1,185 @@
"""L5 Pipeline media — SUBTITLE stage.
Pure SRT/ASS/filter generation, a real ffmpeg burn that must stay playable, and
``main.auto_caption_clip``'s fail-open contract (AUTO_CAPTIONS=0, no words in
range). ``main`` needs the ML stubs before import; see test_render_stage.py.
"""
import os
import shutil
import subprocess
import sys
import types
from types import SimpleNamespace
import pytest
from clipwright.media import subtitles
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
def _install_ml_stubs():
if "ultralytics" in sys.modules and "mediapipe" in sys.modules:
return
class _FakeYOLO:
def __init__(self, *a, **k):
pass
def __call__(self, *a, **k):
return []
def predict(self, *a, **k):
return []
def track(self, *a, **k):
return []
class _FakeFaceDetection:
def __init__(self, *a, **k):
pass
def process(self, *a, **k):
return SimpleNamespace(detections=None)
def close(self):
pass
ul = types.ModuleType("ultralytics")
ul.YOLO = _FakeYOLO
sys.modules["ultralytics"] = ul
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
fd = types.ModuleType("mediapipe.solutions.face_detection")
fd.FaceDetection = _FakeFaceDetection
solutions.face_detection = fd
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = fd
_install_ml_stubs()
from clipwright.pipeline import main # noqa: E402
TRANSCRIPT = {
"language": "en",
"segments": [{
"start": 0.0, "end": 3.0,
"text": " This is a canned transcript",
"words": [
{"word": " This", "start": 0.0, "end": 0.4},
{"word": " is", "start": 0.4, "end": 0.7},
{"word": " a", "start": 0.7, "end": 0.9},
{"word": " canned", "start": 0.9, "end": 1.4},
{"word": " transcript", "start": 1.4, "end": 2.2},
],
}],
}
def _probe_dims(path):
out = subprocess.check_output(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", str(path)],
text=True).strip()
w, h = out.split("x")
return int(w), int(h)
class TestGenerateSrt:
def test_words_are_grouped_into_short_blocks(self, tmp_path):
out = tmp_path / "subs.srt"
assert subtitles.generate_srt(TRANSCRIPT, 0.0, 3.0, str(out),
max_chars=20, max_duration=2.0) is True
text = out.read_text(encoding="utf-8-sig")
assert "This is a canned" in text
assert "transcript" in text
assert " --> " in text
def test_no_words_in_range_writes_nothing(self, tmp_path):
out = tmp_path / "empty.srt"
assert subtitles.generate_srt(TRANSCRIPT, 100.0, 110.0, str(out)) is False
assert not out.exists()
class TestGenerateAss:
def test_ass_carries_a_style_and_word_events(self, tmp_path):
out = tmp_path / "subs.ass"
assert subtitles.generate_ass(TRANSCRIPT, 0.0, 3.0, str(out),
max_chars=8, uppercase=True) is True
text = out.read_text(encoding="utf-8-sig")
assert "[V4+ Styles]" in text and "[Events]" in text
assert "Dialogue: 0," in text
def test_split_ranges_anchor_events_on_the_seam(self, tmp_path):
out = tmp_path / "seam.ass"
# The whole clip is a SPLIT stretch: every event gets the mid-frame \an5.
assert subtitles.generate_ass(TRANSCRIPT, 0.0, 3.0, str(out),
split_ranges=[(0.0, 3.0)]) is True
events = [l for l in out.read_text(encoding="utf-8-sig").splitlines()
if l.startswith("Dialogue:")]
assert events and all("{\\an5}" in e for e in events)
def test_no_words_returns_false(self, tmp_path):
assert subtitles.generate_ass(TRANSCRIPT, 50.0, 60.0,
str(tmp_path / "x.ass")) is False
class TestSubtitlesFilter:
def test_srt_uses_subtitles_filter_with_style(self):
vf = subtitles.subtitles_filter("/tmp/a.srt", alignment="bottom", fontsize=44,
font_name="Anton")
assert vf.startswith("subtitles=filename=")
assert "force_style=" in vf and "Fontname=Anton" in vf
def test_ass_uses_the_ass_filter_and_its_own_styles(self):
vf = subtitles.subtitles_filter("/tmp/a.ass")
assert vf.startswith("ass=filename=")
assert "force_style" not in vf
class TestBurnSubtitles:
def test_real_burn_produces_a_playable_file(self, tmp_path, media_factory):
clip = tmp_path / "clip.mp4"
shutil.copyfile(media_factory.six, clip)
srt = tmp_path / "subs.srt"
assert subtitles.generate_srt(TRANSCRIPT, 0.0, 3.0, str(srt))
out = tmp_path / "burned.mp4"
assert subtitles.burn_subtitles(str(clip), str(srt), str(out),
font_name="Anton") is True
assert out.exists() and out.stat().st_size > 0
assert _probe_dims(out) == (320, 180)
class TestAutoCaptionClip:
def _clip(self, tmp_path, media_factory):
clip = tmp_path / "clip.mp4"
shutil.copyfile(media_factory.six, clip)
return clip
def test_disabled_by_env_returns_none(self, tmp_path, media_factory, monkeypatch):
monkeypatch.setenv("AUTO_CAPTIONS", "0")
clip = self._clip(tmp_path, media_factory)
assert main.auto_caption_clip(str(clip), TRANSCRIPT, 0.0, 3.0) is None
def test_no_words_in_range_returns_none(self, tmp_path, media_factory):
clip = self._clip(tmp_path, media_factory)
assert main.auto_caption_clip(str(clip), TRANSCRIPT, 100.0, 110.0) is None
def test_silent_transcript_returns_none(self, tmp_path, media_factory):
clip = self._clip(tmp_path, media_factory)
assert main.auto_caption_clip(str(clip), {"segments": []}, 0.0, 3.0) is None
def test_real_caption_writes_a_subtitled_derivative(self, tmp_path, media_factory):
clip = self._clip(tmp_path, media_factory)
out = main.auto_caption_clip(str(clip), TRANSCRIPT, 0.0, 3.0)
assert out is not None
name = os.path.basename(out)
assert name.startswith("subtitled_") and name.endswith("_clip.mp4")
assert _probe_dims(out) == (320, 180)
# The clean original stays untouched next to the derivative.
assert clip.exists()

View file

@ -0,0 +1,190 @@
"""L5 Pipeline media — THUMBNAIL stage.
``extract_face_frames`` runs the real cv2/ffmpeg path and must degrade to ``[]``
when no face is found. The pure ranking/spread/text/concept helpers are checked
directly, and ``generate_thumbnail`` runs end to end against a stubbed Gemini
client that returns a scripted concept list and a PIL image — the saved artifact
must be a 1280x720 JPEG under YouTube's 2 MB ceiling.
"""
import base64
import io
import os
import sys
import types
from types import SimpleNamespace
import pytest
from PIL import Image
from clipwright.media import thumbnail
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
def _install_ml_stubs():
if "ultralytics" in sys.modules and "mediapipe" in sys.modules:
return
class _FakeYOLO:
def __init__(self, *a, **k):
pass
def __call__(self, *a, **k):
return []
def predict(self, *a, **k):
return []
def track(self, *a, **k):
return []
class _FakeFaceDetection:
def __init__(self, *a, **k):
pass
def process(self, *a, **k):
return SimpleNamespace(detections=None)
def close(self):
pass
ul = types.ModuleType("ultralytics")
ul.YOLO = _FakeYOLO
sys.modules["ultralytics"] = ul
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
fd = types.ModuleType("mediapipe.solutions.face_detection")
fd.FaceDetection = _FakeFaceDetection
solutions.face_detection = fd
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = fd
_install_ml_stubs()
# extract_face_frames imports main lazily; import it here so the stubs are in
# place even when this file runs on its own.
from clipwright.pipeline import main # noqa: E402,F401
# --- stubbed Gemini client --------------------------------------------------
_CONCEPTS_JSON = (
'{"concepts": ['
'{"text": "BIG WIN", "text_position": "left", "text_color": "yellow",'
' "scene": "a bright desk with a laptop", "why": "bold"},'
'{"text": "HOW TO", "text_position": "right", "text_color": "white",'
' "scene": "a person seen from behind at a screen", "why": "curious"}'
']}'
)
def _png_bytes(width=2048, height=1152):
img = Image.effect_noise((width, height), 60).convert("RGB")
buf = io.BytesIO()
img.save(buf, "PNG")
return buf.getvalue()
class _FakeModels:
def generate_content(self, model=None, contents=None, config=None):
return SimpleNamespace(text=_CONCEPTS_JSON)
class _FakeInteractions:
def create(self, model=None, input=None, response_format=None):
data = base64.b64encode(_png_bytes()).decode("ascii")
return SimpleNamespace(output_text=None,
output_image=SimpleNamespace(data=data),
status=None, errors=None)
class _FakeClient:
def __init__(self, api_key=None, **kwargs):
self.models = _FakeModels()
self.interactions = _FakeInteractions()
# --- helpers ----------------------------------------------------------------
class TestExtractFaceFrames:
def test_no_faces_returns_empty_list(self, tmp_path, media_factory, monkeypatch):
monkeypatch.chdir(tmp_path)
assert thumbnail.extract_face_frames(str(media_factory.six), "sess") == []
class TestRankingAndSpread:
def test_rank_frame_rejects_tiny_faces(self):
assert thumbnail.rank_frame(0, 0.0, None, [0, 0, 50, 50],
(1920, 1080), 100) is None
big = thumbnail.rank_frame(0, 0.0, None, [0, 0, 400, 400],
(1920, 1080), 100)
assert big and big["score"] > 0
def test_pick_spread_keeps_picks_apart_in_time(self):
scored = [
{"idx": 500, "score": 1.0}, {"idx": 505, "score": 0.99},
{"idx": 510, "score": 0.98}, {"idx": 100, "score": 0.5},
{"idx": 900, "score": 0.4},
]
picked = thumbnail.pick_spread(scored, 3, 1000)
assert [p["idx"] for p in picked] == [100, 500, 900]
class TestTextAndFinalize:
def test_burn_text_draws_only_on_its_side(self):
img = Image.new("RGB", (1280, 720), (20, 20, 20))
out = thumbnail.burn_thumbnail_text(img, "0 A 10K", "left", "yellow")
px = out.convert("RGB")
assert max(px.crop((0, 0, 640, 720)).getextrema()[0]) > 200
assert max(px.crop((700, 0, 1280, 720)).getextrema()[0]) < 60
def test_finalize_cover_crops_to_1280x720_under_2mb(self, tmp_path):
noisy = Image.effect_noise((2048, 1536), 80).convert("RGB")
out = tmp_path / "t.jpg"
thumbnail.finalize_thumbnail(noisy, str(out))
with Image.open(out) as saved:
assert saved.size == (1280, 720)
assert out.stat().st_size <= thumbnail.THUMB_MAX_BYTES
class TestConcepts:
def test_normalise_clamps_and_pads(self):
raw = [
{"text": "esto funciona", "text_position": "diagonal",
"text_color": "red", "scene": "a desk"},
{"scene": ""},
"garbage",
]
out = thumbnail.normalise_concepts(raw, 3, "My title",
thumbnail_text_hint="hint")
assert len(out) == 3
assert out[0]["text"] == "ESTO FUNCIONA"
assert out[0]["text_position"] == "left"
assert out[1]["why"] == "fallback"
def test_plan_thumbnail_concepts_parses_the_client_json(self):
concepts = thumbnail.plan_thumbnail_concepts(_FakeClient(), "A title", 2)
assert len(concepts) == 2
assert concepts[0]["text"] == "BIG WIN"
assert concepts[0]["text_color"] == "yellow"
class TestGenerateThumbnail:
def test_end_to_end_against_a_stubbed_image_client(self, tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
monkeypatch.setattr(thumbnail, "genai",
SimpleNamespace(Client=lambda api_key=None, **kw: _FakeClient()))
results = thumbnail.generate_thumbnail("stub-key", "A title", "sess", count=2)
assert len(results) == 2
for r in results:
path = os.path.join("output", "thumbnails", "sess",
os.path.basename(r["url"]))
assert os.path.exists(path)
with Image.open(path) as img:
assert img.size == (1280, 720)
assert os.path.getsize(path) <= thumbnail.THUMB_MAX_BYTES
assert r["url"].startswith("/thumbnails/sess/")

View file

@ -0,0 +1,200 @@
"""L4 — transcribe stage.
Covers the audio-stream probe (real ffmpeg), the backend dispatcher with a
stubbed ASR backend, ``main.transcribe_video`` wiring, and the transcript
checkpoint round-trip. No ASR model is ever loaded.
"""
import json
from types import SimpleNamespace
import pytest
from clipwright.pipeline import transcribe_backends as tb
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
@pytest.fixture(scope="session")
def heavy_stubs():
"""Inject fake ``ultralytics``/``mediapipe`` then import ``main`` lazily."""
import sys
import types
if "ultralytics" not in sys.modules:
ul = types.ModuleType("ultralytics")
class _YOLO:
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return []
ul.YOLO = _YOLO
sys.modules["ultralytics"] = ul
if "mediapipe" not in sys.modules:
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
face_detection = types.ModuleType("mediapipe.solutions.face_detection")
class _FaceDetection:
def __init__(self, *args, **kwargs):
pass
def process(self, *args, **kwargs):
return SimpleNamespace(detections=None)
def close(self):
pass
face_detection.FaceDetection = _FaceDetection
solutions.face_detection = face_detection
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = face_detection
import clipwright.pipeline.main as main
return main
CANNED = {
"text": "hello world this is a canned transcript for tests",
"language": "en",
"segments": [
{"start": 0.0, "end": 2.0, "text": " hello world",
"words": [{"word": " hello", "start": 0.0, "end": 1.0},
{"word": " world", "start": 1.0, "end": 2.0}]},
{"start": 2.0, "end": 4.0, "text": " this is a canned transcript for tests",
"words": [{"word": " this", "start": 2.0, "end": 2.5}]},
],
}
def _clone():
return json.loads(json.dumps(CANNED))
# ---------------------------------------------------------------------------
# _has_audio_stream / NoAudioError — real ffmpeg
# ---------------------------------------------------------------------------
def test_has_audio_stream_true(media_factory):
assert tb._has_audio_stream(str(media_factory.six)) is True
def test_has_audio_stream_false(media_factory):
assert tb._has_audio_stream(str(media_factory.silent)) is False
def test_transcribe_media_raises_no_audio(media_factory):
with pytest.raises(tb.NoAudioError) as excinfo:
tb.transcribe_media(str(media_factory.silent))
assert "no audio track" in str(excinfo.value)
# ---------------------------------------------------------------------------
# transcribe_media dispatcher — stub the backends
# ---------------------------------------------------------------------------
def test_transcribe_media_dispatches_to_whisper(monkeypatch, media_factory):
monkeypatch.setenv("TRANSCRIBE_BACKEND", "whisper")
monkeypatch.setattr(tb, "_transcribe_with_whisper", lambda path: _clone())
assert tb.transcribe_media(str(media_factory.six)) == CANNED
def test_transcribe_media_parakeet_falls_back(monkeypatch, media_factory, capsys):
monkeypatch.setenv("TRANSCRIBE_BACKEND", "parakeet")
def _boom(path):
raise RuntimeError("onnxruntime not available")
monkeypatch.setattr(tb, "_transcribe_with_parakeet", _boom)
monkeypatch.setattr(tb, "_transcribe_with_whisper", lambda path: _clone())
assert tb.transcribe_media(str(media_factory.six)) == CANNED
assert "falling back to whisper" in capsys.readouterr().out
def test_transcribe_media_parakeet_accepted(monkeypatch, media_factory, capsys):
monkeypatch.setenv("TRANSCRIBE_BACKEND", "parakeet")
monkeypatch.setattr(tb, "_transcribe_with_parakeet", lambda path: _clone())
def _unexpected(path):
raise AssertionError("whisper should not run when parakeet succeeds")
monkeypatch.setattr(tb, "_transcribe_with_whisper", _unexpected)
assert tb.transcribe_media(str(media_factory.six)) == CANNED
assert "parakeet ok" in capsys.readouterr().out
# ---------------------------------------------------------------------------
# main.transcribe_video — wiring
# ---------------------------------------------------------------------------
def test_transcribe_video_uses_module_dispatcher(heavy_stubs, monkeypatch, media_factory):
released = []
monkeypatch.setattr(tb, "ASR_HOST_SLOTS", 0) # no flock, no waiting
monkeypatch.setattr(tb, "transcribe_media", lambda path: _clone())
monkeypatch.setattr(tb, "release_models", lambda: released.append(True))
result = heavy_stubs.transcribe_video(str(media_factory.six))
assert result == CANNED
assert released == [True]
def test_host_asr_slot_zero_is_noop(monkeypatch, tmp_path):
slot = tb.host_asr_slot(slots=0, lock_dir=str(tmp_path))
with slot as entered:
assert entered is slot
assert not list(tmp_path.glob(".asr-gpu-*.lock"))
# ---------------------------------------------------------------------------
# Transcript checkpoint round-trip
# ---------------------------------------------------------------------------
def test_checkpoint_roundtrip(heavy_stubs, tmp_path):
out = tmp_path
heavy_stubs.save_transcript_checkpoint(str(out), CANNED, "/jobs/a.mp4", 12.34)
loaded = heavy_stubs.load_transcript_checkpoint(str(out), "/jobs/a.mp4", 12.34)
assert loaded == CANNED
# A different source name is ignored.
assert heavy_stubs.load_transcript_checkpoint(str(out), "/jobs/b.mp4", 12.34) is None
# A different duration is ignored.
assert heavy_stubs.load_transcript_checkpoint(str(out), "/jobs/a.mp4", 20.0) is None
heavy_stubs.clear_transcript_checkpoint(str(out))
assert not (out / heavy_stubs.TRANSCRIPT_CHECKPOINT).exists()
assert heavy_stubs.load_transcript_checkpoint(str(out), "/jobs/a.mp4", 12.34) is None
def test_checkpoint_same_basename_different_dir_is_accepted(heavy_stubs, tmp_path):
out = tmp_path
heavy_stubs.save_transcript_checkpoint(str(out), CANNED, "/first/a.mp4", 6.0)
# The key is basename+duration, so a re-download to another directory matches.
assert heavy_stubs.load_transcript_checkpoint(str(out), "/second/a.mp4", 6.0) == CANNED
def test_checkpoint_malformed_is_ignored(heavy_stubs, tmp_path):
(tmp_path / heavy_stubs.TRANSCRIPT_CHECKPOINT).write_text("{not json")
assert heavy_stubs.load_transcript_checkpoint(str(tmp_path), "/a.mp4", 6.0) is None
def test_checkpoint_without_segments_is_ignored(heavy_stubs, tmp_path):
payload = {"source": {"name": "a.mp4", "duration": 6.0}, "transcript": {}}
(tmp_path / heavy_stubs.TRANSCRIPT_CHECKPOINT).write_text(json.dumps(payload))
assert heavy_stubs.load_transcript_checkpoint(str(tmp_path), "/a.mp4", 6.0) is None
def test_clear_checkpoint_missing_is_ok(heavy_stubs, tmp_path):
heavy_stubs.clear_transcript_checkpoint(str(tmp_path)) # must not raise

View file

@ -0,0 +1,143 @@
"""L5 Pipeline media — WATERMARK stage.
The pure naming helpers, a real ``apply_watermark`` burn against the bundled
``assets/watermark.png``, and ``main.mark_delivery``'s contract: the served
``wm_`` copy is written while the clean twin is left byte-for-byte untouched,
an existing copy is reused, and a failed mark still fails open under the ``wm_``
name.
"""
import os
import shutil
import subprocess
import sys
import types
from types import SimpleNamespace
import pytest
from clipwright.media import watermarked
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
def _install_ml_stubs():
if "ultralytics" in sys.modules and "mediapipe" in sys.modules:
return
class _FakeYOLO:
def __init__(self, *a, **k):
pass
def __call__(self, *a, **k):
return []
def predict(self, *a, **k):
return []
def track(self, *a, **k):
return []
class _FakeFaceDetection:
def __init__(self, *a, **k):
pass
def process(self, *a, **k):
return SimpleNamespace(detections=None)
def close(self):
pass
ul = types.ModuleType("ultralytics")
ul.YOLO = _FakeYOLO
sys.modules["ultralytics"] = ul
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
fd = types.ModuleType("mediapipe.solutions.face_detection")
fd.FaceDetection = _FakeFaceDetection
solutions.face_detection = fd
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = fd
_install_ml_stubs()
from clipwright.pipeline import main # noqa: E402
def _probe_dims(path):
out = subprocess.check_output(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", str(path)],
text=True).strip()
w, h = out.split("x")
return int(w), int(h)
@pytest.fixture
def clip(tmp_path, media_factory):
dest = tmp_path / "t_clip_1.mp4"
shutil.copyfile(media_factory.six, dest)
return dest
class TestWatermarkedNames:
def test_marked_and_clean_are_inverses(self):
assert watermarked.marked_name("a_clip_1.mp4") == "wm_a_clip_1.mp4"
assert watermarked.marked_name("wm_a_clip_1.mp4") == "wm_a_clip_1.mp4"
assert watermarked.clean_name("wm_subtitled_1_a_clip_1.mp4") == \
"subtitled_1_a_clip_1.mp4"
assert watermarked.is_marked("wm_x.mp4") and not watermarked.is_marked("x.mp4")
def test_clean_deliverables_exclude_scratch_and_sidecars(self):
assert watermarked.is_clean_deliverable("t_clip_1.mp4")
assert watermarked.is_clean_deliverable("hooked_1_t_clip_2.mp4")
for name in ("wm_t_clip_1.mp4", "temp_preview_0.mp4", "t_clip_1.layout.json"):
assert not watermarked.is_clean_deliverable(name)
def test_job_marker_round_trip(self, tmp_path):
assert not watermarked.job_is_marked(str(tmp_path))
watermarked.mark_job(str(tmp_path))
assert watermarked.job_is_marked(str(tmp_path))
class TestApplyWatermark:
def test_bundled_asset_is_present(self):
assert os.path.exists(main.watermark_logo_path())
def test_real_burn_writes_a_marked_copy_at_source_dimensions(self, clip, tmp_path):
out = tmp_path / "marked.mp4"
assert main.apply_watermark(str(clip), str(out)) is True
assert out.exists() and out.stat().st_size > 0
assert _probe_dims(out) == (320, 180)
# In-place source untouched when output_path is given.
assert _probe_dims(clip) == (320, 180)
def test_missing_asset_fails_open(self, clip, tmp_path, monkeypatch):
monkeypatch.setattr(main, "watermark_logo_path", lambda: "/nope/watermark.png")
assert main.apply_watermark(str(clip), str(tmp_path / "x.mp4")) is False
class TestMarkDelivery:
def test_writes_the_copy_and_leaves_the_clean_twin_untouched(self, clip, tmp_path):
before = clip.read_bytes()
served = main.mark_delivery(str(clip))
assert os.path.basename(served) == "wm_t_clip_1.mp4"
assert os.path.exists(served) and os.path.getsize(served) > 0
# The clean deliverable is byte-for-byte what it was.
assert clip.read_bytes() == before
def test_reuses_an_existing_copy(self, clip, tmp_path):
existing = tmp_path / "wm_t_clip_1.mp4"
existing.write_bytes(b"already-marked")
served = main.mark_delivery(str(clip), marker=lambda *_: pytest.fail("re-encoded"))
assert served == str(existing)
assert existing.read_bytes() == b"already-marked"
def test_failed_mark_fails_open_under_the_wm_name(self, clip, tmp_path):
served = main.mark_delivery(str(clip), marker=lambda *_: False)
assert os.path.basename(served) == "wm_t_clip_1.mp4"
assert os.path.exists(served)
assert clip.read_bytes() == (tmp_path / "wm_t_clip_1.mp4").read_bytes()