Skip to content

Commit

Permalink
test_runner: validate timeout option
Browse files Browse the repository at this point in the history
  • Loading branch information
aduh95 committed Jul 20, 2022
1 parent 545ecc5 commit da22723
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
10 changes: 8 additions & 2 deletions lib/internal/test_runner/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,13 @@ const {
kEmptyObject,
} = require('internal/util');
const { isPromise } = require('internal/util/types');
const { isUint32, validateAbortSignal } = require('internal/validators');
const {
isUint32,
validateAbortSignal,
validateNumber,
} = require('internal/validators');
const { setTimeout } = require('timers/promises');
const { TIMEOUT_MAX } = require('internal/timers');
const { cpus } = require('os');
const { bigint: hrtime } = process.hrtime;
const kCallbackAndPromisePresent = 'callbackAndPromisePresent';
Expand Down Expand Up @@ -148,7 +153,8 @@ class Test extends AsyncResource {
this.concurrency = concurrency;
}

if (isUint32(timeout)) {
if (timeout != null && timeout !== Infinity) {
validateNumber(timeout, 'options.timeout', 0, TIMEOUT_MAX);
this.timeout = timeout;
}

Expand Down
11 changes: 10 additions & 1 deletion lib/internal/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const {
ArrayPrototypeJoin,
ArrayPrototypeMap,
NumberIsInteger,
NumberIsNaN,
NumberMAX_SAFE_INTEGER,
NumberMIN_SAFE_INTEGER,
NumberParseInt,
Expand Down Expand Up @@ -115,9 +116,17 @@ function validateString(value, name) {
throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
}

function validateNumber(value, name) {
function validateNumber(value, name, min = undefined, max) {
if (typeof value !== 'number')
throw new ERR_INVALID_ARG_TYPE(name, 'number', value);

if ((min != null && value < min) || (max != null && value > max) ||
((min != null || max != null) && NumberIsNaN(value))) {
throw new ERR_OUT_OF_RANGE(
name,
`${min != null ? `>= ${min}` : ''}${min != null && max != null ? ' && ' : ''}${max != null ? `<= ${max}` : ''}`,
value);
}
}

const validateOneOf = hideStackFrames((value, name, oneOf) => {
Expand Down
15 changes: 15 additions & 0 deletions test/parallel/test-runner-option-validation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict';
require('../common');
const assert = require('assert');
const test = require('node:test');

[Symbol(), {}, [], () => {}, 1n, true, '1'].forEach((timeout) => {
assert.throws(() => test({ timeout }), { code: 'ERR_INVALID_ARG_TYPE' });
});
[-1, -Infinity, NaN, 2 ** 33, Number.MAX_SAFE_INTEGER].forEach((timeout) => {
assert.throws(() => test({ timeout }), { code: 'ERR_OUT_OF_RANGE' });
});
[null, undefined, Infinity, 0, 1, 1.1].forEach((timeout) => {
// Valid values should not throw.
test({ timeout });
});

0 comments on commit da22723

Please sign in to comment.