feat(web): panel scroll contract, layout probe and functional suite
- lock the three-column height chain on workbench/PartDesign pages so each side panel scrolls independently and the centre stage keeps its size - dock module task panels above the layout with their own scrollbar instead of letting them push the stage out of the viewport - add tools/layout-probe.mjs (page scroll, aside bounds, pane scrolling, stage stability) and CLI mode for tools/static-host.mjs with relative --root support - add the P0-P4 browser functional suite, manual scenarios and capture tooling; document it under docs/current/web-functional-suite Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
96
tools/functional-suite/cases/chapters.mjs
Normal file
96
tools/functional-suite/cases/chapters.mjs
Normal file
@@ -0,0 +1,96 @@
|
||||
// P1 chapter cases: every manual scenario JSON runs through the same action
|
||||
// interpreter the screenshot capture tool uses, with per-action step evidence.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createActionRunner } from "../../../web/tools/manual/lib/actions.mjs";
|
||||
import { canvasHash, pageState, root } from "../runtime.mjs";
|
||||
|
||||
const SCENARIO_DIR = path.join(root, "web", "manual", "scenarios");
|
||||
// Chapters that import/export large fixtures or drive slow workers need a
|
||||
// longer ceiling than the 10-minute default.
|
||||
const TIMEOUT_OVERRIDES = { ch07: 900000, ch09: 900000, ch10: 900000, ch12: 900000 };
|
||||
|
||||
function group(actions) {
|
||||
const groups = [];
|
||||
let waits = [];
|
||||
for (const action of actions) {
|
||||
if (action.type === "wait") { waits.push(action); continue; }
|
||||
groups.push({ action, waits });
|
||||
waits = [];
|
||||
}
|
||||
if (waits.length) groups.push({ action: null, waits });
|
||||
return groups;
|
||||
}
|
||||
|
||||
function describe(action) {
|
||||
if (!action) return "等待渲染";
|
||||
switch (action.type) {
|
||||
case "goto": return `打开 ${action.url}`;
|
||||
case "click": return `点击 ${action.selector ?? `${action.role}:${action.name}`}`;
|
||||
case "fill": return `填写 ${action.selector}`;
|
||||
case "select": return `选择 ${action.selector}`;
|
||||
case "selectIndex": return `选择 ${action.selector}[${action.index}]`;
|
||||
case "press": return `按键 ${action.key}`;
|
||||
case "shot": return `截图 ${action.name}`;
|
||||
case "save": return "保存 FCStd 到 OPFS";
|
||||
case "seed": return `注入样例 ${action.name ?? path.basename(action.file)}`;
|
||||
case "eval": return "执行页面脚本";
|
||||
case "drag": return `拖拽 ${action.selector}`;
|
||||
case "clickCanvas": return `点击画布 ${action.selector}`;
|
||||
case "waitFor": return `等待 ${action.selector ?? action.text}`;
|
||||
case "waitOptions": return `等待选项 ${action.selector}`;
|
||||
default: return `${action.type} ${action.selector ?? action.contains ?? ""}`.trim();
|
||||
}
|
||||
}
|
||||
|
||||
function expected(action) {
|
||||
if (!action) return "页面稳定";
|
||||
if (action.type === "assertText" || action.type === "assertAnyText") return `文本包含「${action.contains}」`;
|
||||
if (action.type === "assertValue") return `值为 ${action.value}`;
|
||||
if (action.type === "assertVisible") return "元素可见";
|
||||
if (action.type === "shot") return "截图非空(>1KB)";
|
||||
if (action.type === "save") return "OPFS 出现新的 .FCStd";
|
||||
return "动作成功执行";
|
||||
}
|
||||
|
||||
function loadScenarios() {
|
||||
return fs.readdirSync(SCENARIO_DIR).filter(name => name.endsWith(".json")).sort().map(name => {
|
||||
const scenario = JSON.parse(fs.readFileSync(path.join(SCENARIO_DIR, name), "utf8"));
|
||||
return { file: name, scenario };
|
||||
});
|
||||
}
|
||||
|
||||
export const chapterCases = loadScenarios().map(({ file, scenario }) => ({
|
||||
id: `CH-${scenario.chapter}-${scenario.workflow}`,
|
||||
title: `${scenario.title ?? scenario.workflow}(${scenario.chapter})`,
|
||||
priority: "P1",
|
||||
executor: "scenario",
|
||||
module: null,
|
||||
source: `web/manual/scenarios/${file}`,
|
||||
timeoutMs: TIMEOUT_OVERRIDES[scenario.chapter] ?? 600000,
|
||||
async run({ page, origin, step, ctx, caseDir }) {
|
||||
const runner = createActionRunner(page, {
|
||||
origin,
|
||||
shotDir: path.join(caseDir, "shots"),
|
||||
shotPrefix: `${scenario.chapter}/${scenario.workflow}/`,
|
||||
});
|
||||
let index = 0;
|
||||
for (const { action, waits } of group(scenario.actions)) {
|
||||
index += 1;
|
||||
const label = action ? `${index}. ${describe(action)}` : `${index}. ${describe(null)}`;
|
||||
await step(label, expected(action), async () => {
|
||||
for (const wait of waits) await page.waitForTimeout(wait.ms ?? 500);
|
||||
if (action) await runner.run(action);
|
||||
return { type: action?.type ?? "wait", waits: waits.length };
|
||||
});
|
||||
}
|
||||
await step("章末后置断言", "无 pageerror、状态栏无 Error、画布可渲染", async () => {
|
||||
if (ctx.session.pageErrors.length) throw new Error(`page errors: ${JSON.stringify(ctx.session.pageErrors.slice(0, 3))}`);
|
||||
const state = await pageState(page);
|
||||
if (state.status && /^\s*Error:/.test(state.status)) throw new Error(`status bar reports ${state.status}`);
|
||||
const canvas = await canvasHash(page);
|
||||
if (canvas && canvas.bytes < 1024) throw new Error(`canvas screenshot too small: ${canvas.bytes}`);
|
||||
return { status: state.status, canvas: canvas ? { bytes: canvas.bytes, sha256: canvas.sha256 } : null };
|
||||
});
|
||||
},
|
||||
}));
|
||||
344
tools/functional-suite/cases/crosscut.mjs
Normal file
344
tools/functional-suite/cases/crosscut.mjs
Normal file
@@ -0,0 +1,344 @@
|
||||
// P3 cross-cutting cases: export formats, the OPFS contract, save/reopen and
|
||||
// error recovery. Each case prepares its own document from the project shell.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { assertNoPageErrors } from "../../ui-parity-preflight.mjs";
|
||||
import { canvasHash, openRoute, root, VIEWPORT } from "../runtime.mjs";
|
||||
import { closeStartDialog, closeTaskPanel, openFileMenu, waitCubeEnabled } from "./shell.mjs";
|
||||
|
||||
const fail = message => { throw new Error(message); };
|
||||
// storage.ts keeps the two OPFS contracts separate: geometry exports land in
|
||||
// freecad-exports, saved FCStd documents in freecad-documents.
|
||||
const EXPORTS = "freecad-exports";
|
||||
const DOCUMENTS = "freecad-documents";
|
||||
|
||||
async function listExports(page, dirName = EXPORTS) {
|
||||
return page.evaluate(async dirName => {
|
||||
const root = await navigator.storage.getDirectory();
|
||||
let dir;
|
||||
try { dir = await root.getDirectoryHandle(dirName); } catch { return []; }
|
||||
const out = [];
|
||||
for await (const [name, handle] of dir.entries()) {
|
||||
if (handle.kind !== "file") continue;
|
||||
const file = await handle.getFile();
|
||||
out.push({ name, size: file.size });
|
||||
}
|
||||
return out;
|
||||
}, dirName);
|
||||
}
|
||||
|
||||
async function readExport(page, name, dirName = EXPORTS) {
|
||||
return page.evaluate(async ([dirName, fileName]) => {
|
||||
const root = await navigator.storage.getDirectory();
|
||||
const dir = await root.getDirectoryHandle(dirName);
|
||||
const handle = await dir.getFileHandle(fileName);
|
||||
const file = await handle.getFile();
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
let hash = 0x811c9dc5;
|
||||
for (const byte of bytes) { hash ^= byte; hash = Math.imul(hash, 0x01000193) >>> 0; }
|
||||
return { size: bytes.length, hash, head: Array.from(bytes.slice(0, 16)) };
|
||||
}, [dirName, name]);
|
||||
}
|
||||
|
||||
// Export/save controls live inside a collapsed <details>; the shell's menu item
|
||||
// just sets .open, so the case does the same before touching them.
|
||||
async function openFileTools(page) {
|
||||
await page.evaluate(() => { const panel = document.querySelector("details.file-tools"); if (panel) panel.open = true; });
|
||||
await page.waitForTimeout(200);
|
||||
}
|
||||
|
||||
async function openProjectWithCube(page, origin) {
|
||||
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
|
||||
await closeStartDialog(page);
|
||||
const menu = await openFileMenu(page);
|
||||
await menu.locator("button.action", { hasText: "新建 Document" }).first().click();
|
||||
await waitCubeEnabled(page);
|
||||
await page.getByRole("toolbar", { name: "Solids" }).getByRole("button", { name: "Cube", exact: true }).click();
|
||||
await closeTaskPanel(page);
|
||||
await page.waitForFunction(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? "") > 0, null, { timeout: 120000 });
|
||||
const volume = await page.evaluate(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? ""));
|
||||
if (Math.abs(volume - 1000) > 1e-6) fail(`precondition: cube volume ${volume} != 1000`);
|
||||
await openFileTools(page);
|
||||
return { volume };
|
||||
}
|
||||
|
||||
async function selectCube(page) {
|
||||
// The export button only enables for a selected Part:: object.
|
||||
const disabled = await page.locator('button[aria-label="导出选中对象"]').isDisabled();
|
||||
if (disabled) await page.locator('[role="treeitem"]').first().click();
|
||||
await page.waitForTimeout(200);
|
||||
}
|
||||
|
||||
async function exportFormat(page, format) {
|
||||
const before = new Set((await listExports(page)).map(item => item.name));
|
||||
await page.locator('select[aria-label="Native export format"]').selectOption(format);
|
||||
await selectCube(page);
|
||||
await page.locator('button[aria-label="导出选中对象"]').click();
|
||||
const deadline = Date.now() + 120000;
|
||||
while (Date.now() < deadline) {
|
||||
const fresh = (await listExports(page)).filter(item => !before.has(item.name) && item.size > 0);
|
||||
if (fresh.length) return fresh[0];
|
||||
await page.waitForTimeout(400);
|
||||
}
|
||||
throw new Error(`export ${format} produced no OPFS file within 120 s`);
|
||||
}
|
||||
|
||||
export const crosscutCases = [
|
||||
{
|
||||
id: "X-export-formats",
|
||||
title: "五种导出格式全部落 OPFS 且字节非空",
|
||||
priority: "P3",
|
||||
executor: "functional",
|
||||
source: "manual ch07 / OPFS 铁律",
|
||||
timeoutMs: 600000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("准备:新建文档并创建 Cube", "体积 1000 mm³", async () => openProjectWithCube(page, origin));
|
||||
const formats = [["stl", /\.stl$/i], ["step", /\.(step|stp)$/i], ["iges", /\.(iges|igs)$/i], ["brep", /\.(brep|brp)$/i], ["glb", /\.glb$/i]];
|
||||
for (const [format, pattern] of formats) {
|
||||
await step(`导出 ${format.toUpperCase()} 到 OPFS`, `freecad-exports 出现匹配 ${pattern} 的非空文件`, async () => {
|
||||
const file = await exportFormat(page, format);
|
||||
if (!pattern.test(file.name)) fail(`${format} export produced ${file.name}`);
|
||||
return file;
|
||||
});
|
||||
}
|
||||
await step("全程未触发浏览器下载", "downloads 目录为空(下载必须显式)", async () => {
|
||||
const downloads = path.join(ctx.output, "downloads");
|
||||
const files = fs.existsSync(downloads) ? fs.readdirSync(downloads) : [];
|
||||
if (files.length) fail(`unexpected downloads: ${files.join(", ")}`);
|
||||
return { downloads: 0 };
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "X-opfs-roundtrip",
|
||||
title: "FCStd 保存到 OPFS、列目录、回读哈希一致",
|
||||
priority: "P3",
|
||||
executor: "functional",
|
||||
source: "manual ch15 / storage.ts 契约",
|
||||
timeoutMs: 300000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("准备:新建文档并创建 Cube", "体积 1000 mm³", async () => openProjectWithCube(page, origin));
|
||||
await step("保存 FCStd 到 OPFS", "freecad-documents 出现 .FCStd 文件", async () => {
|
||||
const before = new Set((await listExports(page, DOCUMENTS)).map(item => item.name));
|
||||
await page.getByRole("button", { name: "保存 FCStd 到 OPFS" }).click();
|
||||
const deadline = Date.now() + 120000;
|
||||
while (Date.now() < deadline) {
|
||||
const fresh = (await listExports(page, DOCUMENTS)).filter(item => !before.has(item.name) && /\.fcstd$/i.test(item.name));
|
||||
if (fresh.length) return fresh[0];
|
||||
await page.waitForTimeout(400);
|
||||
}
|
||||
const present = (await listExports(page, DOCUMENTS)).map(item => item.name);
|
||||
throw new Error(`save produced no .FCStd file in OPFS within 120 s; freecad-documents=[${present.join(", ")}]`);
|
||||
});
|
||||
await step("OPFS 文档下拉列出该文件", "select[aria-label=\"OPFS document\"] 含保存项", async () => {
|
||||
const options = await page.locator('select[aria-label="OPFS document"] option').evaluateAll(nodes => nodes.map(node => node.value).filter(Boolean));
|
||||
const saved = (await listExports(page, DOCUMENTS)).find(item => /\.fcstd$/i.test(item.name));
|
||||
if (!saved) fail("no .FCStd file to verify");
|
||||
if (!options.includes(saved.name)) fail(`OPFS document select missing ${saved.name}: ${JSON.stringify(options)}`);
|
||||
return { saved: saved.name, options };
|
||||
});
|
||||
await step("两次回读哈希一致", "FNV 哈希与字节长度稳定", async () => {
|
||||
const saved = (await listExports(page, DOCUMENTS)).find(item => /\.fcstd$/i.test(item.name));
|
||||
const first = await readExport(page, saved.name, DOCUMENTS);
|
||||
const second = await readExport(page, saved.name, DOCUMENTS);
|
||||
if (second.size !== first.size || second.hash !== first.hash) fail(`unstable readback: ${first.size}/${first.hash} vs ${second.size}/${second.hash}`);
|
||||
if (!(first.size > 0)) fail("saved FCStd is empty");
|
||||
return first;
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "X-save-reopen",
|
||||
title: "保存后刷新页面可从 OPFS 重新打开文档",
|
||||
priority: "P3",
|
||||
executor: "functional",
|
||||
source: "manual ch15 / OPFS 铁律",
|
||||
timeoutMs: 360000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("准备:新建文档、创建 Cube 并保存", "体积 1000 mm³ 且 OPFS 中存在 .FCStd", async () => {
|
||||
await openProjectWithCube(page, origin);
|
||||
const before = new Set((await listExports(page, DOCUMENTS)).map(item => item.name));
|
||||
await page.getByRole("button", { name: "保存 FCStd 到 OPFS" }).click();
|
||||
const deadline = Date.now() + 120000;
|
||||
while (Date.now() < deadline) {
|
||||
const fresh = (await listExports(page, DOCUMENTS)).filter(item => !before.has(item.name) && /\.fcstd$/i.test(item.name));
|
||||
if (fresh.length) return fresh[0];
|
||||
await page.waitForTimeout(400);
|
||||
}
|
||||
throw new Error("save produced no .FCStd file within 120 s");
|
||||
});
|
||||
await step("刷新后从 OPFS 重新打开", "文档树恢复且体积回到 1000 mm³", async () => {
|
||||
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
|
||||
await closeStartDialog(page);
|
||||
await openFileTools(page);
|
||||
const saved = (await listExports(page, DOCUMENTS)).find(item => /\.fcstd$/i.test(item.name));
|
||||
if (!saved) fail("OPFS lost the saved document across reload");
|
||||
await page.locator('select[aria-label="OPFS document"]').selectOption(saved.name);
|
||||
await page.getByRole("button", { name: "打开 OPFS 文档" }).click();
|
||||
await page.waitForFunction(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? "") > 0, null, { timeout: 180000 });
|
||||
const volume = await page.evaluate(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? ""));
|
||||
const tree = await page.evaluate(() => [...document.querySelectorAll('[role="treeitem"]')].map(node => node.textContent.trim()));
|
||||
if (!tree.length) fail("document tree empty after reopen");
|
||||
if (Math.abs(volume - 1000) > 1e-6) fail(`reopened volume ${volume} != 1000`);
|
||||
return { volume, tree: tree.slice(0, 5) };
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "X-error-recovery",
|
||||
title: "导入损坏 STEP 报错且文档保持完好",
|
||||
priority: "P3",
|
||||
executor: "functional",
|
||||
source: "manual ch07 / 错误恢复",
|
||||
timeoutMs: 300000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("准备:新建文档并创建 Cube", "体积 1000 mm³", async () => openProjectWithCube(page, origin));
|
||||
await step("导入损坏的 STEP 文件", "状态栏报告失败且体积仍为 1000 mm³", async () => {
|
||||
const input = page.locator('input[aria-label="Import JT, PLMXML, STEPZ, 3MF or shape files"]');
|
||||
await input.setInputFiles({ name: "broken.step", mimeType: "text/plain", buffer: Buffer.from("ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=CARTESIAN_POINT('',(0,0));\nENDSEC;\nEND-ISO-10303-21;\n") });
|
||||
await page.waitForFunction(() => {
|
||||
const status = document.querySelector(".desktop-status-bar [role=status]")?.textContent ?? "";
|
||||
return /fail|error|失败|不支持|无法|invalid/i.test(status);
|
||||
}, null, { timeout: 120000 });
|
||||
const status = await page.evaluate(() => document.querySelector(".desktop-status-bar [role=status]")?.textContent ?? "");
|
||||
const volume = await page.evaluate(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? ""));
|
||||
if (!(Math.abs(volume - 1000) < 1e-6)) fail(`document changed after failed import: volume ${volume}`);
|
||||
return { status: status.slice(0, 160), volume };
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "X-viewport",
|
||||
title: "工程页与工作台页均无横向溢出且画布在视口内",
|
||||
priority: "P3",
|
||||
executor: "functional",
|
||||
source: "manual ch01",
|
||||
timeoutMs: 180000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("工程页无横向溢出", "scrollWidth 不超过 clientWidth", async () => {
|
||||
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
|
||||
const metrics = await page.evaluate(() => ({ scrollWidth: document.scrollingElement.scrollWidth, clientWidth: document.scrollingElement.clientWidth, viewport: innerWidth }));
|
||||
if (metrics.scrollWidth > metrics.clientWidth + 1) fail(`project page overflows: ${metrics.scrollWidth} > ${metrics.clientWidth}`);
|
||||
if (metrics.viewport !== VIEWPORT.width) fail(`viewport ${metrics.viewport} != ${VIEWPORT.width}`);
|
||||
return metrics;
|
||||
});
|
||||
await step("画布哈希可采样", "canvas 至少 1024 字节", async () => {
|
||||
const hash = await canvasHash(page);
|
||||
if (!hash || hash.bytes < 1024) fail(`canvas hash too small: ${JSON.stringify(hash)}`);
|
||||
return hash;
|
||||
});
|
||||
await step("工作台页无横向溢出", "workbench scrollWidth 不超过 clientWidth", async () => {
|
||||
await openRoute(page, { origin }, "/workbench.html?module=Part");
|
||||
const metrics = await page.evaluate(() => ({ scrollWidth: document.scrollingElement.scrollWidth, clientWidth: document.scrollingElement.clientWidth }));
|
||||
if (metrics.scrollWidth > metrics.clientWidth + 1) fail(`workbench overflows: ${metrics.scrollWidth} > ${metrics.clientWidth}`);
|
||||
return metrics;
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "X-panel-scroll",
|
||||
title: "所有页面三栏布局的左右面板独立滚动且中间舞台不动",
|
||||
priority: "P3",
|
||||
executor: "functional",
|
||||
source: "布局需求:左右面板各自滚动,三维视口保持可见",
|
||||
timeoutMs: 300000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
// Injects a tall spacer into every side-pane scroller, so overflow is a
|
||||
// property of the layout rather than of whatever content happens to be
|
||||
// loaded; then scrolls both panes and checks the centre stage did not move.
|
||||
const probe = () => page.evaluate(() => {
|
||||
const layout = document.querySelector(".layout, .design-layout");
|
||||
const asides = layout ? [...layout.querySelectorAll(":scope > aside")].filter(node => node.getClientRects().length) : [];
|
||||
const main = layout?.querySelector(":scope > main");
|
||||
const stageBefore = main?.getBoundingClientRect();
|
||||
const panes = [];
|
||||
const scrollers = [];
|
||||
asides.forEach((aside, index) => {
|
||||
const pane = aside.querySelector(":scope > .pane-scroll");
|
||||
const entry = { index, asideOverflow: getComputedStyle(aside).overflow, asideHeight: aside.clientHeight, asideBottom: Math.round(aside.getBoundingClientRect().bottom) };
|
||||
panes.push(entry);
|
||||
if (!pane) { entry.error = "missing .pane-scroll"; return; }
|
||||
const spacer = document.createElement("div");
|
||||
spacer.style.height = "2000px";
|
||||
pane.appendChild(spacer);
|
||||
entry.overflowY = getComputedStyle(pane).overflowY;
|
||||
entry.clientHeight = pane.clientHeight;
|
||||
entry.scrollHeight = pane.scrollHeight;
|
||||
scrollers.push(pane);
|
||||
});
|
||||
for (const pane of scrollers) pane.scrollTop = 400;
|
||||
const stageAfter = main?.getBoundingClientRect();
|
||||
for (const pane of scrollers) { const spacer = pane.lastElementChild; if (spacer?.style.height === "2000px") spacer.remove(); }
|
||||
return {
|
||||
hasLayout: Boolean(layout), asideCount: asides.length, panes,
|
||||
viewportHeight: innerHeight,
|
||||
docScrollHeight: document.scrollingElement?.scrollHeight ?? 0,
|
||||
stageShift: stageBefore && stageAfter
|
||||
? Math.abs(stageAfter.top - stageBefore.top) + Math.abs(stageAfter.height - stageBefore.height) : null,
|
||||
};
|
||||
});
|
||||
const verify = (label, metrics) => {
|
||||
if (!metrics.hasLayout) fail(`${label}: three-column layout missing`);
|
||||
if (metrics.asideCount !== 2) fail(`${label}: expected 2 side panels, found ${metrics.asideCount}`);
|
||||
for (const pane of metrics.panes) {
|
||||
if (pane.error) fail(`${label}: side panel ${pane.index} ${pane.error}`);
|
||||
if (pane.overflowY !== "auto") fail(`${label}: side panel ${pane.index} overflow-y ${pane.overflowY}`);
|
||||
if (!(pane.scrollHeight > pane.clientHeight + 1)) fail(`${label}: side panel ${pane.index} does not scroll (${pane.scrollHeight} <= ${pane.clientHeight})`);
|
||||
if (pane.asideOverflow !== "hidden") fail(`${label}: side panel ${pane.index} overflow ${pane.asideOverflow}`);
|
||||
if (pane.asideBottom > metrics.viewportHeight + 1) fail(`${label}: side panel ${pane.index} bottom ${pane.asideBottom} exceeds viewport ${metrics.viewportHeight}`);
|
||||
}
|
||||
if (metrics.docScrollHeight > metrics.viewportHeight + 1) fail(`${label}: page still scrolls (${metrics.docScrollHeight} > ${metrics.viewportHeight})`);
|
||||
if (metrics.stageShift === null || metrics.stageShift > 1) fail(`${label}: centre stage moved while scrolling panels (${metrics.stageShift})`);
|
||||
};
|
||||
await step("工程页左右面板独立滚动", "两个 aside 各自滚动,整页不滚动,舞台不动", async () => {
|
||||
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
|
||||
await page.waitForSelector(".layout > aside");
|
||||
const metrics = await probe();
|
||||
verify("project.html", metrics);
|
||||
return metrics;
|
||||
});
|
||||
await step("PartDesign 页左右面板独立滚动", "树面板与属性面板各自滚动,视口不动", async () => {
|
||||
await openRoute(page, { origin }, "/partdesign.html");
|
||||
await page.waitForSelector(".design-layout > aside");
|
||||
const metrics = await probe();
|
||||
verify("partdesign.html", metrics);
|
||||
return metrics;
|
||||
});
|
||||
await step("全部工作台模块三栏独立滚动", "每个 module 页两个面板均可滚动", async () => {
|
||||
const registry = JSON.parse(fs.readFileSync(path.join(root, "docs", "current", "feature-capability-registry.json"), "utf8"));
|
||||
const modules = registry.modules.map(meta => meta.module);
|
||||
const checked = [];
|
||||
const failures = [];
|
||||
for (const name of modules) {
|
||||
await openRoute(page, { origin }, `/workbench.html?module=${encodeURIComponent(name)}`);
|
||||
await page.waitForSelector(".layout > aside");
|
||||
const metrics = await probe();
|
||||
try { verify(`workbench:${name}`, metrics); checked.push(name); }
|
||||
catch (error) { failures.push(String(error.message ?? error)); }
|
||||
}
|
||||
if (failures.length) fail(`${failures.length}/${modules.length} module layouts failed: ${failures.slice(0, 5).join(" | ")}`);
|
||||
return { modules: checked.length };
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
];
|
||||
96
tools/functional-suite/cases/handwritten.mjs
Normal file
96
tools/functional-suite/cases/handwritten.mjs
Normal file
@@ -0,0 +1,96 @@
|
||||
// Hand-written chapter cases for the chapters that ship no scenario JSON.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { dismissStartWorkspace, openRoute, root } from "../runtime.mjs";
|
||||
import { runCommand, selectModule } from "./modules.mjs";
|
||||
|
||||
const COURSE = path.join(root, "web", "tools", "line-course");
|
||||
const MEDIA = path.join(root, "web", "teaching", "media", "line-course");
|
||||
|
||||
export const handwrittenCases = [
|
||||
{
|
||||
id: "CH-ch14-production-line",
|
||||
title: "生产线课程:规格表、收口证据与媒体资产",
|
||||
priority: "P1",
|
||||
executor: "assets",
|
||||
source: "web/manual/content/ch14-production-line.md",
|
||||
timeoutMs: 60000,
|
||||
async run({ step }) {
|
||||
await step("line-spec 规格表可解析", "27 个模型 / 88 个部件 / 三角面 > 0 / 6 分量包围盒", async () => {
|
||||
const spec = JSON.parse(fs.readFileSync(path.join(COURSE, "line-spec.json"), "utf8"));
|
||||
const bbox = spec.sceneBBox;
|
||||
if (spec.modelCount !== 27) throw new Error(`modelCount ${spec.modelCount} != 27`);
|
||||
if (spec.partCount !== 88) throw new Error(`partCount ${spec.partCount} != 88`);
|
||||
if (!(spec.triangleCount > 0)) throw new Error(`triangleCount ${spec.triangleCount} is not positive`);
|
||||
if (!Array.isArray(bbox) || bbox.length !== 6 || !bbox.every(value => typeof value === "number" && Number.isFinite(value))) throw new Error(`sceneBBox is not 6 finite numbers: ${JSON.stringify(bbox)}`);
|
||||
return { modelCount: spec.modelCount, partCount: spec.partCount, triangleCount: spec.triangleCount, bbox };
|
||||
});
|
||||
await step("收口证据可解析", "final-status.json 含 state 与 knownBoundaries", async () => {
|
||||
const status = JSON.parse(fs.readFileSync(path.join(COURSE, "evidence", "final-status.json"), "utf8"));
|
||||
if (!status.state) throw new Error("final-status.json has no state");
|
||||
if (!("knownBoundaries" in status)) throw new Error("final-status.json has no knownBoundaries");
|
||||
return { state: status.state, keys: Object.keys(status).length };
|
||||
});
|
||||
await step("媒体目录非空", "至少一集视频或截图", async () => {
|
||||
const count = fs.readdirSync(MEDIA).length;
|
||||
if (count < 1) throw new Error("media directory is empty");
|
||||
return { files: count };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "CH-ch15-help-start",
|
||||
title: "帮助、命令面板、偏好与快捷键(第 15 章)",
|
||||
priority: "P1",
|
||||
executor: "functional",
|
||||
source: "web/manual/content/ch15-help-start.md",
|
||||
timeoutMs: 240000,
|
||||
async run({ page, origin, step }) {
|
||||
await step("Help 工作台源码清点可执行", "help.inspectSourceInventory 返回 kind=result", async () => {
|
||||
await openRoute(page, { origin }, "/workbench.html?module=Help");
|
||||
await dismissStartWorkspace(page);
|
||||
await selectModule(page, "Help");
|
||||
const response = await runCommand(page, "help.inspectSourceInventory");
|
||||
if (response?.kind !== "result") throw new Error(`help.inspectSourceInventory: ${JSON.stringify(response?.error ?? response).slice(0, 240)}`);
|
||||
return { kind: response.kind };
|
||||
});
|
||||
await step("Ctrl+K 打开命令面板并检索到命令", "面板可见且 Part_Box 出现在结果中", async () => {
|
||||
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
|
||||
await page.keyboard.press("Control+k");
|
||||
const palette = page.locator('[role="dialog"][aria-label="Command palette"]');
|
||||
await palette.waitFor({ state: "visible", timeout: 15000 });
|
||||
await palette.getByLabel("Search commands").fill("Part_Box");
|
||||
const hit = palette.locator("button", { has: page.locator("code", { hasText: "Part_Box" }) }).first();
|
||||
await hit.waitFor({ state: "visible", timeout: 15000 });
|
||||
await palette.getByLabel("Close command palette").click();
|
||||
await palette.waitFor({ state: "detached", timeout: 10000 });
|
||||
return { palette: "opened", match: (await hit.count()) > 0 };
|
||||
});
|
||||
await step("偏好对话框可从 Tools 菜单打开", "Preferences 对话框含单位/主题控件", async () => {
|
||||
await page.locator(".utility-menus > button", { hasText: "Tools" }).first().click();
|
||||
await page.locator('[role="menu"][aria-label="Tools"] button', { hasText: "Preferences…" }).click();
|
||||
const dialog = page.locator('[role="dialog"][aria-label="Preferences"]');
|
||||
await dialog.waitFor({ state: "visible", timeout: 15000 });
|
||||
const units = await dialog.getByLabel("Unit system").count();
|
||||
const theme = await dialog.getByLabel("Theme").count();
|
||||
if (!units || !theme) throw new Error(`preferences controls missing: units=${units} theme=${theme}`);
|
||||
await dialog.getByLabel("Close preferences").click();
|
||||
await dialog.waitFor({ state: "detached", timeout: 10000 });
|
||||
return { units, theme };
|
||||
});
|
||||
await step("快捷键管理器可从 Tools 菜单打开", "Customize shortcuts 对话框可搜索命令", async () => {
|
||||
await page.locator(".utility-menus > button", { hasText: "Tools" }).first().click();
|
||||
await page.locator('[role="menu"][aria-label="Tools"] button', { hasText: "Customize shortcuts…" }).click();
|
||||
const dialog = page.locator('[role="dialog"][aria-label="Customize shortcuts"]');
|
||||
await dialog.waitFor({ state: "visible", timeout: 15000 });
|
||||
await dialog.getByLabel("Search shortcuts").fill("Part_Box");
|
||||
await page.waitForTimeout(300);
|
||||
const rows = await dialog.locator("tbody tr").count();
|
||||
if (!rows) throw new Error("shortcut search returned no rows for Part_Box");
|
||||
await dialog.getByLabel("Close shortcut editor").click();
|
||||
await dialog.waitFor({ state: "detached", timeout: 10000 });
|
||||
return { rows };
|
||||
});
|
||||
},
|
||||
},
|
||||
];
|
||||
12
tools/functional-suite/cases/index.mjs
Normal file
12
tools/functional-suite/cases/index.mjs
Normal file
@@ -0,0 +1,12 @@
|
||||
// Case registry. Cross-cutting cases register here as they land.
|
||||
import { chapterCases } from "./chapters.mjs";
|
||||
import { crosscutCases } from "./crosscut.mjs";
|
||||
import { handwrittenCases } from "./handwritten.mjs";
|
||||
import { moduleCases } from "./modules.mjs";
|
||||
import { shellCases } from "./shell.mjs";
|
||||
|
||||
export const CASE_LAYERS = { shell: shellCases, chapters: [...chapterCases, ...handwrittenCases], modules: moduleCases, crosscut: crosscutCases };
|
||||
|
||||
export function allCases() {
|
||||
return [...CASE_LAYERS.shell, ...CASE_LAYERS.chapters, ...CASE_LAYERS.modules, ...CASE_LAYERS.crosscut];
|
||||
}
|
||||
112
tools/functional-suite/cases/modules.mjs
Normal file
112
tools/functional-suite/cases/modules.mjs
Normal file
@@ -0,0 +1,112 @@
|
||||
// P2 module smoke: every registered module must load its shell, expose its
|
||||
// command surface and answer one canonical worker command.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { root } from "../runtime.mjs";
|
||||
import { blockedPrecondition } from "../gap-ledger.mjs";
|
||||
import { dismissStartWorkspace, openRoute } from "../runtime.mjs";
|
||||
|
||||
const REGISTRY = path.join(root, "docs", "current", "feature-capability-registry.json");
|
||||
// Web FreeCAD ships without OpenSCAD (project iron rule) and AddonManager has no
|
||||
// interactive command, so neither is a functional module under test here.
|
||||
const SKIP = new Set(["OpenSCAD", "AddonManager"]);
|
||||
// Read-only commands come first: they exercise worker + registry without
|
||||
// depending on selection state or parameters, so a failure means the module
|
||||
// really is broken rather than under-specified by the smoke.
|
||||
const PREFERRED_SUFFIXES = ["inspectSourceInventory", "inspectPythonApi", "inspectRegistry", "pythonApi", "measurementApi", "navigationBoundary", "serverContract", "createRecompute"];
|
||||
// The Web module has no worker route for serverContract (browser-native module);
|
||||
// its persistence boundary command is the one that actually dispatches.
|
||||
const CANONICAL_OVERRIDES = { Web: "web.saveReopenBoundary" };
|
||||
|
||||
function loadModules() {
|
||||
const registry = JSON.parse(fs.readFileSync(REGISTRY, "utf8"));
|
||||
const byModule = new Map();
|
||||
for (const record of registry.records) {
|
||||
if (!byModule.has(record.module)) byModule.set(record.module, []);
|
||||
byModule.get(record.module).push(record);
|
||||
}
|
||||
const modules = [];
|
||||
for (const meta of registry.modules) {
|
||||
if (SKIP.has(meta.module)) continue;
|
||||
const records = byModule.get(meta.module) ?? [];
|
||||
const interactive = records.filter(record => record.uiStatus === "interactive" && record.implementationStatus === "routed");
|
||||
const override = CANONICAL_OVERRIDES[meta.module];
|
||||
const canonical = (override ? interactive.find(record => record.command === override) : null)
|
||||
?? PREFERRED_SUFFIXES.map(suffix => interactive.find(record => record.command.endsWith(suffix))).find(Boolean)
|
||||
?? interactive[0] ?? null;
|
||||
modules.push({ name: meta.module, interactive: interactive.length, canonical: canonical?.command ?? null });
|
||||
}
|
||||
return modules;
|
||||
}
|
||||
|
||||
export const MODULES = loadModules();
|
||||
|
||||
const escapeRe = text => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
|
||||
export async function selectModule(page, name) {
|
||||
// Anchor the match: "Part" is a substring of "MeshPart" and "PartDesign".
|
||||
const exact = new RegExp(`^\\s*${escapeRe(name)}\\s*$`);
|
||||
const button = page.locator("button.module").filter({ has: page.locator("strong", { hasText: exact }) }).first();
|
||||
if (!(await button.count())) throw blockedPrecondition("entry", `module ${name} is not exposed in the module dock`);
|
||||
await button.click();
|
||||
// Module labels are capitalised ("Assembly") while command ids are lowercase
|
||||
// ("assembly.createRecompute"), so compare case-insensitively.
|
||||
await page.waitForFunction(expected => [...document.querySelectorAll("button.command span")].some(span => String(span.textContent).toLowerCase().startsWith(`${expected}.`)), name.toLowerCase(), { timeout: 60000 });
|
||||
}
|
||||
|
||||
export async function runCommand(page, name) {
|
||||
const exact = new RegExp(`^\\s*${escapeRe(name)}\\s*$`);
|
||||
const command = page.locator("button.command").filter({ has: page.locator("span", { hasText: exact }) }).first();
|
||||
await command.waitFor({ state: "visible", timeout: 60000 });
|
||||
await command.click();
|
||||
// The panel prefills the payload the worker expects; overwriting it with "{}"
|
||||
// is what makes an otherwise valid command fail with invalid_request.
|
||||
const args = page.getByLabel("命令 JSON 参数");
|
||||
let payload = "";
|
||||
if (await args.count()) {
|
||||
payload = (await args.inputValue()).trim();
|
||||
if (!payload) { payload = "{}"; await args.fill(payload); }
|
||||
}
|
||||
const run = page.getByRole("button", { name: "执行选中命令", exact: true });
|
||||
await run.waitFor({ state: "visible", timeout: 30000 });
|
||||
await run.click();
|
||||
await page.waitForFunction(() => window.__freecadWorkbenchState?.response?.kind === "result" || window.__freecadWorkbenchState?.response?.kind === "error", null, { timeout: 180000 });
|
||||
return page.evaluate(() => window.__freecadWorkbenchState.response);
|
||||
}
|
||||
|
||||
export const moduleCases = MODULES.map(meta => ({
|
||||
id: `MOD-${meta.name}-01`,
|
||||
title: `${meta.name} 模块冒烟:壳层、命令面与规范动作`,
|
||||
priority: "P2",
|
||||
executor: "functional",
|
||||
module: meta.name,
|
||||
source: "feature-capability-registry.json",
|
||||
timeoutMs: 240000,
|
||||
async run({ page, origin, step }) {
|
||||
await step("打开模块工作台", "模块壳层挂载且隔离头生效", async () => {
|
||||
const isolation = await openRoute(page, { origin }, `/workbench.html?module=${encodeURIComponent(meta.name)}`);
|
||||
await dismissStartWorkspace(page);
|
||||
return isolation;
|
||||
});
|
||||
await step(`${meta.name} 模块在模块坞中可选中`, "button.module 存在且被选中", async () => {
|
||||
await selectModule(page, meta.name);
|
||||
const selected = await page.evaluate(() => document.querySelector("button.module[aria-current], button.module.selected")?.textContent?.trim().slice(0, 40) ?? null);
|
||||
return { module: meta.name, selected };
|
||||
});
|
||||
await step("命令面已注册", "该模块至少注册一条命令", async () => {
|
||||
await page.waitForFunction(() => document.querySelectorAll("button.command").length > 0, null, { timeout: 60000 });
|
||||
const count = await page.locator("button.command").count();
|
||||
if (count < 1) throw new Error(`${meta.name} exposes no commands`);
|
||||
return { commands: count, registered: meta.interactive };
|
||||
});
|
||||
if (!meta.canonical) throw blockedPrecondition("command-state", `${meta.name} has no interactive routed command`);
|
||||
await step(`规范动作 ${meta.canonical}`, "原生返回 kind=result 且无 sceneError", async () => {
|
||||
const response = await runCommand(page, meta.canonical);
|
||||
if (response?.kind === "error") throw new Error(`command error: ${JSON.stringify(response.error).slice(0, 300)}`);
|
||||
const row = response?.result?.records?.[0];
|
||||
const result = row?.result ?? response?.result;
|
||||
if (result?.sceneError) throw new Error(`scene refresh failed: ${result.sceneError}`);
|
||||
return { kind: response?.kind, command: meta.canonical, hasRow: Boolean(row) };
|
||||
});
|
||||
},
|
||||
}));
|
||||
202
tools/functional-suite/cases/shell.mjs
Normal file
202
tools/functional-suite/cases/shell.mjs
Normal file
@@ -0,0 +1,202 @@
|
||||
// P0 shell cases: entry/isolation, project shell, first document, OPFS contract,
|
||||
// viewport and canvas. These are the preconditions every later case builds on.
|
||||
import { assertNoPageErrors, prepareProjectShell, prepareWorkbenchShell } from "../../ui-parity-preflight.mjs";
|
||||
import { VIEWPORT, canvasHash, dismissStartWorkspace, openRoute, pageState } from "../runtime.mjs";
|
||||
|
||||
const fail = message => { throw new Error(message); };
|
||||
|
||||
export async function waitCubeEnabled(page, timeout = 120000) {
|
||||
await page.waitForFunction(() => {
|
||||
const toolbar = document.querySelector('[role="toolbar"][aria-label="Solids"]');
|
||||
const button = toolbar ? [...toolbar.querySelectorAll("button")].find(node => node.getAttribute("aria-label") === "Cube") : undefined;
|
||||
return Boolean(button && !button.disabled);
|
||||
}, null, { timeout });
|
||||
}
|
||||
|
||||
// The application menu is a <details>/<summary> list, so the item buttons are
|
||||
// not visible until their own menu is opened — role locators never match them.
|
||||
export async function openFileMenu(page) {
|
||||
const menu = page.locator("nav.application-menus details").filter({ has: page.locator("button.action", { hasText: "新建 Document" }) }).first();
|
||||
if (!(await menu.count())) fail("File menu not found");
|
||||
await menu.locator("summary").first().click();
|
||||
await page.waitForTimeout(200);
|
||||
return menu;
|
||||
}
|
||||
|
||||
export async function closeTaskPanel(page) {
|
||||
if (await page.locator('fieldset[aria-label="Task: Box dimensions"]').count()) await page.keyboard.press("Escape");
|
||||
await page.waitForTimeout(300);
|
||||
}
|
||||
|
||||
export async function closeStartDialog(page) {
|
||||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||||
if (await page.locator("dialog[open]").count()) { await page.keyboard.press("Escape"); await page.waitForTimeout(250); continue; }
|
||||
await page.waitForTimeout(300);
|
||||
if ((await page.locator("dialog[open]").count()) === 0) return;
|
||||
}
|
||||
}
|
||||
|
||||
export const shellCases = [
|
||||
{
|
||||
id: "SHELL-01",
|
||||
title: "入口、COOP/COEP 隔离与工作台壳层",
|
||||
priority: "P0",
|
||||
executor: "functional",
|
||||
source: "manual ch00/ch01",
|
||||
timeoutMs: 120000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("打开 Part 工作台并确认隔离头生效", "crossOriginIsolated 且 SharedArrayBuffer 可用", async () => {
|
||||
const isolation = await openRoute(page, { origin }, "/workbench.html?module=Part");
|
||||
return isolation;
|
||||
});
|
||||
await step("工作台壳层可见且无横向溢出", ".dock-workbench 可测量、在视口内", async () => {
|
||||
const { state } = await prepareWorkbenchShell(page, { origin, path: "/workbench.html?module=Part", viewport: VIEWPORT });
|
||||
return state;
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "SHELL-02",
|
||||
title: "工程壳层与 Start 对话框",
|
||||
priority: "P0",
|
||||
executor: "functional",
|
||||
source: "manual ch01",
|
||||
timeoutMs: 120000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("打开工程页并确认工具栏就绪", ".desktop-workspace 与 Solids 工具栏可见", async () => {
|
||||
const { state } = await prepareProjectShell(page, { origin, path: "/project.html", viewport: VIEWPORT, toolbarName: "Solids", minDropdowns: 0 });
|
||||
return state;
|
||||
});
|
||||
await step("Start 对话框可关闭且不拦截操作", "dialog[open] 数量为 0", async () => {
|
||||
await closeStartDialog(page);
|
||||
await dismissStartWorkspace(page);
|
||||
const open = await page.locator("dialog[open]").count();
|
||||
if (open) fail(`Start dialog still open: ${open}`);
|
||||
return { openDialogs: 0 };
|
||||
});
|
||||
await step("工具栏图标全部渲染", "img 均 complete 且 naturalWidth > 0", async () => {
|
||||
// SVG icons 404/sniff-blocked by a wrong static-host MIME show up here
|
||||
// as naturalWidth === 0 while still returning HTTP 200.
|
||||
const icons = await page.evaluate(() => ({ total: document.images.length, broken: [...document.images].filter(image => !image.complete || image.naturalWidth === 0).map(image => image.getAttribute("src")).slice(0, 10) }));
|
||||
if (!icons.total) fail("no icon images rendered");
|
||||
if (icons.broken.length) fail(`broken icons: ${icons.broken.join(", ")}`);
|
||||
return icons;
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "SHELL-03",
|
||||
title: "新建文档、创建 Cube 并显示体积",
|
||||
priority: "P0",
|
||||
executor: "functional",
|
||||
source: "manual ch01/ch02",
|
||||
timeoutMs: 240000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("关闭 Start 并新建 Document", "Solids/Cube 命令可用", async () => {
|
||||
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
|
||||
await closeStartDialog(page);
|
||||
const menu = await openFileMenu(page);
|
||||
await menu.locator("button.action", { hasText: "新建 Document" }).first().click();
|
||||
await waitCubeEnabled(page);
|
||||
await closeStartDialog(page);
|
||||
return { cubeEnabled: true };
|
||||
});
|
||||
await step("执行 Cube 命令", "文档树出现对象且体积为 1000 mm³(默认 10mm 立方体)", async () => {
|
||||
await waitCubeEnabled(page);
|
||||
await page.getByRole("toolbar", { name: "Solids" }).getByRole("button", { name: "Cube", exact: true }).click();
|
||||
await closeTaskPanel(page);
|
||||
await page.waitForFunction(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? "") > 0, null, { timeout: 120000 });
|
||||
const volume = await page.evaluate(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? ""));
|
||||
const tree = await page.evaluate(() => [...document.querySelectorAll('[role="treeitem"]')].map(node => node.textContent.trim()));
|
||||
if (tree.length < 1) fail("document tree is empty after Cube");
|
||||
if (Math.abs(volume - 1000) > 1e-6) fail(`volume ${volume} != 1000`);
|
||||
return { volume, tree: tree.slice(0, 5) };
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "SHELL-04",
|
||||
title: "OPFS 导出目录可写可读",
|
||||
priority: "P0",
|
||||
executor: "functional",
|
||||
source: "OPFS contract (web/src/storage.ts:67)",
|
||||
timeoutMs: 60000,
|
||||
async run({ page, origin, step }) {
|
||||
await step("进入同源页面", "应用挂载", async () => {
|
||||
await openRoute(page, { origin }, "/workbench.html?module=Part");
|
||||
return true;
|
||||
});
|
||||
await step("freecad-exports 目录写入、列出、回读、删除", "四步全部成功", async () => {
|
||||
const result = await page.evaluate(async () => {
|
||||
const name = `functional-suite-probe-${Date.now()}.txt`;
|
||||
const payload = new TextEncoder().encode("freecad-web-suite");
|
||||
const rootDir = await navigator.storage.getDirectory();
|
||||
const exportsDir = await rootDir.getDirectoryHandle("freecad-exports", { create: true });
|
||||
const handle = await exportsDir.getFileHandle(name, { create: true });
|
||||
const writer = await handle.createWritable();
|
||||
await writer.write(payload);
|
||||
await writer.close();
|
||||
const names = [];
|
||||
for await (const [entry] of exportsDir.entries()) names.push(entry);
|
||||
const text = await (await (await exportsDir.getFileHandle(name)).getFile()).text();
|
||||
await exportsDir.removeEntry(name);
|
||||
const after = [];
|
||||
for await (const [entry] of exportsDir.entries()) after.push(entry);
|
||||
return { bytes: payload.byteLength, listed: names.includes(name), text, removed: !after.includes(name) };
|
||||
});
|
||||
if (!result.listed) fail("probe file missing from listing");
|
||||
if (result.text !== "freecad-web-suite") fail(`read-back mismatch: ${result.text}`);
|
||||
if (!result.removed) fail("probe file was not removed");
|
||||
return result;
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "SHELL-05",
|
||||
title: "视口尺寸、画布与场景渲染",
|
||||
priority: "P0",
|
||||
executor: "functional",
|
||||
source: "manual ch01 viewport",
|
||||
timeoutMs: 120000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
// The 3D canvas lives in the project shell; the module shell only renders
|
||||
// the command browser (no canvas by design, verified in the DOM probe).
|
||||
await step("打开工程页并确认视口", "1440x1000 且无横向溢出", async () => {
|
||||
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
|
||||
const state = await page.evaluate(() => ({
|
||||
width: innerWidth, height: innerHeight,
|
||||
overflow: document.documentElement.scrollWidth > document.documentElement.clientWidth,
|
||||
}));
|
||||
if (state.width !== VIEWPORT.width || state.height !== VIEWPORT.height) fail(`viewport ${state.width}x${state.height}`);
|
||||
if (state.overflow) fail("horizontal overflow");
|
||||
return state;
|
||||
});
|
||||
await step("画布存在且有内容", "canvas 尺寸非零、截图 hash 非空", async () => {
|
||||
const canvases = await page.evaluate(() => [...document.querySelectorAll("canvas")].map(canvas => ({ width: canvas.width, height: canvas.height })));
|
||||
if (!canvases.length) fail("no canvas");
|
||||
if (!canvases.some(item => item.width > 0 && item.height > 0)) fail("canvas has zero size");
|
||||
const hash = await canvasHash(page);
|
||||
if (!hash || hash.bytes < 1024) fail(`canvas screenshot too small: ${hash?.bytes ?? 0}`);
|
||||
return { canvases, hash };
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export { pageState };
|
||||
83
tools/functional-suite/cli.mjs
Normal file
83
tools/functional-suite/cli.mjs
Normal file
@@ -0,0 +1,83 @@
|
||||
// CLI contract for the headed Web FreeCAD functional suite.
|
||||
// Every option has an env equivalent so CI wrappers can stay script-free.
|
||||
|
||||
export const USAGE = `Web FreeCAD functional suite (headed by default)
|
||||
|
||||
node tools/web-freecad-functional-suite.mjs [options]
|
||||
|
||||
--only <ids> comma separated case ids (e.g. SHELL-01,CH02-part)
|
||||
--priority <list> comma separated priorities: P0,P1,P2,P3 (default all)
|
||||
--module <list> comma separated module names for MOD-* cases
|
||||
--resume <dir> continue a previous run directory (skip completed ids)
|
||||
--force with --resume, re-run completed cases
|
||||
--headless hide the browser window (default is headed)
|
||||
--gpu drop swiftshader flags (manual perf observation only)
|
||||
--slow <ms> Playwright slowMo pacing for live observation
|
||||
--highlight outline the acted element before each action
|
||||
--screenshots <s> "fails" (default) or "all"
|
||||
--jobs <n> browser workers (1 = single headed window, default 1)
|
||||
--out <dir> evidence root (default docs/current/web-functional-suite)
|
||||
--prune <n> keep only the newest n run directories
|
||||
--legacy-ids <ids> also run tools/run_user_manual_tests.mjs ids (all = 53 cases)
|
||||
--timeout-scale <x> multiply per-case timeouts (default 1)
|
||||
|
||||
With no selection flags every non-legacy case runs.`;
|
||||
|
||||
const list = value => String(value ?? "").split(",").map(item => item.trim()).filter(Boolean);
|
||||
|
||||
export function parseArgs(argv = process.argv.slice(2)) {
|
||||
const options = {
|
||||
only: list(process.env.FREECAD_SUITE_ONLY),
|
||||
priority: list(process.env.FREECAD_SUITE_PRIORITY),
|
||||
module: list(process.env.FREECAD_SUITE_MODULE),
|
||||
resume: null, force: false,
|
||||
headless: process.env.HEADLESS === "1",
|
||||
gpu: false, slow: Number(process.env.FREECAD_SLOWMO ?? 0) || 0, highlight: false,
|
||||
screenshots: process.env.FREECAD_SUITE_SCREENSHOTS === "all" ? "all" : "fails",
|
||||
jobs: 1, out: null, prune: null, legacyIds: [], timeoutScale: 1,
|
||||
};
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const flag = argv[index];
|
||||
const value = () => argv[index + 1] ?? "";
|
||||
switch (flag) {
|
||||
case "--only": options.only = list(value()); index += 1; break;
|
||||
case "--priority": options.priority = list(value()).map(item => item.toUpperCase()); index += 1; break;
|
||||
case "--module": options.module = list(value()); index += 1; break;
|
||||
case "--resume": options.resume = value(); index += 1; break;
|
||||
case "--force": options.force = true; break;
|
||||
case "--headless": options.headless = true; break;
|
||||
case "--headed": options.headless = false; break;
|
||||
case "--gpu": options.gpu = true; break;
|
||||
case "--slow": options.slow = Number(value()) || 0; index += 1; break;
|
||||
case "--highlight": options.highlight = true; break;
|
||||
case "--screenshots": options.screenshots = value() === "all" ? "all" : "fails"; index += 1; break;
|
||||
case "--jobs": options.jobs = Math.max(1, Number(value()) || 1); index += 1; break;
|
||||
case "--out": options.out = value(); index += 1; break;
|
||||
case "--prune": options.prune = Math.max(1, Number(value()) || 1); index += 1; break;
|
||||
case "--legacy-ids": options.legacyIds = list(value()); index += 1; break;
|
||||
case "--timeout-scale": options.timeoutScale = Math.max(0.1, Number(value()) || 1); index += 1; break;
|
||||
case "--help": case "-h": options.help = true; break;
|
||||
default: throw new Error(`unknown option ${flag}\n\n${USAGE}`);
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
export function selectCases(cases, options) {
|
||||
let selected = cases;
|
||||
if (options.only.length) {
|
||||
const ids = new Set(options.only);
|
||||
selected = selected.filter(item => ids.has(item.id));
|
||||
const missing = [...ids].filter(id => !cases.some(item => item.id === id));
|
||||
if (missing.length) throw new Error(`unknown case ids: ${missing.join(", ")}`);
|
||||
}
|
||||
if (options.priority.length) {
|
||||
const priorities = new Set(options.priority);
|
||||
selected = selected.filter(item => priorities.has(item.priority));
|
||||
}
|
||||
if (options.module.length) {
|
||||
const modules = new Set(options.module.map(item => item.toLowerCase()));
|
||||
selected = selected.filter(item => !item.module || modules.has(item.module.toLowerCase()));
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
56
tools/functional-suite/executors/legacy.mjs
Normal file
56
tools/functional-suite/executors/legacy.mjs
Normal file
@@ -0,0 +1,56 @@
|
||||
// Runs the untouched manual runner (tools/run_user_manual_tests.mjs) as a child
|
||||
// process and folds its results into the functional-suite report as LEGACY-*.
|
||||
import { spawn } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { root } from "../runtime.mjs";
|
||||
import { persist } from "../report.mjs";
|
||||
|
||||
const MAP = {
|
||||
passed: { status: "passed", classification: "none", failureClass: null },
|
||||
blocked: { status: "blocked", classification: "precondition", failureClass: "fixture" },
|
||||
failed: { status: "failed", classification: "product-regression", failureClass: "product-regression" },
|
||||
};
|
||||
|
||||
export async function runLegacyCases(options, ctx) {
|
||||
const ids = options.legacyIds.includes("all") ? "" : options.legacyIds.join(",");
|
||||
const env = { ...process.env };
|
||||
if (ids) env.FREECAD_MANUAL_IDS = ids;
|
||||
const child = spawn(process.execPath, [path.join(root, "tools", "run_user_manual_tests.mjs")], {
|
||||
cwd: root, env, stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout.on("data", chunk => { stdout += chunk; process.stdout.write(chunk); });
|
||||
child.stderr.on("data", chunk => { stderr += chunk; });
|
||||
const code = await new Promise(resolve => child.on("close", resolve));
|
||||
|
||||
const lastJson = [...stdout.trim().split("\n")].reverse().find(line => line.startsWith("{") && line.includes('"output"'));
|
||||
if (!lastJson) {
|
||||
const message = `legacy runner exited ${code} without a result line: ${(stderr || stdout).slice(-400)}`;
|
||||
console.error(message);
|
||||
ctx.results.push({ id: "LEGACY-RUNNER", title: "Legacy manual runner", priority: "P4", executor: "legacy", status: "blocked", classification: "precondition", failureClass: "fixture", steps: [], seconds: 0, error: message, startedAt: new Date().toISOString(), artifacts: {} });
|
||||
persist(ctx);
|
||||
return [];
|
||||
}
|
||||
const { output: legacyDir } = JSON.parse(lastJson);
|
||||
const legacy = JSON.parse(fs.readFileSync(path.join(legacyDir, "results.json"), "utf8"));
|
||||
const imported = [];
|
||||
for (const item of legacy.results ?? []) {
|
||||
const mapped = MAP[item.status] ?? MAP.failed;
|
||||
const result = {
|
||||
id: `LEGACY-${item.id}`, title: item.title ?? item.id, priority: "P4", executor: "legacy",
|
||||
module: null, source: path.relative(root, legacyDir) + "/results.json",
|
||||
status: mapped.status, classification: mapped.classification, failureClass: mapped.failureClass,
|
||||
steps: item.steps ?? [], seconds: item.seconds ?? 0, error: item.error ?? null,
|
||||
startedAt: item.startedAt ?? null, artifacts: { legacy: path.relative(root, legacyDir) },
|
||||
};
|
||||
ctx.results.push(result);
|
||||
imported.push(result);
|
||||
if (mapped.status !== "passed") {
|
||||
ctx.gaps.push({ caseId: result.id, status: mapped.status, classification: mapped.classification, failureClass: mapped.failureClass, message: result.error ?? mapped.status, evidence: result.artifacts.legacy });
|
||||
}
|
||||
}
|
||||
persist(ctx);
|
||||
return imported;
|
||||
}
|
||||
61
tools/functional-suite/gap-ledger.mjs
Normal file
61
tools/functional-suite/gap-ledger.mjs
Normal file
@@ -0,0 +1,61 @@
|
||||
// Failure classification for the functional suite.
|
||||
// Precondition failures become `blocked`; product failures become `failed`.
|
||||
// The ledger keeps them separate so a blocked preflight never masks a regression.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { UiParityPreflightError } from "../ui-parity-preflight.mjs";
|
||||
|
||||
const PRECONDITION_CLASSES = new Set([
|
||||
"preview/port", "entry", "fixture", "viewport", "host/iframe", "command-state", "tool-observation",
|
||||
]);
|
||||
|
||||
export function classifyFailure(error) {
|
||||
if (error?.blocked === true) {
|
||||
return { status: "blocked", classification: "precondition", failureClass: error.failureClass ?? "fixture", message: String(error.message ?? error) };
|
||||
}
|
||||
if (error instanceof UiParityPreflightError) {
|
||||
const failureClass = error.failureClass;
|
||||
if (PRECONDITION_CLASSES.has(failureClass)) {
|
||||
return { status: "blocked", classification: "precondition", failureClass, message: error.message };
|
||||
}
|
||||
return { status: "failed", classification: "product-regression", failureClass, message: error.message };
|
||||
}
|
||||
// Plain assertion errors come from product steps; cases may mark a known
|
||||
// unimplemented capability as a product gap instead of a regression.
|
||||
if (error?.productGap === true) {
|
||||
return { status: "failed", classification: "product-gap", failureClass: "product-gap", message: String(error.message ?? error) };
|
||||
}
|
||||
return { status: "failed", classification: "product-regression", failureClass: "product-regression", message: String(error?.message ?? error) };
|
||||
}
|
||||
|
||||
export function blockedPrecondition(failureClass, message) {
|
||||
const error = new Error(message);
|
||||
error.blocked = true;
|
||||
error.failureClass = failureClass;
|
||||
return error;
|
||||
}
|
||||
|
||||
export function createGapLedger(file) {
|
||||
const entries = [];
|
||||
return {
|
||||
record(entry) {
|
||||
const row = { at: new Date().toISOString(), status: "open", ...entry };
|
||||
entries.push(row);
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.appendFileSync(file, `${JSON.stringify(row)}\n`);
|
||||
return row;
|
||||
},
|
||||
entries,
|
||||
};
|
||||
}
|
||||
|
||||
export function renderGapSections(entries) {
|
||||
const blocked = entries.filter(item => item.classification === "precondition");
|
||||
const product = entries.filter(item => item.classification !== "precondition");
|
||||
const line = item => `- \`${item.caseId}\` ${item.failureClass}: ${item.message.slice(0, 240)}${item.evidence ? ` — ${item.evidence}` : ""}`;
|
||||
return {
|
||||
blocked: blocked.length ? blocked.map(line).join("\n") : "- none",
|
||||
product: product.length ? product.map(line).join("\n") : "- none",
|
||||
counts: { blocked: blocked.length, product: product.length },
|
||||
};
|
||||
}
|
||||
126
tools/functional-suite/report.mjs
Normal file
126
tools/functional-suite/report.mjs
Normal file
@@ -0,0 +1,126 @@
|
||||
// Run artefacts: manifest, results, checkpoint, markdown/JUnit/HTML reports.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { renderGapSections } from "./gap-ledger.mjs";
|
||||
|
||||
const ISO_STAMP = () => new Date().toISOString().replace(/[:.]/g, "-");
|
||||
const esc = value => String(value ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
export function createRunContext({ options, root, output, origin }) {
|
||||
return {
|
||||
schema: "freecad-web/functional-suite/v1",
|
||||
root, output, origin,
|
||||
startedAt: new Date().toISOString(),
|
||||
updatedAt: null,
|
||||
options,
|
||||
results: [],
|
||||
gaps: [],
|
||||
counts: { passed: 0, failed: 0, blocked: 0, reference_only: 0, running: 0 },
|
||||
manifest: {},
|
||||
};
|
||||
}
|
||||
|
||||
export function newRunDir(base, resume) {
|
||||
if (resume) return path.resolve(resume);
|
||||
const dir = path.join(base, `run-${ISO_STAMP()}`);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
export function writeManifest(ctx, extra = {}) {
|
||||
ctx.manifest = {
|
||||
schema: "freecad-web/functional-suite-manifest/v1",
|
||||
generatedAt: new Date().toISOString(),
|
||||
origin: ctx.origin,
|
||||
platform: process.platform,
|
||||
node: process.version,
|
||||
display: process.env.DISPLAY ?? null,
|
||||
headless: ctx.options.headless,
|
||||
command: process.argv.join(" "),
|
||||
...extra,
|
||||
};
|
||||
fs.writeFileSync(path.join(ctx.output, "manifest.json"), `${JSON.stringify(ctx.manifest, null, 2)}\n`);
|
||||
}
|
||||
|
||||
export function recount(ctx) {
|
||||
const counts = { passed: 0, failed: 0, blocked: 0, reference_only: 0, running: 0 };
|
||||
for (const result of ctx.results) counts[result.status] = (counts[result.status] ?? 0) + 1;
|
||||
ctx.counts = counts;
|
||||
return counts;
|
||||
}
|
||||
|
||||
export function persist(ctx) {
|
||||
ctx.updatedAt = new Date().toISOString();
|
||||
recount(ctx);
|
||||
fs.writeFileSync(path.join(ctx.output, "results.json"), `${JSON.stringify({
|
||||
schema: ctx.schema, startedAt: ctx.startedAt, updatedAt: ctx.updatedAt, origin: ctx.origin,
|
||||
headless: ctx.options.headless, counts: ctx.counts, results: ctx.results,
|
||||
}, null, 2)}\n`);
|
||||
const completed = ctx.results.filter(item => item.status !== "running").map(item => ({ id: item.id, status: item.status, seconds: item.seconds }));
|
||||
fs.writeFileSync(path.join(ctx.output, "checkpoint.json"), `${JSON.stringify({
|
||||
schema: "freecad-web/functional-suite-checkpoint/v1", updatedAt: ctx.updatedAt,
|
||||
current: ctx.results.find(item => item.status === "running")?.id ?? null, completed,
|
||||
}, null, 2)}\n`);
|
||||
}
|
||||
|
||||
const statusCell = item => {
|
||||
if (item.status === "passed") return "passed";
|
||||
if (item.status === "blocked") return `blocked (${item.failureClass})`;
|
||||
return `${item.status} (${item.classification})`;
|
||||
};
|
||||
|
||||
export function writeMarkdown(ctx) {
|
||||
const gaps = renderGapSections(ctx.gaps);
|
||||
const rows = ctx.results.map(item =>
|
||||
`| ${item.id} | ${item.priority} | ${statusCell(item)} | ${Number(item.seconds ?? 0).toFixed(1)}s | ${item.steps.length} | ${item.error ? item.error.slice(0, 120).replace(/\|/g, "\\|") : ""} |`);
|
||||
return `# Web FreeCAD 功能测试(有头)\n\n` +
|
||||
`- 运行:${ctx.startedAt}\n- Origin:${ctx.origin}\n- 模式:${ctx.options.headless ? "headless" : "headed"}\n` +
|
||||
`- 计数:passed ${ctx.counts.passed} / failed ${ctx.counts.failed} / blocked ${ctx.counts.blocked} / reference_only ${ctx.counts.reference_only}\n\n` +
|
||||
`## 用例\n\n| id | 优先级 | 状态 | 耗时 | 步骤 | 错误 |\n|---|---|---|---|---|---|\n${rows.join("\n")}\n\n` +
|
||||
`## Blocked(前置未满足)\n\n${gaps.blocked}\n\n## Product(产品/UI 缺口)\n\n${gaps.product}\n`;
|
||||
}
|
||||
|
||||
export function writeJUnit(ctx) {
|
||||
const body = ctx.results.map(item => {
|
||||
const time = Number(item.seconds ?? 0).toFixed(3);
|
||||
const failure = item.status === "passed" ? "" :
|
||||
item.status === "blocked"
|
||||
? `\n <skipped message="${esc(item.failureClass)}: ${esc(item.error)}"/>`
|
||||
: `\n <failure message="${esc(item.classification)}">${esc(item.error)}</failure>`;
|
||||
return ` <testcase classname="${esc(item.priority)}" name="${esc(item.id)}" time="${time}">${failure}\n </testcase>`;
|
||||
});
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>\n<testsuite name="web-freecad-functional-suite" tests="${ctx.results.length}" failures="${ctx.counts.failed}" skipped="${ctx.counts.blocked}" time="${(ctx.results.reduce((sum, item) => sum + Number(item.seconds ?? 0), 0)).toFixed(3)}">\n${body.join("\n")}\n</testsuite>\n`;
|
||||
}
|
||||
|
||||
export function writeIndex(ctx) {
|
||||
const rows = ctx.results.map(item => {
|
||||
const color = item.status === "passed" ? "#137333" : item.status === "blocked" ? "#8a6d00" : "#a50e0e";
|
||||
return `<tr><td><a href="cases/${esc(item.id)}/">${esc(item.id)}</a></td><td>${esc(item.priority)}</td><td style="color:${color}">${esc(statusCell(item))}</td><td>${Number(item.seconds ?? 0).toFixed(1)}s</td><td>${esc(item.error ? item.error.slice(0, 160) : "")}</td></tr>`;
|
||||
});
|
||||
return `<!doctype html><meta charset="utf-8"><title>Web FreeCAD functional suite</title>
|
||||
<style>body{font:14px/1.5 system-ui,sans-serif;margin:24px}table{border-collapse:collapse}td,th{border:1px solid #ddd;padding:4px 8px;text-align:left}</style>
|
||||
<h1>Web FreeCAD 功能测试(有头)</h1>
|
||||
<p>${esc(ctx.startedAt)} · origin ${esc(ctx.origin)} · passed ${ctx.counts.passed} / failed ${ctx.counts.failed} / blocked ${ctx.counts.blocked}</p>
|
||||
<table><thead><tr><th>id</th><th>优先级</th><th>状态</th><th>耗时</th><th>错误</th></tr></thead><tbody>${rows.join("")}</tbody></table>
|
||||
<p><a href="report.md">report.md</a> · <a href="results.json">results.json</a> · <a href="junit.xml">junit.xml</a></p>`;
|
||||
}
|
||||
|
||||
export function finalize(ctx) {
|
||||
persist(ctx);
|
||||
fs.writeFileSync(path.join(ctx.output, "report.md"), writeMarkdown(ctx));
|
||||
fs.writeFileSync(path.join(ctx.output, "junit.xml"), writeJUnit(ctx));
|
||||
fs.writeFileSync(path.join(ctx.output, "index.html"), writeIndex(ctx));
|
||||
const gaps = renderGapSections(ctx.gaps);
|
||||
fs.writeFileSync(path.join(ctx.output, "GAPS.md"),
|
||||
`# Gap ledger\n\n## Blocked (preconditions): ${gaps.counts.blocked}\n\n${gaps.blocked}\n\n## Product regressions/gaps: ${gaps.counts.product}\n\n${gaps.product}\n`);
|
||||
}
|
||||
|
||||
export function pruneRuns(base, keep) {
|
||||
if (!fs.existsSync(base)) return [];
|
||||
const dirs = fs.readdirSync(base, { withFileTypes: true })
|
||||
.filter(entry => entry.isDirectory() && entry.name.startsWith("run-"))
|
||||
.map(entry => entry.name).sort();
|
||||
const removed = dirs.slice(0, Math.max(0, dirs.length - keep));
|
||||
for (const name of removed) fs.rmSync(path.join(base, name), { recursive: true, force: true });
|
||||
return removed;
|
||||
}
|
||||
176
tools/functional-suite/runtime.mjs
Normal file
176
tools/functional-suite/runtime.mjs
Normal file
@@ -0,0 +1,176 @@
|
||||
// Headed browser runtime: static host, page lifecycle, per-case isolation,
|
||||
// step recording and failure evidence.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { startStaticHost, findChrome } from "../static-host.mjs";
|
||||
import { UiParityPreflightError, capturePageErrors } from "../ui-parity-preflight.mjs";
|
||||
import { classifyFailure } from "./gap-ledger.mjs";
|
||||
import { persist } from "./report.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const root = path.resolve(here, "../..");
|
||||
export const webRoot = path.join(root, "web");
|
||||
export const distRoot = path.join(webRoot, "dist");
|
||||
const requireWeb = createRequire(path.join(webRoot, "package.json"));
|
||||
export const { chromium } = requireWeb("playwright");
|
||||
|
||||
export const VIEWPORT = { width: 1440, height: 1000 };
|
||||
|
||||
export function launchOptions(options) {
|
||||
const executablePath = findChrome();
|
||||
if (!executablePath) throw new Error(`Chrome not found; set FREECAD_CHROME (tried /usr/bin/google-chrome)`);
|
||||
const args = ["--no-sandbox", "--disable-dev-shm-usage", "--window-size=1600,1000"];
|
||||
// swiftshader keeps canvas hashes and meshes deterministic across headed runs;
|
||||
// --gpu is a manual-observation escape hatch only.
|
||||
if (!options.gpu) args.push("--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader");
|
||||
return { executablePath, headless: options.headless, slowMo: options.slow || undefined, args };
|
||||
}
|
||||
|
||||
export async function startHost() {
|
||||
if (!fs.existsSync(path.join(distRoot, "index.html"))) {
|
||||
throw new Error(`web/dist/index.html is missing; run "npx vite build" in web/ first`);
|
||||
}
|
||||
return startStaticHost(distRoot);
|
||||
}
|
||||
|
||||
export async function openBrowser(options) {
|
||||
return chromium.launch(launchOptions(options));
|
||||
}
|
||||
|
||||
export async function openPage(browser, ctx) {
|
||||
const context = await browser.newContext({ viewport: VIEWPORT, acceptDownloads: true });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
const pageErrors = capturePageErrors(page);
|
||||
const consoleErrors = [];
|
||||
page.on("console", message => { if (message.type() === "error") consoleErrors.push(message.text().slice(0, 300)); });
|
||||
const downloadsDir = path.join(ctx.output, "downloads");
|
||||
fs.mkdirSync(downloadsDir, { recursive: true });
|
||||
page.on("download", async download => {
|
||||
try { await download.saveAs(path.join(downloadsDir, download.suggestedFilename())); } catch { /* download cancelled */ }
|
||||
});
|
||||
return { context, page, pageErrors, consoleErrors };
|
||||
}
|
||||
|
||||
// Same-origin OPFS wipe between cases; keeps HTTP/WASM caches warm.
|
||||
export async function resetState(page, origin) {
|
||||
await page.goto(`${origin}/index.html`, { waitUntil: "domcontentloaded", timeout: 60000 });
|
||||
await page.evaluate(async () => {
|
||||
const rootDir = await navigator.storage.getDirectory();
|
||||
const names = [];
|
||||
for await (const [name] of rootDir.entries()) names.push(name);
|
||||
for (const name of names) await rootDir.removeEntry(name, { recursive: true }).catch(() => {});
|
||||
});
|
||||
await page.goto("about:blank");
|
||||
}
|
||||
|
||||
export async function openRoute(page, ctx, route, { timeout = 60000, dismissStart = false } = {}) {
|
||||
await page.goto(`${ctx.origin}${route}`, { waitUntil: "domcontentloaded", timeout });
|
||||
await page.waitForFunction(() => document.querySelectorAll("#app button").length > 0, null, { timeout });
|
||||
const isolation = await page.evaluate(() => ({ isolated: self.crossOriginIsolated, sab: typeof SharedArrayBuffer === "function" }));
|
||||
if (!isolation.isolated || !isolation.sab) throw new UiParityPreflightError("host/iframe", "COOP/COEP isolation missing");
|
||||
if (dismissStart) await dismissStartWorkspace(page);
|
||||
return isolation;
|
||||
}
|
||||
|
||||
export async function dismissStartWorkspace(page) {
|
||||
const button = page.getByRole("button", { name: "Dismiss Start", exact: true });
|
||||
if (await button.count()) { try { await button.first().click({ timeout: 3000 }); } catch { /* already gone */ } }
|
||||
await page.waitForTimeout(300);
|
||||
}
|
||||
|
||||
export async function pageState(page) {
|
||||
return page.evaluate(() => ({
|
||||
url: location.href,
|
||||
title: document.title,
|
||||
status: document.querySelector(".desktop-status-bar [role=status]")?.textContent ?? null,
|
||||
tree: [...document.querySelectorAll('[role="treeitem"]')].map(node => node.textContent.trim().slice(0, 60)).slice(0, 20),
|
||||
tabs: [...document.querySelectorAll('.document-tabs [role="tab"]')].map(node => ({ text: node.textContent.trim(), active: node.getAttribute("aria-selected") === "true" })),
|
||||
canvases: [...document.querySelectorAll("canvas")].map(canvas => ({ width: canvas.width, height: canvas.height })),
|
||||
appButtons: document.querySelectorAll("#app button").length,
|
||||
})).catch(error => ({ error: String(error) }));
|
||||
}
|
||||
|
||||
export async function canvasHash(page, selector = "canvas") {
|
||||
const locator = page.locator(selector).first();
|
||||
if ((await locator.count()) === 0) return null;
|
||||
let buffer = null;
|
||||
try {
|
||||
buffer = await locator.screenshot({ timeout: 20000 });
|
||||
} catch {
|
||||
// An element screenshot scrolls the canvas into view; a modal Start dialog
|
||||
// or a tall panel can keep that from ever settling. Clip a viewport shot to
|
||||
// the canvas box instead — the pixels are the same evidence.
|
||||
try {
|
||||
const box = await locator.boundingBox({ timeout: 5000 });
|
||||
if (box && box.width > 0 && box.height > 0) buffer = await page.screenshot({ clip: box, timeout: 20000 });
|
||||
} catch { /* canvas gone or unreachable */ }
|
||||
}
|
||||
if (!buffer) return null;
|
||||
return { selector, bytes: buffer.length, sha256: createHash("sha256").update(buffer).digest("hex") };
|
||||
}
|
||||
|
||||
async function captureFailure(page, caseDir, result, ctx) {
|
||||
const evidence = { at: new Date().toISOString(), ...(await pageState(page)), steps: result.steps };
|
||||
fs.writeFileSync(path.join(caseDir, "failure.json"), `${JSON.stringify(evidence, null, 2)}\n`);
|
||||
try { await page.screenshot({ path: path.join(caseDir, "failure.png"), fullPage: true }); } catch { /* page gone */ }
|
||||
const canvas = await canvasHash(page).catch(() => null);
|
||||
if (canvas && (await page.locator("canvas").count())) {
|
||||
try { await page.locator("canvas").first().screenshot({ path: path.join(caseDir, "failure-canvas.png") }); } catch { /* detached */ }
|
||||
}
|
||||
result.artifacts = { ...result.artifacts, failure: path.relative(ctx.output, path.join(caseDir, "failure.png")), canvas };
|
||||
}
|
||||
|
||||
export async function runCase(page, definition, ctx) {
|
||||
const caseDir = path.join(ctx.output, "cases", definition.id);
|
||||
fs.mkdirSync(caseDir, { recursive: true });
|
||||
const started = Date.now();
|
||||
const result = {
|
||||
id: definition.id, title: definition.title, priority: definition.priority,
|
||||
executor: definition.executor, module: definition.module ?? null, source: definition.source ?? null,
|
||||
status: "running", classification: "none", failureClass: null, steps: [], seconds: 0,
|
||||
error: null, startedAt: new Date().toISOString(), artifacts: {},
|
||||
};
|
||||
ctx.results.push(result);
|
||||
const step = async (name, expected, fn) => {
|
||||
const item = { number: result.steps.length + 1, name, expected, status: "running", startedAt: new Date().toISOString() };
|
||||
result.steps.push(item);
|
||||
persist(ctx);
|
||||
const begin = Date.now();
|
||||
try {
|
||||
item.actual = await fn();
|
||||
item.status = "passed";
|
||||
} catch (error) {
|
||||
item.status = "failed";
|
||||
item.error = String(error?.message ?? error);
|
||||
throw error;
|
||||
} finally {
|
||||
item.seconds = Number(((Date.now() - begin) / 1000).toFixed(3));
|
||||
persist(ctx);
|
||||
}
|
||||
};
|
||||
try {
|
||||
await definition.run({ page, origin: ctx.origin, step, ctx, caseDir, timeoutMs: Math.round((definition.timeoutMs ?? 120000) * ctx.options.timeoutScale) });
|
||||
result.status = "passed";
|
||||
} catch (error) {
|
||||
const verdict = classifyFailure(error);
|
||||
result.status = verdict.status;
|
||||
result.classification = verdict.classification;
|
||||
result.failureClass = verdict.failureClass;
|
||||
result.error = verdict.message;
|
||||
await captureFailure(page, caseDir, result, ctx);
|
||||
ctx.gaps.push({ caseId: result.id, ...verdict, evidence: path.relative(ctx.output, caseDir) });
|
||||
} finally {
|
||||
result.seconds = Number(((Date.now() - started) / 1000).toFixed(3));
|
||||
if (result.status === "passed" && ctx.options.screenshots === "all") {
|
||||
try { await page.screenshot({ path: path.join(caseDir, "pass.png"), fullPage: true }); } catch { /* page gone */ }
|
||||
}
|
||||
fs.writeFileSync(path.join(caseDir, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
|
||||
persist(ctx);
|
||||
}
|
||||
console.log(`${result.id}: ${result.status} (${result.seconds}s)${result.failureClass ? ` [${result.failureClass}]` : ""}`);
|
||||
return result;
|
||||
}
|
||||
Reference in New Issue
Block a user