Add a smoke test runner, a shared harness, and safer build scripts
- pnpm smoke runs tests/smoke/ in parallel. It starts Vite when nothing serves SMOKE_URL, finds an installed Chrome when Playwright has no Chromium, and skips a test with a reason when a requirement that the test declares with "// @requires" is missing. Logs go to output/smoke/logs/. - tests/smoke/_harness/ holds the Playwright launch, page error collection, the Tauri IPC mock with an in-memory workspace, and output folders. tabs/order uses it as the first converted test. - Pin Playwright 1.63.0, the version that browser-runtime uses. - RUNESTONE_PLUGIN_REPOS names the folder of the sibling plugin checkouts for buildPlugins, the menu audit, and the smoke tests. - buildInstaller restores the version fields after Ctrl+C, keeps the backups of each attempt, stops when the browser runtime is not staged, and writes the file name instead of absolute paths to host.json. - buildPlugins clears the staged Table Formulas package before copying. - plugins/choiceMenus used the wrong Local Autocomplete folder name.
This commit is contained in:
@@ -0,0 +1,188 @@
|
||||
// Shared setup for the browser smoke tests: Playwright, the Tauri IPC mock, and output folders.
|
||||
// Run a test with `pnpm smoke <name>`, or run its file with Node while `pnpm dev` serves the app.
|
||||
import { createRequire } from "node:module";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
|
||||
export const repoRoot = fileURLToPath(new URL("../../../", import.meta.url));
|
||||
export const smokeUrl = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
|
||||
/** The path of a sibling plugin checkout, for example pluginRepo("RuneStone_Git"). */
|
||||
export function pluginRepo(folder) {
|
||||
return path.resolve(process.env.RUNESTONE_PLUGIN_REPOS || path.join(repoRoot, ".."), folder);
|
||||
}
|
||||
|
||||
/** Playwright, from PLAYWRIGHT_MODULE or the project dependency. */
|
||||
export function playwright() {
|
||||
return createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
}
|
||||
|
||||
/** Start headless Chromium. CHROME_PATH selects an installed browser. */
|
||||
export function launchBrowser(options = {}) {
|
||||
const executablePath = process.env.CHROME_PATH;
|
||||
return playwright().chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}), ...options });
|
||||
}
|
||||
|
||||
/** Open a page that collects uncaught page errors in `page.errors`. */
|
||||
export async function openPage(target, { viewport = { width: 1440, height: 1000 }, timeout = 10000, ...options } = {}) {
|
||||
const page = await target.newPage({ viewport, ...options });
|
||||
page.setDefaultTimeout(timeout);
|
||||
page.errors = [];
|
||||
page.on("pageerror", error => page.errors.push(error.message));
|
||||
return page;
|
||||
}
|
||||
|
||||
/** Create and return output/smoke/<name>/ for screenshots and reports. */
|
||||
export async function outputDir(name) {
|
||||
const dir = path.join(repoRoot, "output", "smoke", name);
|
||||
await mkdir(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
/** Wait two animation frames, so layout and Svelte updates settle. */
|
||||
export function settle(page) {
|
||||
return page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
}
|
||||
|
||||
/**
|
||||
* Mock the Tauri IPC layer before the app loads. The mock handles the event plugin.
|
||||
*
|
||||
* `commands(test)` runs in the page and returns a map from command name to handler `(args, test) => result`.
|
||||
* It cannot use variables from the test file. Pass data through `state`, which must be JSON.
|
||||
* `test` is also `window.__TEST__`: `{ state, calls, emit(event, payload), label, workspace(options) }`.
|
||||
* A command without a handler throws "Unhandled IPC", or returns null when `strict` is false.
|
||||
*/
|
||||
export function mockTauri(target, { label = "main", state = {}, commands, strict = true } = {}) {
|
||||
const options = JSON.stringify({ label, state, strict });
|
||||
return target.addInitScript(`(${installMock})(${options}, ${commands ? commands.toString() : "undefined"});`);
|
||||
}
|
||||
|
||||
// This function runs in the page. Keep it self-contained.
|
||||
function installMock(options, commands) {
|
||||
let sequence = 0;
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
|
||||
// An in-memory workspace: `files` maps workspace paths to text. Folders come from the paths and `folders`.
|
||||
// Create, rename, and delete emit "workspace-event". Writes emit it only when `writeEvents` is true.
|
||||
const workspace = ({ root = "C:\\workspace", name = root.split(/[\\/]/).pop(), files = {}, folders = [], watchMode = "native", recent = [], writeEvents = false } = {}) => {
|
||||
const store = files instanceof Map ? files : new Map(Object.entries(files));
|
||||
const dirs = new Set(folders);
|
||||
const parentOf = rel => rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : "";
|
||||
const allFolders = () => {
|
||||
const result = new Set(dirs);
|
||||
for (const rel of store.keys()) for (let dir = parentOf(rel); dir; dir = parentOf(dir)) result.add(dir);
|
||||
return result;
|
||||
};
|
||||
const changed = (kind, paths) => emit("workspace-event", { root, kind, paths });
|
||||
const handlers = {
|
||||
workspace_last_path: () => root,
|
||||
workspace_recent: () => recent,
|
||||
workspace_open: () => ({ root, name, watch_mode: watchMode }),
|
||||
workspace_list: ({ rel = "" }) => {
|
||||
const children = [];
|
||||
for (const dir of allFolders()) if (parentOf(dir) === rel) children.push({ name: dir.split("/").pop(), rel_path: dir, kind: "folder" });
|
||||
for (const file of store.keys()) if (parentOf(file) === rel) children.push({ name: file.split("/").pop(), rel_path: file, kind: "file" });
|
||||
return children;
|
||||
},
|
||||
workspace_list_markdown: () => [...store.keys()].filter(rel => /\.md$/i.test(rel)).sort(),
|
||||
workspace_read: ({ rel }) => {
|
||||
if (!store.has(rel)) throw new Error(`Missing file: ${rel}`);
|
||||
return store.get(rel);
|
||||
},
|
||||
workspace_read_many: ({ paths }) => paths.map(rel => store.has(rel) ? { path: rel, source: store.get(rel) } : { path: rel, error: "Missing file" }),
|
||||
workspace_write: ({ rel, contents }) => {
|
||||
store.set(rel, contents);
|
||||
if (writeEvents) changed("modify", [rel]);
|
||||
return null;
|
||||
},
|
||||
workspace_create: ({ rel, kind }) => {
|
||||
if (store.has(rel) || allFolders().has(rel)) throw new Error("Destination exists");
|
||||
if (kind === "folder") dirs.add(rel); else store.set(rel, "");
|
||||
changed("create", [rel]);
|
||||
return null;
|
||||
},
|
||||
workspace_rename: ({ from, to }) => {
|
||||
if (store.has(to) || allFolders().has(to)) throw new Error("Destination exists");
|
||||
for (const [rel, text] of [...store]) {
|
||||
if (rel === from || rel.startsWith(from + "/")) { store.delete(rel); store.set(to + rel.slice(from.length), text); }
|
||||
}
|
||||
for (const dir of [...dirs]) if (dir === from || dir.startsWith(from + "/")) { dirs.delete(dir); dirs.add(to + dir.slice(from.length)); }
|
||||
changed("rename", [from, to]);
|
||||
return null;
|
||||
},
|
||||
workspace_delete: ({ rel }) => {
|
||||
for (const key of [...store.keys()]) if (key === rel || key.startsWith(rel + "/")) store.delete(key);
|
||||
for (const dir of [...dirs]) if (dir === rel || dir.startsWith(rel + "/")) dirs.delete(dir);
|
||||
changed("remove", [rel]);
|
||||
return null;
|
||||
},
|
||||
workspace_search: ({ query }) => {
|
||||
const hits = [];
|
||||
for (const [rel, text] of store) text.split("\n").forEach((line, index) => {
|
||||
if (query && line.toLowerCase().includes(query.toLowerCase())) hits.push({ rel_path: rel, line: index + 1, text: line });
|
||||
});
|
||||
return hits;
|
||||
},
|
||||
workspace_abs_path: ({ rel }) => `${root}\\${rel.replaceAll("/", "\\")}`,
|
||||
};
|
||||
return Object.assign(handlers, { files: store, folders: dirs, root, name });
|
||||
};
|
||||
|
||||
const test = { state: options.state, calls: [], emit, label: options.label, workspace };
|
||||
const table = commands ? commands(test) || {} : {};
|
||||
window.isTauri = true;
|
||||
window.__TEST__ = test;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: options.label }, currentWebview: { label: options.label } },
|
||||
transformCallback: callback => {
|
||||
const id = ++sequence;
|
||||
callbacks.set(id, callback);
|
||||
return id;
|
||||
},
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
test.calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || [];
|
||||
list.push(args.handler);
|
||||
listeners.set(args.event, list);
|
||||
return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return null; }
|
||||
if (command === "plugin:event|emit" || command === "plugin:event|emit_to") { emit(args.event, args.payload); return null; }
|
||||
const handler = table[command];
|
||||
if (typeof handler === "function") {
|
||||
const result = await handler(args, test);
|
||||
return result === undefined ? null : result;
|
||||
}
|
||||
if (options.strict) throw new Error(`Unhandled IPC: ${command}`);
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Run one smoke test: start the browser, run `body`, fail on page errors, and close the browser.
|
||||
* `body({ browser, page })` returns nothing. Set `allowPageErrors` for tests that expect page errors.
|
||||
*/
|
||||
export async function runSmoke(name, body, { viewport, timeout, allowPageErrors = false } = {}) {
|
||||
const browser = await launchBrowser();
|
||||
try {
|
||||
const page = await openPage(browser, { viewport, timeout });
|
||||
await body({ browser, page });
|
||||
if (!allowPageErrors && page.errors.length) throw new Error(`Page errors:\n${page.errors.join("\n")}`);
|
||||
console.log(`PASS ${name}`);
|
||||
} catch (error) {
|
||||
console.error(`FAIL ${name}`);
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user