Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <ms>` — 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
Expand Down
2 changes: 2 additions & 0 deletions bin/inband.js
Original file line number Diff line number Diff line change
@@ -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)))
})
Expand Down
26 changes: 22 additions & 4 deletions bin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ function parseOptions() {
require: [],
testNamePattern: [],
testTimeout: undefined,
fileTimeout: undefined,
reporter: undefined,
}

Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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]
Expand All @@ -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 }
}

Expand Down
29 changes: 29 additions & 0 deletions loader/file-timeout.js
Original file line number Diff line number Diff line change
@@ -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))
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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}'",
Expand Down
64 changes: 64 additions & 0 deletions tests/cli/file-timeout.test.js
Original file line number Diff line number Diff line change
@@ -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/)
})
})
3 changes: 3 additions & 0 deletions tests/integration/file-timeout/1-slow.inband.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
test('slow but healthy', async () => {
await new Promise((resolve) => setTimeout(resolve, 700))
})
3 changes: 3 additions & 0 deletions tests/integration/file-timeout/2-slow.inband.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
test('slow but healthy', async () => {
await new Promise((resolve) => setTimeout(resolve, 700))
})
1 change: 1 addition & 0 deletions tests/integration/file-timeout/blocking.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
for (;;) {}
3 changes: 3 additions & 0 deletions tests/integration/file-timeout/passing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
test('passes', () => {
expect(true).toBe(true)
})
2 changes: 2 additions & 0 deletions tests/integration/file-timeout/toplevel-await.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
setInterval(() => {}, 1000)
await new Promise(() => {})