Files
workinf_Blender_Wasm/tools/web/run-deployed-functional-tests.mjs
mes123456 a5f772e18f
Some checks failed
M6 deployable RC / quick (push) Has been cancelled
M6 deployable RC / chromium (push) Has been cancelled
M6 deployable RC / release (push) Has been cancelled
feat(web): deployed functional suite, outliner expansion fix and local-first runs
Outliner: react-accessible-treeview's controlled expandedIds sync expands a
node together with its parent, then the next pass treats that extra parent id
as removed from the controlled set and collapses the whole branch. Reproduced
as a collapsed tree after ch11 -> ch12 (scene rows complete in React, one
collapsed row in the DOM). Keep OUTLINER_ROOT_ID in the controlled set so both
passes agree, and drop the rows-digest memo that regressed the normal path.
Also arm a bounded post-open OUTLINER_REFRESH loop so the tree settles on rows
of the newly opened Main instead of the previous one.

Tests: web/playwright.deployed.config.ts + web/tests/deployed walk the 31
manual chapters and the 31 capability rows headed against a deployed origin,
and tools/web/run-deployed-functional-tests.mjs preflights, runs and reports.
--local serves the production bundle from web/dist on loopback with the same
COOP/COEP/CORP/CSP headers, so a case costs compile time instead of a 300 MB
download: full local suite 60/60 in 10.3 min, also 60/60 against the deployed
release. Report dirs are resolved absolute and [ch28a]-style tags map to their
chapter.

Area layout: split from the clamped source rect and keep the area switcher
inside a narrow header.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 16:12:26 +08:00

416 lines
20 KiB
JavaScript

