CenaForge: primeira versão pública
Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz, Clipador de lives e Publicador para YouTube, TikTok e Instagram. Inclui a leitura das visualizações dos posts para o Dashboard e o botão "Publicar no <rede>" nos cartões das publicações. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,195 @@
|
||||
// Testes do lançador: falhas de subprocesso, trava de render, conferência de
|
||||
// quadros, critérios do FFprobe e áudio opcional.
|
||||
import { test, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { runProcess, succeeded, describeFailure, cancelActiveProcesses, resetCancellation } from "../lib/process.ts";
|
||||
import { parseArgs } from "../lib/args.ts";
|
||||
import { acquireLock, applyProfile } from "../lib/render.ts";
|
||||
import { checkFrames, readPngSize } from "../lib/frames.ts";
|
||||
import { evaluateProbe, parseProbe, type ProbeSummary } from "../lib/verify.ts";
|
||||
import { planAudio, audioFfmpegArgs, AudioError } from "../lib/audio.ts";
|
||||
import { findTool, type Tool } from "../lib/tools.ts";
|
||||
|
||||
const created: string[] = [];
|
||||
const tmp = () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cenaforge-test-"));
|
||||
created.push(dir);
|
||||
return dir;
|
||||
};
|
||||
after(() => created.forEach((dir) => fs.rmSync(dir, { recursive: true, force: true })));
|
||||
const node = process.execPath;
|
||||
|
||||
function tryTool(name: "ffmpeg" | "ffprobe"): Tool | null {
|
||||
try {
|
||||
return findTool(name);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// --- subprocessos -------------------------------------------------------------
|
||||
|
||||
test("código de saída diferente de zero não é sucesso", async () => {
|
||||
const r = await runProcess(node, ["-e", "process.exit(3)"]);
|
||||
assert.equal(r.exitCode, 3);
|
||||
assert.equal(succeeded(r), false);
|
||||
assert.match(describeFailure("node", r), /código 3/);
|
||||
});
|
||||
|
||||
test("executável inexistente vira falha, não exceção nem sucesso", async () => {
|
||||
const r = await runProcess(path.join(tmp(), "nao-existe.exe"), []);
|
||||
assert.equal(succeeded(r), false);
|
||||
assert.ok(r.spawnError);
|
||||
});
|
||||
|
||||
test("argumentos com espaços chegam intactos (sem shell)", async () => {
|
||||
const arg = "C:/pasta com espaço/arquivo; echo injetado.json";
|
||||
const r = await runProcess(node, ["-e", "process.stdout.write(process.argv[1])", arg]);
|
||||
assert.ok(succeeded(r));
|
||||
assert.equal(r.stdout, arg);
|
||||
});
|
||||
|
||||
test("timeout encerra o processo e é falha", async () => {
|
||||
const r = await runProcess(node, ["-e", "setTimeout(() => {}, 60000)"], { timeoutMs: 300 });
|
||||
assert.equal(r.timedOut, true);
|
||||
assert.equal(succeeded(r), false);
|
||||
});
|
||||
|
||||
test("cancelamento encerra o subprocesso e marca como cancelado", async () => {
|
||||
const pending = runProcess(node, ["-e", "setTimeout(() => {}, 60000)"]);
|
||||
setTimeout(cancelActiveProcesses, 200);
|
||||
const r = await pending;
|
||||
resetCancellation();
|
||||
assert.equal(r.cancelled, true);
|
||||
assert.equal(succeeded(r), false);
|
||||
assert.ok(r.durationMs < 30_000);
|
||||
});
|
||||
|
||||
test("FFmpeg com erro não resulta em sucesso", { skip: !tryTool("ffmpeg") && "ffmpeg ausente" }, async () => {
|
||||
const ffmpeg = tryTool("ffmpeg")!;
|
||||
const dir = tmp();
|
||||
const r = await runProcess(ffmpeg.path, ["-hide_banner", "-y", "-framerate", "30", "-i", path.join(dir, "frame%08d.png"), path.join(dir, "out.mp4")]);
|
||||
assert.equal(succeeded(r), false);
|
||||
assert.notEqual(r.exitCode, 0);
|
||||
});
|
||||
|
||||
// --- argumentos e perfil --------------------------------------------------------
|
||||
|
||||
test("'--' solto repassado pelo pnpm é ignorado", () => {
|
||||
const a = parseArgs(["--", "--config", "config/x.json", "--profile=final", "--keep-frames"]);
|
||||
assert.equal(a.options.get("config"), "config/x.json");
|
||||
assert.equal(a.options.get("profile"), "final");
|
||||
assert.equal(a.options.get("keep-frames"), true);
|
||||
});
|
||||
|
||||
test("perfil altera só a resolução e não muta o original", () => {
|
||||
const raw = { id: "x", video: { width: 540, height: 960, fps: 30, durationSeconds: 12 } };
|
||||
const out = applyProfile(raw, { width: 1080, height: 1920 }) as { video: Record<string, number> };
|
||||
assert.deepEqual(out.video, { width: 1080, height: 1920, fps: 30, durationSeconds: 12 });
|
||||
assert.equal(raw.video.width, 540);
|
||||
});
|
||||
|
||||
// --- trava ----------------------------------------------------------------------
|
||||
|
||||
test("só um render por vez; trava abandonada é recuperada", () => {
|
||||
const lock = path.join(tmp(), ".render.lock");
|
||||
const release = acquireLock(lock);
|
||||
assert.equal(typeof release, "function");
|
||||
assert.match(String(acquireLock(lock)), /em andamento/);
|
||||
(release as () => void)();
|
||||
// Trava de um processo que não existe mais.
|
||||
fs.writeFileSync(lock, JSON.stringify({ pid: 999_999_999 }));
|
||||
const again = acquireLock(lock);
|
||||
assert.equal(typeof again, "function");
|
||||
(again as () => void)();
|
||||
});
|
||||
|
||||
// --- quadros --------------------------------------------------------------------
|
||||
|
||||
function fakePng(file: string, width: number, height: number): void {
|
||||
const header = Buffer.alloc(24);
|
||||
Buffer.from("89504e470d0a1a0a", "hex").copy(header, 0);
|
||||
header.writeUInt32BE(13, 8);
|
||||
header.write("IHDR", 12, "ascii");
|
||||
header.writeUInt32BE(width, 16);
|
||||
header.writeUInt32BE(height, 20);
|
||||
fs.writeFileSync(file, Buffer.concat([header, Buffer.alloc(4096, 1)]));
|
||||
}
|
||||
|
||||
test("sequência completa passa; lacuna, quantidade e tamanho errados falham", () => {
|
||||
const dir = tmp();
|
||||
for (let i = 0; i < 5; i++) fakePng(path.join(dir, `frame${String(i).padStart(8, "0")}.png`), 540, 960);
|
||||
assert.deepEqual(readPngSize(path.join(dir, "frame00000000.png")), { width: 540, height: 960 });
|
||||
assert.equal(checkFrames(dir, 5, { width: 540, height: 960 }, 1).ok, true);
|
||||
|
||||
const wrongCount = checkFrames(dir, 6, { width: 540, height: 960 }, 1);
|
||||
assert.equal(wrongCount.ok, false);
|
||||
assert.match(wrongCount.problems.join(), /esperado 6/);
|
||||
|
||||
const wrongSize = checkFrames(dir, 5, { width: 1080, height: 1920 }, 1);
|
||||
assert.match(wrongSize.problems.join(), /esperado 1080x1920/);
|
||||
|
||||
fs.rmSync(path.join(dir, "frame00000002.png"));
|
||||
assert.match(checkFrames(dir, 4, { width: 540, height: 960 }, 1).problems.join(), /lacuna/);
|
||||
});
|
||||
|
||||
test("pasta sem PNG falha", () => {
|
||||
assert.equal(checkFrames(tmp(), 360, { width: 540, height: 960 }, 3).ok, false);
|
||||
});
|
||||
|
||||
// --- critérios do FFprobe ------------------------------------------------------
|
||||
|
||||
const goodProbe: ProbeSummary = parseProbe(JSON.stringify({
|
||||
streams: [{ codec_type: "video", codec_name: "h264", width: 540, height: 960, pix_fmt: "yuv420p", r_frame_rate: "30/1", avg_frame_rate: "30/1", nb_read_frames: "360" }],
|
||||
format: { format_name: "mov,mp4,m4a,3gp,3g2,mj2", duration: "12.000000", size: "1234567" },
|
||||
}));
|
||||
const expected = { width: 540, height: 960, fps: 30, durationSeconds: 12, frames: 360, audio: false };
|
||||
|
||||
test("MP4 correto passa em todos os critérios", () => {
|
||||
const failed = evaluateProbe(goodProbe, expected).filter((c) => !c.ok);
|
||||
assert.deepEqual(failed, []);
|
||||
});
|
||||
|
||||
test("duração fora da tolerância de um quadro falha; dentro passa", () => {
|
||||
const off = (d: number) => evaluateProbe({ ...goodProbe, durationSeconds: d }, expected).find((c) => c.name.startsWith("duração"))!;
|
||||
assert.equal(off(12 + 1 / 30).ok, true);
|
||||
assert.equal(off(12 + 2 / 30).ok, false);
|
||||
});
|
||||
|
||||
test("FPS, dimensões e contagem errados falham", () => {
|
||||
const bad = { ...goodProbe, video: { ...goodProbe.video!, rFrameRate: "25/1", width: 720, frames: 359 } };
|
||||
const failed = evaluateProbe(bad, expected).filter((c) => !c.ok).map((c) => c.name);
|
||||
assert.ok(failed.includes("FPS"));
|
||||
assert.ok(failed.includes("dimensões"));
|
||||
assert.ok(failed.includes("total de quadros"));
|
||||
});
|
||||
|
||||
// --- áudio opcional ------------------------------------------------------------
|
||||
|
||||
test("áudio desabilitado não gera plano", async () => {
|
||||
const fakeProbe: Tool = { name: "ffprobe", path: "nao-usado", source: "PATH" };
|
||||
assert.equal(await planAudio({ enabled: false, file: null }, 12, fakeProbe), null);
|
||||
});
|
||||
|
||||
test("arquivo de áudio inexistente é rejeitado com mensagem clara", async () => {
|
||||
const fakeProbe: Tool = { name: "ffprobe", path: "nao-usado", source: "PATH" };
|
||||
await assert.rejects(planAudio({ enabled: true, file: "audio/nao-existe.wav" }, 12, fakeProbe), (e: unknown) => e instanceof AudioError && /não encontrado/.test(e.message));
|
||||
await assert.rejects(planAudio({ enabled: true, file: null }, 12, fakeProbe), AudioError);
|
||||
});
|
||||
|
||||
test("áudio maior que a cena gera aviso de corte; filtro não usa -shortest", { skip: !(tryTool("ffmpeg") && tryTool("ffprobe")) && "ffmpeg/ffprobe ausentes" }, async () => {
|
||||
const dir = tmp();
|
||||
const wav = path.join(dir, "tom de teste.wav");
|
||||
const gen = await runProcess(tryTool("ffmpeg")!.path, ["-hide_banner", "-y", "-f", "lavfi", "-i", "sine=frequency=440:duration=5", wav]);
|
||||
assert.ok(succeeded(gen));
|
||||
const plan = (await planAudio({ enabled: true, file: wav, offsetSeconds: 9 }, 12, tryTool("ffprobe")!))!;
|
||||
assert.ok(Math.abs(plan.sourceDurationSeconds - 5) < 0.05);
|
||||
assert.ok(Math.abs(plan.cutSeconds - 2) < 0.05);
|
||||
assert.match(plan.warnings.join(), /CORTADO/);
|
||||
const args = audioFfmpegArgs(plan);
|
||||
assert.ok(!args.mapping.includes("-shortest"));
|
||||
assert.match(args.mapping.join(" "), /adelay=delays=9000:all=1,apad,atrim=end=12/);
|
||||
});
|
||||
Reference in New Issue
Block a user