Files
RuneStone/tests/smoke/_harness/index.mjs
T
Knotty Wyvern 69f90df571 Move the smoke tests onto the shared harness
Each smoke test now uses tests/smoke/_harness/ for Playwright, the Tauri
IPC mock, the in-memory workspace, and output folders, instead of its
own copy. The tests keep their interactions and assertions. Mock
handlers that the app never calls are gone.

- Split the four mixed regression scripts into 18 feature tests.
- Update tests that broke when the app changed on purpose. Each update
  cites the app source that shows the new behavior.
- Mark two real app defects with @known-issue: the settings window
  controls are 1px shorter than the main window controls, and plugin
  tabs cannot be reordered by dragging without a workspace.
- Merge three palette unit tests into one table-driven test.
- The native tests load Playwright through the harness and read
  NATIVE_CDP_URL, with their old variable names as fallbacks.
- A failed smoke test saves a screenshot and prints the console errors.
- The runner runs failed tests once more, alone, and reports a test
  that then passes as flaky.

Result: 89 passed, 1 flaky, 2 known issues, 0 failed. Before, 45 of 78
passed.
2026-10-27 20:58:55 -07:00

205 lines
9.7 KiB
JavaScript

// 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`, and console errors and warnings in `page.console`.
* `target` is a browser or a browser context. A context page keeps the context viewport unless `viewport` is given.
*/
export async function openPage(target, { viewport, timeout = 10000, ...options } = {}) {
const isContext = typeof target.browser === "function";
const page = isContext ? await target.newPage() : await target.newPage({ viewport: viewport ?? { width: 1440, height: 1000 }, ...options });
if (isContext && viewport) await page.setViewportSize(viewport);
page.setDefaultTimeout(timeout);
page.errors = [];
page.console = [];
page.on("pageerror", error => page.errors.push(error.message));
page.on("console", message => {
if (["error", "warning"].includes(message.type())) page.console.push(`${message.type()}: ${message.text()}`);
});
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.
* On failure, the test saves `failure.png` in its output folder and prints the console errors and warnings.
*/
export async function runSmoke(name, body, { viewport, timeout, allowPageErrors = false } = {}) {
const browser = await launchBrowser();
let page;
try {
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);
if (page) {
if (page.console.length) console.error(`Console:\n${page.console.join("\n")}`);
const file = path.join(await outputDir(name), "failure.png");
if (await page.screenshot({ path: file }).then(() => true, () => false)) console.error(`Screenshot: ${file}`);
}
process.exitCode = 1;
} finally {
await browser.close();
}
}