dressup-generate.test.js
8.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// Integration test for the T8 single-generation orchestration
// (POST/GET /api/admin/generate): submit -> forward assets to H3 /v1/assets
// -> POST /v1/videos -> poll -> land a clip in library.json with
// characterId/garmentId/refDanceVideoId. Runs server.js against a mock H3
// Console (not the real one) so it's fast and offline.
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const os = require("node:os");
const http = require("node:http");
const { spawn } = require("node:child_process");
const PORT = 21934 + Math.floor(Math.random() * 1000);
const BASE = `http://localhost:${PORT}`;
const ADMIN_PASSWORD = "test-password-only-for-this-run";
let cookie;
let child;
let cwd;
let mockH3;
let mockH3Port;
let videoPollCounts; // h3JobId -> number of GETs seen, so we can return "generating" once then "done"
function waitForServer(url, timeoutMs = 10000) {
const deadline = Date.now() + timeoutMs;
return (async function poll() {
while (Date.now() < deadline) {
try {
await fetch(url);
return;
} catch {
await new Promise((r) => setTimeout(r, 100));
}
}
throw new Error("server did not come up in time");
})();
}
function authed(opts = {}) {
return { ...opts, headers: { "Content-Type": "application/json", Cookie: cookie, ...opts.headers } };
}
// Minimal stand-in for H3 Console: enough of /v1/assets, /v1/videos and
// /v1/videos/:id to exercise generateDanceVideo end to end.
function startMockH3() {
videoPollCounts = new Map();
let nextId = 1;
return new Promise((resolve) => {
mockH3 = http.createServer((req, res) => {
// h3ConsoleFetch builds paths as `${new URL(H3_CONSOLE_BASE).pathname}${path}`;
// with a bare "http://host:port" base (pathname "/") that yields a
// leading "//v1/...", which real deployments avoid by pointing
// H3_CONSOLE_BASE at a sub-path (e.g. ".../console"). Normalize here
// so the mock matches routes regardless.
req.url = req.url.replace(/^\/+/, "/");
const chunks = [];
req.on("data", (c) => chunks.push(c));
req.on("end", () => {
if (req.method === "POST" && req.url === "/v1/assets") {
const id = `asset-${nextId++}`;
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ id, url: `http://mock-h3/asset/${id}`, kind: "image" }));
return;
}
if (req.method === "POST" && req.url === "/v1/videos") {
const id = `job-${nextId++}`;
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ id }));
return;
}
const pollMatch = req.method === "GET" && req.url.match(/^\/v1\/videos\/(.+)$/);
if (pollMatch) {
const id = pollMatch[1];
const seen = (videoPollCounts.get(id) || 0) + 1;
videoPollCounts.set(id, seen);
if (seen < 2) {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ id, status: "generating" }));
return;
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
id,
status: "done",
partition: "ref2va",
req: { width: 480, height: 832, frames: 240 },
})
);
return;
}
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not found in mock" }));
});
});
mockH3.listen(0, () => {
mockH3Port = mockH3.address().port;
resolve();
});
});
}
test.before(async () => {
await startMockH3();
cwd = fs.mkdtempSync(path.join(os.tmpdir(), "dressup-generate-"));
for (const f of ["server.js", "ingest.js", "uploads.js", "store.js", "dressup-store.js", "prompt-template.js"]) {
fs.copyFileSync(path.join(__dirname, f), path.join(cwd, f));
}
// ensureH3AssetUrl reads these off disk (path.join(__dirname, record.imageUrl))
// before forwarding to /v1/assets, so they need to actually exist.
fs.mkdirSync(path.join(cwd, "uploads"), { recursive: true });
fs.writeFileSync(path.join(cwd, "uploads", "person.png"), "fake-png-bytes");
fs.writeFileSync(path.join(cwd, "uploads", "garment.png"), "fake-png-bytes");
fs.writeFileSync(path.join(cwd, "uploads", "ref.mp4"), "fake-mp4-bytes");
child = spawn(process.execPath, ["server.js"], {
cwd,
env: {
...process.env,
PORT: String(PORT),
H3_CONSOLE_BASE: `http://localhost:${mockH3Port}`,
H3_CONSOLE_TOKEN: "mock-token",
ADMIN_PASSWORD,
GENERATION_POLL_INTERVAL_MS: "20",
},
stdio: "pipe",
});
await waitForServer(BASE);
const loginRes = await fetch(`${BASE}/api/admin/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: ADMIN_PASSWORD }),
});
cookie = (loginRes.headers.get("set-cookie") || "").split(";")[0];
});
test.after(() => {
child.kill();
mockH3.close();
fs.rmSync(cwd, { recursive: true, force: true });
});
async function waitForJobDone(jobId, timeoutMs = 5000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const job = await fetch(`${BASE}/api/admin/generate/${jobId}`, authed()).then((r) => r.json());
if (job.status === "done" || job.status === "failed") return job;
await new Promise((r) => setTimeout(r, 30));
}
throw new Error("job did not finish in time");
}
test("generate: full happy path lands a clip with character/garment/dance-ref traceability", async () => {
const character = await fetch(
`${BASE}/api/admin/characters`,
authed({ method: "POST", body: JSON.stringify({ name: "小美", imageUrl: "/uploads/person.png", appearanceDescriptor: "black hair" }) })
).then((r) => r.json());
const garment = await fetch(
`${BASE}/api/admin/garments`,
authed({ method: "POST", body: JSON.stringify({ name: "红旗袍", imageUrl: "/uploads/garment.png", appearanceDescriptor: "red qipao" }) })
).then((r) => r.json());
const danceRef = await fetch(
`${BASE}/api/admin/dance-refs`,
authed({ method: "POST", body: JSON.stringify({ name: "拉丁舞", videoUrl: "/uploads/ref.mp4", motionDescriptor: "hip sways" }) })
).then((r) => r.json());
const submitRes = await fetch(
`${BASE}/api/admin/generate`,
authed({ method: "POST", body: JSON.stringify({ characterId: character.id, garmentId: garment.id }) })
);
assert.equal(submitRes.status, 200);
const submitted = await submitRes.json();
assert.equal(submitted.cached, false);
assert.ok(submitted.jobId);
const job = await waitForJobDone(submitted.jobId);
assert.equal(job.status, "done");
assert.equal(job.refDanceVideoId, danceRef.id); // auto-picked since none was given
assert.ok(job.generatedVideoId);
const library = await fetch(`${BASE}/api/library`).then((r) => r.json());
const clip = library.find((c) => c.id === job.generatedVideoId);
assert.ok(clip, "generated clip should show up in /api/library");
assert.equal(clip.characterId, character.id);
assert.equal(clip.garmentId, garment.id);
assert.equal(clip.refDanceVideoId, danceRef.id);
assert.equal(clip.channel, "dance");
// Re-submitting the same character x garment combo should hit the M.7
// dedupe cache instead of generating again.
const repeatRes = await fetch(
`${BASE}/api/admin/generate`,
authed({ method: "POST", body: JSON.stringify({ characterId: character.id, garmentId: garment.id }) })
);
const repeat = await repeatRes.json();
assert.equal(repeat.cached, true);
assert.equal(repeat.clip.id, clip.id);
});
test("generate: rejects unknown character/garment ids", async () => {
const res = await fetch(`${BASE}/api/admin/generate`, authed({ method: "POST", body: JSON.stringify({ characterId: "nope", garmentId: "nope" }) }));
assert.equal(res.status, 400);
});
test("generate: 404 for unknown job id", async () => {
const res = await fetch(`${BASE}/api/admin/generate/nonexistent`, authed());
assert.equal(res.status, 404);
});