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:
@@ -23,6 +23,9 @@ if (config.bundle?.windows?.allowDowngrades === true) throw Error('Downgrade pro
|
||||
const platformConfig = JSON.parse(await fs.readFile(path.join(root, 'src-tauri/tauri.windows.conf.json'), 'utf8'));
|
||||
if (platformConfig.bundle.windows.allowDowngrades !== false) throw Error('Downgrade protection must remain enabled.');
|
||||
if (process.platform !== 'win32') throw Error('Build the Windows installer on Windows.');
|
||||
if (!(await exists(path.join(root, 'src-tauri/browser-engine/RuneStone-Browser.exe')))) {
|
||||
throw Error('The browser runtime is not staged. Run pnpm browser:stage first. See docs/development.md#built-in-browser-runtime.');
|
||||
}
|
||||
const artifactDir = path.join(root, 'src-tauri/target/release/bundle/nsis');
|
||||
const artifact = path.join(artifactDir, `RuneStone_${next.version}_x64-setup.exe`);
|
||||
const internalArtifact = path.join(artifactDir, `RuneStone_${next.toolchain}_x64-setup.exe`);
|
||||
@@ -30,7 +33,8 @@ const releaseDir = path.join(root, 'releases', next.version);
|
||||
const releaseArtifact = path.join(releaseDir, path.basename(artifact));
|
||||
const metadataPath = path.join(releaseDir, 'host.json');
|
||||
for (const file of new Set([artifact, internalArtifact, releaseArtifact, metadataPath])) if (await exists(file)) throw Error('The release file already exists: ' + file);
|
||||
const staging = path.join(root, 'output/installer-build', next.version);
|
||||
// Each attempt keeps its own backups, so a later attempt cannot replace them.
|
||||
const staging = path.join(root, 'output/installer-build', next.version, new Date().toISOString().replaceAll(':', '-'));
|
||||
await fs.mkdir(staging, { recursive: true });
|
||||
for (let i = 0; i < files.length; i++) await fs.writeFile(path.join(staging, path.basename(files[i]) + '.before'), before[i]);
|
||||
let template = await fs.readFile(path.join(root, 'src-tauri/windows/installer.nsi'), 'utf8');
|
||||
@@ -53,12 +57,17 @@ if (/\[package\.metadata\.runestone\]/.test(cargo)) {
|
||||
const lock = before[3].replace(/(name = "runestone"\r?\nversion = ")[^"]+"/, `$1${next.toolchain}"`);
|
||||
const updated = [JSON.stringify(packageJson, null, 2) + '\n', JSON.stringify(config, null, 2) + '\n', cargo, lock];
|
||||
const env = { ...process.env, GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'safe.directory', GIT_CONFIG_VALUE_0: root.replaceAll('\\', '/') };
|
||||
// Ctrl+C also stops the child build. Keep this process alive so that the version files are restored.
|
||||
let interrupted = false;
|
||||
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => { interrupted = true; process.exitCode = 130; });
|
||||
async function run(command, parameters) {
|
||||
if (interrupted) throw Error('The build was interrupted.');
|
||||
console.log(command + ' ' + parameters.join(' '));
|
||||
const code = await new Promise((resolve, reject) => {
|
||||
const child = spawn(command, parameters, { cwd: root, env, stdio: 'inherit', windowsHide: true });
|
||||
child.on('error', reject); child.on('exit', resolve);
|
||||
});
|
||||
if (interrupted) throw Error('The build was interrupted.');
|
||||
if (code !== 0) throw Error('The build command failed with exit code ' + code);
|
||||
}
|
||||
let complete = false;
|
||||
@@ -75,7 +84,7 @@ try {
|
||||
await fs.copyFile(artifact, releaseArtifact, 1);
|
||||
const bytes = await fs.readFile(releaseArtifact);
|
||||
const metadata = { version: next.version, toolchainVersion: next.toolchain, windowsVersion: next.windows,
|
||||
source: releaseArtifact, path: releaseArtifact, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
|
||||
file: path.basename(releaseArtifact), bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
|
||||
await fs.writeFile(metadataPath, JSON.stringify(metadata, null, 2) + '\n', { flag: 'wx' });
|
||||
await fs.unlink(artifact);
|
||||
complete = true;
|
||||
@@ -83,6 +92,7 @@ try {
|
||||
} finally {
|
||||
if (!complete) {
|
||||
for (let i = 0; i < files.length; i++) await fs.writeFile(files[i], before[i]);
|
||||
console.error('The build did not complete. The version fields are restored. Backups: ' + staging);
|
||||
for (const file of new Set([artifact, internalArtifact, releaseArtifact, metadataPath])) {
|
||||
if (await exists(file)) await fs.rename(file, path.join(staging, path.basename(file) + '.failed-' + Date.now()));
|
||||
}
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
import { mkdir, cp, access } from "node:fs/promises";
|
||||
import { mkdir, cp, access, rm } from "node:fs/promises";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { packagePlugin } from "./packagePlugin.mjs";
|
||||
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const formulasRoot = resolve(process.env.RUNESTONE_TABLE_FORMULAS_ROOT || resolve(root, "../RuneStone_Table_Formulas"));
|
||||
const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || resolve(root, "..");
|
||||
const formulasRoot = resolve(process.env.RUNESTONE_TABLE_FORMULAS_ROOT || resolve(pluginRepos, "RuneStone_Table_Formulas"));
|
||||
const formulasBuild = resolve(formulasRoot, "scripts/build.mjs");
|
||||
try {
|
||||
await access(formulasBuild);
|
||||
} catch {
|
||||
throw new Error("Clone RuneStone_Table_Formulas beside RuneStone, or set RUNESTONE_TABLE_FORMULAS_ROOT. Install its dependencies before building plugins.");
|
||||
throw new Error("Clone RuneStone_Table_Formulas beside RuneStone, or set RUNESTONE_PLUGIN_REPOS or RUNESTONE_TABLE_FORMULAS_ROOT. Install its dependencies before building plugins.");
|
||||
}
|
||||
execFileSync(process.execPath, [formulasBuild], { cwd: formulasRoot, stdio: "inherit" });
|
||||
const formulasOutput = resolve(root, "plugin-packages/table-formulas");
|
||||
// Remove the previous build, so deleted plugin files do not stay in the package.
|
||||
await rm(formulasOutput, { recursive: true, force: true });
|
||||
await mkdir(formulasOutput, { recursive: true });
|
||||
await cp(resolve(formulasRoot, "dist/plugin"), formulasOutput, { recursive: true });
|
||||
console.log(await packagePlugin(formulasOutput, resolve(formulasRoot, "releases")));
|
||||
|
||||
@@ -3,6 +3,7 @@ import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||
const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || path.resolve(root, '..');
|
||||
export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_Terminal', 'RuneStone_Background_Slideshow', 'RuneStone_Local_Autocomplete', 'RuneStone_Git', 'RuneStone_PDF_Viewer', 'RuneStone_Table_Formulas', 'RuneStone_CSV_Viewer'];
|
||||
const patterns = {
|
||||
action: /\b(?:showActionMenu|actionMenu)\s*\(/g,
|
||||
@@ -20,7 +21,7 @@ async function files(dir) {
|
||||
export async function discover() {
|
||||
const surfaces = {}, missing = [];
|
||||
for (const project of projects) {
|
||||
const base = project === 'RuneStone' ? root : path.resolve(root, '..', project);
|
||||
const base = project === 'RuneStone' ? root : path.resolve(pluginRepos, project);
|
||||
let sources;
|
||||
try { sources = await files(path.join(base, 'src')); } catch (error) { if (error.code === 'ENOENT') { missing.push(project); continue; } throw error; }
|
||||
for (const file of sources) {
|
||||
@@ -45,7 +46,7 @@ export async function checkInventory() {
|
||||
for (const name of ['actionMenu.ts', 'managedActionMenu.ts', 'IconButton.svelte']) {
|
||||
try {
|
||||
const host = await readFile(path.join(root, 'src/lib/ui', name), 'utf8');
|
||||
const terminal = await readFile(path.resolve(root, '../RuneStone_Terminal/vendor/runestone/ui', name), 'utf8');
|
||||
const terminal = await readFile(path.resolve(pluginRepos, 'RuneStone_Terminal/vendor/runestone/ui', name), 'utf8');
|
||||
if (host.replaceAll('\r\n', '\n') !== terminal.replaceAll('\r\n', '\n')) failures.push(`Terminal shared snapshot differs: ${name}`);
|
||||
} catch (error) { failures.push(`Cannot check Terminal snapshot ${name}: ${error.code}`); }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
// Run the browser smoke tests in tests/smoke/. See docs/development.md#browser-smoke-tests.
|
||||
//
|
||||
// pnpm smoke [filter...] [--list] [--jobs N] [--timeout seconds] [--no-serve]
|
||||
//
|
||||
// A filter selects the tests whose path contains it, for example `tabs` or `tables/drag`.
|
||||
// A test declares what it needs on a line near the top:
|
||||
// // @requires plugin:terminal plugin:table-formulas repo:RuneStone_Git/dist electron
|
||||
// The runner skips a test, with the reason, when a requirement is missing.
|
||||
import { spawn } from "node:child_process";
|
||||
import { createWriteStream, existsSync } from "node:fs";
|
||||
import { mkdir, readdir, readFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const smokeRoot = path.join(root, "tests", "smoke");
|
||||
const logRoot = path.join(root, "output", "smoke", "logs");
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const option = (name, fallback) => {
|
||||
const index = args.indexOf(name);
|
||||
if (index < 0) return fallback;
|
||||
const [value] = args.splice(index, 2).slice(1);
|
||||
return value;
|
||||
};
|
||||
const flag = name => {
|
||||
const index = args.indexOf(name);
|
||||
if (index >= 0) args.splice(index, 1);
|
||||
return index >= 0;
|
||||
};
|
||||
const list = flag("--list");
|
||||
const serve = !flag("--no-serve");
|
||||
const jobs = Math.max(1, Number(option("--jobs", "4")));
|
||||
const timeoutMs = Math.max(10, Number(option("--timeout", "180"))) * 1000;
|
||||
const filters = args;
|
||||
|
||||
const env = { ...process.env, SMOKE_URL: process.env.SMOKE_URL || "http://127.0.0.1:1420" };
|
||||
const pluginRepos = env.RUNESTONE_PLUGIN_REPOS || path.join(root, "..");
|
||||
|
||||
async function findTests(dir) {
|
||||
const result = [];
|
||||
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory() && !entry.name.startsWith("_")) result.push(...await findTests(full));
|
||||
else if (entry.isFile() && entry.name.endsWith(".smoke.mjs")) result.push(full);
|
||||
}
|
||||
return result.sort();
|
||||
}
|
||||
|
||||
async function requirements(file) {
|
||||
const head = (await readFile(file, "utf8")).split("\n").slice(0, 10).join("\n");
|
||||
return head.match(/@requires\s+([^\n]+)/)?.[1].trim().split(/\s+/) ?? [];
|
||||
}
|
||||
|
||||
function missing(requirement) {
|
||||
const [kind, value = ""] = requirement.split(/:(.*)/s);
|
||||
if (kind === "plugin" && value === "terminal") {
|
||||
const dist = env.RUNESTONE_TERMINAL_DIST || path.join(pluginRepos, "RuneStone_Terminal", "dist");
|
||||
return existsSync(path.join(dist, "main.js")) ? null : `the Terminal plugin is not built at ${dist}`;
|
||||
}
|
||||
if (kind === "plugin") {
|
||||
const entry = path.join(root, "plugin-packages", value, "main.js");
|
||||
return existsSync(entry) ? null : `plugin-packages/${value} is missing; run pnpm build:plugins`;
|
||||
}
|
||||
if (kind === "repo") {
|
||||
const target = path.join(pluginRepos, value);
|
||||
return existsSync(target) ? null : `${target} is missing; set RUNESTONE_PLUGIN_REPOS to the folder of the plugin checkouts`;
|
||||
}
|
||||
if (kind === "electron") {
|
||||
return existsSync(path.join(root, "browser-runtime", "node_modules", "electron")) ? null : "Electron is missing; run npm ci --prefix browser-runtime";
|
||||
}
|
||||
return `unknown requirement "${requirement}"`;
|
||||
}
|
||||
|
||||
function findChrome() {
|
||||
if (env.CHROME_PATH || env.PLAYWRIGHT_MODULE) return;
|
||||
try {
|
||||
const bundled = createRequire(import.meta.url)("playwright").chromium.executablePath();
|
||||
if (existsSync(bundled)) return;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const candidates = {
|
||||
win32: [
|
||||
path.join(env.PROGRAMFILES || "C:\\Program Files", "Google\\Chrome\\Application\\chrome.exe"),
|
||||
path.join(env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)", "Microsoft\\Edge\\Application\\msedge.exe"),
|
||||
path.join(env.PROGRAMFILES || "C:\\Program Files", "Microsoft\\Edge\\Application\\msedge.exe"),
|
||||
],
|
||||
darwin: ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium"],
|
||||
linux: ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"],
|
||||
}[process.platform] ?? [];
|
||||
const found = candidates.find(existsSync);
|
||||
if (found) env.CHROME_PATH = found;
|
||||
else console.warn("No Chromium found. Run `pnpm exec playwright install chromium`, or set CHROME_PATH.");
|
||||
}
|
||||
|
||||
async function reachable(url) {
|
||||
try {
|
||||
await fetch(url, { signal: AbortSignal.timeout(2000) });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function startServer() {
|
||||
const vite = path.join(root, "node_modules", "vite", "bin", "vite.js");
|
||||
const server = spawn(process.execPath, [vite, "dev"], { cwd: root, stdio: "ignore", windowsHide: true });
|
||||
for (let waited = 0; waited < 60000; waited += 500) {
|
||||
if (await reachable(env.SMOKE_URL)) return server;
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
}
|
||||
server.kill();
|
||||
throw new Error(`The dev server did not start at ${env.SMOKE_URL}.`);
|
||||
}
|
||||
|
||||
function run(file) {
|
||||
const name = path.relative(smokeRoot, file).replace(/\\/g, "/").replace(/\.smoke\.mjs$/, "");
|
||||
const log = path.join(logRoot, name.replaceAll("/", "__") + ".log");
|
||||
const started = Date.now();
|
||||
return new Promise(resolve => {
|
||||
const out = createWriteStream(log);
|
||||
const child = spawn(process.execPath, [file], { cwd: root, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
||||
child.stdout.pipe(out, { end: false });
|
||||
child.stderr.pipe(out, { end: false });
|
||||
const timer = setTimeout(() => child.kill(), timeoutMs);
|
||||
child.on("close", code => {
|
||||
clearTimeout(timer);
|
||||
out.end();
|
||||
const seconds = ((Date.now() - started) / 1000).toFixed(1);
|
||||
const status = code === 0 ? "pass" : Date.now() - started >= timeoutMs ? "timeout" : "fail";
|
||||
resolve({ name, status, detail: `${seconds}s`, log });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const tests = (await findTests(smokeRoot)).filter(file => {
|
||||
const rel = path.relative(smokeRoot, file).replace(/\\/g, "/");
|
||||
return !filters.length || filters.some(filter => rel.includes(filter));
|
||||
});
|
||||
if (!tests.length) {
|
||||
console.error(`No smoke tests match: ${filters.join(" ")}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const plan = [];
|
||||
for (const file of tests) {
|
||||
const needs = await requirements(file);
|
||||
const reasons = needs.map(missing).filter(Boolean);
|
||||
plan.push({ file, needs, reasons });
|
||||
}
|
||||
|
||||
if (list) {
|
||||
for (const { file, needs, reasons } of plan) {
|
||||
const name = path.relative(smokeRoot, file).replace(/\\/g, "/");
|
||||
console.log(`${reasons.length ? "skip" : "run "} ${name}${needs.length ? ` [${needs.join(" ")}]` : ""}${reasons.length ? ` (${reasons.join("; ")})` : ""}`);
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
findChrome();
|
||||
await mkdir(logRoot, { recursive: true });
|
||||
let server;
|
||||
if (!(await reachable(env.SMOKE_URL))) {
|
||||
if (!serve) {
|
||||
console.error(`Nothing serves ${env.SMOKE_URL}. Start pnpm dev, or run without --no-serve.`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`Starting the dev server at ${env.SMOKE_URL}...`);
|
||||
server = await startServer();
|
||||
}
|
||||
|
||||
const results = [];
|
||||
const queue = plan.filter(item => !item.reasons.length);
|
||||
for (const item of plan.filter(item => item.reasons.length)) {
|
||||
results.push({ name: path.relative(smokeRoot, item.file).replace(/\\/g, "/").replace(/\.smoke\.mjs$/, ""), status: "skip", detail: item.reasons.join("; ") });
|
||||
}
|
||||
async function worker() {
|
||||
while (queue.length) {
|
||||
const { file } = queue.shift();
|
||||
const result = await run(file);
|
||||
results.push(result);
|
||||
console.log(`${result.status.padEnd(7)} ${result.name} (${result.detail})`);
|
||||
}
|
||||
}
|
||||
try {
|
||||
await Promise.all(Array.from({ length: Math.min(jobs, queue.length || 1) }, worker));
|
||||
} finally {
|
||||
server?.kill();
|
||||
}
|
||||
|
||||
const count = status => results.filter(result => result.status === status).length;
|
||||
console.log("");
|
||||
for (const result of results.filter(item => item.status !== "pass").sort((a, b) => a.name.localeCompare(b.name))) {
|
||||
console.log(`${result.status.padEnd(7)} ${result.name}: ${result.status === "skip" ? result.detail : path.relative(root, result.log)}`);
|
||||
}
|
||||
console.log(`\n${count("pass")} passed, ${count("fail") + count("timeout")} failed, ${count("skip")} skipped. Logs: ${path.relative(root, logRoot)}`);
|
||||
process.exitCode = count("fail") + count("timeout") ? 1 : 0;
|
||||
Reference in New Issue
Block a user