Organize test files

This commit is contained in:
Formsmith
2026-06-14 22:13:39 +03:00
parent 753a1c2833
commit 4ba8cb723c
7 changed files with 17 additions and 11 deletions
+208
View File
@@ -0,0 +1,208 @@
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import type { WorkplaneShape } from "@/types/sketchforge";
type ImportedShapeFromStl = (fileName: string, buffer: ArrayBuffer) => WorkplaneShape;
type BenchRow = {
workload: string;
step: string;
triangles?: number;
bytes?: number;
runs: number;
avgMs: number;
minMs: number;
maxMs: number;
heapDeltaMb: number;
};
const SYNTHETIC_WORKLOADS = [
{ label: "synthetic-small", triangles: 1200 },
{ label: "synthetic-medium", triangles: 12000 },
{ label: "synthetic-large", triangles: 60000 },
];
if (process.env.SKETCHFORGE_PERF_LARGE === "1") {
SYNTHETIC_WORKLOADS.push({ label: "synthetic-xl", triangles: 150000 });
}
function formatMs(value: number) {
return Number(value.toFixed(2));
}
function formatMb(value: number) {
return Number(value.toFixed(2));
}
function heapUsedMb() {
return process.memoryUsage().heapUsed / 1024 / 1024;
}
async function measure<T>(
rows: BenchRow[],
workload: string,
step: string,
runs: number,
metadata: Pick<BenchRow, "triangles" | "bytes">,
fn: () => T | Promise<T>,
) {
const durations: number[] = [];
const heapBefore = heapUsedMb();
let value: T | undefined;
for (let run = 0; run < runs; run += 1) {
const start = performance.now();
value = await fn();
durations.push(performance.now() - start);
}
const heapAfter = heapUsedMb();
const avgMs = durations.reduce((total, duration) => total + duration, 0) / durations.length;
rows.push({
workload,
step,
...metadata,
runs,
avgMs,
minMs: Math.min(...durations),
maxMs: Math.max(...durations),
heapDeltaMb: heapAfter - heapBefore,
});
return value as T;
}
function writeTriangle(view: DataView, offset: number, normal: number[], a: number[], b: number[], c: number[]) {
const values = [...normal, ...a, ...b, ...c];
let cursor = offset;
values.forEach((value) => {
view.setFloat32(cursor, value, true);
cursor += 4;
});
view.setUint16(cursor, 0, true);
return cursor + 2;
}
function createSyntheticBinaryStl(requestedTriangles: number) {
const cubeCount = Math.ceil(requestedTriangles / 12);
const triangleCount = cubeCount * 12;
const buffer = new ArrayBuffer(84 + triangleCount * 50);
const view = new DataView(buffer);
view.setUint32(80, triangleCount, true);
const faces = [
{ normal: [0, 0, 1], corners: [[0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]] },
{ normal: [0, 0, -1], corners: [[1, 0, 0], [0, 0, 0], [0, 1, 0], [1, 1, 0]] },
{ normal: [0, 1, 0], corners: [[0, 1, 1], [1, 1, 1], [1, 1, 0], [0, 1, 0]] },
{ normal: [0, -1, 0], corners: [[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]] },
{ normal: [1, 0, 0], corners: [[1, 0, 1], [1, 0, 0], [1, 1, 0], [1, 1, 1]] },
{ normal: [-1, 0, 0], corners: [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0]] },
];
const columns = Math.ceil(Math.sqrt(cubeCount));
let offset = 84;
for (let cube = 0; cube < cubeCount; cube += 1) {
const x = (cube % columns) * 1.4;
const y = Math.floor(cube / (columns * columns)) * 1.4;
const z = Math.floor(cube / columns) % columns * 1.4;
const translate = ([px, py, pz]: number[]) => [px + x, py + y, pz + z];
faces.forEach(({ normal, corners }) => {
const [a, b, c, d] = corners.map(translate);
offset = writeTriangle(view, offset, normal, a, b, c);
offset = writeTriangle(view, offset, normal, a, c, d);
});
}
return { buffer, triangleCount };
}
function toArrayBuffer(bytes: Buffer) {
const copy = new Uint8Array(bytes.byteLength);
copy.set(bytes);
return copy.buffer;
}
function findRealStlFiles() {
const configured = process.env.SKETCHFORGE_PERF_STL_DIR?.trim();
if (!configured) {
return [];
}
const directory = path.resolve(configured);
if (!existsSync(directory) || !statSync(directory).isDirectory()) {
throw new Error(`SKETCHFORGE_PERF_STL_DIR is not a directory: ${directory}`);
}
return readdirSync(directory)
.filter((entry) => entry.toLowerCase().endsWith(".stl"))
.map((entry) => path.join(directory, entry))
.filter((entry) => statSync(entry).isFile())
.slice(0, 12);
}
function printReport(rows: BenchRow[]) {
const table = rows.map((row) => ({
workload: row.workload,
step: row.step,
triangles: row.triangles ?? "",
mb: row.bytes ? formatMb(row.bytes / 1024 / 1024) : "",
runs: row.runs,
avgMs: formatMs(row.avgMs),
minMs: formatMs(row.minMs),
maxMs: formatMs(row.maxMs),
heapDeltaMb: formatMb(row.heapDeltaMb),
msPer10kTriangles: row.triangles ? formatMs((row.avgMs / row.triangles) * 10000) : "",
}));
const bottlenecks = [...table].sort((a, b) => Number(b.avgMs) - Number(a.avgMs)).slice(0, 8);
const totalsByStep = new Map<string, number>();
rows.forEach((row) => totalsByStep.set(row.step, (totalsByStep.get(row.step) ?? 0) + row.avgMs));
const stepTotals = [...totalsByStep.entries()]
.map(([step, totalMs]) => ({ step, totalMs: formatMs(totalMs) }))
.sort((a, b) => Number(b.totalMs) - Number(a.totalMs));
console.log("\nSketchForge STL performance report");
console.log("Tip: set SKETCHFORGE_PERF_STL_DIR=C:\\path\\to\\stls to include real STL files.");
console.table(table);
console.log("\nRanked bottlenecks by average duration");
console.table(bottlenecks);
console.log("\nTotal time by pipeline step");
console.table(stepTotals);
}
describe("STL performance benchmark", () => {
it("measures import and local-first persistence costs", async () => {
const rows: BenchRow[] = [];
const stlModule = await measure(rows, "startup", "load STL import module", 1, {}, () => import("@/lib/stlImport"));
const importedShapeFromStl = stlModule.importedShapeFromStl as ImportedShapeFromStl;
for (const workload of SYNTHETIC_WORKLOADS) {
const stl = await measure(rows, workload.label, "generate synthetic binary STL", 1, { triangles: workload.triangles }, () =>
createSyntheticBinaryStl(workload.triangles),
);
const runs = stl.triangleCount >= 60000 ? 2 : 3;
const shape = await measure(rows, workload.label, "import STL into WorkplaneShape", runs, { triangles: stl.triangleCount, bytes: stl.buffer.byteLength }, () =>
importedShapeFromStl(`${workload.label}.stl`, stl.buffer),
);
expect(shape.importedMesh?.triangleCount).toBe(stl.triangleCount);
const json = await measure(rows, workload.label, "serialize shape JSON", runs, { triangles: stl.triangleCount }, () => JSON.stringify(shape));
await measure(rows, workload.label, "parse shape JSON", runs, { triangles: stl.triangleCount, bytes: json.length }, () => JSON.parse(json));
}
for (const filePath of findRealStlFiles()) {
const label = `real-${path.basename(filePath)}`;
const bytes = await measure(rows, label, "read STL file", 1, { bytes: statSync(filePath).size }, () => readFileSync(filePath));
const shape = await measure(rows, label, "import STL into WorkplaneShape", 2, { bytes: bytes.byteLength }, () =>
importedShapeFromStl(path.basename(filePath), toArrayBuffer(bytes)),
);
const triangles = shape.importedMesh?.triangleCount ?? 0;
expect(triangles).toBeGreaterThan(0);
const json = await measure(rows, label, "serialize shape JSON", 2, { triangles }, () => JSON.stringify(shape));
await measure(rows, label, "parse shape JSON", 2, { triangles, bytes: json.length }, () => JSON.parse(json));
}
printReport(rows);
});
});
+73
View File
@@ -0,0 +1,73 @@
import { describe, expect, it } from "vitest";
import type { ShapeAsset } from "@/types/sketchforge";
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets } from "@/lib/shapeCatalog";
describe("shape catalog", () => {
it("does not expose removed decorative shapes in the toolbar catalog", () => {
const kinds = toolbarShapeAssets.map((asset) => asset.kind);
expect(kinds).not.toContain("star");
expect(kinds).not.toContain("heart");
});
it("creates placed shapes from toolbar assets", () => {
const asset: ShapeAsset = { id: "box", name: "Box", src: "box.png", kind: "box", color: "#d41721" };
const placed = makeShapeFromAsset(asset, { x: 12, z: -8, elevation: 4 });
expect(placed.id).toMatch(/^box-/);
expect(placed).toMatchObject({
name: "Box",
kind: "box",
color: "#d41721",
x: 12,
z: -8,
elevation: 4,
size: 20,
width: 20,
depth: 20,
height: 20,
radius: 0,
steps: 10,
locked: false,
hidden: false,
});
});
it("uses shape-specific defaults for text and round profiles", () => {
const text = makeShapeFromAsset({ id: "text", name: "Text", src: "text.png", kind: "text", color: "#cf101b" });
const torus = makeShapeFromAsset({ id: "torus", name: "Torus", src: "torus.png", kind: "torus", color: "#0098c7" });
expect(text).toMatchObject({ width: 86, depth: 28, height: 10, text: "TEXT", font: "Multilanguage" });
expect(torus).toMatchObject({ size: 22, width: 22, depth: 22, height: 5 });
});
it("creates canonical scene shapes with stable defaults", () => {
const created = sceneShape({
name: "Part",
kind: "box",
color: "#d41721",
width: 12,
depth: 18,
rotation: 359.9,
mirrorX: false,
});
expect(created.id).toMatch(/^shape-/);
expect(created).toMatchObject({
name: "Part",
kind: "box",
color: "#d41721",
x: 0,
z: 0,
elevation: 0,
width: 12,
depth: 18,
height: 20,
size: 18,
rotation: 0,
locked: false,
hidden: false,
});
expect(created.mirrorX).toBeUndefined();
});
});
+61
View File
@@ -0,0 +1,61 @@
import { describe, expect, it } from "vitest";
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
describe("workplane settings helpers", () => {
it("accepts known snap grid values and falls back for unknown values", () => {
expect(normalizeSnapGrid("0.5 mm")).toBe("0.5 mm");
expect(normalizeSnapGrid("Huge")).toBe(DEFAULT_SNAP_GRID);
expect(normalizeSnapGrid(null, "Off")).toBe("Off");
});
it("normalizes workspace settings from partial or invalid data", () => {
const fallback: WorkplaneWorkspaceSettings = {
...DEFAULT_WORKPLANE_WORKSPACE,
width: 300,
depth: 250,
background: "#ffffff",
};
expect(normalizeWorkspaceSettings(null, fallback)).toEqual(fallback);
expect(
normalizeWorkspaceSettings(
{
width: 500,
depth: Number.NaN,
sizePreset: "",
gridBlockSize: 2.5,
gridBlockPreset: "Custom",
background: "#123456",
showShadows: false,
showGrid: false,
cruiseShapes: false,
zoomSpeed: Infinity,
units: "Bricks",
scale: "1:10 (centimeters)",
},
fallback,
),
).toEqual({
...fallback,
width: 500,
gridBlockSize: 2.5,
gridBlockPreset: "Custom",
background: "#123456",
showShadows: false,
showGrid: false,
cruiseShapes: false,
units: "Bricks",
scale: "1:10 (centimeters)",
});
});
it("fingerprints workspace and snap settings together", () => {
const base = workplaneSettingsFingerprint(DEFAULT_WORKPLANE_WORKSPACE, "1.0 mm");
const changedSnap = workplaneSettingsFingerprint(DEFAULT_WORKPLANE_WORKSPACE, "5.0 mm");
const changedWorkspace = workplaneSettingsFingerprint({ ...DEFAULT_WORKPLANE_WORKSPACE, width: 300 }, "1.0 mm");
expect(changedSnap).not.toBe(base);
expect(changedWorkspace).not.toBe(base);
});
});
+113
View File
@@ -0,0 +1,113 @@
import { describe, expect, it } from "vitest";
import type { WorkplaneShape } from "@/types/sketchforge";
import {
canonicalizeShape,
cleanNearZero,
cleanRotationDegrees,
fallbackSolidColor,
mirroredAxisCount,
mirrorSign,
normalizeDegrees,
proportionalResizeScale,
resizedShapeSize,
serializeShapesForSync,
shapeDepth,
shapeWidth,
workplaneShapesEqual,
} from "@/lib/workplaneShapes";
function shape(overrides: Partial<WorkplaneShape> = {}): WorkplaneShape {
return {
id: "box-1",
name: "Box",
kind: "box",
color: "#d41721",
x: 0,
z: 0,
elevation: 0,
size: 20,
width: 20,
depth: 20,
height: 20,
rotation: 0,
locked: false,
hidden: false,
...overrides,
};
}
describe("workplane shape helpers", () => {
it("normalizes and cleans rotations", () => {
expect(normalizeDegrees(-90)).toBe(270);
expect(normalizeDegrees(450)).toBe(90);
expect(cleanRotationDegrees(Number.NaN)).toBe(0);
expect(cleanRotationDegrees(-0.2)).toBe(0);
expect(cleanRotationDegrees(359.8)).toBe(0);
expect(cleanRotationDegrees(12.34)).toBe(12.3);
});
it("cleans near-zero values and derives dimensions", () => {
const base = shape({ size: 30, width: 18, depth: 24 });
expect(cleanNearZero(0.004)).toBe(0);
expect(cleanNearZero(0.006)).toBe(0.006);
expect(shapeWidth(base)).toBe(18);
expect(shapeDepth(base)).toBe(24);
expect(resizedShapeSize(18, 24)).toBe(24);
});
it("uses proportional scale instead of square dimensions while shift-resizing", () => {
expect(proportionalResizeScale(50, 100, 100, 150)).toBe(2);
expect(proportionalResizeScale(50, 100, 60, 200)).toBe(2);
expect(proportionalResizeScale(50, 100, 25, 80)).toBe(0.5);
});
it("canonicalizes mirror flags and nested group rotations", () => {
const canonical = canonicalizeShape(
shape({
rotation: 360,
rotationX: -0.1,
rotationZ: 45.04,
mirrorX: false,
mirrorY: true,
groupedShapes: [shape({ id: "child", rotation: 720, mirrorZ: false })],
}),
);
expect(canonical.rotation).toBe(0);
expect(canonical.rotationX).toBe(0);
expect(canonical.rotationZ).toBe(45);
expect(canonical.mirrorX).toBeUndefined();
expect(canonical.mirrorY).toBe(true);
expect(canonical.groupedShapes?.[0].rotation).toBe(0);
expect(canonical.groupedShapes?.[0].mirrorZ).toBeUndefined();
});
it("keeps shallow equality strict for shape payload references", () => {
const importedMesh = { positions: [0, 0, 0], baseWidth: 1, baseDepth: 1, baseHeight: 1, triangleCount: 0, sourceFormat: "json" as const };
const first = shape({ importedMesh });
const sameReference = shape({ importedMesh });
const sameValues = shape({ importedMesh: { ...importedMesh, positions: [...importedMesh.positions] } });
expect(workplaneShapesEqual(first, sameReference)).toBe(true);
expect(workplaneShapesEqual(first, sameValues)).toBe(false);
});
it("serializes canonical shapes for sync", () => {
expect(JSON.parse(serializeShapesForSync([shape({ rotation: 359.9, mirrorX: false })]))).toEqual([
expect.objectContaining({
id: "box-1",
rotation: 0,
rotationX: 0,
rotationZ: 0,
}),
]);
});
it("maps helper flags and fallback colors", () => {
expect(mirrorSign(true)).toBe(-1);
expect(mirrorSign(false)).toBe(1);
expect(mirroredAxisCount(shape({ mirrorX: true, mirrorY: true }))).toBe(2);
expect(fallbackSolidColor(shape({ kind: "sphere" }))).toBe("#0098c7");
expect(fallbackSolidColor(shape({ kind: "box" }))).toBe("#d41721");
});
});
+17
View File
@@ -0,0 +1,17 @@
import path from "node:path";
import { defineConfig } from "vitest/config";
const rootDir = path.resolve(__dirname, "..");
export default defineConfig({
root: rootDir,
resolve: {
alias: {
"@": path.resolve(rootDir, "apps/web/src"),
},
},
test: {
environment: "node",
include: ["tests/unit/**/*.test.ts"],
},
});
+19
View File
@@ -0,0 +1,19 @@
import path from "node:path";
import { defineConfig } from "vitest/config";
const rootDir = path.resolve(__dirname, "..");
export default defineConfig({
root: rootDir,
resolve: {
alias: {
"@": path.resolve(rootDir, "apps/web/src"),
},
},
test: {
environment: "node",
include: ["tests/perf/**/*.perf.ts"],
testTimeout: 120000,
hookTimeout: 120000,
},
});