test: ensure assertions are reached on more tests

PR-URL: https://github.com/nodejs/node/pull/60498
Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
This commit is contained in:
Antoine du Hamel 2025-11-07 17:22:01 +01:00 committed by GitHub
parent 2703db7985
commit 572cc6fa55
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
63 changed files with 454 additions and 449 deletions

View File

@ -193,11 +193,11 @@ export default [
'wpt',
].join(',')}}/**/*.{js,mjs,cjs}`,
`test/parallel/test-{${
// 0x61 is code for 'a', this generates a string enumerating latin letters: 'a*,b*,…'
Array.from({ length: 3 }, (_, i) => String.fromCharCode(0x61 + i, 42)).join(',')
},${
// 0x61 is code for 'a', this generates a string enumerating latin letters: 'z*,y*,…'
Array.from({ length: 2 }, (_, i) => String.fromCharCode(0x61 + 25 - i, 42)).join(',')
},${
// 0x61 is code for 'a', this generates a string enumerating latin letters: 'a*,b*,…'
Array.from({ length: 2 }, (_, i) => String.fromCharCode(0x61 + i, 42)).join(',')
}}.{js,mjs,cjs}`,
],
rules: {

View File

@ -36,31 +36,31 @@ function createChild(options, callback) {
}
test('normal execution of a child process is handled', (_, done) => {
createChild({}, (err, stdout, stderr) => {
createChild({}, common.mustCall((err, stdout, stderr) => {
assert.strictEqual(err, null);
assert.strictEqual(stdout, '');
assert.strictEqual(stderr, '');
done();
});
}));
});
test('execution with an error event is handled', (_, done) => {
const error = new Error('foo');
const child = createChild({}, (err, stdout, stderr) => {
const child = createChild({}, common.mustCall((err, stdout, stderr) => {
assert.strictEqual(err, error);
assert.strictEqual(stdout, '');
assert.strictEqual(stderr, '');
done();
});
}));
child.emit('error', error);
});
test('execution with a killed process is handled', (_, done) => {
createChild({ timeout: 1 }, (err, stdout, stderr) => {
createChild({ timeout: 1 }, common.mustCall((err, stdout, stderr) => {
assert.strictEqual(err.killed, true);
assert.strictEqual(stdout, '');
assert.strictEqual(stderr, '');
done();
});
}));
});

View File

@ -2,7 +2,7 @@
// Tests that a spawned child process can write to stdout without throwing.
// See https://github.com/nodejs/node-v0.x-archive/issues/1899.
require('../common');
const common = require('../common');
const fixtures = require('../common/fixtures');
const assert = require('assert');
const spawn = require('child_process').spawn;
@ -16,7 +16,7 @@ child.stdout.on('data', function(data) {
output += data;
});
child.on('exit', function(code, signal) {
child.on('exit', common.mustCall((code) => {
assert.strictEqual(code, 0);
assert.strictEqual(output, 'hello, world!\n');
});
}));

View File

@ -32,7 +32,7 @@ const { spawn } = require('child_process');
// - whether the child pid is undefined or number,
// - whether the exit code equals expectCode,
// - optionally whether the trimmed stdout result matches expectData
function testCwd(options, expectPidType, expectCode = 0, expectData) {
function testCwd(options, expectPidType, expectCode = 0, expectData, shouldCallExit = true) {
const child = spawn(...common.pwdCommand, options);
assert.strictEqual(typeof child.pid, expectPidType);
@ -47,9 +47,9 @@ function testCwd(options, expectPidType, expectCode = 0, expectData) {
// Can't assert callback, as stayed in to API:
// _The 'exit' event may or may not fire after an error has occurred._
child.on('exit', function(code, signal) {
child.on('exit', shouldCallExit ? common.mustCall((code) => {
assert.strictEqual(code, expectCode);
});
}) : common.mustNotCall());
child.on('close', common.mustCall(function() {
if (expectData) {
@ -68,7 +68,7 @@ function testCwd(options, expectPidType, expectCode = 0, expectData) {
// Assume does-not-exist doesn't exist, expect exitCode=-1 and errno=ENOENT
{
testCwd({ cwd: 'does-not-exist' }, 'undefined', -1)
testCwd({ cwd: 'does-not-exist' }, 'undefined', -1, undefined, false)
.on('error', common.mustCall(function(e) {
assert.strictEqual(e.code, 'ENOENT');
}));

View File

@ -30,13 +30,13 @@ if (process.argv[2] === 'child') {
// Check that the 'disconnect' event is deferred to the next event loop tick.
const disconnect = process.disconnect;
process.disconnect = function() {
process.disconnect = common.mustCall(function() {
disconnect.apply(this, arguments);
// If the event is emitted synchronously, we're too late by now.
process.once('disconnect', common.mustCall(disconnectIsNotAsync));
// The funky function name makes it show up legible in mustCall errors.
function disconnectIsNotAsync() {}
};
});
const server = net.createServer();
@ -81,13 +81,13 @@ if (process.argv[2] === 'child') {
child.on('exit', common.mustCall());
// When child is listening
child.on('message', function(obj) {
child.on('message', common.mustCallAtLeast((obj) => {
if (obj && obj.msg === 'ready') {
// Connect to child using TCP to know if disconnect was emitted
const socket = net.connect(obj.port);
socket.on('data', function(data) {
socket.on('data', common.mustCallAtLeast((data) => {
data = data.toString();
// Ready to be disconnected
@ -103,10 +103,10 @@ if (process.argv[2] === 'child') {
// 'disconnect' is emitted
childFlag = (data === 'true');
});
}));
}
});
}));
process.on('exit', function() {
assert.strictEqual(childFlag, false);

View File

@ -22,28 +22,28 @@ if (process.argv[2] === 'child') {
}
// Test default encoding, which should be utf8.
run({}, (stdout, stderr) => {
run({}, common.mustCall((stdout, stderr) => {
assert.strictEqual(typeof stdout, 'string');
assert.strictEqual(typeof stderr, 'string');
assert.strictEqual(stdout, expectedStdout);
assert.strictEqual(stderr, expectedStderr);
});
}));
// Test explicit utf8 encoding.
run({ encoding: 'utf8' }, (stdout, stderr) => {
run({ encoding: 'utf8' }, common.mustCall((stdout, stderr) => {
assert.strictEqual(typeof stdout, 'string');
assert.strictEqual(typeof stderr, 'string');
assert.strictEqual(stdout, expectedStdout);
assert.strictEqual(stderr, expectedStderr);
});
}));
// Test cases that result in buffer encodings.
[undefined, null, 'buffer', 'invalid'].forEach((encoding) => {
run({ encoding }, (stdout, stderr) => {
run({ encoding }, common.mustCall((stdout, stderr) => {
assert(stdout instanceof Buffer);
assert(stdout instanceof Buffer);
assert.strictEqual(stdout.toString(), expectedStdout);
assert.strictEqual(stderr.toString(), expectedStderr);
});
}));
});
}

View File

@ -65,14 +65,14 @@ common.expectWarning(
const ac = new AbortController();
const { signal } = ac;
const test = () => {
const test = common.mustCall(() => {
const check = common.mustCall((err) => {
assert.strictEqual(err.code, 'ABORT_ERR');
assert.strictEqual(err.name, 'AbortError');
assert.strictEqual(err.signal, undefined);
});
execFile(process.execPath, [echoFixture, 0], { signal }, check);
};
});
// Verify that it still works the same way now that the signal is aborted.
test();

View File

@ -17,7 +17,7 @@ p.on('close', common.mustCall((code, signal) => {
p.stdout.read();
const spawnWithReadable = () => {
const spawnWithReadable = common.mustCall(() => {
const buffer = [];
const p = cp.spawn('echo', ['123'], opts);
p.on('close', common.mustCall((code, signal) => {
@ -30,4 +30,4 @@ const spawnWithReadable = () => {
while ((buf = p.stdout.read()) !== null)
buffer.push(buf);
});
};
});

View File

@ -1,7 +1,7 @@
'use strict';
const { mustCall, mustNotCall } = require('../common');
const { strictEqual } = require('assert');
const assert = require('assert');
const fixtures = require('../common/fixtures');
const { fork } = require('child_process');
@ -13,11 +13,11 @@ const { fork } = require('child_process');
signal
});
cp.on('exit', mustCall((code, killSignal) => {
strictEqual(code, null);
strictEqual(killSignal, 'SIGTERM');
assert.strictEqual(code, null);
assert.strictEqual(killSignal, 'SIGTERM');
}));
cp.on('error', mustCall((err) => {
strictEqual(err.name, 'AbortError');
assert.strictEqual(err.name, 'AbortError');
}));
process.nextTick(() => ac.abort());
}
@ -30,13 +30,13 @@ const { fork } = require('child_process');
signal
});
cp.on('exit', mustCall((code, killSignal) => {
strictEqual(code, null);
strictEqual(killSignal, 'SIGTERM');
assert.strictEqual(code, null);
assert.strictEqual(killSignal, 'SIGTERM');
}));
cp.on('error', mustCall((err) => {
strictEqual(err.name, 'AbortError');
strictEqual(err.cause.name, 'Error');
strictEqual(err.cause.message, 'boom');
assert.strictEqual(err.name, 'AbortError');
assert.strictEqual(err.cause.name, 'Error');
assert.strictEqual(err.cause.message, 'boom');
}));
process.nextTick(() => ac.abort(new Error('boom')));
}
@ -48,11 +48,11 @@ const { fork } = require('child_process');
signal
});
cp.on('exit', mustCall((code, killSignal) => {
strictEqual(code, null);
strictEqual(killSignal, 'SIGTERM');
assert.strictEqual(code, null);
assert.strictEqual(killSignal, 'SIGTERM');
}));
cp.on('error', mustCall((err) => {
strictEqual(err.name, 'AbortError');
assert.strictEqual(err.name, 'AbortError');
}));
}
@ -63,13 +63,13 @@ const { fork } = require('child_process');
signal
});
cp.on('exit', mustCall((code, killSignal) => {
strictEqual(code, null);
strictEqual(killSignal, 'SIGTERM');
assert.strictEqual(code, null);
assert.strictEqual(killSignal, 'SIGTERM');
}));
cp.on('error', mustCall((err) => {
strictEqual(err.name, 'AbortError');
strictEqual(err.cause.name, 'Error');
strictEqual(err.cause.message, 'boom');
assert.strictEqual(err.name, 'AbortError');
assert.strictEqual(err.cause.name, 'Error');
assert.strictEqual(err.cause.message, 'boom');
}));
}
@ -81,11 +81,11 @@ const { fork } = require('child_process');
killSignal: 'SIGKILL',
});
cp.on('exit', mustCall((code, killSignal) => {
strictEqual(code, null);
strictEqual(killSignal, 'SIGKILL');
assert.strictEqual(code, null);
assert.strictEqual(killSignal, 'SIGKILL');
}));
cp.on('error', mustCall((err) => {
strictEqual(err.name, 'AbortError');
assert.strictEqual(err.name, 'AbortError');
}));
}

View File

@ -28,7 +28,7 @@ const server = net
s.destroy();
}, 100);
})
.listen(0, function() {
.listen(0, common.mustCall(() => {
const worker = cluster.fork();
worker.on('error', function(err) {
@ -70,9 +70,8 @@ const server = net
})
);
worker.on('online', function() {
send(function(err) {
assert.ifError(err);
worker.on('online', common.mustCall(() => {
send(common.mustSucceed(() => {
send(function(err) {
// Ignore errors when sending the second handle because the worker
// may already have exited.
@ -83,6 +82,6 @@ const server = net
throw err;
}
});
});
});
});
}));
}));
}));

View File

@ -92,9 +92,7 @@ if (process.argv[2] === 'child') {
msg.length,
serverPort,
'127.0.0.1',
(err) => {
assert.ifError(err);
}
common.mustSucceed(),
);
}
}, 1);

View File

@ -60,7 +60,7 @@ if (process.argv[2] === 'child') {
// TODO(@jasnell): The close event is not called consistently
// across platforms. Need to investigate if it can be made
// more consistent.
const onClose = (msg) => {
const onClose = common.mustCallAtLeast((msg) => {
if (msg.what !== 'close') return;
process.removeListener('message', onClose);
@ -68,7 +68,7 @@ if (process.argv[2] === 'child') {
process.send({ what: 'close' });
}));
serverScope.close();
};
});
process.on('message', onClose);
@ -86,13 +86,13 @@ if (process.argv[2] === 'child') {
function testServer(callback) {
// Destroy server execute callback when done.
const countdown = new Countdown(2, () => {
const countdown = new Countdown(2, common.mustCall(() => {
server.on('close', common.mustCall(() => {
debug('PARENT: server closed');
child.send({ what: 'close' });
}));
server.close();
});
}));
// We expect 4 connections and close events.
const connections = new Countdown(4, () => countdown.dec());
@ -122,7 +122,7 @@ if (process.argv[2] === 'child') {
// event is emitted appears to be variable across platforms.
// Need to investigate why and whether it can be made
// more consistent.
const messageHandlers = (msg) => {
const messageHandlers = common.mustCallAtLeast((msg) => {
if (msg.what === 'listening') {
// Make connections.
let socket;
@ -143,7 +143,7 @@ if (process.argv[2] === 'child') {
child.removeListener('message', messageHandlers);
callback();
}
};
});
child.on('message', messageHandlers);
}

View File

@ -20,7 +20,7 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
require('../common');
const common = require('../common');
const assert = require('assert');
const fork = require('child_process').fork;
@ -52,8 +52,8 @@ if (process.argv[2] === 'child') {
stdout += chunk;
});
child.once('exit', function() {
child.once('exit', common.mustCall(() => {
assert.deepStrictEqual(ipc, ['1', '2']);
assert.strictEqual(stdout, '3');
});
}));
}

View File

@ -1,7 +1,7 @@
'use strict';
const { mustCall } = require('../common');
const { strictEqual, throws } = require('assert');
const assert = require('assert');
const fixtures = require('../common/fixtures');
const { fork } = require('child_process');
const { getEventListeners } = require('events');
@ -11,7 +11,7 @@ const { getEventListeners } = require('events');
const cp = fork(fixtures.path('child-process-stay-alive-forever.js'), {
timeout: 5,
});
cp.on('exit', mustCall((code, ks) => strictEqual(ks, 'SIGTERM')));
cp.on('exit', mustCall((code, ks) => assert.strictEqual(ks, 'SIGTERM')));
}
{
@ -20,16 +20,16 @@ const { getEventListeners } = require('events');
timeout: 5,
killSignal: 'SIGKILL',
});
cp.on('exit', mustCall((code, ks) => strictEqual(ks, 'SIGKILL')));
cp.on('exit', mustCall((code, ks) => assert.strictEqual(ks, 'SIGKILL')));
}
{
// Verify timeout verification
throws(() => fork(fixtures.path('child-process-stay-alive-forever.js'), {
assert.throws(() => fork(fixtures.path('child-process-stay-alive-forever.js'), {
timeout: 'badValue',
}), /ERR_INVALID_ARG_TYPE/);
throws(() => fork(fixtures.path('child-process-stay-alive-forever.js'), {
assert.throws(() => fork(fixtures.path('child-process-stay-alive-forever.js'), {
timeout: {},
}), /ERR_INVALID_ARG_TYPE/);
}
@ -43,8 +43,8 @@ const { getEventListeners } = require('events');
timeout: 6,
signal,
});
strictEqual(getEventListeners(signal, 'abort').length, 1);
assert.strictEqual(getEventListeners(signal, 'abort').length, 1);
cp.on('exit', mustCall(() => {
strictEqual(getEventListeners(signal, 'abort').length, 0);
assert.strictEqual(getEventListeners(signal, 'abort').length, 0);
}));
}

View File

@ -30,10 +30,10 @@ const n = fork(fixtures.path('child-process-spawn-node.js'), args);
assert.deepStrictEqual(args, ['foo', 'bar']);
n.on('message', (m) => {
n.on('message', common.mustCall((m) => {
debug('PARENT got message:', m);
assert.ok(m.foo);
});
}));
// https://github.com/joyent/node/issues/2355 - JSON.stringify(undefined)
// returns "undefined" but JSON.parse() cannot parse that...

View File

@ -39,7 +39,7 @@ const server = http.createServer(common.mustCall((req, res) => {
server.listen(0, common.mustCall(() => {
child = fork(__filename, [ 'child' ]);
child.once('message', (msg) => {
child.once('message', common.mustCall((msg) => {
assert.strictEqual(msg, 'ready');
const req = http.request({
port: server.address().port,
@ -53,5 +53,5 @@ server.listen(0, common.mustCall(() => {
}));
req.end();
});
}));
}));

View File

@ -67,10 +67,10 @@ process.stdout.write('x');`;
const checkProcess = spawn(process.execPath, ['-e', code]);
checkProcess.on('exit', (code, signal) => {
checkProcess.on('exit', common.mustCall((code, signal) => {
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});
}));
checkProcess.stdout.on('data', common.mustCall((chunk) => {
assert.strictEqual(chunk.toString(), 'x');

View File

@ -1,7 +1,7 @@
import * as common from '../common/index.mjs';
import * as fixtures from '../common/fixtures.mjs';
import { EOL } from 'node:os';
import { strictEqual, notStrictEqual, throws } from 'node:assert';
import assert from 'node:assert';
import cp from 'node:child_process';
// TODO(LiviaMedeiros): test on different platforms
@ -15,17 +15,17 @@ for (const tamperedCwd of ['', '/tmp', '/not/existing/malicious/path', 42n]) {
Object.prototype.cwd = tamperedCwd;
cp.exec('pwd', common.mustSucceed((out) => {
strictEqual(`${out}`, `${expectedCWD}${EOL}`);
assert.strictEqual(`${out}`, `${expectedCWD}${EOL}`);
}));
strictEqual(`${cp.execSync('pwd')}`, `${expectedCWD}${EOL}`);
assert.strictEqual(`${cp.execSync('pwd')}`, `${expectedCWD}${EOL}`);
cp.execFile('pwd', common.mustSucceed((out) => {
strictEqual(`${out}`, `${expectedCWD}${EOL}`);
assert.strictEqual(`${out}`, `${expectedCWD}${EOL}`);
}));
strictEqual(`${cp.execFileSync('pwd')}`, `${expectedCWD}${EOL}`);
assert.strictEqual(`${cp.execFileSync('pwd')}`, `${expectedCWD}${EOL}`);
cp.spawn('pwd').stdout.on('data', common.mustCall((out) => {
strictEqual(`${out}`, `${expectedCWD}${EOL}`);
assert.strictEqual(`${out}`, `${expectedCWD}${EOL}`);
}));
strictEqual(`${cp.spawnSync('pwd').stdout}`, `${expectedCWD}${EOL}`);
assert.strictEqual(`${cp.spawnSync('pwd').stdout}`, `${expectedCWD}${EOL}`);
delete Object.prototype.cwd;
}
@ -34,17 +34,17 @@ for (const tamperedUID of [0, 1, 999, 1000, 0n, 'gwak']) {
Object.prototype.uid = tamperedUID;
cp.exec('id -u', common.mustSucceed((out) => {
strictEqual(`${out}`, `${expectedUID}${EOL}`);
assert.strictEqual(`${out}`, `${expectedUID}${EOL}`);
}));
strictEqual(`${cp.execSync('id -u')}`, `${expectedUID}${EOL}`);
assert.strictEqual(`${cp.execSync('id -u')}`, `${expectedUID}${EOL}`);
cp.execFile('id', ['-u'], common.mustSucceed((out) => {
strictEqual(`${out}`, `${expectedUID}${EOL}`);
assert.strictEqual(`${out}`, `${expectedUID}${EOL}`);
}));
strictEqual(`${cp.execFileSync('id', ['-u'])}`, `${expectedUID}${EOL}`);
assert.strictEqual(`${cp.execFileSync('id', ['-u'])}`, `${expectedUID}${EOL}`);
cp.spawn('id', ['-u']).stdout.on('data', common.mustCall((out) => {
strictEqual(`${out}`, `${expectedUID}${EOL}`);
assert.strictEqual(`${out}`, `${expectedUID}${EOL}`);
}));
strictEqual(`${cp.spawnSync('id', ['-u']).stdout}`, `${expectedUID}${EOL}`);
assert.strictEqual(`${cp.spawnSync('id', ['-u']).stdout}`, `${expectedUID}${EOL}`);
delete Object.prototype.uid;
}
@ -68,24 +68,24 @@ for (const shellCommandArgument of ['-L && echo "tampered"']) {
program.stdout.on('data', common.mustNotCall());
program.on('exit', common.mustCall((code) => {
notStrictEqual(code, 0);
assert.notStrictEqual(code, 0);
}));
cp.execFile(cmd, [shellCommandArgument], { cwd: expectedCWD },
common.mustCall((err) => {
notStrictEqual(err.code, 0);
assert.notStrictEqual(err.code, 0);
})
);
throws(() => {
assert.throws(() => {
cp.execFileSync(cmd, [shellCommandArgument], { cwd: expectedCWD });
}, (e) => {
notStrictEqual(e.status, 0);
assert.notStrictEqual(e.status, 0);
return true;
});
cmdExitCode = cp.spawnSync(cmd, [shellCommandArgument], { cwd: expectedCWD }).status;
notStrictEqual(cmdExitCode, 0);
assert.notStrictEqual(cmdExitCode, 0);
delete Object.prototype.shell;
}

View File

@ -3,7 +3,7 @@ const { mustNotCall } = require('../common');
// Regression test for https://github.com/nodejs/node/issues/44768
const { throws } = require('assert');
const assert = require('assert');
const {
exec,
execFile,
@ -16,56 +16,56 @@ const {
// Tests for the 'command' argument
throws(() => exec(`${process.execPath} ${__filename} AAA BBB\0XXX CCC`, mustNotCall()), {
assert.throws(() => exec(`${process.execPath} ${__filename} AAA BBB\0XXX CCC`, mustNotCall()), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => exec('BBB\0XXX AAA CCC', mustNotCall()), {
assert.throws(() => exec('BBB\0XXX AAA CCC', mustNotCall()), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execSync(`${process.execPath} ${__filename} AAA BBB\0XXX CCC`), {
assert.throws(() => execSync(`${process.execPath} ${__filename} AAA BBB\0XXX CCC`), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execSync('BBB\0XXX AAA CCC'), {
assert.throws(() => execSync('BBB\0XXX AAA CCC'), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
// Tests for the 'file' argument
throws(() => spawn('BBB\0XXX'), {
assert.throws(() => spawn('BBB\0XXX'), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execFile('BBB\0XXX', mustNotCall()), {
assert.throws(() => execFile('BBB\0XXX', mustNotCall()), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execFileSync('BBB\0XXX'), {
assert.throws(() => execFileSync('BBB\0XXX'), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => spawn('BBB\0XXX'), {
assert.throws(() => spawn('BBB\0XXX'), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => spawnSync('BBB\0XXX'), {
assert.throws(() => spawnSync('BBB\0XXX'), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
// Tests for the 'modulePath' argument
throws(() => fork('BBB\0XXX'), {
assert.throws(() => fork('BBB\0XXX'), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
@ -75,123 +75,123 @@ throws(() => fork('BBB\0XXX'), {
// Not testing exec() and execSync() because these accept 'args' as a part of
// 'command' as space-separated arguments.
throws(() => execFile(process.execPath, [__filename, 'AAA', 'BBB\0XXX', 'CCC'], mustNotCall()), {
assert.throws(() => execFile(process.execPath, [__filename, 'AAA', 'BBB\0XXX', 'CCC'], mustNotCall()), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execFileSync(process.execPath, [__filename, 'AAA', 'BBB\0XXX', 'CCC']), {
assert.throws(() => execFileSync(process.execPath, [__filename, 'AAA', 'BBB\0XXX', 'CCC']), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => fork(__filename, ['AAA', 'BBB\0XXX', 'CCC']), {
assert.throws(() => fork(__filename, ['AAA', 'BBB\0XXX', 'CCC']), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => spawn(process.execPath, [__filename, 'AAA', 'BBB\0XXX', 'CCC']), {
assert.throws(() => spawn(process.execPath, [__filename, 'AAA', 'BBB\0XXX', 'CCC']), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => spawnSync(process.execPath, [__filename, 'AAA', 'BBB\0XXX', 'CCC']), {
assert.throws(() => spawnSync(process.execPath, [__filename, 'AAA', 'BBB\0XXX', 'CCC']), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
// Tests for the 'options.cwd' argument
throws(() => exec(process.execPath, { cwd: 'BBB\0XXX' }, mustNotCall()), {
assert.throws(() => exec(process.execPath, { cwd: 'BBB\0XXX' }, mustNotCall()), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execFile(process.execPath, { cwd: 'BBB\0XXX' }, mustNotCall()), {
assert.throws(() => execFile(process.execPath, { cwd: 'BBB\0XXX' }, mustNotCall()), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execFileSync(process.execPath, { cwd: 'BBB\0XXX' }), {
assert.throws(() => execFileSync(process.execPath, { cwd: 'BBB\0XXX' }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execSync(process.execPath, { cwd: 'BBB\0XXX' }), {
assert.throws(() => execSync(process.execPath, { cwd: 'BBB\0XXX' }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => fork(__filename, { cwd: 'BBB\0XXX' }), {
assert.throws(() => fork(__filename, { cwd: 'BBB\0XXX' }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => spawn(process.execPath, { cwd: 'BBB\0XXX' }), {
assert.throws(() => spawn(process.execPath, { cwd: 'BBB\0XXX' }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => spawnSync(process.execPath, { cwd: 'BBB\0XXX' }), {
assert.throws(() => spawnSync(process.execPath, { cwd: 'BBB\0XXX' }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
// Tests for the 'options.argv0' argument
throws(() => exec(process.execPath, { argv0: 'BBB\0XXX' }, mustNotCall()), {
assert.throws(() => exec(process.execPath, { argv0: 'BBB\0XXX' }, mustNotCall()), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execFile(process.execPath, { argv0: 'BBB\0XXX' }, mustNotCall()), {
assert.throws(() => execFile(process.execPath, { argv0: 'BBB\0XXX' }, mustNotCall()), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execFileSync(process.execPath, { argv0: 'BBB\0XXX' }), {
assert.throws(() => execFileSync(process.execPath, { argv0: 'BBB\0XXX' }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execSync(process.execPath, { argv0: 'BBB\0XXX' }), {
assert.throws(() => execSync(process.execPath, { argv0: 'BBB\0XXX' }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => fork(__filename, { argv0: 'BBB\0XXX' }), {
assert.throws(() => fork(__filename, { argv0: 'BBB\0XXX' }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => spawn(process.execPath, { argv0: 'BBB\0XXX' }), {
assert.throws(() => spawn(process.execPath, { argv0: 'BBB\0XXX' }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => spawnSync(process.execPath, { argv0: 'BBB\0XXX' }), {
assert.throws(() => spawnSync(process.execPath, { argv0: 'BBB\0XXX' }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
// Tests for the 'options.shell' argument
throws(() => exec(process.execPath, { shell: 'BBB\0XXX' }, mustNotCall()), {
assert.throws(() => exec(process.execPath, { shell: 'BBB\0XXX' }, mustNotCall()), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execFile(process.execPath, { shell: 'BBB\0XXX' }, mustNotCall()), {
assert.throws(() => execFile(process.execPath, { shell: 'BBB\0XXX' }, mustNotCall()), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execFileSync(process.execPath, { shell: 'BBB\0XXX' }), {
assert.throws(() => execFileSync(process.execPath, { shell: 'BBB\0XXX' }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execSync(process.execPath, { shell: 'BBB\0XXX' }), {
assert.throws(() => execSync(process.execPath, { shell: 'BBB\0XXX' }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
@ -199,96 +199,96 @@ throws(() => execSync(process.execPath, { shell: 'BBB\0XXX' }), {
// Not testing fork() because it doesn't accept the shell option (internally it
// explicitly sets shell to false).
throws(() => spawn(process.execPath, { shell: 'BBB\0XXX' }), {
assert.throws(() => spawn(process.execPath, { shell: 'BBB\0XXX' }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => spawnSync(process.execPath, { shell: 'BBB\0XXX' }), {
assert.throws(() => spawnSync(process.execPath, { shell: 'BBB\0XXX' }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
// Tests for the 'options.env' argument
throws(() => exec(process.execPath, { env: { 'AAA': 'BBB\0XXX' } }, mustNotCall()), {
assert.throws(() => exec(process.execPath, { env: { 'AAA': 'BBB\0XXX' } }, mustNotCall()), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => exec(process.execPath, { env: { 'BBB\0XXX': 'AAA' } }, mustNotCall()), {
assert.throws(() => exec(process.execPath, { env: { 'BBB\0XXX': 'AAA' } }, mustNotCall()), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execFile(process.execPath, { env: { 'AAA': 'BBB\0XXX' } }, mustNotCall()), {
assert.throws(() => execFile(process.execPath, { env: { 'AAA': 'BBB\0XXX' } }, mustNotCall()), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execFile(process.execPath, { env: { 'BBB\0XXX': 'AAA' } }, mustNotCall()), {
assert.throws(() => execFile(process.execPath, { env: { 'BBB\0XXX': 'AAA' } }, mustNotCall()), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execFileSync(process.execPath, { env: { 'AAA': 'BBB\0XXX' } }), {
assert.throws(() => execFileSync(process.execPath, { env: { 'AAA': 'BBB\0XXX' } }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execFileSync(process.execPath, { env: { 'BBB\0XXX': 'AAA' } }), {
assert.throws(() => execFileSync(process.execPath, { env: { 'BBB\0XXX': 'AAA' } }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execSync(process.execPath, { env: { 'AAA': 'BBB\0XXX' } }), {
assert.throws(() => execSync(process.execPath, { env: { 'AAA': 'BBB\0XXX' } }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => execSync(process.execPath, { env: { 'BBB\0XXX': 'AAA' } }), {
assert.throws(() => execSync(process.execPath, { env: { 'BBB\0XXX': 'AAA' } }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => fork(__filename, { env: { 'AAA': 'BBB\0XXX' } }), {
assert.throws(() => fork(__filename, { env: { 'AAA': 'BBB\0XXX' } }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => fork(__filename, { env: { 'BBB\0XXX': 'AAA' } }), {
assert.throws(() => fork(__filename, { env: { 'BBB\0XXX': 'AAA' } }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => spawn(process.execPath, { env: { 'AAA': 'BBB\0XXX' } }), {
assert.throws(() => spawn(process.execPath, { env: { 'AAA': 'BBB\0XXX' } }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => spawn(process.execPath, { env: { 'BBB\0XXX': 'AAA' } }), {
assert.throws(() => spawn(process.execPath, { env: { 'BBB\0XXX': 'AAA' } }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => spawnSync(process.execPath, { env: { 'AAA': 'BBB\0XXX' } }), {
assert.throws(() => spawnSync(process.execPath, { env: { 'AAA': 'BBB\0XXX' } }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
throws(() => spawnSync(process.execPath, { env: { 'BBB\0XXX': 'AAA' } }), {
assert.throws(() => spawnSync(process.execPath, { env: { 'BBB\0XXX': 'AAA' } }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
// Tests for the 'options.execPath' argument
throws(() => fork(__filename, { execPath: 'BBB\0XXX' }), {
assert.throws(() => fork(__filename, { execPath: 'BBB\0XXX' }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});
// Tests for the 'options.execArgv' argument
throws(() => fork(__filename, { execArgv: ['AAA', 'BBB\0XXX', 'CCC'] }), {
assert.throws(() => fork(__filename, { execArgv: ['AAA', 'BBB\0XXX', 'CCC'] }), {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
});

View File

@ -23,7 +23,7 @@ if (process.argv[2] !== 'child') {
assert.strictEqual(signalCode, null);
}));
const server = net.createServer((socket) => {
const server = net.createServer(common.mustCall((socket) => {
child.on('message', common.mustCall((msg) => {
assert.strictEqual(msg, 'child_done');
socket.end('parent', () => {
@ -33,7 +33,7 @@ if (process.argv[2] !== 'child') {
}));
child.send('socket', socket, { keepOpen: true }, common.mustSucceed());
});
}));
server.listen(0, () => {
const socket = net.connect(server.address().port, common.localhostIPv4);

View File

@ -28,7 +28,7 @@ const subScript = fixtures.path('child-process-persistent.js');
const spawnOptions = { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] };
const s = spawn(process.execPath, [subScript], spawnOptions);
const server = net.createServer(common.mustNotCall()).listen(0, () => {
const server = net.createServer(common.mustNotCall()).listen(0, common.mustCall(() => {
const handle = server._handle;
// Sending a handle and not giving the tickQueue time to acknowledge should
@ -42,8 +42,7 @@ const subScript = fixtures.path('child-process-persistent.js');
// The backlog should now be indicate to backoff.
const rv3 = s.send('three', assert.ifError);
assert.strictEqual(rv3, false);
const rv4 = s.send('four', (err) => {
assert.ifError(err);
const rv4 = s.send('four', common.mustSucceed(() => {
// `send` queue should have been drained.
const rv5 = s.send('5', handle, assert.ifError);
assert.strictEqual(rv5, true);
@ -52,7 +51,7 @@ const subScript = fixtures.path('child-process-persistent.js');
s.kill();
handle.close();
server.close();
});
}));
assert.strictEqual(rv4, false);
});
}));
}

View File

@ -24,17 +24,17 @@ if (process.argv[2] !== 'child') {
}
// Child
const server = net.createServer((conn) => {
const server = net.createServer(common.mustCall((conn) => {
spawn(process.execPath, ['-v'], {
stdio: ['ignore', conn, 'ignore']
}).on('close', common.mustCall(() => {
conn.end();
}));
}).listen(common.PIPE, () => {
})).listen(common.PIPE, common.mustCall(() => {
const client = net.connect(common.PIPE, common.mustCall());
client.once('data', () => {
client.end(() => {
server.close();
});
});
});
}));

View File

@ -1,7 +1,7 @@
'use strict';
const { mustCall } = require('../common');
const { strictEqual, throws } = require('assert');
const assert = require('assert');
const fixtures = require('../common/fixtures');
const { spawn } = require('child_process');
const { getEventListeners } = require('events');
@ -12,7 +12,7 @@ const aliveForeverFile = 'child-process-stay-alive-forever.js';
const cp = spawn(process.execPath, [fixtures.path(aliveForeverFile)], {
timeout: 5,
});
cp.on('exit', mustCall((code, ks) => strictEqual(ks, 'SIGTERM')));
cp.on('exit', mustCall((code, ks) => assert.strictEqual(ks, 'SIGTERM')));
}
{
@ -21,16 +21,16 @@ const aliveForeverFile = 'child-process-stay-alive-forever.js';
timeout: 6,
killSignal: 'SIGKILL',
});
cp.on('exit', mustCall((code, ks) => strictEqual(ks, 'SIGKILL')));
cp.on('exit', mustCall((code, ks) => assert.strictEqual(ks, 'SIGKILL')));
}
{
// Verify timeout verification
throws(() => spawn(process.execPath, [fixtures.path(aliveForeverFile)], {
assert.throws(() => spawn(process.execPath, [fixtures.path(aliveForeverFile)], {
timeout: 'badValue',
}), /ERR_INVALID_ARG_TYPE/);
throws(() => spawn(process.execPath, [fixtures.path(aliveForeverFile)], {
assert.throws(() => spawn(process.execPath, [fixtures.path(aliveForeverFile)], {
timeout: {},
}), /ERR_INVALID_ARG_TYPE/);
}
@ -43,8 +43,8 @@ const aliveForeverFile = 'child-process-stay-alive-forever.js';
timeout: 6,
signal,
});
strictEqual(getEventListeners(signal, 'abort').length, 1);
assert.strictEqual(getEventListeners(signal, 'abort').length, 1);
cp.on('exit', mustCall(() => {
strictEqual(getEventListeners(signal, 'abort').length, 0);
assert.strictEqual(getEventListeners(signal, 'abort').length, 0);
}));
}

View File

@ -32,7 +32,7 @@ const testCases = [
const expectedResult = tmpdir.path.trim().toLowerCase();
const results = testCases.map((testCase) => {
const results = testCases.map(common.mustCallAtLeast((testCase) => {
const { stdout, stderr, error } = spawnSync(
command,
testCase,
@ -43,6 +43,6 @@ const results = testCases.map((testCase) => {
assert.deepStrictEqual(stderr, Buffer.alloc(0));
return stdout.toString().trim().toLowerCase();
});
}));
assert.deepStrictEqual([...new Set(results)], [expectedResult]);

View File

@ -35,18 +35,18 @@ if (process.argv[2] === 'child') {
// Verify that the default kill signal is SIGTERM.
{
const child = spawn(undefined, (opts) => {
const child = spawn(undefined, common.mustCall((opts) => {
assert.strictEqual(opts.killSignal, undefined);
});
}));
assert.strictEqual(child.signal, 'SIGTERM');
}
// Verify that a string signal name is handled properly.
{
const child = spawn('SIGKILL', (opts) => {
const child = spawn('SIGKILL', common.mustCall((opts) => {
assert.strictEqual(opts.killSignal, SIGKILL);
});
}));
assert.strictEqual(child.signal, 'SIGKILL');
}
@ -55,9 +55,9 @@ if (process.argv[2] === 'child') {
{
assert.strictEqual(typeof SIGKILL, 'number');
const child = spawn(SIGKILL, (opts) => {
const child = spawn(SIGKILL, common.mustCall((opts) => {
assert.strictEqual(opts.killSignal, SIGKILL);
});
}));
assert.strictEqual(child.signal, 'SIGKILL');
}

View File

@ -20,7 +20,7 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
require('../common');
const common = require('../common');
const assert = require('assert');
const spawn = require('child_process').spawn;
@ -42,12 +42,12 @@ function grandparent() {
child.stdin.end(input);
child.on('close', function(code, signal) {
child.on('close', common.mustCall((code, signal) => {
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
// 'cat' on windows adds a \r\n at the end.
assert.strictEqual(output.trim(), input.trim());
});
}));
}
function parent() {

View File

@ -112,7 +112,7 @@ function expect(
if (typeof want === 'string')
want = new RegExp(want);
const test = (type) => common.mustCall((err, stdout) => {
const test = common.mustCallAtLeast((type) => common.mustCall((err, stdout) => {
const o = JSON.stringify(opt);
if (wantsError) {
assert.ok(err, `${type}: expected error for ${o}`);
@ -125,7 +125,7 @@ function expect(
assert.fail(
`${type}: for ${o}, failed to find ${want} in: <\n${stdout}\n>`
);
});
}));
exec(process.execPath, argv, opts, test('child process'));
if (testWorker)

View File

@ -40,15 +40,15 @@ function validateNodePrintHelp() {
function testForSubstring(options) {
if (options.compileConstant) {
options.flags.forEach((flag) => {
assert.strictEqual(stdOut.indexOf(flag) !== -1, true,
`Missing flag ${flag} in ${stdOut}`);
});
for (const flag of options.flags) {
assert.notStrictEqual(stdOut.indexOf(flag), -1,
`Missing flag ${flag} in ${stdOut}`);
}
} else {
options.flags.forEach((flag) => {
for (const flag of options.flags) {
assert.strictEqual(stdOut.indexOf(flag), -1,
`Unexpected flag ${flag} in ${stdOut}`);
});
}
}
}

View File

@ -4,7 +4,7 @@ const {
spawnPromisified,
} = require('../common');
const fixtures = require('../common/fixtures');
const { strictEqual } = require('node:assert');
const assert = require('node:assert');
const { describe, it } = require('node:test');
const path = require('node:path');
@ -21,11 +21,11 @@ describe('getOptionsAsFlagsFromBinding', () => {
fixtureFile,
]);
strictEqual(result.code, 0);
assert.strictEqual(result.code, 0);
const flags = JSON.parse(result.stdout.trim());
strictEqual(flags.includes('--no-warnings'), true);
strictEqual(flags.includes('--stack-trace-limit=512'), true);
assert.strictEqual(flags.includes('--no-warnings'), true);
assert.strictEqual(flags.includes('--stack-trace-limit=512'), true);
});
it('should extract flags from NODE_OPTIONS environment variable', async () => {
@ -40,13 +40,13 @@ describe('getOptionsAsFlagsFromBinding', () => {
}
});
strictEqual(result.code, 0);
assert.strictEqual(result.code, 0);
const flags = JSON.parse(result.stdout.trim());
// Should contain the flag from NODE_OPTIONS
strictEqual(flags.includes('--stack-trace-limit=4096'), true);
assert.strictEqual(flags.includes('--stack-trace-limit=4096'), true);
// Should also contain command line flags
strictEqual(flags.includes('--no-warnings'), true);
assert.strictEqual(flags.includes('--no-warnings'), true);
});
it('should extract flags from config file', async () => {
@ -58,15 +58,15 @@ describe('getOptionsAsFlagsFromBinding', () => {
fixtureFile,
]);
strictEqual(result.code, 0);
assert.strictEqual(result.code, 0);
const flags = JSON.parse(result.stdout.trim());
// Should contain flags from config file
strictEqual(flags.includes('--experimental-transform-types'), true);
strictEqual(flags.includes('--max-http-header-size=8192'), true);
strictEqual(flags.includes('--test-isolation=none'), true);
assert.strictEqual(flags.includes('--experimental-transform-types'), true);
assert.strictEqual(flags.includes('--max-http-header-size=8192'), true);
assert.strictEqual(flags.includes('--test-isolation=none'), true);
// Should also contain command line flags
strictEqual(flags.includes('--no-warnings'), true);
assert.strictEqual(flags.includes('--no-warnings'), true);
});
it('should extract flags from config file and command line', async () => {
@ -79,17 +79,17 @@ describe('getOptionsAsFlagsFromBinding', () => {
fixtureFile,
]);
strictEqual(result.code, 0);
assert.strictEqual(result.code, 0);
const flags = JSON.parse(result.stdout.trim());
// Should contain flags from command line arguments
strictEqual(flags.includes('--no-warnings'), true);
strictEqual(flags.includes('--stack-trace-limit=512'), true);
assert.strictEqual(flags.includes('--no-warnings'), true);
assert.strictEqual(flags.includes('--stack-trace-limit=512'), true);
// Should contain flags from config file
strictEqual(flags.includes('--experimental-transform-types'), true);
strictEqual(flags.includes('--max-http-header-size=8192'), true);
strictEqual(flags.includes('--test-isolation=none'), true);
assert.strictEqual(flags.includes('--experimental-transform-types'), true);
assert.strictEqual(flags.includes('--max-http-header-size=8192'), true);
assert.strictEqual(flags.includes('--test-isolation=none'), true);
});
it('should extract flags from .env file', async () => {
@ -100,12 +100,12 @@ describe('getOptionsAsFlagsFromBinding', () => {
fixtureFile,
]);
strictEqual(result.code, 0);
assert.strictEqual(result.code, 0);
const flags = JSON.parse(result.stdout.trim());
// Should contain flags from .env file (NODE_OPTIONS)
strictEqual(flags.includes('--v8-pool-size=8'), true);
assert.strictEqual(flags.includes('--v8-pool-size=8'), true);
// Should also contain command line flags
strictEqual(flags.includes('--no-warnings'), true);
assert.strictEqual(flags.includes('--no-warnings'), true);
});
});

View File

@ -7,12 +7,12 @@ const cluster = require('cluster');
const rr = require('internal/cluster/round_robin_handle');
if (cluster.isPrimary) {
const distribute = rr.prototype.distribute;
rr.prototype.distribute = function(err, handle) {
const originalDistribute = rr.prototype.distribute;
rr.prototype.distribute = common.mustCall(function distribute(err, handle) {
assert.strictEqual(err, 0);
handle.close();
distribute.call(this, -1, undefined);
};
originalDistribute.call(this, -1, undefined);
});
cluster.schedulingPolicy = cluster.SCHED_RR;
cluster.fork();
} else {

View File

@ -92,7 +92,7 @@ if (cluster.isWorker) {
const stateNames = Object.keys(checks.worker.states);
// Check events, states, and emit arguments
forEach(checks.cluster.events, (bool, name, index) => {
forEach(checks.cluster.events, common.mustCallAtLeast((bool, name, index) => {
// Listen on event
cluster.on(name, common.mustCall(function(/* worker */) {
@ -107,7 +107,7 @@ if (cluster.isWorker) {
const state = stateNames[index];
checks.worker.states[state] = (state === worker.state);
}));
});
}));
// Kill worker when listening
cluster.on('listening', common.mustCall(() => {
@ -124,7 +124,7 @@ if (cluster.isWorker) {
'the worker is not a instance of the Worker constructor');
// Check event
forEach(checks.worker.events, function(bool, name, index) {
forEach(checks.worker.events, common.mustCallAtLeast((bool, name, index) => {
worker.on(name, common.mustCall(function() {
// Set event
checks.worker.events[name] = true;
@ -157,7 +157,7 @@ if (cluster.isWorker) {
break;
}
}));
});
}));
// Check all values
process.once('exit', () => {

View File

@ -24,14 +24,14 @@ if (cluster.isPrimary) {
// These errors can occur due to the nature of the test, we might be trying
// to send messages when the worker is disconnecting.
worker.on('error', (err) => {
worker.on('error', common.mustCallAtLeast((err) => {
assert.strictEqual(err.syscall, 'write');
if (common.isMacOS) {
assert(['EPIPE', 'ENOTCONN'].includes(err.code), err);
} else {
assert(['EPIPE', 'ECONNRESET'].includes(err.code), err);
}
});
}, 0));
worker.once('disconnect', common.mustCall(() => {
for (const worker of workers)

View File

@ -8,9 +8,9 @@ const assert = require('assert');
const cluster = require('cluster');
if (cluster.isPrimary) {
cluster.on('exit', (worker, code) => {
cluster.on('exit', common.mustCall((worker, code) => {
assert.strictEqual(code, 0, `worker exited with code: ${code}, expected 0`);
});
}));
return cluster.fork();
}

View File

@ -38,8 +38,8 @@ if (cluster.isWorker) {
const serverPorts = new Set();
// Test a single TCP server
const testConnection = (port, cb) => {
const socket = net.connect(port, '127.0.0.1', () => {
const testConnection = common.mustCallAtLeast((port, cb) => {
const socket = net.connect(port, '127.0.0.1', common.mustCall(() => {
// buffer result
let result = '';
socket.on('data', (chunk) => { result += chunk; });
@ -49,27 +49,27 @@ if (cluster.isWorker) {
cb(result === 'echo');
serverPorts.delete(port);
}));
});
};
}));
});
// Test both servers created in the cluster
const testCluster = (cb) => {
const testCluster = common.mustCallAtLeast((cb) => {
let done = 0;
const portsArray = Array.from(serverPorts);
for (let i = 0; i < servers; i++) {
testConnection(portsArray[i], (success) => {
testConnection(portsArray[i], common.mustCall((success) => {
assert.ok(success);
done += 1;
if (done === servers) {
cb();
}
});
}));
}
};
});
// Start two workers and execute callback when both is listening
const startCluster = (cb) => {
const startCluster = common.mustCallAtLeast((cb) => {
const workers = 8;
let online = 0;
@ -83,9 +83,9 @@ if (cluster.isWorker) {
}
}, servers));
}
};
});
const test = (again) => {
const test = common.mustCall((again) => {
// 1. start cluster
startCluster(common.mustCall(() => {
// 2. test cluster
@ -99,7 +99,7 @@ if (cluster.isWorker) {
}));
}));
}));
};
}, 2);
test(true);
}

View File

@ -49,13 +49,13 @@ if (id === 'undefined') {
server.on('error', common.mustCall(function(e) {
assert(e.code, 'EADDRINUSE');
process.send('stop-listening');
process.once('message', function(msg) {
process.once('message', common.mustCall((msg) => {
if (msg !== 'stopped-listening') return;
server = net.createServer(common.mustNotCall());
server.listen(port, common.mustCall(function() {
server.close();
}));
});
}));
}));
} else {
assert(0); // Bad argument.

View File

@ -33,8 +33,8 @@ if (cluster.isPrimary) {
const pipe = new net.Socket({ fd: 4 });
pipe.unref();
pipe.on('data', (data) => {
pipe.on('data', common.mustCallAtLeast((data) => {
assert.ok(data instanceof Buffer);
pipe.write(data);
});
}));
}

View File

@ -30,11 +30,11 @@ if (!process.argv[2]) {
})
};
primary.on('message', (msg) => {
primary.on('message', common.mustCallAtLeast((msg) => {
const handler = messageHandlers[msg.type];
assert.ok(handler);
handler(msg);
});
}));
primary.on('exit', common.mustCall((code, signal) => {
assert.strictEqual(code, 0);

View File

@ -103,13 +103,13 @@ if (cluster.isWorker) {
worker.on('message', function(message) {
check('primary', message === 'message from worker');
});
cluster.on('message', function(worker_, message) {
cluster.on('message', common.mustCall((worker_, message) => {
assert.strictEqual(worker_, worker);
check('global', message === 'message from worker');
});
}));
// When a TCP server is listening in the worker connect to it
worker.on('listening', function(address) {
worker.on('listening', common.mustCall((address) => {
client = net.connect(address.port, function() {
// Send message to worker.
@ -135,12 +135,12 @@ if (cluster.isWorker) {
worker.on('exit', common.mustCall(function() {
process.exit(0);
}));
});
}));
process.once('exit', function() {
forEach(checks, function(check, type) {
for (const [type, check] of Object.entries(checks)) {
assert.ok(check.receive, `The ${type} did not receive any message`);
assert.ok(check.correct, `The ${type} did not get the correct message`);
});
}
});
}

View File

@ -36,10 +36,10 @@ if (process.argv[2] !== 'child') {
assert.ok(handle);
worker.send('got');
handle.on('data', function(data) {
handle.on('data', common.mustCall((data) => {
called = true;
assert.strictEqual(data.toString(), 'hello');
});
}));
handle.on('end', function() {
worker.kill();
@ -59,13 +59,13 @@ if (process.argv[2] !== 'child') {
process.send('handle', socket);
}
const server = net.createServer(function(c) {
const server = net.createServer(common.mustCall((c) => {
process.once('message', common.mustCall(function(msg) {
assert.strictEqual(msg, 'got');
c.end('hello');
}));
socketConnected();
});
}));
server.listen(0, function() {
socket = net.connect(server.address().port, '127.0.0.1', socketConnected);

View File

@ -13,10 +13,10 @@ if (cluster.isPrimary) {
worker.on('exit', () => {
exited = true;
});
setTimeout(() => {
setTimeout(common.mustCall(() => {
assert.ok(!exited);
worker.kill();
}, 3000);
}), 3000);
} else {
const server = net.createServer(common.mustNotCall());
server.listen(0, common.mustCall(() => process.channel.unref()));

View File

@ -23,18 +23,18 @@
// Testing mutual send of handles: from primary to worker, and from worker to
// primary.
require('../common');
const common = require('../common');
const assert = require('assert');
const cluster = require('cluster');
const net = require('net');
if (cluster.isPrimary) {
const worker = cluster.fork();
worker.on('exit', (code, signal) => {
worker.on('exit', common.mustCall((code, signal) => {
assert.strictEqual(code, 0, `Worker exited with an error code: ${code}`);
assert(!signal, `Worker exited by a signal: ${signal}`);
server.close();
});
}));
const server = net.createServer((socket) => {
worker.send('handle', socket);

View File

@ -45,14 +45,14 @@ if (cluster.isPrimary) {
process.send('send-handle-2', socket);
}));
server.listen(0, function() {
server.listen(0, common.mustCall(() => {
const client = net.connect({
host: 'localhost',
port: server.address().port
});
client.on('close', common.mustCall(() => { cluster.worker.disconnect(); }));
client.on('connect', () => { client.end(); });
}).on('error', function(e) {
})).on('error', function(e) {
console.error(e);
assert.fail('server.listen failed');
});

View File

@ -9,7 +9,7 @@ if (cluster.isPrimary) {
const worker1 = cluster.fork();
worker1.on('listening', common.mustCall(() => {
const worker2 = cluster.fork();
worker2.on('exit', (code, signal) => {
worker2.on('exit', common.mustCall((code, signal) => {
assert.strictEqual(code, 0,
'worker2 did not exit normally. ' +
`exited with code ${code}`);
@ -17,7 +17,7 @@ if (cluster.isPrimary) {
'worker2 did not exit normally. ' +
`exited with signal ${signal}`);
worker1.disconnect();
});
}));
}));
worker1.on('exit', common.mustCall((code, signal) => {
@ -33,13 +33,13 @@ if (cluster.isPrimary) {
const server = net.createServer();
server.listen(0, common.mustCall(() => {
if (cluster.worker.id === 2) {
server.close(() => {
server.close(common.mustCall(() => {
server.listen(0, common.mustCall(() => {
server.close(() => {
process.disconnect();
});
}));
});
}));
}
}));
}

View File

@ -9,7 +9,7 @@ if (cluster.isPrimary) {
const worker1 = cluster.fork();
worker1.on('listening', common.mustCall(() => {
const worker2 = cluster.fork();
worker2.on('exit', (code, signal) => {
worker2.on('exit', common.mustCall((code, signal) => {
assert.strictEqual(
code,
0,
@ -21,7 +21,7 @@ if (cluster.isPrimary) {
`worker${worker2.id} did not exit normally. Exit with signal: ${signal}`
);
worker1.disconnect();
});
}));
}));
worker1.on('exit', common.mustCall((code, signal) => {
@ -41,13 +41,13 @@ if (cluster.isPrimary) {
const server = net.createServer();
server.listen(0, common.mustCall(() => {
if (cluster.worker.id === 2) {
server.close(() => {
server.close(common.mustCall(() => {
server.listen(0, common.mustCall(() => {
server.close(() => {
process.disconnect();
});
}));
});
}));
}
}));
}

View File

@ -15,7 +15,7 @@ if (cluster.isPrimary) {
const worker1 = cluster.fork();
worker1.on('listening', common.mustCall(function(address) {
worker2 = cluster.fork();
worker2.on('online', function() {
worker2.on('online', common.mustCall(() => {
conn = net.connect(address.port, common.mustCall(function() {
worker1.disconnect();
worker2.disconnect();
@ -25,16 +25,16 @@ if (cluster.isPrimary) {
if (e.code !== 'ECONNRESET')
throw e;
});
});
}));
}));
cluster.on('exit', function(worker, exitCode, signalCode) {
cluster.on('exit', common.mustCall((worker, exitCode, signalCode) => {
assert(worker === worker1 || worker === worker2);
assert.strictEqual(exitCode, 0);
assert.strictEqual(signalCode, null);
if (Object.keys(cluster.workers).length === 0)
conn.destroy();
});
}, 2));
return;
}

View File

@ -20,7 +20,7 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
require('../common');
const common = require('../common');
const assert = require('assert');
const cluster = require('cluster');
@ -30,10 +30,10 @@ if (cluster.isPrimary) {
const worker = cluster.fork();
worker.on('exit', (code) => {
worker.on('exit', common.mustCall((code) => {
assert.strictEqual(code, OK);
process.exit(0);
});
}));
const result = worker.send('SOME MESSAGE');
assert.strictEqual(result, true);
@ -51,20 +51,20 @@ let sawWorker;
const messages = [];
const check = (m) => {
const check = common.mustCallAtLeast((m) => {
messages.push(m);
if (messages.length < 2) return;
assert.deepStrictEqual(messages[0], messages[1]);
cluster.worker.once('error', (e) => {
cluster.worker.once('error', common.mustCall((e) => {
assert.strictEqual(e, 'HI');
process.exit(OK);
});
}));
process.emit('error', 'HI');
};
});
process.on('message', (m) => {
assert(!sawProcess);

View File

@ -1,5 +1,5 @@
'use strict';
require('../common');
const common = require('../common');
const cluster = require('cluster');
const assert = require('assert');
@ -10,12 +10,12 @@ if (cluster.isPrimary) {
`isDead() returned ${workerDead}. isDead() should return ` +
'false right after the worker has been created.');
worker.on('exit', function() {
worker.on('exit', common.mustCall(() => {
workerDead = worker.isDead();
assert.ok(workerDead,
`isDead() returned ${workerDead}. After an event has been ` +
'emitted, isDead should return true');
});
}));
worker.on('message', function(msg) {
if (msg === 'readyToDie') {

View File

@ -10,7 +10,7 @@ const testFunction1 = common.mustNotCall(message);
const testFunction2 = common.mustNotCall(message);
const createValidate = (line, args = []) => common.mustCall((e) => {
const createValidate = common.mustCallAtLeast((line, args = []) => common.mustCall((e) => {
const prefix = `${message} at `;
assert.ok(e.message.startsWith(prefix));
if (process.platform === 'win32') {
@ -24,7 +24,7 @@ const createValidate = (line, args = []) => common.mustCall((e) => {
const argsInfo = args.length > 0 ?
`\ncalled with arguments: ${args.map(util.inspect).join(', ')}` : '';
assert.strictEqual(rest, line + argsInfo);
});
}));
const validate1 = createValidate('9');
try {

View File

@ -8,7 +8,7 @@ const {
skipIfSQLiteMissing();
const fixtures = require('../common/fixtures');
const tmpdir = require('../common/tmpdir');
const { match, strictEqual, deepStrictEqual } = require('node:assert');
const assert = require('node:assert');
const { test, it, describe } = require('node:test');
const { chmodSync, writeFileSync, constants } = require('node:fs');
const { join } = require('node:path');
@ -19,10 +19,10 @@ test('should handle non existing json', async () => {
'i-do-not-exist.json',
'-p', '"Hello, World!"',
]);
match(result.stderr, /Cannot read configuration from i-do-not-exist\.json: no such file or directory/);
match(result.stderr, /i-do-not-exist\.json: not found/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /Cannot read configuration from i-do-not-exist\.json: no such file or directory/);
assert.match(result.stderr, /i-do-not-exist\.json: not found/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
test('should handle empty json', async () => {
@ -31,10 +31,10 @@ test('should handle empty json', async () => {
fixtures.path('rc/empty.json'),
'-p', '"Hello, World!"',
]);
match(result.stderr, /Can't parse/);
match(result.stderr, /empty\.json: invalid content/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /Can't parse/);
assert.match(result.stderr, /empty\.json: invalid content/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
test('should handle empty object json', async () => {
@ -44,9 +44,9 @@ test('should handle empty object json', async () => {
fixtures.path('rc/empty-object.json'),
'-p', '"Hello, World!"',
]);
strictEqual(result.stderr, '');
match(result.stdout, /Hello, World!/);
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.match(result.stdout, /Hello, World!/);
assert.strictEqual(result.code, 0);
});
test('should parse boolean flag', async () => {
@ -55,9 +55,9 @@ test('should parse boolean flag', async () => {
fixtures.path('rc/transform-types.json'),
fixtures.path('typescript/ts/transformation/test-enum.ts'),
]);
match(result.stderr, /--experimental-config-file is an experimental feature and might change at any time/);
match(result.stdout, /Hello, TypeScript!/);
strictEqual(result.code, 0);
assert.match(result.stderr, /--experimental-config-file is an experimental feature and might change at any time/);
assert.match(result.stdout, /Hello, TypeScript!/);
assert.strictEqual(result.code, 0);
});
test('should parse boolean flag defaulted to true', async () => {
@ -66,9 +66,9 @@ test('should parse boolean flag defaulted to true', async () => {
fixtures.path('rc/warnings-false.json'),
'-p', 'process.emitWarning("A warning")',
]);
strictEqual(result.stderr, '');
strictEqual(result.stdout, 'undefined\n');
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.strictEqual(result.stdout, 'undefined\n');
assert.strictEqual(result.code, 0);
});
test('should throw an error when a flag is declared twice', async () => {
@ -78,9 +78,9 @@ test('should throw an error when a flag is declared twice', async () => {
fixtures.path('rc/override-property.json'),
fixtures.path('typescript/ts/transformation/test-enum.ts'),
]);
match(result.stderr, /Option --experimental-transform-types is already defined/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /Option --experimental-transform-types is already defined/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
@ -92,9 +92,9 @@ test('should override env-file', async () => {
'--env-file', fixtures.path('dotenv/node-options-no-tranform.env'),
fixtures.path('typescript/ts/transformation/test-enum.ts'),
]);
strictEqual(result.stderr, '');
match(result.stdout, /Hello, TypeScript!/);
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.match(result.stdout, /Hello, TypeScript!/);
assert.strictEqual(result.code, 0);
});
test('should not override NODE_OPTIONS', async () => {
@ -109,9 +109,9 @@ test('should not override NODE_OPTIONS', async () => {
NODE_OPTIONS: '--no-experimental-transform-types',
},
});
match(result.stderr, /ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX/);
strictEqual(result.stdout, '');
strictEqual(result.code, 1);
assert.match(result.stderr, /ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 1);
});
test('should not override CLI flags', async () => {
@ -122,9 +122,9 @@ test('should not override CLI flags', async () => {
fixtures.path('rc/transform-types.json'),
fixtures.path('typescript/ts/transformation/test-enum.ts'),
]);
match(result.stderr, /ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX/);
strictEqual(result.stdout, '');
strictEqual(result.code, 1);
assert.match(result.stderr, /ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 1);
});
test('should parse array flag correctly', async () => {
@ -134,9 +134,9 @@ test('should parse array flag correctly', async () => {
fixtures.path('rc/import.json'),
'--eval', 'setTimeout(() => console.log("D"),99)',
]);
strictEqual(result.stderr, '');
strictEqual(result.stdout, 'A\nB\nC\nD\n');
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.strictEqual(result.stdout, 'A\nB\nC\nD\n');
assert.strictEqual(result.code, 0);
});
test('should validate invalid array flag', async () => {
@ -146,9 +146,9 @@ test('should validate invalid array flag', async () => {
fixtures.path('rc/invalid-import.json'),
'--eval', 'setTimeout(() => console.log("D"),99)',
]);
match(result.stderr, /invalid-import\.json: invalid content/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /invalid-import\.json: invalid content/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
test('should validate array flag as string', async () => {
@ -158,9 +158,9 @@ test('should validate array flag as string', async () => {
fixtures.path('rc/import-as-string.json'),
'--eval', 'setTimeout(() => console.log("B"),99)',
]);
strictEqual(result.stderr, '');
strictEqual(result.stdout, 'A\nB\n');
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.strictEqual(result.stdout, 'A\nB\n');
assert.strictEqual(result.code, 0);
});
test('should throw at unknown flag', async () => {
@ -170,9 +170,9 @@ test('should throw at unknown flag', async () => {
fixtures.path('rc/unknown-flag.json'),
'-p', '"Hello, World!"',
]);
match(result.stderr, /Unknown or not allowed option some-unknown-flag for namespace nodeOptions/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /Unknown or not allowed option some-unknown-flag for namespace nodeOptions/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
test('should throw at flag not available in NODE_OPTIONS', async () => {
@ -182,9 +182,9 @@ test('should throw at flag not available in NODE_OPTIONS', async () => {
fixtures.path('rc/not-node-options-flag.json'),
'-p', '"Hello, World!"',
]);
match(result.stderr, /Unknown or not allowed option test for namespace nodeOptions/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /Unknown or not allowed option test for namespace nodeOptions/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
test('unsigned flag should be parsed correctly', async () => {
@ -194,9 +194,9 @@ test('unsigned flag should be parsed correctly', async () => {
fixtures.path('rc/numeric.json'),
'-p', 'http.maxHeaderSize',
]);
strictEqual(result.stderr, '');
strictEqual(result.stdout, '4294967295\n');
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.strictEqual(result.stdout, '4294967295\n');
assert.strictEqual(result.code, 0);
});
test('numeric flag should not allow negative values', async () => {
@ -206,10 +206,10 @@ test('numeric flag should not allow negative values', async () => {
fixtures.path('rc/negative-numeric.json'),
'-p', 'http.maxHeaderSize',
]);
match(result.stderr, /Invalid value for --max-http-header-size/);
match(result.stderr, /negative-numeric\.json: invalid content/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /Invalid value for --max-http-header-size/);
assert.match(result.stderr, /negative-numeric\.json: invalid content/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
test('v8 flag should not be allowed in config file', async () => {
@ -219,9 +219,9 @@ test('v8 flag should not be allowed in config file', async () => {
fixtures.path('rc/v8-flag.json'),
'-p', '"Hello, World!"',
]);
match(result.stderr, /V8 flag --abort-on-uncaught-exception is currently not supported/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /V8 flag --abort-on-uncaught-exception is currently not supported/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
test('string flag should be parsed correctly', async () => {
@ -232,9 +232,9 @@ test('string flag should be parsed correctly', async () => {
fixtures.path('rc/string.json'),
fixtures.path('rc/test.js'),
]);
strictEqual(result.stderr, '');
strictEqual(result.stdout, '.\n');
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.strictEqual(result.stdout, '.\n');
assert.strictEqual(result.code, 0);
});
test('host port flag should be parsed correctly', { skip: !process.features.inspector }, async () => {
@ -245,9 +245,9 @@ test('host port flag should be parsed correctly', { skip: !process.features.insp
fixtures.path('rc/host-port.json'),
'-p', 'require("internal/options").getOptionValue("--inspect-port").port',
]);
strictEqual(result.stderr, '');
strictEqual(result.stdout, '65535\n');
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.strictEqual(result.stdout, '65535\n');
assert.strictEqual(result.code, 0);
});
test('--inspect=true should be parsed correctly', { skip: !process.features.inspector }, async () => {
@ -258,9 +258,9 @@ test('--inspect=true should be parsed correctly', { skip: !process.features.insp
'--inspect-port', '0',
'-p', 'require("node:inspector").url()',
]);
match(result.stderr, /^Debugger listening on (ws:\/\/[^\s]+)/);
match(result.stdout, /ws:\/\/[^\s]+/);
strictEqual(result.code, 0);
assert.match(result.stderr, /^Debugger listening on (ws:\/\/[^\s]+)/);
assert.match(result.stdout, /ws:\/\/[^\s]+/);
assert.strictEqual(result.code, 0);
});
test('--inspect=false should be parsed correctly', { skip: !process.features.inspector }, async () => {
@ -270,9 +270,9 @@ test('--inspect=false should be parsed correctly', { skip: !process.features.ins
fixtures.path('rc/inspect-false.json'),
'-p', 'require("node:inspector").url()',
]);
strictEqual(result.stderr, '');
strictEqual(result.stdout, 'undefined\n');
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.strictEqual(result.stdout, 'undefined\n');
assert.strictEqual(result.code, 0);
});
test('no op flag should throw', async () => {
@ -282,10 +282,10 @@ test('no op flag should throw', async () => {
fixtures.path('rc/no-op.json'),
'-p', '"Hello, World!"',
]);
match(result.stderr, /No-op flag --http-parser is currently not supported/);
match(result.stderr, /no-op\.json: invalid content/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /No-op flag --http-parser is currently not supported/);
assert.match(result.stderr, /no-op\.json: invalid content/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
test('should not allow users to sneak in a flag', async () => {
@ -295,9 +295,9 @@ test('should not allow users to sneak in a flag', async () => {
fixtures.path('rc/sneaky-flag.json'),
'-p', '"Hello, World!"',
]);
match(result.stderr, /The number of NODE_OPTIONS doesn't match the number of flags in the config file/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /The number of NODE_OPTIONS doesn't match the number of flags in the config file/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
test('non object root', async () => {
@ -307,9 +307,9 @@ test('non object root', async () => {
fixtures.path('rc/non-object-root.json'),
'-p', '"Hello, World!"',
]);
match(result.stderr, /Root value unexpected not an object for/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /Root value unexpected not an object for/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
test('non object node options', async () => {
@ -319,9 +319,9 @@ test('non object node options', async () => {
fixtures.path('rc/non-object-node-options.json'),
'-p', '"Hello, World!"',
]);
match(result.stderr, /"nodeOptions" value unexpected for/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /"nodeOptions" value unexpected for/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
test('should throw correct error when a json is broken', async () => {
@ -331,10 +331,10 @@ test('should throw correct error when a json is broken', async () => {
fixtures.path('rc/broken.json'),
'-p', '"Hello, World!"',
]);
match(result.stderr, /Can't parse/);
match(result.stderr, /broken\.json: invalid content/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /Can't parse/);
assert.match(result.stderr, /broken\.json: invalid content/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
test('broken value in node_options', async () => {
@ -344,10 +344,10 @@ test('broken value in node_options', async () => {
fixtures.path('rc/broken-node-options.json'),
'-p', '"Hello, World!"',
]);
match(result.stderr, /Can't parse/);
match(result.stderr, /broken-node-options\.json: invalid content/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /Can't parse/);
assert.match(result.stderr, /broken-node-options\.json: invalid content/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
test('should use node.config.json as default', async () => {
@ -358,9 +358,9 @@ test('should use node.config.json as default', async () => {
], {
cwd: fixtures.path('rc/default'),
});
strictEqual(result.stderr, '');
strictEqual(result.stdout, '10\n');
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.strictEqual(result.stdout, '10\n');
assert.strictEqual(result.code, 0);
});
test('should override node.config.json when specificied', async () => {
@ -373,9 +373,9 @@ test('should override node.config.json when specificied', async () => {
], {
cwd: fixtures.path('rc/default'),
});
strictEqual(result.stderr, '');
strictEqual(result.stdout, '20\n');
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.strictEqual(result.stdout, '20\n');
assert.strictEqual(result.code, 0);
});
// Skip on windows because it doesn't support chmod changing read permissions
// Also skip if user is root because it would have read permissions anyway
@ -395,9 +395,9 @@ test('should throw an error when the file is non readable', {
], {
cwd: tmpdir.path,
});
match(result.stderr, /Cannot read configuration from node\.config\.json: permission denied/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /Cannot read configuration from node\.config\.json: permission denied/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
describe('namespace-scoped options', () => {
@ -409,9 +409,9 @@ describe('namespace-scoped options', () => {
fixtures.path('rc/namespaced/node.config.json'),
'-p', 'require("internal/options").getOptionValue("--test-isolation")',
]);
strictEqual(result.stderr, '');
strictEqual(result.stdout, 'none\n');
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.strictEqual(result.stdout, 'none\n');
assert.strictEqual(result.code, 0);
});
it('should throw an error when a namespace-scoped option is not recognised', async () => {
@ -421,9 +421,9 @@ describe('namespace-scoped options', () => {
fixtures.path('rc/unknown-flag-namespace.json'),
'-p', '"Hello, World!"',
]);
match(result.stderr, /Unknown or not allowed option unknown-flag for namespace testRunner/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /Unknown or not allowed option unknown-flag for namespace testRunner/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
it('should not throw an error when a namespace is not recognised', async () => {
@ -433,9 +433,9 @@ describe('namespace-scoped options', () => {
fixtures.path('rc/unknown-namespace.json'),
'-p', '"Hello, World!"',
]);
strictEqual(result.stderr, '');
strictEqual(result.stdout, 'Hello, World!\n');
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.strictEqual(result.stdout, 'Hello, World!\n');
assert.strictEqual(result.code, 0);
});
it('should handle an empty namespace valid namespace', async () => {
@ -445,9 +445,9 @@ describe('namespace-scoped options', () => {
fixtures.path('rc/empty-valid-namespace.json'),
'-p', '"Hello, World!"',
]);
strictEqual(result.stderr, '');
strictEqual(result.stdout, 'Hello, World!\n');
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.strictEqual(result.stdout, 'Hello, World!\n');
assert.strictEqual(result.code, 0);
});
it('should throw an error if a namespace-scoped option has already been set in node options', async () => {
@ -458,9 +458,9 @@ describe('namespace-scoped options', () => {
fixtures.path('rc/override-node-option-with-namespace.json'),
'-p', 'require("internal/options").getOptionValue("--test-isolation")',
]);
match(result.stderr, /Option --test-isolation is already defined/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /Option --test-isolation is already defined/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
it('should throw an error if a node option has already been set in a namespace-scoped option', async () => {
@ -471,9 +471,9 @@ describe('namespace-scoped options', () => {
fixtures.path('rc/override-namespace.json'),
'-p', 'require("internal/options").getOptionValue("--test-isolation")',
]);
match(result.stderr, /Option --test-isolation is already defined/);
strictEqual(result.stdout, '');
strictEqual(result.code, 9);
assert.match(result.stderr, /Option --test-isolation is already defined/);
assert.strictEqual(result.stdout, '');
assert.strictEqual(result.code, 9);
});
it('should prioritise CLI namespace-scoped options over config file options', async () => {
@ -485,9 +485,9 @@ describe('namespace-scoped options', () => {
fixtures.path('rc/namespaced/node.config.json'),
'-p', 'require("internal/options").getOptionValue("--test-isolation")',
]);
strictEqual(result.stderr, '');
strictEqual(result.stdout, 'process\n');
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.strictEqual(result.stdout, 'process\n');
assert.strictEqual(result.code, 0);
});
it('should append namespace-scoped config file options with CLI options in case of array', async () => {
@ -500,7 +500,7 @@ describe('namespace-scoped options', () => {
fixtures.path('rc/namespace-with-array.json'),
'-p', 'JSON.stringify(require("internal/options").getOptionValue("--test-coverage-exclude"))',
]);
strictEqual(result.stderr, '');
assert.strictEqual(result.stderr, '');
const excludePatterns = JSON.parse(result.stdout);
const expected = [
'config-pattern1',
@ -508,8 +508,8 @@ describe('namespace-scoped options', () => {
'cli-pattern1',
'cli-pattern2',
];
deepStrictEqual(excludePatterns, expected);
strictEqual(result.code, 0);
assert.deepStrictEqual(excludePatterns, expected);
assert.strictEqual(result.code, 0);
});
it('should allow setting kDisallowedInEnvvar in the config file if part of a namespace', async () => {
@ -522,9 +522,9 @@ describe('namespace-scoped options', () => {
fixtures.path('rc/namespace-with-disallowed-envvar.json'),
'-p', 'require("internal/options").getOptionValue("--test-concurrency")',
]);
strictEqual(result.stderr, '');
strictEqual(result.stdout, '1\n');
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.strictEqual(result.stdout, '1\n');
assert.strictEqual(result.code, 0);
});
it('should override namespace-scoped config file options with CLI options', async () => {
@ -538,8 +538,8 @@ describe('namespace-scoped options', () => {
fixtures.path('rc/namespace-with-disallowed-envvar.json'),
'-p', 'require("internal/options").getOptionValue("--test-concurrency")',
]);
strictEqual(result.stderr, '');
strictEqual(result.stdout, '2\n');
strictEqual(result.code, 0);
assert.strictEqual(result.stderr, '');
assert.strictEqual(result.stdout, '2\n');
assert.strictEqual(result.code, 0);
});
});

View File

@ -1,7 +1,7 @@
'use strict';
const { mustCall } = require('../common');
const { deepStrictEqual, ok, strictEqual } = require('assert');
const assert = require('assert');
const { channel } = require('diagnostics_channel');
@ -54,10 +54,10 @@ for (const method of methods) {
channels[method].subscribe(mustCall((args) => {
// Should not have been formatted yet.
intercepted = true;
ok(!formatted);
assert.ok(!formatted);
// Should receive expected log message args.
deepStrictEqual(args, [foo, bar, baz]);
assert.deepStrictEqual(args, [foo, bar, baz]);
// Should be able to mutate message args and have it reflected in output.
bar.added = true;
@ -66,10 +66,10 @@ for (const method of methods) {
hijack(mustCall((output) => {
// Should have already been intercepted.
formatted = true;
ok(intercepted);
assert.ok(intercepted);
// Should produce expected formatted output with mutated message args.
strictEqual(output, 'string { key: /value/, added: true } [ 1, 2, 3 ]\n');
assert.strictEqual(output, 'string { key: /value/, added: true } [ 1, 2, 3 ]\n');
}));
console[method](foo, bar, baz);

View File

@ -2,7 +2,7 @@
require('../common');
const { Console } = require('console');
const { PassThrough } = require('stream');
const { strict: assert } = require('assert');
const assert = require('assert');
const stdout = new PassThrough().setEncoding('utf8');
const stderr = new PassThrough().setEncoding('utf8');

View File

@ -179,11 +179,11 @@ console.timeEnd(NaN);
// Make sure calling time twice without timeEnd doesn't reset the timer.
console.time('test');
const time = console._times.get('test');
setTimeout(() => {
setTimeout(common.mustCall(() => {
console.time('test');
assert.deepStrictEqual(console._times.get('test'), time);
console.timeEnd('test');
}, 1);
}), 1);
console.time('log1');
console.timeLog('log1');

View File

@ -15,16 +15,16 @@ assert.ok(binding.fs);
assert.ok(binding.crypto);
['os', 'fs', 'crypto'].forEach((l) => {
Object.keys(binding[l]).forEach((k) => {
for (const k of Object.keys(binding[l])) {
if (typeof binding[l][k] === 'object') { // errno and signals
Object.keys(binding[l][k]).forEach((j) => {
for (const j of Object.keys(binding[l][k])) {
assert.strictEqual(binding[l][k][j], constants[j]);
});
}
}
if (l !== 'os') { // Top level os constant isn't currently copied
assert.strictEqual(binding[l][k], constants[k]);
}
});
}
});
assert.ok(Object.isFrozen(constants));

View File

@ -40,7 +40,7 @@ const expectedSpaceKeys = [
'free_list_stats',
].sort();
heapStatsDetailed.space_statistics.forEach((space) => {
for (const space of heapStatsDetailed.space_statistics) {
const actualSpaceKeys = Object.keys(space).sort();
assert.deepStrictEqual(actualSpaceKeys, expectedSpaceKeys);
assert.strictEqual(typeof space.name, 'string');
@ -49,7 +49,7 @@ heapStatsDetailed.space_statistics.forEach((space) => {
assert.strictEqual(typeof space.used_size_bytes, 'number');
assert.strictEqual(Array.isArray(space.page_stats), true);
assert.strictEqual(typeof space.free_list_stats, 'object');
});
}
// Check page statistics array
const expectedPageKeys = [
@ -59,46 +59,46 @@ const expectedPageKeys = [
'object_statistics',
].sort();
heapStatsDetailed.space_statistics.forEach((space) => {
space.page_stats.forEach((page) => {
for (const space of heapStatsDetailed.space_statistics) {
for (const page of space.page_stats) {
const actualPageKeys = Object.keys(page).sort();
assert.deepStrictEqual(actualPageKeys, expectedPageKeys);
assert.strictEqual(typeof page.committed_size_bytes, 'number');
assert.strictEqual(typeof page.resident_size_bytes, 'number');
assert.strictEqual(typeof page.used_size_bytes, 'number');
assert.strictEqual(Array.isArray(page.object_statistics), true);
});
});
}
}
// Check free list statistics
const expectedFreeListKeys = ['bucket_size', 'free_count', 'free_size'].sort();
heapStatsDetailed.space_statistics.forEach((space) => {
for (const space of heapStatsDetailed.space_statistics) {
const actualFreeListKeys = Object.keys(space.free_list_stats).sort();
assert.deepStrictEqual(actualFreeListKeys, expectedFreeListKeys);
assert.strictEqual(Array.isArray(space.free_list_stats.bucket_size), true);
assert.strictEqual(Array.isArray(space.free_list_stats.free_count), true);
assert.strictEqual(Array.isArray(space.free_list_stats.free_size), true);
});
}
// Check object statistics
const expectedObjectStatsKeys = ['allocated_bytes', 'object_count'].sort();
heapStatsDetailed.space_statistics.forEach((space) => {
space.page_stats.forEach((page) => {
page.object_statistics.forEach((objectStats) => {
for (const space of heapStatsDetailed.space_statistics) {
for (const page of space.page_stats) {
for (const objectStats of page.object_statistics) {
const actualObjectStatsKeys = Object.keys(objectStats).sort();
assert.deepStrictEqual(actualObjectStatsKeys, expectedObjectStatsKeys);
assert.strictEqual(typeof objectStats.allocated_bytes, 'number');
assert.strictEqual(typeof objectStats.object_count, 'number');
});
});
});
}
}
}
// Check type names
heapStatsDetailed.type_names.forEach((typeName) => {
for (const typeName of heapStatsDetailed.type_names) {
assert.strictEqual(typeof typeName, 'string');
});
}
// Brief heap statistics
const heapStatsBrief = v8.getCppHeapStatistics('brief');

View File

@ -56,9 +56,9 @@ const { hasOpenSSL3 } = require('../common/crypto');
}, ['public']);
// The public key is outdated: generateKeys() generates only the public key.
testGenerateKeysChangesKeys((dh) => {
testGenerateKeysChangesKeys(common.mustCall((dh) => {
const oldPublicKey = dh.generateKeys();
dh.setPrivateKey(Buffer.from('01020304', 'hex'));
assert.deepStrictEqual(dh.getPublicKey(), oldPublicKey);
}, ['public']);
}), ['public']);
}

View File

@ -28,7 +28,7 @@ const assert = require('assert');
const crypto = require('crypto');
const domain = require('domain');
const test = (fn) => {
function test(fn) {
const ex = new Error('BAM');
const d = domain.create();
d.on('error', common.mustCall(function(err) {
@ -37,11 +37,11 @@ const test = (fn) => {
const cb = common.mustCall(function() {
throw ex;
});
d.run(cb);
d.run(fn, cb);
};
test(function(cb) {
crypto.pbkdf2('password', 'salt', 1, 8, cb);
crypto.pbkdf2('password', 'salt', 1, 8, 'sha1', cb);
});
test(function(cb) {

View File

@ -243,14 +243,14 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
assert(Buffer.isBuffer(privateDER));
const plaintext = Buffer.from('Hello world', 'utf8');
const testDecryption = (fn, ciphertexts, decryptionKeys) => {
const testDecryption = common.mustCall((fn, ciphertexts, decryptionKeys) => {
for (const ciphertext of ciphertexts) {
for (const key of decryptionKeys) {
const deciphered = fn(key, ciphertext);
assert.deepStrictEqual(deciphered, plaintext);
}
}
};
}, 2);
testDecryption(privateDecrypt, [
// Encrypt using the public key.

View File

@ -22,6 +22,7 @@ generateKeyPair('rsa', {
format: 'pem'
}
}, (err/* , publicKey, privateKey */) => {
// eslint-disable-next-line node-core/must-call-assert
assert.ifError(err);
});

View File

@ -42,6 +42,7 @@ if (!hasOpenSSL(3, 5)) {
}
for (const [publicKeyEncoding, validate] of [
/* eslint-disable node-core/must-call-assert */
[undefined, (publicKey) => {
assert.strictEqual(publicKey.type, 'public');
assert.strictEqual(publicKey.asymmetricKeyType, asymmetricKeyType);
@ -50,10 +51,12 @@ if (!hasOpenSSL(3, 5)) {
[{ format: 'jwk' }, (publicKey) => assertPublicJwk(publicKey)],
[{ format: 'pem', type: 'spki' }, (publicKey) => assert.strictEqual(typeof publicKey, 'string')],
[{ format: 'der', type: 'spki' }, (publicKey) => assert.strictEqual(Buffer.isBuffer(publicKey), true)],
/* eslint-enable node-core/must-call-assert */
]) {
generateKeyPair(asymmetricKeyType, { publicKeyEncoding }, common.mustSucceed(validate));
}
for (const [privateKeyEncoding, validate] of [
/* eslint-disable node-core/must-call-assert */
[undefined, (_, privateKey) => {
assert.strictEqual(privateKey.type, 'private');
assert.strictEqual(privateKey.asymmetricKeyType, asymmetricKeyType);
@ -62,6 +65,7 @@ if (!hasOpenSSL(3, 5)) {
[{ format: 'jwk' }, (_, privateKey) => assertPrivateJwk(privateKey)],
[{ format: 'pem', type: 'pkcs8' }, (_, privateKey) => assert.strictEqual(typeof privateKey, 'string')],
[{ format: 'der', type: 'pkcs8' }, (_, privateKey) => assert.strictEqual(Buffer.isBuffer(privateKey), true)],
/* eslint-enable node-core/must-call-assert */
]) {
generateKeyPair(asymmetricKeyType, { privateKeyEncoding }, common.mustSucceed(validate));
}

View File

@ -21,6 +21,7 @@ if (!hasOpenSSL(3, 5)) {
} else {
for (const asymmetricKeyType of ['ml-kem-512', 'ml-kem-768', 'ml-kem-1024']) {
for (const [publicKeyEncoding, validate] of [
/* eslint-disable node-core/must-call-assert */
[undefined, (publicKey) => {
assert.strictEqual(publicKey.type, 'public');
assert.strictEqual(publicKey.asymmetricKeyType, asymmetricKeyType);
@ -28,10 +29,12 @@ if (!hasOpenSSL(3, 5)) {
}],
[{ format: 'pem', type: 'spki' }, (publicKey) => assert.strictEqual(typeof publicKey, 'string')],
[{ format: 'der', type: 'spki' }, (publicKey) => assert.strictEqual(Buffer.isBuffer(publicKey), true)],
/* eslint-enable node-core/must-call-assert */
]) {
generateKeyPair(asymmetricKeyType, { publicKeyEncoding }, common.mustSucceed(validate));
}
for (const [privateKeyEncoding, validate] of [
/* eslint-disable node-core/must-call-assert */
[undefined, (_, privateKey) => {
assert.strictEqual(privateKey.type, 'private');
assert.strictEqual(privateKey.asymmetricKeyType, asymmetricKeyType);
@ -39,6 +42,7 @@ if (!hasOpenSSL(3, 5)) {
}],
[{ format: 'pem', type: 'pkcs8' }, (_, privateKey) => assert.strictEqual(typeof privateKey, 'string')],
[{ format: 'der', type: 'pkcs8' }, (_, privateKey) => assert.strictEqual(Buffer.isBuffer(privateKey), true)],
/* eslint-enable node-core/must-call-assert */
]) {
generateKeyPair(asymmetricKeyType, { privateKeyEncoding }, common.mustSucceed(validate));
}

View File

@ -29,6 +29,7 @@ if (!hasOpenSSL(3, 5)) {
'slh-dsa-shake-192f', 'slh-dsa-shake-192s', 'slh-dsa-shake-256f', 'slh-dsa-shake-256s',
]) {
for (const [publicKeyEncoding, validate] of [
/* eslint-disable node-core/must-call-assert */
[undefined, (publicKey) => {
assert.strictEqual(publicKey.type, 'public');
assert.strictEqual(publicKey.asymmetricKeyType, asymmetricKeyType);
@ -47,6 +48,7 @@ if (!hasOpenSSL(3, 5)) {
}],
[{ format: 'pem', type: 'pkcs8' }, (_, privateKey) => assert.strictEqual(typeof privateKey, 'string')],
[{ format: 'der', type: 'pkcs8' }, (_, privateKey) => assert.strictEqual(Buffer.isBuffer(privateKey), true)],
/* eslint-enable node-core/must-call-assert */
]) {
generateKeyPair(asymmetricKeyType, { privateKeyEncoding }, common.mustSucceed(validate));
}

View File

@ -4,7 +4,7 @@ if (!common.hasCrypto)
common.skip('missing crypto');
const { randomFillSync } = require('crypto');
const { notStrictEqual } = require('assert');
const assert = require('assert');
const ab = new ArrayBuffer(20);
const buf = Buffer.from(ab, 10);
@ -15,4 +15,4 @@ randomFillSync(buf);
const after = buf.toString('hex');
notStrictEqual(before, after);
assert.notStrictEqual(before, after);

View File

@ -34,6 +34,4 @@ const { subtle } = globalThis.crypto;
}, k, e);
assert(v instanceof ArrayBuffer);
assert.strictEqual(v.byteLength, 0);
})().then(common.mustCall()).catch((e) => {
assert.ifError(e);
});
})().then(common.mustCall());