diff --git a/README.md b/README.md index adab6d72..465aebff 100644 --- a/README.md +++ b/README.md @@ -210,6 +210,10 @@ Use `--engine` (or `EXODUS_TEST_ENGINE=`) to specify one of: - `--test-force-exit` — force exit after tests are done +- `--file-timeout ` — kill a test file still running after this many ms and mark it as failed + (default: 50x `testTimeout`, must be greater than `testTimeout`). + Not supported on `deno:test` and `bun:test`, disabled on `node:test` with `--inspect*` + - `--engine` — specify one of [Engines](#engines) to run on ## Reporter samples diff --git a/bin/inband.js b/bin/inband.js index 50bd48b9..977e633b 100644 --- a/bin/inband.js +++ b/bin/inband.js @@ -1,11 +1,13 @@ import { resolve } from 'node:path' import { pathToFileURL } from 'node:url' import { describe, after } from '../src/engine.js' +import { restartFileTimeout } from '../loader/file-timeout.js' const files = JSON.parse(process.env.EXODUS_TEST_INBAND) if (!Array.isArray(files)) throw new Error('Unexpected') for (const file of files.sort()) { + restartFileTimeout(file) await describe(`EXODUS_TEST_INBAND:${file}`, async () => { await import(pathToFileURL(resolve(file))) }) diff --git a/bin/index.js b/bin/index.js index c746e852..056ec3e1 100755 --- a/bin/index.js +++ b/bin/index.js @@ -110,6 +110,7 @@ function parseOptions() { require: [], testNamePattern: [], testTimeout: undefined, + fileTimeout: undefined, reporter: undefined, } @@ -253,6 +254,9 @@ function parseOptions() { case '--testTimeout': options.testTimeout = Number(args.shift()) break + case '--file-timeout': + options.fileTimeout = Number(args.shift()) + break case '--reporter': case '--test-reporter': options.reporter = String(args.shift()) @@ -340,7 +344,9 @@ if (options.pure) { args.push('--expose-internals') // this is unoptimal and hopefully temporary, see rationale in src/dark.cjs } else if (options.engine === 'deno:test') { assert(!options.jest, 'deno:test engine does not support --jest yet') + assert(options.fileTimeout === undefined, engineFlagError('file-timeout')) } else if (options.engine === 'bun:test') { + assert(options.fileTimeout === undefined, engineFlagError('file-timeout')) args.push('test') throw new Error('bun:test is unavailable because Bun test runner has many bugs and does not work') } else { @@ -433,6 +439,19 @@ if (options.jest) { } } +const testTimeout = options.testTimeout || jestConfig?.testTimeout || 5000 +if (options.fileTimeout === undefined) { + options.fileTimeout = testTimeout * 50 // fallback for hangs, tests can adjust their own timeouts +} else { + const valid = Number.isSafeInteger(options.fileTimeout) && options.fileTimeout > testTimeout + assert(valid, `--file-timeout should be an integer greater than testTimeout (${testTimeout}ms)`) +} + +if (['node:test', 'electron-as-node:test'].includes(options.engine) && !options.devtools) { + setEnv('EXODUS_TEST_FILE_TIMEOUT', String(options.fileTimeout)) + args.push('--import', import.meta.resolve('../loader/file-timeout.js')) +} + const cpus = availableParallelism() // increase from default cpus - 1 on default GH CI runners, but not on browsers which already use other processes if (!options.concurrency && isCI && !isBrowserLike && cpus === 2) options.concurrency = cpus @@ -759,9 +778,7 @@ const mainWorker :Workerd.Worker = ( return out || (ok ? `✔ PASS ${file}` : `✖ FAIL ${file}`) } - // Timeout is fallback if timeout in script hangs, 50x as it can be adjusted per-script inside them - // Do we want to extract timeouts from script code instead? Also, hermes might be slower, so makes sense to increase - const timeout = (options.testTimeout || jestConfig?.testTimeout || 5000) * 50 + const timeout = options.fileTimeout const start = process.hrtime.bigint() try { const fullArgs = [...(options.binaryArgs ?? []), ...args, file] @@ -777,7 +794,8 @@ const mainWorker :Workerd.Worker = ( if (code === null) { assert(signal) const message = ` ${signal}${killed ? ' (killed)' : ''}` - const comment = killed && signal === 'SIGTERM' ? ' Most likely due to timeout reached' : '' + const comment = + killed && signal === 'SIGTERM' ? ` File timeout of ${timeout}ms reached` : '' return { ok: false, output: [stdout, stderr, message, comment], ms } } diff --git a/loader/file-timeout.js b/loader/file-timeout.js new file mode 100644 index 00000000..3ab1bba5 --- /dev/null +++ b/loader/file-timeout.js @@ -0,0 +1,29 @@ +import { relative } from 'node:path' +import { Worker } from 'node:worker_threads' + +const watchdog = ` +const { writeSync } = require('node:fs') +const { parentPort, workerData } = require('node:worker_threads') +let timer +const arm = (file) => { + clearTimeout(timer) + timer = setTimeout(() => { + writeSync(2, \`\\n‼ FATAL File timeout of \${workerData.ms}ms reached, killing \${file}\\n\`) + process.kill(process.pid, 'SIGKILL') + }, workerData.ms) +} +parentPort.on('message', arm) +arm(workerData.file) +` + +const ms = Number(process.env.EXODUS_TEST_FILE_TIMEOUT) +const isTestChild = process.env.NODE_TEST_CONTEXT?.startsWith('child') +const name = (file) => relative(process.cwd(), file) + +let worker +if (ms > 0 && isTestChild) { + worker = new Worker(watchdog, { eval: true, workerData: { ms, file: name(process.argv[1]) } }) + worker.unref() +} + +export const restartFileTimeout = (file) => worker?.postMessage(name(file)) diff --git a/package.json b/package.json index 734ef1fd..b45f728f 100644 --- a/package.json +++ b/package.json @@ -75,6 +75,7 @@ "loader/deno-import-map.pure.json", "loader/esbuild.js", "loader/esbuild.optional.js", + "loader/file-timeout.js", "loader/flow.js", "loader/jest.js", "loader/remap.cjs", @@ -127,7 +128,7 @@ "tape.js" ], "scripts": { - "test:_bundle": "EXODUS_TEST_IGNORE='tests/{{vendor/jest-extended,inband}/**,vendor/jest-when/when.test.*,jest/jest.resetModules.*,jest/mock/jest.mock.mocks-dir.test.js}' npm run test --", + "test:_bundle": "EXODUS_TEST_IGNORE='tests/{{vendor/jest-extended,inband,cli}/**,vendor/jest-when/when.test.*,jest/jest.resetModules.*,jest/mock/jest.mock.mocks-dir.test.js}' npm run test --", "test": "npm run test:jest --", "test:all": "npm run test:simple && npm run test:jest && npm run test:tape && npm run test:native && npm run test:esbuild && npm run test:pure && npm run test:fetch && npm run test:jsdom && npm run test:bundle", "test:native": "EXODUS_TEST_IGNORE='**/jest.transformed/**/*' ./bin/index.js --jest 'tests/**/*.test.{js,cjs,mjs}'", diff --git a/tests/cli/file-timeout.test.js b/tests/cli/file-timeout.test.js new file mode 100644 index 00000000..0e0019e3 --- /dev/null +++ b/tests/cli/file-timeout.test.js @@ -0,0 +1,64 @@ +import { describe, test } from 'node:test' +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' + +const bin = fileURLToPath(import.meta.resolve('../../bin/index.js')) +const dir = 'tests/integration/file-timeout' +const env = Object.fromEntries( + Object.entries(process.env).filter( + ([k]) => !k.startsWith('EXODUS_TEST_') && k !== 'NODE_TEST_CONTEXT' + ) +) + +const run = (...args) => { + const res = spawnSync('node', [bin, '--no-colors', ...args], { env, encoding: 'utf8' }) + return { code: res.status, out: `${res.stdout}${res.stderr}` } +} + +const failedSuites = (out) => { + const [, list = ''] = out.split('Failed test suites:\n') + return list + .split('\n') + .filter((x) => x.startsWith(' ')) + .map((x) => x.trim()) +} + +describe('--file-timeout', { timeout: 60_000 }, () => { + test('kills hanging files on node:test and keeps running the rest', () => { + const files = ['blocking', 'toplevel-await', 'passing', '1-slow.inband', '2-slow.inband'] + const args = ['--jest', '--testTimeout', '900', '--file-timeout', '1000'] + const { code, out } = run(...args, ...files.map((f) => `${dir}/${f}.js`)) + assert.equal(code, 1) + assert.deepEqual(failedSuites(out), [`${dir}/blocking.js`, `${dir}/toplevel-await.js`]) + for (const file of ['blocking', 'toplevel-await']) { + assert.ok(out.includes(`File timeout of 1000ms reached, killing ${dir}/${file}.js`), out) + } + + assert.match(out, /PASS passes/) + }) + + test('overrides the deadline on pure engines', () => { + const args = ['--engine', 'node:pure', '--testTimeout', '100', '--file-timeout', '1000'] + const { code, out } = run(...args, `${dir}/blocking.js`) + assert.equal(code, 1) + assert.match(out, /File timeout of 1000ms reached/) + assert.deepEqual(failedSuites(out), [`${dir}/blocking.js`]) + }) + + for (const value of ['0', '-1', '1.5', 'abc', '100']) { + test(`rejects ${value}`, () => { + const args = ['--testTimeout', '100', '--file-timeout', value] + const { code, out } = run(...args, `${dir}/passing.js`) + assert.equal(code, 1) + assert.match(out, /--file-timeout should be an integer greater than testTimeout \(100ms\)/) + }) + } + + test('rejects deno:test', () => { + const args = ['--engine', 'deno:test', '--file-timeout', '6000'] + const { code, out } = run(...args, `${dir}/passing.js`) + assert.equal(code, 1) + assert.match(out, /deno:test engine does not support --file-timeout/) + }) +}) diff --git a/tests/integration/file-timeout/1-slow.inband.js b/tests/integration/file-timeout/1-slow.inband.js new file mode 100644 index 00000000..43dfdb90 --- /dev/null +++ b/tests/integration/file-timeout/1-slow.inband.js @@ -0,0 +1,3 @@ +test('slow but healthy', async () => { + await new Promise((resolve) => setTimeout(resolve, 700)) +}) diff --git a/tests/integration/file-timeout/2-slow.inband.js b/tests/integration/file-timeout/2-slow.inband.js new file mode 100644 index 00000000..43dfdb90 --- /dev/null +++ b/tests/integration/file-timeout/2-slow.inband.js @@ -0,0 +1,3 @@ +test('slow but healthy', async () => { + await new Promise((resolve) => setTimeout(resolve, 700)) +}) diff --git a/tests/integration/file-timeout/blocking.js b/tests/integration/file-timeout/blocking.js new file mode 100644 index 00000000..3199f087 --- /dev/null +++ b/tests/integration/file-timeout/blocking.js @@ -0,0 +1 @@ +for (;;) {} diff --git a/tests/integration/file-timeout/passing.js b/tests/integration/file-timeout/passing.js new file mode 100644 index 00000000..a0e9632f --- /dev/null +++ b/tests/integration/file-timeout/passing.js @@ -0,0 +1,3 @@ +test('passes', () => { + expect(true).toBe(true) +}) diff --git a/tests/integration/file-timeout/toplevel-await.js b/tests/integration/file-timeout/toplevel-await.js new file mode 100644 index 00000000..785f3a91 --- /dev/null +++ b/tests/integration/file-timeout/toplevel-await.js @@ -0,0 +1,2 @@ +setInterval(() => {}, 1000) +await new Promise(() => {})