#!/usr/bin/env node
/**
* Headed functional test runner for the deployed site.
*
* node tools/web/run-deployed-functional-tests.mjs # full suite
* node tools/web/run-deployed-functional-tests.mjs --smoke # post-deploy subset
* node tools/web/run-deployed-functional-tests.mjs --only 00,01 # spec file prefixes
* node tools/web/run-deployed-functional-tests.mjs --grep "ch07"
* node tools/web/run-deployed-functional-tests.mjs --local # serve web/dist on loopback first
*
* Preflight runs before Playwright: display, TLS expiry, isolation headers,
* engine manifest and the local build hash. A hard preflight failure exits 2
* without opening a browser, so an unreachable origin cannot look like a
* product failure.
*/
import { spawnSync } from "node:child_process";
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import tls from "node:tls";
const REPO_ROOT = path.resolve(import.meta.dirname, "../..");
const WEB_DIR = path.join(REPO_ROOT, "web");
const SPEC_DIR = path.join(WEB_DIR, "tests/deployed");
const DEFAULT_ORIGIN = "https://49.232.250.35:58014";
function parseArgs(argv) {
const options = {
origin: process.env.WEB_ORIGIN ?? DEFAULT_ORIGIN, only: null, grep: null, smoke: false,
video: null, jsonOnly: false, isolate: false, workers: 1, freshProfile: false, local: false,
};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === "--origin") options.origin = argv[++index];
else if (arg === "--only") options.only = argv[++index];
else if (arg === "--grep") options.grep = argv[++index];
else if (arg === "--smoke") options.smoke = true;
else if (arg === "--record-video") { options.video = "all"; options.isolate = true; }
else if (arg === "--isolate") options.isolate = true;
else if (arg === "--workers") options.workers = Math.max(1, Number(argv[++index]) || 1);
else if (arg === "--fresh-profile") options.freshProfile = true;
else if (arg === "--json-only") options.jsonOnly = true;
else if (arg === "--local") options.local = true;
else if (arg === "--help" || arg === "-h") {
console.log([
"usage: run-deployed-functional-tests.mjs [options]",
" --origin URL deployed origin (default https://49.232.250.35:58014)",
" --only 00,01 run spec files by prefix",
" --grep PATTERN Playwright title filter",
" --smoke post-deploy subset (tests tagged @smoke)",
" --isolate one fresh browser context per case (implies --record-video)",
" --record-video record video per case; only possible with --isolate",
" --workers N parallel browsers; each compiles its own engine (default 1)",
" --fresh-profile wipe the cached Chromium profile before running",
" --json-only write report.json but skip report.html",
" --local serve web/dist on loopback (disk-speed WASM) instead of the remote origin",
].join("\n"));
process.exit(0);
}
else { console.error(`unknown argument: ${arg}`); process.exit(64); }
}
options.origin = options.origin.replace(/\/+$/, "");
return options;
}
const options = parseArgs(process.argv.slice(2));
/* Absolute: Playwright resolves PLAYWRIGHT_JSON_OUTPUT_FILE from its own cwd
* (web/), so a relative report dir would be created here and written there. */
let reportDir = path.resolve(process.env.DEPLOYED_REPORT_DIR ?? path.join(REPO_ROOT, "tests/golden", `DEPLOYED-FUNCTIONAL-${stamp()}`));
const preflight = [];
/* `--local` static server child; process.exit() skips finally blocks, so the
* exit hook owns the cleanup. */
let localServer = null;
process.on("exit", () => { localServer?.kill(); });
function stamp() {
/* Local date: reports are named by the day the operator ran them. */
const now = new Date();
return `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}`;
}
function record(name, ok, detail = null, hard = true) { preflight.push({ name, ok, detail, hard }); }
function hasHardFailure() { return preflight.some((item) => item.ok === false && item.hard); }
async function http(url, init = {}) {
return fetch(url, { ...init, signal: AbortSignal.timeout(60_000) });
}
function certInfo(origin) {
const url = new URL(origin);
const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
return new Promise((resolve) => {
if (url.protocol !== "https:") { resolve(null); return; }
const socket = tls.connect({ host: url.hostname, port, servername: url.hostname, rejectUnauthorized: false }, () => {
const certificate = socket.getPeerCertificate();
socket.end();
resolve({ validTo: certificate?.valid_to ?? null, issuer: certificate?.issuer?.CN ?? null });
});
socket.on("error", () => resolve(null));
socket.setTimeout(15_000, () => { socket.destroy(); resolve(null); });
});
}
function localWasmFile() {
for (const candidate of ["web/dist/vendor/blender/web_engine.wasm", "web/app/public/vendor/blender/web_engine.wasm"]) {
const file = path.join(REPO_ROOT, candidate);
if (fs.existsSync(file)) return file;
}
return null;
}
async function runPreflight() {
/* 1. A headed run needs a real X display; xvfb would drop the ANGLE path. */
const display = process.env.DISPLAY ?? null;
if (!display) record("display", false, "DISPLAY is unset; headed run needs X11 (export DISPLAY=:1)", true);
else record("display", true, display);
/* 2. Origin reachable and serving the production contract. */
let index = null;
try {
index = await http(`${options.origin}/`, { redirect: "manual" });
record("origin", index.status === 200, `${options.origin}/ -> ${index.status}`);
}
catch (error) {
record("origin", false, `cannot reach ${options.origin}: ${error?.cause?.code ?? error?.message ?? error}`);
}
if (index?.ok) {
const headers = index.headers;
const expected = {
"cross-origin-opener-policy": "same-origin",
"cross-origin-embedder-policy": "require-corp",
"cross-origin-resource-policy": "same-origin",
};
for (const [name, value] of Object.entries(expected)) {
record(`header ${name}`, headers.get(name) === value, headers.get(name));
}
const csp = headers.get("content-security-policy") ?? "";
record("header content-security-policy", csp.includes("wasm-unsafe-eval"), csp ? "present" : "missing");
let manifest = null;
try {
const response = await http(`${options.origin}/wasm-module-manifest.json`);
manifest = await response.json();
record("wasm-module-manifest", response.status === 200 && typeof manifest?.releaseId === "string", manifest?.releaseId ?? response.status);
}
catch (error) { record("wasm-module-manifest", false, String(error?.message ?? error)); }
const manifestWasm = manifest?.modules?.find((module) => module.id === "debug-incremental")?.resources?.single?.sha256
?? manifest?.modules?.[0]?.resources?.single?.sha256 ?? null;
const wasmFile = localWasmFile();
if (manifestWasm && wasmFile) {
const localSha = crypto.createHash("sha256").update(fs.readFileSync(wasmFile)).digest("hex");
record("wasm hash matches local build", manifestWasm === localSha, { remote: manifestWasm, local: localSha, file: path.relative(REPO_ROOT, wasmFile) }, false);
}
else record("wasm hash matches local build", false, "manifest or local build missing", false);
const manual = await http(`${options.origin}/manuals/index.html`).catch(() => null);
record("manual page", manual?.status === 200, `${options.origin}/manuals/index.html -> ${manual?.status ?? "unreachable"}`, false);
/* 3. TLS expiry: warn at 14 days, block once expired. */
const certificate = await certInfo(options.origin);
if (certificate?.validTo) {
const expiresAt = new Date(certificate.validTo);
const daysLeft = Math.floor((expiresAt.getTime() - Date.now()) / 86_400_000);
record("tls certificate", daysLeft > 0, { validTo: certificate.validTo, daysLeft, issuer: certificate.issuer }, true);
if (daysLeft > 0 && daysLeft <= 14) record("tls renewal reminder", false, `${daysLeft} days left (${certificate.validTo})`, false);
}
else record("tls certificate", false, "could not read certificate", false);
record("release identity", Boolean(manifest?.releaseId), manifest?.releaseId ?? null);
record("index etag", Boolean(headers.get("etag")), headers.get("etag") ?? null, false);
fs.mkdirSync(reportDir, { recursive: true });
fs.writeFileSync(path.join(reportDir, "preflight.json"), JSON.stringify({
schemaVersion: 1, origin: options.origin, observedAt: new Date().toISOString(), checks: preflight,
}, null, 2));
}
}
function specsForOnly(only) {
if (!only) return [];
const prefixes = only.split(",").map((value) => value.trim()).filter(Boolean);
return fs.readdirSync(SPEC_DIR)
.filter((file) => file.endsWith(".spec.ts") && prefixes.some((prefix) => file.startsWith(prefix)))
.map((file) => `tests/deployed/${file}`);
}
function flattenSuites(suites, fileHint, out) {
for (const suite of suites ?? []) {
const file = suite.file ?? fileHint ?? "";
for (const spec of suite.specs ?? []) {
const testEntry = spec.tests?.[0];
const result = testEntry?.results?.at(-1);
const title = spec.title;
const tag = /\[([a-z0-9][a-z0-9-]*)\]/.exec(title)?.[1] ?? null;
/* `[ch28a]` / `[ch28b]` are still chapter 28. */
const chapterTag = tag && /^ch\d{2}/.test(tag) ? tag.slice(0, 4) : null;
const capabilityTag = tag && tag.startsWith("cap-") ? tag : null;
/* `spec.ok` is true for skipped specs too, so read the result status:
* a skipped case must never be counted as a pass. */
const status = testEntry?.status === "skipped" || result?.status === "skipped"
? "SKIP"
: result?.status === "passed" ? "PASS" : "FAIL";
out.push({
caseId: tag ?? title.replace(/[^\w.-]+/g, "-").slice(0, 72),
title, file: file ? path.relative(REPO_ROOT, path.join(WEB_DIR, file)) : null,
chapter: chapterTag, capability: capabilityTag,
status, durationMs: result?.duration ?? 0,
retry: testEntry?.results?.length ?? 0,
error: result?.error?.message ? result.error.message.split("\n").slice(0, 6).join("\n") : null,
attachments: (result?.attachments ?? []).map((attachment) => ({ name: attachment.name, path: attachment.path ?? null })),
});
}
flattenSuites(suite.suites, file, out);
}
}
function copyFailures(cases) {
const dir = path.join(reportDir, "failures");
fs.mkdirSync(dir, { recursive: true });
for (const item of cases) {
if (item.status !== "FAIL") continue;
for (const attachment of item.attachments) {
if (!attachment.path || !fs.existsSync(attachment.path)) continue;
const target = path.join(dir, `${item.caseId}-${attachment.name.replace(/[^\w.-]+/g, "-")}${path.extname(attachment.path)}`);
fs.copyFileSync(attachment.path, target);
attachment.copiedTo = path.relative(REPO_ROOT, target);
}
}
}
function manualChapterIds() {
try {
const manual = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, "user-manual/WEB_Blender_Web_Manual_20261113/manual.json"), "utf8"));
return manual.chapters.map((chapter) => chapter.id);
}
catch { return []; }
}
function renderHtml(report) {
const escape = (value) => String(value ?? "").replace(/[&<>"]/g, (character) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[character]));
const rows = report.cases.map((item) => `
<tr class="status-${item.status.toLowerCase()}">
<td>${escape(item.caseId)}</td>
<td>${escape(item.title)}</td>
<td>${item.status}</td>
<td>${Math.round(item.durationMs / 1000)}s</td>
<td>${item.error ? `<pre>${escape(item.error)}</pre>` : ""}</td>
</tr>`).join("");
const uncovered = report.summary.notCovered.length
? `<p class="warn">未覆盖章节:${report.summary.notCovered.map(escape).join(", ")}</p>` : "";
return `<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><title>Deployed functional report ${escape(report.generatedAt)}</title>
<style>
body{font:13px/1.5 system-ui,sans-serif;margin:24px;color:#1c1c1c;background:#fafafa}
h1{font-size:20px;margin:0 0 4px}h2{font-size:15px;margin:22px 0 6px}
.meta{color:#555;margin-bottom:14px}code{background:#eee;padding:1px 4px;border-radius:3px}
table{border-collapse:collapse;width:100%;background:#fff}th,td{border:1px solid #ddd;padding:5px 7px;text-align:left;vertical-align:top}
th{background:#f0f0f0}.status-fail td{background:#fff1f0}.status-skip td{background:#fffbe6}
pre{margin:0;white-space:pre-wrap;font-size:11px;color:#8a1f1f}.warn{color:#8a1f1f;font-weight:600}
.summary span{margin-right:14px}
</style></head><body>
<h1>线上功能测试报告</h1>
<div class="meta">${escape(report.origin)} · 生成于 ${escape(report.generatedAt)} · release <code>${escape(report.release.releaseId ?? "unknown")}</code>
<br>wasm <code>${escape((report.release.wasmSha256 ?? "").slice(0, 16))}</code> · 验收:<code>${escape(report.acceptance)}</code></div>
<div class="summary"><span>PASS ${report.summary.pass}</span><span>FAIL ${report.summary.fail}</span><span>SKIP ${report.summary.skip}</span><span>BLOCKED ${report.summary.blocked}</span></div>
${uncovered}
<h2>预检</h2>
<table><tr><th>检查</th><th>结果</th><th>详情</th></tr>
${report.preflight.map((item) => `<tr class="${item.ok ? "" : "status-fail"}"><td>${escape(item.name)}</td><td>${item.ok ? "OK" : "FAIL"}</td><td>${escape(typeof item.detail === "object" ? JSON.stringify(item.detail) : item.detail)}</td></tr>`).join("")}
</table>
<h2>用例</h2>
<table><tr><th>编号</th><th>用例</th><th>状态</th><th>耗时</th><th>错误</th></tr>${rows}</table>
</body></html>`;
}
async function main() {
if (options.local) {
/* Serve the built bundle from disk: the 308 MB WASM and its 82 MB gzip
* never cross the network, so a case costs compile time only. Same server
* code and contract headers as the deploy, so this is the production
* bundle, not the dev server. It must be its own process: Playwright is
* spawned synchronously below, which blocks this event loop, and an
* in-process server would answer nothing for the whole run. */
const { spawn } = await import("node:child_process");
localServer = spawn(process.execPath, [path.join(REPO_ROOT, "tools/web/deployment-http-server.mjs"), path.join(WEB_DIR, "dist")], {
env: { ...process.env, BLENDER_WEB_HTTP_PORT: String(process.env.DEPLOYED_LOCAL_PORT ?? 0) },
stdio: ["ignore", "pipe", "inherit"],
});
options.origin = await new Promise((resolve, reject) => {
let buffer = "";
const timer = setTimeout(() => reject(new Error("local server did not report an origin in 15s")), 15_000);
localServer.stdout.on("data", (chunk) => {
buffer += chunk;
const match = /deployment-http-server (http:\/\/\S+)/.exec(buffer);
if (match) { clearTimeout(timer); resolve(match[1]); }
});
localServer.once("exit", (code) => { clearTimeout(timer); reject(new Error(`local server exited ${code}`)); });
});
if (!process.env.DEPLOYED_REPORT_DIR) {
reportDir = path.join(REPO_ROOT, "tests/golden", `DEPLOYED-FUNCTIONAL-LOCAL-${stamp()}`);
}
}
console.log(`deployed functional tests -> ${options.origin}${options.local ? " (local dist)" : ""}`);
await runPreflight();
const failedPreflight = preflight.filter((item) => !item.ok);
for (const item of failedPreflight) console.warn(`preflight ${item.ok ? "ok" : "FAIL"} ${item.name}: ${typeof item.detail === "object" ? JSON.stringify(item.detail) : item.detail}`);
if (hasHardFailure()) {
console.error("preflight blocked the run; no browser was started.");
process.exit(2);
}
fs.mkdirSync(reportDir, { recursive: true });
const jsonPath = path.join(reportDir, ".playwright-results.json");
const specFiles = specsForOnly(options.only);
if (options.only && specFiles.length === 0) {
console.error(`no spec under tests/deployed matches --only ${options.only}`);
process.exit(64);
}
/* Shared mode reuses one persistent context per worker: the engine is
* downloaded and compiled once instead of once per case. Isolated mode buys
* per-case contexts and video at ~3 minutes per case. */
const profile = process.env.DEPLOYED_PROFILE ?? path.join(WEB_DIR, ".cache/deployed-profile");
if (!options.isolate) {
/* A previous interrupted run can leave Chromium holding the persistent
* profile; launching then fails with "Opening in existing browser session".
* Only processes pinned to this exact profile are touched. */
spawnSync("pkill", ["-f", `--user-data-dir=${profile}`], { stdio: "ignore" });
}
if (options.freshProfile) {
fs.rmSync(profile, { recursive: true, force: true });
console.log(`wiped browser profile ${path.relative(REPO_ROOT, profile)}`);
}
const cli = ["playwright", "test", "--config", "playwright.deployed.config.ts", `--workers=${options.workers}`];
if (options.smoke) cli.push("-g", "@smoke");
if (options.grep) cli.push("-g", options.grep);
cli.push(...specFiles);
const startedAt = Date.now();
const result = spawnSync("npx", cli, {
cwd: WEB_DIR,
stdio: "inherit",
env: {
...process.env,
WEB_ORIGIN: options.origin,
PLAYWRIGHT_JSON_OUTPUT_FILE: jsonPath,
DEPLOYED_REPORT_DIR: reportDir,
DEPLOYED_WORKERS: String(options.workers),
...(options.isolate ? { DEPLOYED_ISOLATE: "1" } : {}),
...(options.video ? { DEPLOYED_VIDEO: options.video } : {}),
},
});
const wallMs = Date.now() - startedAt;
if (result.error) { console.error(`cannot start playwright: ${result.error.message}`); process.exit(2); }
let raw = null;
try { raw = JSON.parse(fs.readFileSync(jsonPath, "utf8")); }
catch (error) { console.error(`playwright wrote no JSON report: ${error.message}`); process.exit(2); }
const cases = [];
flattenSuites(raw.suites, null, cases);
copyFailures(cases);
const covered = new Set(cases.map((item) => item.chapter).filter(Boolean));
const notCovered = manualChapterIds().filter((id) => !covered.has(id));
const summary = {
pass: cases.filter((item) => item.status === "PASS").length,
fail: cases.filter((item) => item.status === "FAIL").length,
skip: cases.filter((item) => item.status === "SKIP").length,
blocked: hasHardFailure() ? 1 : 0,
total: cases.length,
notCovered,
};
/* How many engine loads did the run pay for? Shared mode loads once per
* worker; isolated mode loads once per case. This is the number the suite is
* optimised on, so it belongs in the report next to the wall clock. */
let session = null;
try { session = JSON.parse(fs.readFileSync(path.join(reportDir, "session.json"), "utf8")); }
catch { /* isolated mode writes no session record */ }
const engineLoads = options.isolate ? cases.length : options.workers * (session ? 1 : 0);
const report = {
schemaVersion: 1,
generatedAt: new Date().toISOString(),
origin: options.origin,
release: {
releaseId: preflight.find((item) => item.name === "release identity")?.detail ?? null,
wasmSha256: preflight.find((item) => item.name === "wasm hash matches local build")?.detail?.local ?? null,
indexEtag: preflight.find((item) => item.name === "index etag")?.detail ?? null,
},
environment: { display: process.env.DISPLAY ?? null, gpuMode: process.env.GPU_MODE ?? (process.env.DISPLAY ? "hardware" : "swiftshader"), node: process.version },
performance: {
strategy: options.isolate ? "isolated-contexts" : "shared-persistent-context",
workers: options.workers,
engineLoads,
firstBootMs: session?.bootMs ?? null,
wallMs,
isolatedWouldLoad: cases.length,
profile: session?.profile ?? null,
},
preflight, cases, summary,
mode: options.smoke ? "smoke" : options.only ? `only:${options.only}` : "full",
acceptance: "NOT_CLAIMED",
};
fs.writeFileSync(path.join(reportDir, "report.json"), JSON.stringify(report, null, 2));
if (!options.jsonOnly) fs.writeFileSync(path.join(reportDir, "report.html"), renderHtml(report));
fs.rmSync(jsonPath, { force: true });
console.log(`\nreport: ${path.relative(REPO_ROOT, path.join(reportDir, "report.json"))}`);
console.log(`PASS ${summary.pass} · FAIL ${summary.fail} · SKIP ${summary.skip} · 未覆盖章节 ${notCovered.length}`);
if (summary.fail > 0) process.exit(1);
if (summary.blocked > 0) process.exit(2);
process.exit(0);
}
main().catch((error) => { console.error(error); process.exit(2); });