示例工程 51-test-pyramid
51-test-pyramid/app/main/index.ts
import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import {
assertAdd,
assertE2E,
assertToggle,
CH,
type CaseResult,
type EventRow,
type Snapshot,
} from "../shared/ipc";
import { runCases, type Layer } from "../shared/spec";
import { addTodo, toggleTodo, type Todo } from "../shared/todo";
app.setName("Test Pyramid Lab");
const isSmoke =
process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
const tempData =
isSmoke || isShots ? path.join(os.tmpdir(), `pyramid51-${process.pid}`) : "";
if (tempData) app.setPath("userData", tempData);
let win: BrowserWindow | null = null;
let events: EventRow[] = [];
let injectFailure = false;
let todos: Todo[] = [
{ id: 1, title: "写单元测试", done: true },
{ id: 2, title: "写集成测试", done: false },
{ id: 3, title: "写 E2E", done: false },
];
let results: CaseResult[] = [];
function log(kind: string, detail: string): void {
events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
broadcast();
}
function broadcast(): void {
if (win && !win.isDestroyed()) {
win.webContents.send("tests:event", { at: Date.now() });
}
}
function runSuite(): void {
const start = performance.now();
const out = runCases(todos, injectFailure);
results = [...out.results, ...results.filter((row) => row.layer === "e2e")];
log(
"run",
`${out.results.filter((row) => row.pass).length}/${out.results.length} · ${Math.round(performance.now() - start)}ms`,
);
}
function counts(rows: CaseResult[]): Record<Layer, number> {
return {
unit: rows.filter((row) => row.layer === "unit").length,
integration: rows.filter((row) => row.layer === "integration").length,
e2e: rows.filter((row) => row.layer === "e2e").length,
};
}
function snapshot(): Snapshot {
const passed = results.filter((row) => row.pass).length;
return {
platform: process.platform,
electronVersion: process.versions.electron,
nodeVersion: process.versions.node,
todos: todos.map((todo) => ({ ...todo })),
results: results.map((row) => ({ ...row })),
counts: counts(results),
summary: {
total: results.length,
passed,
failed: results.length - passed,
ms: Math.round(results.reduce((sum, row) => sum + row.ms, 0) * 100) / 100,
},
injectFailure,
events: events.map((row) => ({ ...row })),
};
}
function resolvePreload(): string {
const candidates = [
path.join(__dirname, "preload.cjs"),
path.join(__dirname, "../preload/index.cjs"),
path.join(__dirname, "preload.js"),
];
return (
candidates.find((candidate) => fsSync.existsSync(candidate)) ??
candidates[0] ??
""
);
}
function createWindow(): BrowserWindow {
const window = new BrowserWindow({
width: 1100,
height: 860,
show: false,
title: "测试金字塔实验室",
backgroundColor: "#ffffff",
webPreferences: {
preload: resolvePreload(),
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
webSecurity: true,
allowRunningInsecureContent: false,
experimentalFeatures: false,
webviewTag: false,
spellcheck: false,
backgroundThrottling: true,
},
});
const contents = window.webContents;
contents.setWindowOpenHandler(() => ({ action: "deny" }));
contents.on("will-navigate", (event, url) => {
if (!url.startsWith("file://")) event.preventDefault();
});
contents.on("will-attach-webview", (event) => event.preventDefault());
window.once("ready-to-show", () => window.show());
contents.once("did-finish-load", () => {
if (!window.isDestroyed() && !window.isVisible()) window.show();
log("ready", "测试金字塔界面已加载");
});
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
void window.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
} else {
void window.loadFile(
path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
);
}
win = window;
return window;
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function evalRenderer<T>(
window: BrowserWindow,
code: string,
): Promise<T> {
let lastCaught: unknown = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return (await window.webContents.executeJavaScript(code)) as T;
} catch (caught) {
lastCaught = caught;
await delay(150);
}
}
throw lastCaught instanceof Error
? lastCaught
: new Error(String(lastCaught));
}
async function waitForRenderer(window: BrowserWindow): Promise<void> {
for (let attempt = 0; attempt < 160; attempt += 1) {
if (window.isDestroyed()) return;
try {
const ready = await evalRenderer<boolean>(
window,
"typeof window.__demo === 'function'",
);
if (ready) return;
} catch {
// 页面仍在加载。
}
await delay(100);
}
throw new Error("renderer did not become ready");
}
type DemoState = {
total: number;
passed: number;
failed: number;
unit: number;
integration: number;
e2e: number;
e2ePassed: number;
inject: boolean;
todos: number;
ms: number;
};
async function runSmoke(window: BrowserWindow): Promise<void> {
try {
await waitForRenderer(window);
await delay(600);
await waitForRenderer(window);
await evalRenderer(window, "window.__runE2E()");
await delay(300);
const state = await evalRenderer<DemoState>(window, "window.__demo()");
process.stdout.write(
`${JSON.stringify({
evt: "smoke",
ok:
state.total === 19 &&
state.passed === 19 &&
state.failed === 0 &&
state.unit === 10 &&
state.integration === 5 &&
state.e2e === 4 &&
state.e2ePassed === 4 &&
!state.inject &&
state.todos >= 3,
...state,
})}\n`,
);
app.quit();
} catch (caught) {
process.stdout.write(
`${JSON.stringify({ evt: "smoke", ok: false, message: String(caught) })}\n`,
);
app.exit(1);
}
}
async function capture(
window: BrowserWindow,
dir: string,
file: string,
): Promise<void> {
const image = await window.webContents.capturePage();
if (image.isEmpty()) throw new Error(`empty capture: ${file}`);
const png = image.toPNG();
fsSync.writeFileSync(path.join(dir, file), png);
fsSync.writeFileSync(path.join(dir, "raw", file), png);
}
async function runShots(window: BrowserWindow): Promise<void> {
try {
const dir = path.resolve(
process.cwd(),
"../../../docs/assets/images/51-test-pyramid",
);
fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
await waitForRenderer(window);
await delay(600);
await waitForRenderer(window);
await evalRenderer(window, `window.__prepareShots("overview")`);
await delay(300);
await capture(window, dir, "51-01-overview.png");
await evalRenderer(window, `window.__prepareShots("failure")`);
await delay(300);
await capture(window, dir, "51-02-failure.png");
await evalRenderer(window, `window.__prepareShots("e2e")`);
await delay(300);
await capture(window, dir, "51-03-e2e.png");
app.quit();
} catch (caught) {
process.stdout.write(
`${JSON.stringify({ evt: "shots-error", message: String(caught) })}\n`,
);
app.exit(1);
}
}
ipcMain.handle(CH.snapshot, () => snapshot());
ipcMain.handle(CH.run, () => {
runSuite();
return snapshot();
});
ipcMain.handle(CH.add, (_event, raw: unknown) => {
assertAdd(raw);
todos = addTodo(todos, raw.title);
log("todo-add", raw.title);
return snapshot();
});
ipcMain.handle(CH.toggle, (_event, raw: unknown) => {
assertToggle(raw);
todos = toggleTodo(todos, raw.id);
log("todo-toggle", String(raw.id));
return snapshot();
});
ipcMain.handle(CH.reportE2E, (_event, raw: unknown) => {
assertE2E(raw);
results = [...results.filter((row) => row.layer !== "e2e"), ...raw.results];
log(
"e2e",
`${raw.results.filter((row) => row.pass).length}/${raw.results.length}`,
);
return snapshot();
});
ipcMain.handle(CH.inject, (_event, enabled: boolean) => {
injectFailure = Boolean(enabled);
runSuite();
log("inject", `失败注入 ${injectFailure ? "on" : "off"}`);
return snapshot();
});
ipcMain.handle(CH.refresh, () => snapshot());
app.whenReady().then(() => {
runSuite();
const window = createWindow();
if (isSmoke) {
void runSmoke(window);
} else if (isShots) {
void runShots(window);
}
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
} else {
win?.show();
win?.focus();
}
});
});
app.on("will-quit", () => {
if (tempData) {
try {
fsSync.rmSync(tempData, { recursive: true, force: true });
} catch {
// 清理失败不影响退出。
}
}
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit();
});