#!/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) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[character])); const rows = report.cases.map((item) => `
${escape(item.error)}` : ""}未覆盖章节:${report.summary.notCovered.map(escape).join(", ")}
` : ""; return `| 检查 | 结果 | 详情 |
|---|---|---|
| ${escape(item.name)} | ${item.ok ? "OK" : "FAIL"} | ${escape(typeof item.detail === "object" ? JSON.stringify(item.detail) : item.detail)} |
| 编号 | 用例 | 状态 | 耗时 | 错误 |
|---|