Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

fix(gate): a browser-free file cannot spawn a browser directly [C7,O5]

Corey Olson84d1dd4d6bea
diff --git a/bin/run-tests.js b/bin/run-tests.js
index 06d5da2c..22513fd5 100644
--- a/bin/run-tests.js
+++ b/bin/run-tests.js
@@ -1412,8 +1412,11 @@ if (process.argv[1] && resolve(process.argv[1]) === runner) {
process.once('exit', () => lease.release());
if (byLaunch) process.env.PULLBOARD_TEST_BROWSER_SLOT = 'held';
} else if (byLaunch) {
- // test/chrome-fixture.js refuses a launch from this file and its children by name (BROWSER_SLOT_REQUIRED).
+ // Any browser spawn from this file or a Node child it starts is refused by name (BROWSER_SLOT_REQUIRED).
process.env.PULLBOARD_TEST_BROWSER_SLOT = 'none';
+ const guard = new URL('../src/browser-slot-guard.js', import.meta.url);
+ await import(guard.href);
+ process.env.NODE_OPTIONS = [process.env.NODE_OPTIONS, `--import=${guard.href}`].filter(Boolean).join(' ');
}
}
if (!landingWorker) installTestWatchdog();
diff --git a/docs/api.md b/docs/api.md
index 980ebd7a..5d384b1b 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -12,7 +12,7 @@ A successful command returns the fields listed below. `version` is always the nu
Browser-free check admission is opt-in per machine with `"gate": { "browserFreeChecks": true }` in `~/.pullboard/settings.json`; it defaults to `false`. When enabled, the reviewed test classifier can let checks use a CPU-only gate slot. An absent or false setting keeps every check browser-gated, and uncertain or unsupported test commands remain browser-gated even when enabled. The same setting controls the wider frozen-check classification introduced in 0.8.26.
-Classifying test files by launch is opt-in per machine with `"gate": { "browserByLaunch": true }` in `~/.pullboard/settings.json`; it defaults to `false`. When enabled, the test runner gives a test file a browser slot only when its import graph reaches a real Chrome launch: an import of `startChrome` or `launchChromeProcess` (or any binding other than the launch-free helpers) from `test/chrome-fixture.js`, directly or through a helper, or a process starter beside a Chrome executable reference. Cockpit test files keep the browser slot. Every other file runs without one, and a file that launches Chrome through `test/chrome-fixture.js` while classified browser-free fails at once with `BROWSER_SLOT_REQUIRED` naming the file. An absent or false setting classifies exactly as before, and the launch guard is inert.
+Classifying test files by launch is opt-in per machine with `"gate": { "browserByLaunch": true }` in `~/.pullboard/settings.json`; it defaults to `false`. When enabled, the test runner gives a test file a browser slot only when its import graph reaches a real Chrome launch: an import of `startChrome`, `launchChromeProcess`, `findChromeExecutable` (or any binding other than the DevTools-only helpers) from `test/chrome-fixture.js`, directly or through a helper, or a process starter beside a Chrome executable reference. Cockpit test files keep the browser slot. Every other file runs without one. In such a file, and in every Node child it starts (the runner adds the guard to `NODE_OPTIONS`), a `node:child_process` call that would start a browser (Chrome's install paths, `PULLBOARD_CHROME`'s value, a browser executable name, or one of those inside a shell command string) fails at once with `BROWSER_SLOT_REQUIRED` naming the file, before the browser starts; `test/chrome-fixture.js` checks again at its launch point. An absent or false setting classifies exactly as before, and the launch guard is inert.
The machine gate pool admits landings first and then everything else in arrival order. A machine opts in to reviews first with `"gate": { "queue": { "reviewsFirst": true } }` in `~/.pullboard/settings.json`: the pool then admits landing runs, then reviews, then submits and item checks, then focused and other runs, first come first served within each class. `gate.queue.agingMinutes` (a positive whole number, default `30`) is how long a waiting run waits before it moves up one class, so no class starves; it is used only while `reviewsFirst` is true. `pullboard settings` prints both values, and `pullboard resources` names the order in effect.
diff --git a/src/browser-admission.js b/src/browser-admission.js
index f4791ff4..c66848fd 100644
--- a/src/browser-admission.js
+++ b/src/browser-admission.js
@@ -10,8 +10,12 @@ const CHROME_FIXTURE = 'test/chrome-fixture.js';
const FIXTURE_CHILD = 'test/fixture-child.js';
const JOURNEYS_TEST = 'test/journeys.test.js';
const TEST_RUNNER = 'bin/run-tests.js';
-/** Chrome fixture exports that never start a browser; any other binding, a new export included, counts as a launch. */
-const LAUNCH_FREE_CHROME_EXPORTS = new Set(['findChromeExecutable', 'requireBrowserSlot', 'waitForTargetAbsent', 'createWaiter', 'createSender',
+/**
+ * Chrome fixture exports that neither start a browser nor yield a browser path or launch arguments; any
+ * other binding, findChromeExecutable and a new export included, counts as a launch. These six only work
+ * over an existing DevTools connection, or refuse.
+ */
+const LAUNCH_FREE_CHROME_EXPORTS = new Set(['requireBrowserSlot', 'waitForTargetAbsent', 'createWaiter', 'createSender',
'createEvaluator', 'createPageStepEvaluator']);
/** Imports that let a module start another process or module, which by launch counts only with a Chrome reference. */
const PROCESS_STARTERS = new Set(['node:child_process', 'node:worker_threads', 'node:cluster', 'node:module', 'node:vm']);
@@ -263,9 +267,23 @@ function browserFallback(onFallback, file, reason) {
return true;
}
+/** The runner's launch guard preload for browser-free test files (gate.browserByLaunch): it loads only src/browser-slot-guard.js. */
+const SLOT_GUARD_IMPORT = `--import=${new URL('./browser-slot-guard.js', import.meta.url).href}`;
+
+/**
+ * Whether NODE_OPTIONS may load a module the classifier has not seen. The one exception is this checkout's
+ * own launch guard, which a browser-free test file passes to its children; anything else is unclassified.
+ *
+ * @param {string | undefined} value
+ * @returns {boolean}
+ */
+function unclassifiedNodeOptions(value) {
+ return String(value ?? '').split(/\s+/u).filter(Boolean).some(token => token !== SLOT_GUARD_IMPORT);
+}
+
/** Parse the frozen check and classify its explicit test files, failing closed on unknown shell. */
export async function checkNeedsBrowser(root, command, { commit, env = process.env, onFallback } = {}) {
- if (env.NODE_OPTIONS) return browserFallback(onFallback, '<frozen check>', 'NODE_OPTIONS may load an unclassified module');
+ if (unclassifiedNodeOptions(env.NODE_OPTIONS)) return browserFallback(onFallback, '<frozen check>', 'NODE_OPTIONS may load an unclassified module');
let words = literalShellWords(command);
if (!words) {
const inner = capturedRunner(command);
diff --git a/src/browser-slot-guard.js b/src/browser-slot-guard.js
new file mode 100644
index 00000000..e28bd613
--- /dev/null
+++ b/src/browser-slot-guard.js
@@ -0,0 +1,172 @@
+/**
+ * The runtime half of gate.browserByLaunch [C7]: a test file the runner admitted without a browser slot
+ * (PULLBOARD_TEST_BROWSER_SLOT=none) cannot start a browser, whatever path it takes to one.
+ *
+ * The runner imports this module in each browser-free test file's process before the test body, and
+ * puts it in NODE_OPTIONS so every Node child the file starts installs it too. Installed, it wraps
+ * node:child_process's spawn, spawnSync, exec, execSync, execFile, execFileSync and fork: a call whose
+ * executable is a browser (Chrome's known install paths, PULLBOARD_CHROME's value, or a browser basename,
+ * directly, through PATH or inside a shell command string) throws BROWSER_SLOT_REQUIRED naming the file,
+ * before anything starts. test/chrome-fixture.js keeps its own check at the launch point as a second layer.
+ * Without the marker, importing this module changes nothing.
+ */
+import childProcess from 'node:child_process';
+import { statSync, realpathSync } from 'node:fs';
+import { syncBuiltinESMExports } from 'node:module';
+import { basename, delimiter, isAbsolute, relative, resolve } from 'node:path';
+import { promisify } from 'node:util';
+import { Refused } from './refused.js';
+
+/** The marker the runner sets in a test file's process: held, none, or unset when the setting is off. */
+export const BROWSER_SLOT_ENV = 'PULLBOARD_TEST_BROWSER_SLOT';
+/** Install paths test/chrome-fixture.js's findChromeExecutable looks in, besides PULLBOARD_CHROME. */
+const KNOWN_BROWSERS = ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome',
+ '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser'];
+/** Executable names that are a browser wherever they live. */
+const BROWSER_NAME = /^(?:chrome|chromium|chromium-browser|google-chrome(?:-stable|-beta|-unstable)?|headless_shell|chrome-headless-shell|google chrome(?: for testing| canary)?)(?:\.exe)?$/iu;
+/** Shells whose -c argument is a command string this guard reads word by word. */
+const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'ash']);
+const INSTALLED = Symbol.for('pullboard.browserSlotGuard');
+
+/**
+ * The refusal for a browser launch without a slot, naming the test file the runner recorded.
+ *
+ * @param {string} what - what was started, for the message
+ * @returns {Refused}
+ */
+export function browserSlotRefusal(what) {
+ const absolute = process.env.PULLBOARD_TEST_FILE ? resolve(process.env.PULLBOARD_TEST_FILE) : '';
+ const local = absolute ? relative(process.cwd(), absolute) : '';
+ const file = !absolute ? 'this test file' : (local && !local.startsWith('..') && !isAbsolute(local) ? local : absolute).split('\\').join('/');
+ return new Refused('BROWSER_SLOT_REQUIRED', `${file} launched Chrome (${what}), but the gate classified it browser-free, so it holds no browser slot; import startChrome or launchChromeProcess from test/chrome-fixture.js in that file's own import graph so the gate admits it with a browser slot`,
+ `import startChrome or launchChromeProcess from test/chrome-fixture.js in ${file}'s import graph, then run it again`);
+}
+
+/** A path with symlinks resolved when it exists, so a link to Chrome still reads as Chrome. */
+function canonical(path) {
+ try { return realpathSync(path); } catch { return resolve(path); }
+}
+
+/** Find a bare command through PATH the way the spawn would, or null when it is not there. */
+function onPath(command, pathValue) {
+ for (const directory of String(pathValue ?? '').split(delimiter)) {
+ const candidate = resolve(directory || '.', command);
+ try { if (statSync(candidate).isFile()) return candidate; } catch { /* not in this PATH entry */ }
+ }
+ return null;
+}
+
+/**
+ * Whether one executable word names a browser: by basename, by PATH, or as PULLBOARD_CHROME's value or a
+ * known install path once symlinks are resolved.
+ *
+ * @param {unknown} word
+ * @param {{cwd?: string | URL, env?: Record<string, string | undefined>}} [options]
+ * @returns {boolean}
+ */
+export function isBrowserExecutable(word, { cwd, env } = {}) {
+ if (typeof word !== 'string' && !(word instanceof URL)) return false;
+ const text = word instanceof URL ? word.pathname : word;
+ if (!text) return false;
+ if (BROWSER_NAME.test(basename(text))) return true;
+ const base = cwd instanceof URL ? cwd.pathname : (cwd ?? process.cwd());
+ const path = text.includes('/') ? resolve(String(base), text) : onPath(text, env?.PATH ?? process.env.PATH);
+ if (!path) return false;
+ const real = canonical(path);
+ if (BROWSER_NAME.test(basename(real))) return true;
+ const targets = [process.env.PULLBOARD_CHROME, env?.PULLBOARD_CHROME, ...KNOWN_BROWSERS].filter(Boolean).map(canonical);
+ return targets.includes(real);
+}
+
+/**
+ * The words of a shell command string, quotes removed, split at blanks and shell operators. A reference
+ * to $PULLBOARD_CHROME expands to its value. It errs toward finding a browser, never toward missing one.
+ *
+ * @param {string} command
+ * @returns {string[]}
+ */
+function shellWords(command) {
+ const chrome = process.env.PULLBOARD_CHROME ?? '';
+ const expanded = String(command).replace(/\$\{PULLBOARD_CHROME\}|\$PULLBOARD_CHROME\b/gu, () => (chrome ? `'${chrome}'` : 'google-chrome'));
+ const words = [];
+ let word = '';
+ let quote = '';
+ for (const character of expanded) {
+ if (quote) {
+ if (character === quote) quote = '';
+ else word += character;
+ } else if (character === '"' || character === "'") quote = character;
+ else if (/[\s;&|()<>`]/u.test(character)) { if (word) words.push(word); word = ''; }
+ else if (character !== '\\') word += character;
+ }
+ if (word) words.push(word);
+ return words;
+}
+
+/** Whether a shell command string starts a browser in any word position. */
+function shellStartsBrowser(command, options) {
+ return shellWords(command).some(word => isBrowserExecutable(word, options));
+}
+
+/**
+ * What browser a child_process call would start, or null: the executable itself, a shell's -c string,
+ * a command run with shell: true, or fork's execPath.
+ *
+ * @param {string} method
+ * @param {unknown[]} input
+ * @returns {string | null}
+ */
+export function browserInCall(method, input) {
+ const [first, second, third] = input;
+ if (method === 'exec' || method === 'execSync') {
+ const options = second && typeof second === 'object' ? second : {};
+ return typeof first === 'string' && shellStartsBrowser(first, options) ? first : null;
+ }
+ const args = Array.isArray(second) ? second.map(String) : [];
+ const raw = Array.isArray(second) ? third : second;
+ const options = raw && typeof raw === 'object' ? raw : {};
+ if (method === 'fork') return options.execPath && isBrowserExecutable(options.execPath, options) ? String(options.execPath) : null;
+ if (isBrowserExecutable(first, options)) return String(first);
+ if (options.shell && shellStartsBrowser([first, ...args].join(' '), options)) return [first, ...args].join(' ');
+ if (typeof first === 'string' && SHELLS.has(basename(first))) {
+ const flag = args.findIndex(arg => /^-[a-z]*c[a-z]*$/iu.test(arg));
+ if (flag >= 0 && args[flag + 1] !== undefined && shellStartsBrowser(args[flag + 1], options)) return args[flag + 1];
+ }
+ if (typeof options.shell === 'string' && isBrowserExecutable(options.shell, options)) return options.shell;
+ return null;
+}
+
+/**
+ * Wrap node:child_process so a browser-free test file cannot start a browser, and publish the wrapped
+ * functions to ES module importers. Idempotent; inert unless the marker says none.
+ *
+ * @returns {boolean} whether the guard is installed
+ */
+export function installBrowserSlotGuard() {
+ if (process.env[BROWSER_SLOT_ENV] !== 'none') return false;
+ if (globalThis[INSTALLED]) return true;
+ globalThis[INSTALLED] = true;
+ for (const method of ['spawn', 'spawnSync', 'exec', 'execSync', 'execFile', 'execFileSync', 'fork']) {
+ const original = childProcess[method];
+ /** Refuse a browser before the original call can start it; anything else runs unchanged. */
+ const guarded = function guardedChildProcess(...input) {
+ const browser = browserInCall(method, input);
+ if (browser) throw browserSlotRefusal(browser);
+ return original.apply(this, input);
+ };
+ const custom = original[promisify.custom];
+ if (custom) {
+ /** The promisified form takes the same arguments, so it gets the same check. */
+ guarded[promisify.custom] = function guardedPromisified(...input) {
+ const browser = browserInCall(method, input);
+ if (browser) return Promise.reject(browserSlotRefusal(browser));
+ return custom.apply(this, input);
+ };
+ }
+ childProcess[method] = guarded;
+ }
+ syncBuiltinESMExports();
+ return true;
+}
+
+installBrowserSlotGuard();
diff --git a/test/chrome-fixture.js b/test/chrome-fixture.js
index 2b8616da..62d2a585 100644
--- a/test/chrome-fixture.js
+++ b/test/chrome-fixture.js
@@ -3,8 +3,8 @@ import { startFixtureChild as spawn } from './fixture-child.js';
import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { loadavg, tmpdir } from 'node:os';
import { monitorEventLoopDelay } from 'node:perf_hooks';
-import { isAbsolute, join, relative, resolve } from 'node:path';
-import { Refused } from '../src/refused.js';
+import { join, resolve } from 'node:path';
+import { browserSlotRefusal } from '../src/browser-slot-guard.js';
const STARTUP_TIMEOUT_MS = 30_000;
const COMMAND_TIMEOUT_MS = 15_000;
@@ -141,16 +141,12 @@ async function stopProcessGroup(child, stopped, timeoutMs = CLEANUP_TIMEOUT_MS)
/**
* Refuse a Chrome launch from a test file the runner admitted without a browser slot [C7].
* With gate.browserByLaunch on, the runner marks each file's worker held or none; a launch under none
- * means the classifier missed a launch path, so the file fails here by name before Chrome starts,
- * and a wrong classification can never run Chrome outside the slot. Without a marker this is inert.
+ * means the classifier missed a launch path, so the file fails here by name before Chrome starts.
+ * This is the second layer: src/browser-slot-guard.js refuses any browser spawn under none as well.
+ * Without a marker this is inert.
*/
export function requireBrowserSlot() {
- if (process.env.PULLBOARD_TEST_BROWSER_SLOT !== 'none') return;
- const absolute = process.env.PULLBOARD_TEST_FILE ? resolve(process.env.PULLBOARD_TEST_FILE) : '';
- const local = absolute ? relative(process.cwd(), absolute) : '';
- const file = !absolute ? 'this test file' : (local && !local.startsWith('..') && !isAbsolute(local) ? local : absolute).split('\\').join('/');
- throw new Refused('BROWSER_SLOT_REQUIRED', `${file} launched Chrome, but the gate classified it browser-free, so it holds no browser slot; import startChrome or launchChromeProcess from test/chrome-fixture.js in that file's own import graph so the gate admits it with a browser slot`,
- `import startChrome or launchChromeProcess from test/chrome-fixture.js in ${file}'s import graph, then run it again`);
+ if (process.env.PULLBOARD_TEST_BROWSER_SLOT === 'none') throw browserSlotRefusal('through test/chrome-fixture.js');
}
/** Launch an executable as a detached process group and retain its stderr and launch timing. */
diff --git a/test/test-resources.test.js b/test/test-resources.test.js
index 7018b40f..3c8e79ea 100644
--- a/test/test-resources.test.js
+++ b/test/test-resources.test.js
@@ -8,6 +8,7 @@ import { tmpdir } from 'node:os';
import { delimiter, dirname, join, resolve } from 'node:path';
import { test } from 'node:test';
import { browserBoundFiles, checkNeedsBrowser, testsNeedBrowser } from '../src/browser-admission.js';
+import { browserInCall } from '../src/browser-slot-guard.js';
const TEST_RUNNER = resolve(import.meta.dirname, '../bin/run-tests.js');
@@ -134,6 +135,12 @@ test('frozen checks classify only explicit source-backed test commands [C7]', as
assert.equal(await checkNeedsBrowser(root, command, {
env: { ...classifyEnv, NODE_OPTIONS: '--import=unclassified-loader.mjs' },
}), true, 'an unknown Node preload still fails closed to browser admission');
+ assert.equal(await checkNeedsBrowser(root, command, {
+ env: { ...classifyEnv, NODE_OPTIONS: `--import=${new URL('../src/browser-slot-guard.js', import.meta.url).href}` },
+ }), false, "the runner's own launch guard preload, inherited from a browser-free test file, is not an unknown preload [C7,O5]");
+ assert.equal(await checkNeedsBrowser(root, command, {
+ env: { ...classifyEnv, NODE_OPTIONS: `--import=${new URL('../src/browser-slot-guard.js', import.meta.url).href} --import=x.mjs` },
+ }), true, 'the guard preload does not excuse another preload beside it');
const runnerPath = join(root, 'bin/run-tests.js');
rmSync(runnerPath);
@@ -271,15 +278,19 @@ function runnerFixture(t, tests) {
chmodSync(chrome, 0o755);
const init = spawnSync('git', ['init', '-q'], { cwd: root, env: plainGitEnvironment(), encoding: 'utf8' });
assert.equal(init.status, 0, init.stderr);
- /** Run the copied runner on named files with gate.browserByLaunch set as given; return its output and records. */
- function run(byLaunch, files) {
+ /**
+ * Run the copied runner on named files with gate.browserByLaunch set as given; return its output and records.
+ * PULLBOARD_CHROME names the stand-in only when asked, so a run can show which guard layer refused.
+ */
+ function run(byLaunch, files, { chromeSetting = false } = {}) {
writeFileSync(join(root, 'machine/settings.json'), `${JSON.stringify({ gate: { browserByLaunch: byLaunch } })}\n`);
for (const record of ['markers', 'launches']) rmSync(join(root, record), { force: true });
const env = plainGitEnvironment();
for (const key of Object.keys(env)) {
if (key.startsWith('PULLBOARD_GATE_SLOT_') || key.startsWith('PULLBOARD_TEST_BROWSER_')) delete env[key];
}
- for (const key of ['NODE_TEST_CONTEXT', 'NODE_OPTIONS', 'PULLBOARD_BROWSER_SLOT_HELD', 'PULLBOARD_TEST_FILE']) delete env[key];
+ for (const key of ['NODE_TEST_CONTEXT', 'NODE_OPTIONS', 'PULLBOARD_BROWSER_SLOT_HELD', 'PULLBOARD_TEST_FILE', 'PULLBOARD_CHROME']) delete env[key];
+ if (chromeSetting) env.PULLBOARD_CHROME = chrome;
Object.assign(env, { PULLBOARD_MACHINE_HOME: join(root, 'machine'), PULLBOARD_FIXTURE_MARKERS: join(root, 'markers'),
PULLBOARD_FIXTURE_LAUNCHES: join(root, 'launches'), FIXTURE_BROWSER: chrome });
const result = spawnSync(process.execPath, ['bin/run-tests.js', ...files], { cwd: root, env, encoding: 'utf8' });
@@ -301,7 +312,8 @@ test('${name} records its browser slot marker', () => {
test('only a file that reaches a browser launch takes a browser slot [C7,O5]', async t => {
const root = sourceFixture(t, {
'test/chrome-fixture.js': "throw new Error('admission must never launch or evaluate Chrome');",
- 'test/helpers.test.js': "import { spawnSync } from 'node:child_process';\nimport { createWaiter, findChromeExecutable } from './chrome-fixture.js';\nvoid spawnSync; void createWaiter; void findChromeExecutable;",
+ 'test/helpers.test.js': "import { spawnSync } from 'node:child_process';\nimport { createWaiter, createEvaluator } from './chrome-fixture.js';\nvoid spawnSync; void createWaiter; void createEvaluator;",
+ 'test/finder.test.js': "import { findChromeExecutable } from './chrome-fixture.js';\nvoid findChromeExecutable;",
'test/launch.test.js': "import { startChrome } from './chrome-fixture.js';\nvoid startChrome;",
'test/renamed.test.js': "import { launchChromeProcess as begin } from './chrome-fixture.js';\nvoid begin;",
'test/wrapped.test.js': "import { open } from '../wrapper.js';\nvoid open;",
@@ -314,7 +326,7 @@ test('only a file that reaches a browser launch takes a browser slot [C7,O5]', a
assert.equal(await byLaunch('test/helpers.test.js'), false,
'importing launch-free Chrome fixture helpers and child_process takes no browser slot by launch');
assert.equal(await byLaunch('test/spawner.test.js'), false, 'a process starter with no Chrome reference takes no browser slot by launch');
- for (const file of ['launch', 'renamed', 'wrapped', 'everything', 'direct']) {
+ for (const file of ['launch', 'renamed', 'wrapped', 'everything', 'finder', 'direct']) {
assert.equal(await byLaunch(`test/${file}.test.js`), true, `${file}: a graph that reaches a Chrome launch takes the browser slot`);
}
assert.equal(await byLaunch('test/cockpit/items.test.js'), true,
@@ -387,4 +399,54 @@ test('child launches from a process the test starts', () => {
const off = runner.run(false, ['test/hidden.test.js']);
assert.equal(off.status, 0, off.output);
assert.deepEqual(off.launches, ['hidden'], 'with gate.browserByLaunch off the guard is inert and the file launches as today');
+
+ // tests-42's counterexample (shout 11929): browser starts that never pass through test/chrome-fixture.js.
+ const direct = runnerFixture(t, {
+ 'test/direct.test.js': `import { spawnSync } from 'node:child_process';
+import { test } from 'node:test';
+test('direct starts the configured browser path itself', () => { spawnSync(process.env.FIXTURE_BROWSER, ['direct']); });
+`,
+ 'test/finder.test.js': `import { spawnSync } from 'node:child_process';
+import { test } from 'node:test';
+test('finder starts the path the normal browser finder returns', async () => {
+ const { findChromeExecutable } = await import(['.', 'chrome-fixture.js'].join('/'));
+ spawnSync(findChromeExecutable(), ['finder']);
+});
+`,
+ 'test/shell.test.js': `import { execSync, spawnSync } from 'node:child_process';
+import { test } from 'node:test';
+test('shell starts the browser from an sh -c string', () => { spawnSync('sh', ['-c', \`'\${process.env.FIXTURE_BROWSER}' shell\`]); });
+test('shell starts the browser through exec', () => { execSync(\`'\${process.env.FIXTURE_BROWSER}' exec\`); });
+`,
+ 'test/spawned.test.js': `import { spawnSync } from 'node:child_process';
+import { test } from 'node:test';
+test('spawned starts a Node child that starts the browser', () => {
+ const result = spawnSync(process.execPath, ['test/direct-helper.mjs'], { encoding: 'utf8' });
+ if (result.status !== 0) throw new Error(result.stderr);
+});
+`,
+ 'test/direct-helper.mjs': "import { spawnSync } from 'node:child_process';\nspawnSync(process.env.FIXTURE_BROWSER, ['grandchild']);\n",
+ 'test/static-finder.test.js': "import { findChromeExecutable } from './chrome-fixture.js';\nvoid findChromeExecutable;\n",
+ });
+ const directFiles = ['test/direct.test.js', 'test/finder.test.js', 'test/shell.test.js', 'test/spawned.test.js'];
+ for (const file of directFiles) {
+ assert.equal(await testsNeedBrowser(direct.root, [file], { byLaunch: true }), false, `${file}: the fixture really is classified browser-free`);
+ }
+ assert.equal(await testsNeedBrowser(direct.root, ['test/static-finder.test.js'], { byLaunch: true }), true,
+ 'importing findChromeExecutable yields a browser path, so it counts as a launch');
+ const spawned = direct.run(true, directFiles, { chromeSetting: true });
+ assert.notEqual(spawned.status, 0, spawned.output);
+ for (const file of directFiles) {
+ assert.match(spawned.output, new RegExp(`\\[BROWSER_SLOT_REQUIRED\\] test/${file.slice(5).replaceAll('.', '\\.')} launched Chrome`, 'u'),
+ `${file}: a direct browser spawn fails by file name`);
+ }
+ assert.deepEqual(spawned.launches, [], 'no direct, finder, shell, exec or child spawn started the browser outside the slot');
+ for (const [method, input] of [
+ ['spawn', ['google-chrome', ['--headless']]], ['execFileSync', ['/opt/x/chromium', []]], ['spawnSync', ['headless_shell']],
+ ['spawn', ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', []]], ['execSync', ['cd /tmp && google-chrome-stable --version']],
+ ['spawnSync', ['bash', ['-lc', 'exec chromium-browser']]], ['spawn', ['echo chrome', [], { shell: true }]], ['fork', ['x.js', [], { execPath: '/usr/bin/chromium' }]],
+ ]) assert.ok(browserInCall(method, input), `${method} ${JSON.stringify(input)} names a browser by basename`);
+ for (const [method, input] of [['spawnSync', ['git', ['status']]], ['execSync', ['printf chrome-fixture.js']], ['spawn', [process.execPath, ['-e', 'google-chrome']]]]) {
+ assert.equal(browserInCall(method, input), null, `${method} ${JSON.stringify(input)} is not a browser`);
+ }
});