238 lines
10 KiB
JavaScript
238 lines
10 KiB
JavaScript
// Run the browser smoke tests in tests/smoke/. See docs/development.md#browser-smoke-tests.
|
|
//
|
|
// pnpm smoke [filter...] [--list] [--jobs N] [--timeout seconds] [--retries N] [--no-serve] [--csp]
|
|
//
|
|
// A filter selects the tests whose path contains it, for example `tabs` or `tables/drag`.
|
|
// After the parallel run, the runner runs each failed test again, one at a time (--retries, default 1).
|
|
// A test that passes on a retry counts as "flaky". The summary lists it, but the run does not fail.
|
|
// A test declares what it needs on a line near the top:
|
|
// // @requires repo:RuneStone_Local_Autocomplete/src electron
|
|
// The runner skips a test, with the reason, when a requirement is missing.
|
|
// A test that fails because of a known app defect states it near the top:
|
|
// // @known-issue <the defect>
|
|
// It still runs. A failure counts as "known". A pass counts as a failure, so remove the stale line.
|
|
// --csp runs the tests under the app's content security policy (RUNESTONE_CSP=1). A test fails on any violation.
|
|
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 retries = Math.max(0, Number(option("--retries", "1")));
|
|
const csp = flag("--csp");
|
|
const filters = args;
|
|
|
|
const env = { ...process.env, SMOKE_URL: process.env.SMOKE_URL || "http://127.0.0.1:1420" };
|
|
if (csp) env.RUNESTONE_CSP = "1";
|
|
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 header(file) {
|
|
const head = (await readFile(file, "utf8")).split("\n").slice(0, 10).join("\n");
|
|
return {
|
|
needs: head.match(/@requires\s+([^\r\n]+)/)?.[1].trim().split(/\s+/) ?? [],
|
|
knownIssue: head.match(/@known-issue\s+([^\r\n]+)/)?.[1].trim(),
|
|
};
|
|
}
|
|
|
|
function missing(requirement) {
|
|
const [kind, value = ""] = requirement.split(/:(.*)/s);
|
|
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;
|
|
}
|
|
}
|
|
|
|
/** True when the server sends the content security policy with the app page (see vite.config.js). */
|
|
async function sendsPolicy(url) {
|
|
try {
|
|
const response = await fetch(url, { headers: { accept: "text/html" }, signal: AbortSignal.timeout(10000) });
|
|
return response.headers.has("content-security-policy");
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async function startServer() {
|
|
const vite = path.join(root, "node_modules", "vite", "bin", "vite.js");
|
|
// Serve on the port in SMOKE_URL, so that two checkouts can run their tests at the same time.
|
|
const port = new URL(env.SMOKE_URL).port || "1420";
|
|
const server = spawn(process.execPath, [vite, "dev", "--port", port, "--strictPort"], { cwd: root, env, 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, knownIssue, logSuffix = "") {
|
|
const name = path.relative(smokeRoot, file).replace(/\\/g, "/").replace(/\.smoke\.mjs$/, "");
|
|
const log = path.join(logRoot, name.replaceAll("/", "__") + logSuffix + ".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);
|
|
let status = code === 0 ? "pass" : Date.now() - started >= timeoutMs ? "timeout" : "fail";
|
|
if (knownIssue) status = status === "pass" ? "unexpected-pass" : "known";
|
|
resolve({ name, status, detail: status === "known" ? knownIssue : `${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, knownIssue } = await header(file);
|
|
const reasons = needs.map(missing).filter(Boolean);
|
|
plan.push({ file, needs, reasons, knownIssue });
|
|
}
|
|
|
|
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();
|
|
// Tests that load plugin source resolve "@runestone/plugin-sdk" to this build.
|
|
if (!existsSync(path.join(root, "packages", "plugin-sdk", "dist", "index.js"))) {
|
|
console.log("Building the plugin SDK...");
|
|
const build = spawn(process.execPath, [path.join(root, "scripts", "buildSdk.mjs")], { cwd: root, stdio: "inherit", windowsHide: true });
|
|
const code = await new Promise(resolve => build.on("close", resolve));
|
|
if (code !== 0) throw new Error("The plugin SDK build failed. Run pnpm sdk:build.");
|
|
}
|
|
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}${csp ? " in CSP mode" : ""}...`);
|
|
server = await startServer();
|
|
}
|
|
if (csp && !(await sendsPolicy(env.SMOKE_URL))) {
|
|
server?.kill();
|
|
console.error(`The server at ${env.SMOKE_URL} does not send a content security policy. Stop it, or set SMOKE_URL to a free port, so that --csp can start a server with RUNESTONE_CSP=1.`);
|
|
process.exit(1);
|
|
}
|
|
|
|
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, knownIssue } = queue.shift();
|
|
const result = { ...await run(file, knownIssue), 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));
|
|
for (let attempt = 1; attempt <= retries; attempt++) {
|
|
for (const result of results.filter(item => ["fail", "timeout"].includes(item.status))) {
|
|
const retry = await run(result.file, undefined, `.retry${attempt}`);
|
|
console.log(`retry ${retry.name}: ${retry.status} (${retry.detail})`);
|
|
if (retry.status === "pass") result.status = "flaky";
|
|
}
|
|
}
|
|
} 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))) {
|
|
const detail = ["skip", "known"].includes(result.status) ? result.detail : path.relative(root, result.log);
|
|
console.log(`${result.status.padEnd(7)} ${result.name}: ${detail}`);
|
|
}
|
|
const failed = count("fail") + count("timeout") + count("unexpected-pass");
|
|
console.log(`\n${count("pass")} passed, ${count("flaky")} flaky, ${failed} failed, ${count("known")} known issues, ${count("skip")} skipped. Logs: ${path.relative(root, logRoot)}`);
|
|
process.exitCode = failed ? 1 : 0;
|