test: ensure assertions are reached on more tests

PR-URL: https://github.com/nodejs/node/pull/60641
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
This commit is contained in:
Antoine du Hamel authored and GitHub committed 2025-11-11 09:56:18 +00:00
1 parent 57b4a315ce
commit f1f6f3df84
78 files changed
+324 -297

No files matched your search

@@ -17,6 +17,6 @@ async_hooks.createHook({
}),
}).enable();
runInCallbackScope({}, 1000, 1000, () => {
runInCallbackScope({}, 1000, 1000, common.mustCallAtLeast(() => {
assert(insideHook);
});
}));
@@ -9,4 +9,4 @@ const { testResolveAsync } = require(`./build/${common.buildType}/binding`);
let called = false;
testResolveAsync().then(() => { called = true; });
process.on('beforeExit', () => { assert(called); });
process.on('beforeExit', common.mustCall(() => { assert(called); }));
@@ -9,13 +9,13 @@ const server = http.createServer((req, res) => {
res.end('ok');
});
server.listen(0, () => {
asyncLocalStorage.run(new Map(), () => {
server.listen(0, mustCall(() => {
asyncLocalStorage.run(new Map(), mustCall(() => {
const store = asyncLocalStorage.getStore();
store.set('hello', 'world');
http.get({ host: 'localhost', port: server.address().port }, mustCall(() => {
assert.strictEqual(asyncLocalStorage.getStore().get('hello'), 'world');
server.close();
}));
});
});
}));
}));
+1 -1
View File
@@ -194,7 +194,7 @@ export default [
].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(',')
Array.from({ length: 4 }, (_, 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(',')
@@ -15,11 +15,11 @@ const { cjs, esm } = require('../fixtures/es-modules/custom-condition/load.cjs')
// allow a CJS to be resolved with that condition.
{
const hooks = registerHooks({
resolve(specifier, context, nextResolve) {
resolve: common.mustCall((specifier, context, nextResolve) => {
assert(Array.isArray(context.conditions));
context.conditions = ['foo', ...context.conditions];
return nextResolve(specifier, context);
},
}, 2),
});
assert.strictEqual(cjs('foo/second').result, 'foo');
assert.strictEqual((await esm('foo/second')).result, 'foo');
@@ -30,11 +30,11 @@ const { cjs, esm } = require('../fixtures/es-modules/custom-condition/load.cjs')
// allow a ESM to be resolved with that condition.
{
const hooks = registerHooks({
resolve(specifier, context, nextResolve) {
resolve: common.mustCall((specifier, context, nextResolve) => {
assert(Array.isArray(context.conditions));
context.conditions = ['foo-esm', ...context.conditions];
return nextResolve(specifier, context);
},
}, 2),
});
assert.strictEqual(cjs('foo/third').result, 'foo-esm');
assert.strictEqual((await esm('foo/third')).result, 'foo-esm');
@@ -44,11 +44,11 @@ const { cjs, esm } = require('../fixtures/es-modules/custom-condition/load.cjs')
// Duplicating the 'foo' condition in the resolve hook should not change the result.
{
const hooks = registerHooks({
resolve(specifier, context, nextResolve) {
resolve: common.mustCall((specifier, context, nextResolve) => {
assert(Array.isArray(context.conditions));
context.conditions = ['foo', ...context.conditions, 'foo'];
return nextResolve(specifier, context);
},
}, 2),
});
assert.strictEqual(cjs('foo/fourth').result, 'foo');
assert.strictEqual((await esm('foo/fourth')).result, 'foo');
@@ -1,5 +1,5 @@
// This tests that custom conditions can be used in module resolution hooks.
import '../common/index.mjs';
import * as common from '../common/index.mjs';
import { registerHooks } from 'node:module';
import assert from 'node:assert';
import { cjs, esm } from '../fixtures/es-modules/custom-condition/load.cjs';
@@ -12,11 +12,11 @@ assert.strictEqual((await esm('foo')).result, 'default');
// allow a CJS to be resolved with that condition.
{
const hooks = registerHooks({
resolve(specifier, context, nextResolve) {
resolve: common.mustCall((specifier, context, nextResolve) => {
assert(Array.isArray(context.conditions));
context.conditions = ['foo', ...context.conditions];
return nextResolve(specifier, context);
},
}, 2),
});
assert.strictEqual(cjs('foo/second').result, 'foo');
assert.strictEqual((await esm('foo/second')).result, 'foo');
@@ -27,11 +27,11 @@ assert.strictEqual((await esm('foo')).result, 'default');
// allow a ESM to be resolved with that condition.
{
const hooks = registerHooks({
resolve(specifier, context, nextResolve) {
resolve: common.mustCall((specifier, context, nextResolve) => {
assert(Array.isArray(context.conditions));
context.conditions = ['foo-esm', ...context.conditions];
return nextResolve(specifier, context);
},
}, 2),
});
assert.strictEqual(cjs('foo/third').result, 'foo-esm');
assert.strictEqual((await esm('foo/third')).result, 'foo-esm');
@@ -41,11 +41,11 @@ assert.strictEqual((await esm('foo')).result, 'default');
// Duplicating the 'foo' condition in the resolve hook should not change the result.
{
const hooks = registerHooks({
resolve(specifier, context, nextResolve) {
resolve: common.mustCall((specifier, context, nextResolve) => {
assert(Array.isArray(context.conditions));
context.conditions = ['foo', ...context.conditions, 'foo'];
return nextResolve(specifier, context);
},
}, 2),
});
assert.strictEqual(cjs('foo/fourth').result, 'foo');
assert.strictEqual((await esm('foo/fourth')).result, 'foo');
@@ -34,6 +34,6 @@ async_hooks.createHook({
}),
}).enable();
runInCallbackScope(expectedResource, expectedResourceType, () => {
runInCallbackScope(expectedResource, expectedResourceType, common.mustCall(() => {
assert(insideHook);
});
}));
+2 -2
View File
@@ -21,7 +21,7 @@
'use strict';
const { invalidArgTypeHelper } = require('../common');
const { invalidArgTypeHelper, mustCall } = require('../common');
const assert = require('assert');
const { inspect } = require('util');
const { test } = require('node:test');
@@ -605,7 +605,7 @@ test('Test strict assert', () => {
}
);
strict.throws(
() => assert(),
mustCall(() => assert()),
{
message: 'No value argument passed to `assert.ok()`',
name: 'AssertionError'
+2 -2
View File
@@ -172,12 +172,12 @@ if (process.argv[2] === 'child') {
function closeServer() {
server.close();
setTimeout(() => {
setTimeout(mustCall(() => {
assert(!closeEmitted);
child1.send('close');
child2.send('close');
child3.disconnect();
}, platformTimeout(200));
}), platformTimeout(200));
}
process.on('exit', function() {
+11 -11
View File
@@ -160,36 +160,36 @@ if (cluster.isWorker) {
}));
// Check all values
process.once('exit', () => {
process.on('exit', () => {
// Check cluster events
forEach(checks.cluster.events, (check, name) => {
for (const [ name, check ] of Object.entries(checks.cluster.events)) {
assert(check,
`The cluster event "${name}" on the cluster object did not fire`);
});
}
// Check cluster event arguments
forEach(checks.cluster.equal, (check, name) => {
for (const [ name, check ] of Object.entries(checks.cluster.equal)) {
assert(check,
`The cluster event "${name}" did not emit with correct argument`);
});
}
// Check worker states
forEach(checks.worker.states, (check, name) => {
for (const [ name, check ] of Object.entries(checks.worker.states)) {
assert(check,
`The worker state "${name}" was not set to true`);
});
}
// Check worker events
forEach(checks.worker.events, (check, name) => {
for (const [ name, check ] of Object.entries(checks.worker.events)) {
assert(check,
`The worker event "${name}" on the worker object did not fire`);
});
}
// Check worker event arguments
forEach(checks.worker.equal, (check, name) => {
for (const [ name, check ] of Object.entries(checks.worker.equal)) {
assert(check,
`The worker event "${name}" did not emit with correct argument`);
});
}
});
}
+3 -3
View File
@@ -44,8 +44,8 @@ if (cluster.isPrimary) {
worker.send({ message: 'listen', port: server.address().port });
});
} else {
process.on('message', (msg, handle) => {
if (msg.message && msg.message === 'listen') {
process.on('message', common.mustCallAtLeast((msg, handle) => {
if (msg.message === 'listen') {
assert(msg.port);
const client1 = net.connect({
host: 'localhost',
@@ -69,5 +69,5 @@ if (cluster.isPrimary) {
} else {
process.send('reply', handle);
}
});
}));
}
+4 -4
View File
@@ -66,14 +66,14 @@ const check = common.mustCallAtLeast((m) => {
process.emit('error', 'HI');
});
process.on('message', (m) => {
process.on('message', common.mustCall((m) => {
assert(!sawProcess);
sawProcess = true;
check(m);
});
}));
cluster.worker.on('message', (m) => {
cluster.worker.on('message', common.mustCall((m) => {
assert(!sawWorker);
sawWorker = true;
check(m);
});
}));
+5 -5
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');
const net = require('net');
@@ -41,7 +41,7 @@ let server;
// 4 destroy connection
// 5 confirm it does exit
if (cluster.isPrimary) {
server = net.createServer(function(conn) {
server = net.createServer(common.mustCall((conn) => {
server.close();
worker.disconnect();
worker.once('disconnect', function() {
@@ -49,13 +49,13 @@ if (cluster.isPrimary) {
conn.destroy();
destroyed = true;
}, 1000);
}).once('exit', function() {
}).once('exit', common.mustCall(() => {
// Worker should not exit while it has a connection
assert(destroyed, 'worker exited before connection destroyed');
success = true;
});
}));
}).listen(0, function() {
})).listen(0, function() {
const port = this.address().port;
worker = cluster.fork()
@@ -23,11 +23,11 @@ if (cluster.isWorker) {
const keepOpen = setInterval(() => {}, 9999);
// Check worker events and properties
process.once('disconnect', function() {
process.once('disconnect', common.mustCall(() => {
// Disconnect should occur after socket close
assert(serverClosed);
clearInterval(keepOpen);
});
}));
} else if (cluster.isPrimary) {
// start worker
const worker = cluster.fork();
+4 -5
View File
@@ -218,9 +218,8 @@ algorithms.forEach(([ hash, secret, salt, info, length ]) => {
if (!hasOpenSSL3) {
const kKnownUnsupported = ['shake128', 'shake256'];
getHashes()
.filter((hash) => !kKnownUnsupported.includes(hash))
.forEach((hash) => {
assert(hkdfSync(hash, 'key', 'salt', 'info', 5));
});
for (const hash of getHashes()) {
if (kKnownUnsupported.includes(hash)) continue;
assert(hkdfSync(hash, 'key', 'salt', 'info', 5));
}
}
+2 -2
View File
@@ -274,12 +274,12 @@ function testEncoding(options, assertionHash) {
const hash = crypto.createHash('sha256', options);
let hashValue = '';
hash.on('data', (data) => {
hash.on('data', common.mustCall((data) => {
// The defaultEncoding has no effect on the hash value. It only affects data
// consumed by the Hash transform stream.
assert(Buffer.isBuffer(data));
hashValue += data.toString('hex');
});
}));
hash.on('end', common.mustCall(() => {
assert.strictEqual(hashValue, assertionHash);
+3 -3
View File
@@ -6,7 +6,7 @@ import { path as _path } from '../common/fixtures.js';
import startCLI from '../common/debugger.js';
import { addLibraryPath } from '../common/shared-lib-util.js';
import { deepStrictEqual, strictEqual } from 'assert';
import assert from 'assert';
import { relative } from 'path';
addLibraryPath(process.env);
@@ -24,10 +24,10 @@ addLibraryPath(process.env);
const cli = startCLI([script], [], { env });
await cli.waitForInitialBreak();
deepStrictEqual(cli.breakInfo, {
assert.deepStrictEqual(cli.breakInfo, {
filename: script,
line: 10,
});
const code = await cli.quit();
strictEqual(code, 0);
assert.strictEqual(code, 0);
}
@@ -13,7 +13,7 @@ const scriptFullPath = fixtures.path('debugger', 'three-lines.js');
const script = path.relative(process.cwd(), scriptFullPath);
// Run after quit.
const runTest = async () => {
(async () => {
const cli = startCLI([script]);
try {
await cli.waitForInitialBreak();
@@ -42,6 +42,4 @@ const runTest = async () => {
} finally {
await cli.quit();
}
};
runTest();
})().then(common.mustCall());
@@ -35,10 +35,10 @@ const server = http.createServer(common.mustCall((req, res) => {
childProcess.spawn(process.execPath, ['inspect', `localhost:${port}`]);
let stdout = '';
proc.stdout.on('data', (data) => {
proc.stdout.on('data', common.mustCallAtLeast((data) => {
stdout += data.toString();
assert.doesNotMatch(stdout, /\bok\b/);
});
}));
let stderr = '';
proc.stderr.on('data', (data) => {
@@ -9,7 +9,7 @@ const dgram = require('dgram');
process.on('warning', common.mustNotCall());
const reservePortSocket = dgram.createSocket('udp4');
reservePortSocket.bind(() => {
reservePortSocket.bind(common.mustCall(() => {
const { port } = reservePortSocket.address();
const newSocket = dgram.createSocket('udp4');
@@ -24,4 +24,4 @@ reservePortSocket.bind(() => {
}
}, 20));
newSocket.bind(port, common.mustNotCall());
});
}));
+3 -3
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 dgram = require('dgram');
@@ -32,8 +32,8 @@ client.send(
message.length,
41234,
'localhost',
function(err, bytes) {
common.mustCall((err, bytes) => {
assert.strictEqual(bytes, message.length);
client.close();
}
}),
);
@@ -16,8 +16,7 @@ const received = [];
server.on('listening', common.mustCall(() => {
const port = server.address().port;
client.connect(port, (err) => {
assert.ifError(err);
client.connect(port, common.mustSucceed(() => {
client.send(toSend[0], 0, toSend[0].length);
client.send(toSend[1]);
client.send([toSend[2]]);
@@ -28,7 +27,7 @@ server.on('listening', common.mustCall(() => {
client.send([new Uint8Array(toSend[2])]);
client.send(new Uint8Array(Buffer.from(toSend[3])),
0, toSend[3].length);
});
}));
}));
server.on('message', common.mustCall((buf, info) => {
@@ -11,9 +11,9 @@ client.bind(0, common.mustCall(function() {
client.on('message', common.mustCall(callback));
const buf = Buffer.alloc(1);
const interval = setInterval(function() {
const interval = setInterval(common.mustCallAtLeast(() => {
client.send(buf, 0, 0, common.mustCall(callback));
}, 10);
}), 10);
function callback(firstArg) {
// If client.send() callback, firstArg should be null.
@@ -10,8 +10,8 @@ socket.on('message', common.mustCall((msg, rinfo) => {
assert.deepStrictEqual(msg.toString(), data.join(''));
}));
socket.bind(0, () => {
socket.bind(0, common.mustCall(() => {
socket.connect(socket.address().port, common.mustCall(() => {
socket.send(data);
}));
});
}));
@@ -51,7 +51,7 @@ if (cluster.isPrimary) {
target.close();
});
target.on('message', function(buf, rinfo) {
target.on('message', common.mustCallAtLeast((buf, rinfo) => {
if (pids.includes(buf.toString()))
return;
pids.push(buf.toString());
@@ -67,7 +67,7 @@ if (cluster.isPrimary) {
assert.strictEqual(Object.keys(ports).length, 3);
done();
}
});
}));
target.on('listening', function() {
cluster.fork({ PORT: target.address().port });
@@ -11,7 +11,7 @@ const onMessage = common.mustSucceed((bytes) => {
assert.strictEqual(bytes, buf.length);
}, defaultCases.length + 1);
const client = dgram.createSocket('udp4').bind(0, () => {
const client = dgram.createSocket('udp4').bind(0, common.mustCall(() => {
const port = client.address().port;
// Check valid addresses
@@ -42,6 +42,6 @@ const client = dgram.createSocket('udp4').bind(0, () => {
};
assert.throws(() => client.send(buf, port, invalidInput), expectedError);
});
});
}));
client.unref();
@@ -37,7 +37,7 @@ client.bind(0, common.mustCall(function() {
}));
const buf = Buffer.alloc(0);
const interval = setInterval(function() {
const interval = setInterval(common.mustCallAtLeast(() => {
client.send(buf, 0, 0, port, '127.0.0.1', common.mustCall());
}, 10);
}), 10);
}));
@@ -13,9 +13,9 @@ client.bind(0, common.mustCall(function() {
const port = this.address().port;
const buf = Buffer.alloc(1);
const interval = setInterval(function() {
const interval = setInterval(common.mustCallAtLeast(() => {
client.send(buf, 0, 0, port, '127.0.0.1', common.mustCall(callback));
}, 10);
}), 10);
function callback(firstArg) {
// If client.send() callback, firstArg should be null.
+4 -4
View File
@@ -23,23 +23,23 @@ function getSocket(callback) {
return socket;
}
getSocket((socket) => {
getSocket(common.mustCall((socket) => {
socket.on('error', common.mustCall((err) => {
socket.close();
assert.strictEqual(err, mockError);
}));
socket.send('foo', socket.address().port, 'localhost');
});
}));
getSocket((socket) => {
getSocket(common.mustCall((socket) => {
const callback = common.mustCall((err) => {
socket.close();
assert.strictEqual(err, mockError);
});
socket.send('foo', socket.address().port, 'localhost', callback);
});
}));
{
const socket = dgram.createSocket('udp4');
@@ -24,7 +24,7 @@ const server = http.createServer(common.mustCall((_, res) => {
res.end('done');
}));
server.listen(async () => {
server.listen(common.mustCall(async () => {
const { port } = server.address();
const req = http.request({
port,
@@ -36,4 +36,4 @@ server.listen(async () => {
}));
req.setHeader('baz', 'bar');
req.end();
});
}));
@@ -32,7 +32,7 @@ const server = http.createServer(common.mustCall((_, res) => {
res.end('done');
}));
server.listen(() => {
server.listen(common.mustCall(() => {
const { port } = server.address();
http.get({
port,
@@ -42,4 +42,4 @@ server.listen(() => {
}, common.mustCall(() => {
server.close();
}));
});
}));
@@ -1,7 +1,7 @@
// Flags: --expose-gc
'use strict';
require('../common');
const common = require('../common');
const assert = require('assert');
const { channel } = require('diagnostics_channel');
@@ -12,10 +12,10 @@ function test() {
subscribe();
setTimeout(() => {
setTimeout(common.mustCall(() => {
global.gc();
assert.ok(channel('test-gc').hasSubscribers, 'Channel must have subscribers');
});
}));
}
test();
@@ -1,18 +1,18 @@
// Flags: --expose-gc
'use strict';
require('../common');
const common = require('../common');
const assert = require('assert');
const { channel } = require('diagnostics_channel');
function test() {
const testChannel = channel('test-gc');
setTimeout(() => {
setTimeout(common.mustCall(() => {
const testChannel2 = channel('test-gc');
assert.ok(testChannel === testChannel2, 'Channel instances must be the same');
});
}));
}
test();
@@ -40,7 +40,7 @@ server.listen(0, common.mustCall(() => {
const port = server.address().port;
const client = http2.connect(`http://localhost:${port}`);
const countdown = new Countdown(serverHttp2StreamCreationCount, () => {
const countdown = new Countdown(serverHttp2StreamCreationCount, common.mustCall(() => {
client.close();
server.close();
@@ -50,7 +50,7 @@ server.listen(0, common.mustCall(() => {
for (const { createdTime, startTime } of timings) {
assert.ok(createdTime < startTime);
}
});
}));
const stream = client.request({});
stream.on('response', common.mustCall(() => {
@@ -9,7 +9,7 @@ const events = [];
let lastEvent;
function track(name) {
return (event) => {
return common.mustCall((event) => {
// Verify every event after the first is the same object
if (events.length) {
assert.strictEqual(event, lastEvent);
@@ -17,7 +17,7 @@ function track(name) {
lastEvent = event;
events.push({ name, ...event });
};
});
}
trace.subscribe({
@@ -9,7 +9,7 @@ const events = [];
let lastEvent;
function track(name) {
return (event) => {
return common.mustCall((event) => {
// Verify every event after the first is the same object
if (events.length) {
assert.strictEqual(event, lastEvent);
@@ -17,15 +17,15 @@ function track(name) {
lastEvent = event;
events.push({ name, ...event });
};
});
}
trace.subscribe({
start: common.mustCall(track('start')),
end: common.mustCall(track('end')),
asyncStart: common.mustCall(track('asyncStart')),
asyncEnd: common.mustCall(track('asyncEnd')),
error: common.mustNotCall(track('error')),
start: track('start'),
end: track('end'),
asyncStart: track('asyncStart'),
asyncEnd: track('asyncEnd'),
error: common.mustNotCall('error'),
});
import('http').then(
@@ -8,7 +8,7 @@ const events = [];
let lastEvent;
function track(name) {
return (event) => {
return common.mustCall((event) => {
// Verify every event after the first is the same object
if (events.length) {
assert.strictEqual(event, lastEvent);
@@ -16,15 +16,15 @@ function track(name) {
lastEvent = event;
events.push({ name, ...event });
};
});
}
trace.subscribe({
start: common.mustCall(track('start')),
end: common.mustCall(track('end')),
asyncStart: common.mustNotCall(track('asyncStart')),
asyncEnd: common.mustNotCall(track('asyncEnd')),
error: common.mustCall(track('error')),
start: track('start'),
end: track('end'),
asyncStart: common.mustNotCall('asyncStart'),
asyncEnd: common.mustNotCall('asyncEnd'),
error: track('error'),
});
let error;
@@ -8,7 +8,7 @@ const events = [];
let lastEvent;
function track(name) {
return (event) => {
return common.mustCall((event) => {
// Verify every event after the first is the same object
if (events.length) {
assert.strictEqual(event, lastEvent);
@@ -16,15 +16,15 @@ function track(name) {
lastEvent = event;
events.push({ name, ...event });
};
});
}
trace.subscribe({
start: common.mustCall(track('start')),
end: common.mustCall(track('end')),
asyncStart: common.mustNotCall(track('asyncStart')),
asyncEnd: common.mustNotCall(track('asyncEnd')),
error: common.mustNotCall(track('error')),
start: track('start'),
end: track('end'),
asyncStart: common.mustNotCall('asyncStart'),
asyncEnd: common.mustNotCall('asyncEnd'),
error: common.mustNotCall('error'),
});
const result = require('http');
@@ -69,7 +69,7 @@ const testSuccessfulListen = common.mustCall(() => {
const testFailingListen = common.mustCall(() => {
const originalServer = net.createServer(common.mustNotCall());
originalServer.listen(() => {
originalServer.listen(common.mustCall(() => {
const server = net.createServer(common.mustNotCall());
testDiagnosticChannel(
@@ -95,7 +95,7 @@ const testFailingListen = common.mustCall(() => {
server.close();
})
);
});
}));
});
testSuccessfulListen();
@@ -27,10 +27,10 @@ const handlers = {
channel.subscribe(handlers);
channel.traceCallback(function(cb, err) {
channel.traceCallback(common.mustCall(function(cb, err) {
assert.deepStrictEqual(this, thisArg);
setImmediate(cb, err);
}, 0, input, thisArg, common.mustCall((err, res) => {
}), 0, input, thisArg, common.mustCall((err, res) => {
assert.strictEqual(err, expectedError);
assert.strictEqual(res, undefined);
}), expectedError);
@@ -30,10 +30,10 @@ const handlers = {
channel.subscribe(handlers);
channel.traceCallback(function(cb, err, res) {
channel.traceCallback(common.mustCall(function(cb, err, res) {
assert.deepStrictEqual(this, thisArg);
setImmediate(cb, err, res);
}, 0, input, thisArg, common.mustCall((err, res) => {
}), 0, input, thisArg, common.mustCall((err, res) => {
assert.strictEqual(err, null);
assert.deepStrictEqual(res, expectedResult);
}), null, expectedResult);
@@ -27,10 +27,10 @@ const handlers = {
channel.subscribe(handlers);
channel.tracePromise(function(value) {
channel.tracePromise(common.mustCall(function(value) {
assert.deepStrictEqual(this, thisArg);
return Promise.reject(value);
}, input, thisArg, expectedError).then(
}), input, thisArg, expectedError).then(
common.mustNotCall(),
common.mustCall((value) => {
assert.deepStrictEqual(value, expectedError);
@@ -32,7 +32,7 @@ const handlers = {
channel.subscribe(handlers);
// Set no then/catch handler to verify unhandledRejection happens
channel.tracePromise(function(value) {
channel.tracePromise(common.mustCall(function(value) {
assert.deepStrictEqual(this, thisArg);
return Promise.reject(value);
}, input, thisArg, expectedError);
}), input, thisArg, expectedError);
@@ -30,10 +30,10 @@ const handlers = {
channel.subscribe(handlers);
channel.tracePromise(function(value) {
channel.tracePromise(common.mustCall(function(value) {
assert.deepStrictEqual(this, thisArg);
return Promise.resolve(value);
}, input, thisArg, expectedResult).then(
}), input, thisArg, expectedResult).then(
common.mustCall((value) => {
assert.deepStrictEqual(value, expectedResult);
}),
@@ -27,11 +27,11 @@ const handlers = {
channel.subscribe(handlers);
try {
channel.traceSync(function(err) {
channel.traceSync(common.mustCall(function(err) {
assert.deepStrictEqual(this, thisArg);
assert.strictEqual(err, expectedError);
throw err;
}, input, thisArg, expectedError);
}), input, thisArg, expectedError);
throw new Error('It should not reach this error');
} catch (error) {
@@ -29,18 +29,18 @@ const handlers = {
assert.strictEqual(channel.start.hasSubscribers, false);
channel.subscribe(handlers);
assert.strictEqual(channel.start.hasSubscribers, true);
const result1 = channel.traceSync(function(arg1) {
const result1 = channel.traceSync(common.mustCall(function(arg1) {
assert.strictEqual(arg1, arg);
assert.strictEqual(this, thisArg);
return expectedResult;
}, input, thisArg, arg);
}), input, thisArg, arg);
assert.strictEqual(result1, expectedResult);
channel.unsubscribe(handlers);
assert.strictEqual(channel.start.hasSubscribers, false);
const result2 = channel.traceSync(function(arg1) {
const result2 = channel.traceSync(common.mustCall(function(arg1) {
assert.strictEqual(arg1, arg);
assert.strictEqual(this, thisArg);
return expectedResult;
}, input, thisArg, arg);
}), input, thisArg, arg);
assert.strictEqual(result2, expectedResult);
+7 -7
View File
@@ -2,7 +2,7 @@
require('../common');
const { describe, it } = require('node:test');
const { deepStrictEqual, throws } = require('node:assert');
const assert = require('node:assert');
const { diff } = require('util');
@@ -11,7 +11,7 @@ describe('diff', () => {
const actual = {};
const expected = 'foo';
throws(() => diff(actual, expected), {
assert.throws(() => diff(actual, expected), {
message: 'The "actual" argument must be of type string. Received an instance of Object'
});
});
@@ -20,7 +20,7 @@ describe('diff', () => {
const actual = 'foo';
const expected = {};
throws(() => diff(actual, expected), {
assert.throws(() => diff(actual, expected), {
message: 'The "expected" argument must be of type string. Received an instance of Object'
});
});
@@ -30,7 +30,7 @@ describe('diff', () => {
const actual = ['1', { b: 2 }];
const expected = ['1', '2'];
throws(() => diff(actual, expected), {
assert.throws(() => diff(actual, expected), {
message: 'The "actual[1]" argument must be of type string. Received an instance of Object'
});
});
@@ -40,7 +40,7 @@ describe('diff', () => {
const expected = 'foo';
const result = diff(actual, expected);
deepStrictEqual(result, []);
assert.deepStrictEqual(result, []);
});
it('returns the diff for strings', () => {
@@ -48,7 +48,7 @@ describe('diff', () => {
const expected = '12!!5!7!';
const result = diff(actual, expected);
deepStrictEqual(result, [
assert.deepStrictEqual(result, [
[0, '1'],
[0, '2'],
[1, '3'],
@@ -69,7 +69,7 @@ describe('diff', () => {
const expected = ['1', '3', '4'];
const result = diff(actual, expected);
deepStrictEqual(result, [
assert.deepStrictEqual(result, [
[0, '1'],
[1, '2'],
[0, '3'],
+2 -2
View File
@@ -28,12 +28,12 @@ function allowFailed(fn) {
(async () => {
let callsLength = 0;
const checkParameter = (expected) => {
const checkParameter = common.mustCallAtLeast((expected) => {
assert.strictEqual(calls.length, callsLength + 1);
const order = calls[callsLength][4];
assert.strictEqual(order, expected);
callsLength += 1;
};
});
await allowFailed(promisify(dns.lookup)('example.org'));
checkParameter(cares.DNS_ORDER_IPV4_FIRST);
+2 -2
View File
@@ -28,12 +28,12 @@ function allowFailed(fn) {
(async () => {
let callsLength = 0;
const checkParameter = (expected) => {
const checkParameter = common.mustCallAtLeast((expected) => {
assert.strictEqual(calls.length, callsLength + 1);
const order = calls[callsLength][4];
assert.strictEqual(order, expected);
callsLength += 1;
};
});
await allowFailed(promisify(dns.lookup)('example.org'));
checkParameter(cares.DNS_ORDER_IPV6_FIRST);
@@ -28,12 +28,12 @@ function allowFailed(fn) {
(async () => {
let callsLength = 0;
const checkParameter = (expected) => {
const checkParameter = common.mustCallAtLeast((expected) => {
assert.strictEqual(calls.length, callsLength + 1);
const order = calls[callsLength][4];
assert.strictEqual(order, expected);
callsLength += 1;
};
});
await allowFailed(promisify(dns.lookup)('example.org'));
checkParameter(cares.DNS_ORDER_VERBATIM);
+4 -4
View File
@@ -13,21 +13,21 @@ cares.getaddrinfo = (req) => getaddrinfoStub(req);
const dnsPromises = require('dns').promises;
function getaddrinfoNegative() {
return function getaddrinfoNegativeHandler(req) {
return common.mustCall(function getaddrinfoNegativeHandler(req) {
const originalReject = req.reject;
req.resolve = common.mustNotCall();
req.reject = common.mustCall(originalReject);
req.oncomplete(internalBinding('uv').UV_ENOMEM);
};
});
}
function getaddrinfoPositive(addresses) {
return function getaddrinfo_positive(req) {
return common.mustCall(function getaddrinfo_positive(req) {
const originalResolve = req.resolve;
req.reject = common.mustNotCall();
req.resolve = common.mustCall(originalResolve);
req.oncomplete(null, addresses);
};
});
}
async function lookupPositive() {
+2 -2
View File
@@ -42,12 +42,12 @@ assert.throws(() => dns.promises.setDefaultResultOrder(4), {
(async () => {
let callsLength = 0;
const checkParameter = (expected) => {
const checkParameter = common.mustCallAtLeast((expected) => {
assert.strictEqual(calls.length, callsLength + 1);
const order = calls[callsLength][4];
assert.strictEqual(order, expected);
callsLength += 1;
};
});
dns.setDefaultResultOrder('verbatim');
await allowFailed(promisify(dns.lookup)('example.org'));
+4 -5
View File
@@ -374,7 +374,7 @@ assert.throws(() => {
}, err);
}
const portErr = (port) => {
[null, undefined, 65538, 'test', NaN, Infinity, Symbol(), 0n, true, false, '', () => {}, {}].forEach((port) => {
const err = {
code: 'ERR_SOCKET_BAD_PORT',
name: 'RangeError'
@@ -387,8 +387,7 @@ const portErr = (port) => {
assert.throws(() => {
dns.lookupService('0.0.0.0', port, common.mustNotCall());
}, err);
};
[null, undefined, 65538, 'test', NaN, Infinity, Symbol(), 0n, true, false, '', () => {}, {}].forEach(portErr);
});
assert.throws(() => {
dns.lookupService('0.0.0.0', 80, null);
@@ -398,12 +397,12 @@ assert.throws(() => {
});
{
dns.resolveMx('foo.onion', function(err) {
dns.resolveMx('foo.onion', common.mustCall((err) => {
assert.strictEqual(err.code, 'ENOTFOUND');
assert.strictEqual(err.syscall, 'queryMx');
assert.strictEqual(err.hostname, 'foo.onion');
assert.strictEqual(err.message, 'queryMx ENOTFOUND foo.onion');
});
}));
}
{
+26 -26
View File
@@ -11,7 +11,7 @@ const domain = require('domain');
const child_process = require('child_process');
const tests = [
function nextTick() {
common.mustCallAtLeast(function nextTick() {
const d = domain.create();
d.once('error', common.mustCall());
@@ -21,9 +21,9 @@ const tests = [
throw new Error('exceptional!');
});
});
},
}, 0),
function timer() {
common.mustCallAtLeast(function timer() {
const d = domain.create();
d.on('error', common.mustCall());
@@ -33,9 +33,9 @@ const tests = [
throw new Error('exceptional!');
}, 33);
});
},
}, 0),
function immediate() {
common.mustCallAtLeast(function immediate() {
const d = domain.create();
d.on('error', common.mustCall());
@@ -45,9 +45,9 @@ const tests = [
throw new Error('boom!');
});
});
},
}, 0),
function timerPlusNextTick() {
common.mustCallAtLeast(function timerPlusNextTick() {
const d = domain.create();
d.on('error', common.mustCall());
@@ -59,9 +59,9 @@ const tests = [
});
}, 33);
});
},
}, 0),
function firstRun() {
common.mustCallAtLeast(function firstRun() {
const d = domain.create();
d.on('error', common.mustCall());
@@ -69,9 +69,9 @@ const tests = [
d.run(function() {
throw new Error('exceptional!');
});
},
}, 0),
function fsAsync() {
common.mustCallAtLeast(function fsAsync() {
const d = domain.create();
d.on('error', common.mustCall());
@@ -82,9 +82,9 @@ const tests = [
throw new Error('boom!');
});
});
},
}, 0),
function netServer() {
common.mustCallAtLeast(function netServer() {
const net = require('net');
const d = domain.create();
@@ -103,9 +103,9 @@ const tests = [
server.close();
});
});
},
}, 0),
function firstRunOnlyTopLevelErrorHandler() {
common.mustCallAtLeast(function firstRunOnlyTopLevelErrorHandler() {
const d = domain.create();
const d2 = domain.create();
@@ -116,9 +116,9 @@ const tests = [
throw new Error('boom!');
});
});
},
}, 0),
function firstRunNestedWithErrorHandler() {
common.mustCallAtLeast(function firstRunNestedWithErrorHandler() {
const d = domain.create();
const d2 = domain.create();
@@ -129,9 +129,9 @@ const tests = [
throw new Error('boom!');
});
});
},
}, 0),
function timeoutNestedWithErrorHandler() {
common.mustCallAtLeast(function timeoutNestedWithErrorHandler() {
const d = domain.create();
const d2 = domain.create();
@@ -145,9 +145,9 @@ const tests = [
}, 33);
});
});
},
}, 0),
function setImmediateNestedWithErrorHandler() {
common.mustCallAtLeast(function setImmediateNestedWithErrorHandler() {
const d = domain.create();
const d2 = domain.create();
@@ -160,9 +160,9 @@ const tests = [
});
});
});
},
}, 0),
function nextTickNestedWithErrorHandler() {
common.mustCallAtLeast(function nextTickNestedWithErrorHandler() {
const d = domain.create();
const d2 = domain.create();
@@ -175,9 +175,9 @@ const tests = [
});
});
});
},
}, 0),
function fsAsyncNestedWithErrorHandler() {
common.mustCallAtLeast(function fsAsyncNestedWithErrorHandler() {
const d = domain.create();
const d2 = domain.create();
@@ -191,7 +191,7 @@ const tests = [
});
});
});
},
}, 0),
];
if (process.argv[2] === 'child') {
@@ -16,7 +16,7 @@ const isEnumerable = Function.call.bind(Object.prototype.propertyIsEnumerable);
let d = domain.create();
let resourceGCed = false; let domainGCed = false; let
emitterGCed = false;
d.run(() => {
d.run(common.mustCall(() => {
const resource = new async_hooks.AsyncResource('TestResource');
const emitter = new EventEmitter();
@@ -36,7 +36,7 @@ d.run(() => {
onGC(resource, { ongc: common.mustCall(() => { resourceGCed = true; }) });
onGC(d, { ongc: common.mustCall(() => { domainGCed = true; }) });
onGC(emitter, { ongc: common.mustCall(() => { emitterGCed = true; }) });
});
}));
d = null;
@@ -70,7 +70,7 @@ d3.on('error', common.mustCall((err) => {
checkExpectedDomains(err);
}, 1));
d1.run(() => {
d1.run(common.mustCall(() => {
const ee = new EventEmitter();
assert.strictEqual(process.domain, d1);
assert.strictEqual(domain._stack.length, 1);
@@ -82,10 +82,10 @@ d1.run(() => {
assert.strictEqual(process.domain, d1);
assert.strictEqual(domain._stack.length, 1);
});
}));
d1.run(() => {
d1.run(() => {
d1.run(common.mustCall(() => {
d1.run(common.mustCall(() => {
const ee = new EventEmitter();
assert.strictEqual(process.domain, d1);
@@ -98,11 +98,11 @@ d1.run(() => {
assert.strictEqual(process.domain, d1);
assert.strictEqual(domain._stack.length, 2);
});
});
}));
}));
d1.run(() => {
d2.run(() => {
d1.run(common.mustCall(() => {
d2.run(common.mustCall(() => {
const ee = new EventEmitter();
assert.strictEqual(process.domain, d2);
@@ -115,12 +115,12 @@ d1.run(() => {
assert.strictEqual(process.domain, d2);
assert.strictEqual(domain._stack.length, 2);
});
});
}));
}));
d1.run(() => {
d2.run(() => {
d2.run(() => {
d1.run(common.mustCall(() => {
d2.run(common.mustCall(() => {
d2.run(common.mustCall(() => {
const ee = new EventEmitter();
assert.strictEqual(process.domain, d2);
@@ -133,14 +133,14 @@ d1.run(() => {
assert.strictEqual(process.domain, d2);
assert.strictEqual(domain._stack.length, 3);
});
});
});
}));
}));
}));
d3.run(() => {
d1.run(() => {
d3.run(() => {
d3.run(() => {
d3.run(common.mustCall(() => {
d1.run(common.mustCall(() => {
d3.run(common.mustCall(() => {
d3.run(common.mustCall(() => {
const ee = new EventEmitter();
assert.strictEqual(process.domain, d3);
@@ -153,7 +153,7 @@ d3.run(() => {
assert.strictEqual(process.domain, d3);
assert.strictEqual(domain._stack.length, 4);
});
});
});
});
}));
}));
}));
}));
+4 -4
View File
@@ -34,7 +34,7 @@ objects.baz.asdf = objects;
let serverCaught = 0;
let clientCaught = 0;
const server = http.createServer(function(req, res) {
const server = http.createServer(common.mustCallAtLeast(function(req, res) {
const dom = domain.create();
req.resume();
dom.add(req);
@@ -48,7 +48,7 @@ const server = http.createServer(function(req, res) {
res.end(er.stack || er.message || 'Unknown error');
});
dom.run(function() {
dom.run(common.mustCall(() => {
// Now, an action that has the potential to fail!
// if you request 'baz', then it'll throw a JSON circular ref error.
const data = JSON.stringify(objects[req.url.replace(/[^a-z]/g, '')]);
@@ -58,8 +58,8 @@ const server = http.createServer(function(req, res) {
res.writeHead(200);
res.end(data);
});
});
}));
}));
server.listen(0, next);
+9 -8
View File
@@ -49,14 +49,15 @@ d.on('error', common.mustCall(function(er) {
// Everything that happens between the domain.enter() and domain.exit()
// calls will be bound to the domain, even if multiple levels of
// handles are created.
d.run(function() {
setTimeout(function() {
d.run(common.mustCall(() => {
setTimeout(common.mustCall(() => {
const fs = require('fs');
fs.readdir(__dirname, function() {
fs.open('this file does not exist', 'r', function(er) {
fs.readdir(__dirname, common.mustCall(() => {
// eslint-disable-next-line node-core/prefer-common-mustsucceed
fs.open('this file does not exist', 'r', common.mustCall((er) => {
assert.ifError(er);
throw new Error('should not get here!');
});
});
}, 100);
});
}));
}));
}), 100);
}));
+3 -3
View File
@@ -33,7 +33,7 @@ a.enter(); // This will be our "root" domain
a.on('error', common.mustNotCall());
const server = http.createServer((req, res) => {
const server = http.createServer(common.mustCallAtLeast((req, res) => {
// child domain of a.
const b = domain.create();
a.add(b);
@@ -61,7 +61,7 @@ const server = http.createServer((req, res) => {
throw new Error('this kills domain B, not A');
}));
}).listen(0, () => {
})).listen(0, common.mustCall(() => {
const c = domain.create();
const req = http.get({ host: 'localhost', port: server.address().port });
@@ -75,4 +75,4 @@ const server = http.createServer((req, res) => {
});
c.on('error', common.mustCall());
});
}));
+3 -4
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 domain = require('domain');
@@ -35,10 +35,9 @@ function parent() {
const spawn = require('child_process').spawn;
const opt = { stdio: 'inherit' };
const child = spawn(node, [__filename, 'child'], opt);
child.on('exit', function(c) {
child.on('exit', common.mustCall((c) => {
assert(!c);
console.log('ok');
});
}));
}
let gotDomain1Error = false;
@@ -51,7 +51,7 @@ if (process.argv[2] === 'child') {
function runTestWithoutAbortOnUncaughtException() {
child_process.exec(
...createTestCmdLine(),
function onTestDone(err, stdout, stderr) {
common.mustCall(function onTestDone(err, stdout, stderr) {
// When _not_ passing --abort-on-uncaught-exception, the process'
// uncaughtException handler _must_ be called, and thus the error
// message must include only the message of the error thrown from the
@@ -65,20 +65,20 @@ function runTestWithoutAbortOnUncaughtException() {
assert.notStrictEqual(err.code, 0,
'child process should have exited with a ' +
'non-zero exit code, but did not');
}
}),
);
}
function runTestWithAbortOnUncaughtException() {
child_process.exec(...createTestCmdLine({
withAbortOnUncaughtException: true
}), function onTestDone(err, stdout, stderr) {
}), common.mustCall(function onTestDone(err, stdout, stderr) {
assert.notStrictEqual(err.code, RAN_UNCAUGHT_EXCEPTION_HANDLER_EXIT_CODE,
'child process should not have run its ' +
'uncaughtException event handler');
assert(common.nodeProcessAborted(err.code, err.signal),
'process should have aborted, but did not');
});
}));
}
function createTestCmdLine(options) {
@@ -9,15 +9,15 @@ const assert = require('assert');
let first = false;
domain.run(function() {
domain.run(common.mustCall(() => {
setTimeout(() => { throw new Error('FAIL'); }, 1);
setTimeout(() => { first = true; }, 1);
setTimeout(() => { assert.strictEqual(first, true); }, 2);
setTimeout(common.mustCall(() => { assert.strictEqual(first, true); }), 2);
// Ensure that 2 ms have really passed
let i = 1e6;
while (i--);
});
}));
domain.once('error', common.mustCall((err) => {
assert(err);
@@ -5,7 +5,7 @@
// the process reports the error message from the error thrown in the
// top-level error handler, not the one from the previous error.
require('../common');
const common = require('../common');
const domainErrHandlerExMessage = 'exception from domain error handler';
const internalExMessage = 'You should NOT see me';
@@ -34,17 +34,17 @@ if (process.argv[2] === 'child') {
stderrOutput += data.toString();
});
child.on('close', function onChildClosed() {
child.on('close', common.mustCall(function onChildClosed() {
assert(stderrOutput.includes(domainErrHandlerExMessage));
assert.strictEqual(stderrOutput.includes(internalExMessage), false);
});
}));
child.on('exit', function onChildExited(exitCode, signal) {
child.on('exit', common.mustCall(function onChildExited(exitCode, signal) {
const expectedExitCode = 7;
const expectedSignal = null;
assert.strictEqual(exitCode, expectedExitCode);
assert.strictEqual(signal, expectedSignal);
});
}));
}
}
@@ -104,7 +104,7 @@ if (process.argv[2] === 'child') {
const child = exec(...escapedArgs);
if (child) {
child.on('exit', function onChildExited(exitCode, signal) {
child.on('exit', common.mustCall(function onChildExited(exitCode, signal) {
// When throwing errors from the top-level domain error handler
// outside of a try/catch block, the process should not exit gracefully
if (!options.useTryCatch && options.throwInDomainErrHandler) {
@@ -124,7 +124,7 @@ if (process.argv[2] === 'child') {
assert.strictEqual(exitCode, 0);
assert.strictEqual(signal, null);
}
});
}));
}
}
+13 -13
View File
@@ -1,33 +1,33 @@
'use strict';
require('../common');
const { strictEqual, deepStrictEqual } = require('assert');
const assert = require('assert');
{
const domException = new DOMException('no cause', 'abc');
strictEqual(domException.name, 'abc');
strictEqual('cause' in domException, false);
strictEqual(domException.cause, undefined);
assert.strictEqual(domException.name, 'abc');
assert.strictEqual('cause' in domException, false);
assert.strictEqual(domException.cause, undefined);
}
{
const domException = new DOMException('with undefined cause', { name: 'abc', cause: undefined });
strictEqual(domException.name, 'abc');
strictEqual('cause' in domException, true);
strictEqual(domException.cause, undefined);
assert.strictEqual(domException.name, 'abc');
assert.strictEqual('cause' in domException, true);
assert.strictEqual(domException.cause, undefined);
}
{
const domException = new DOMException('with string cause', { name: 'abc', cause: 'foo' });
strictEqual(domException.name, 'abc');
strictEqual('cause' in domException, true);
strictEqual(domException.cause, 'foo');
assert.strictEqual(domException.name, 'abc');
assert.strictEqual('cause' in domException, true);
assert.strictEqual(domException.cause, 'foo');
}
{
const object = { reason: 'foo' };
const domException = new DOMException('with object cause', { name: 'abc', cause: object });
strictEqual(domException.name, 'abc');
strictEqual('cause' in domException, true);
deepStrictEqual(domException.cause, object);
assert.strictEqual(domException.name, 'abc');
assert.strictEqual('cause' in domException, true);
assert.deepStrictEqual(domException.cause, object);
}
+4 -4
View File
@@ -22,12 +22,12 @@ const server = tls.createServer({
cert: fixtures.readKey('agent1-cert.pem'),
})
.listen(client)
.on('secureConnection', (serverTlsSock) => {
serverTlsSock.on('data', (chunk) => {
.on('secureConnection', common.mustCall((serverTlsSock) => {
serverTlsSock.on('data', common.mustCallAtLeast((chunk) => {
assert.strictEqual(chunk.toString(), HEAD);
subserver.emit('connection', serverTlsSock);
});
});
}));
}));
function client() {
const down = tls.connect({
+2 -2
View File
@@ -67,7 +67,7 @@ const serverReplaySize = 2 * 1024 * 1024;
const recv = [];
let revcLen = 0;
clientTlsSock.on('data', (chunk) => {
clientTlsSock.on('data', common.mustCallAtLeast((chunk) => {
revcLen += chunk.length;
recv.push(chunk);
if (revcLen > serverReplaySize) {
@@ -76,7 +76,7 @@ const serverReplaySize = 2 * 1024 * 1024;
assert.strictEqual(serverHelloFstByte.toString('hex'), '16');
process.exit(0);
}
});
}));
// In reality, one may want to send a HTTP CONNECT before starting this double TLS
clientTlsSock.write(tlsClientHello);
@@ -84,6 +84,10 @@ tester.run('must-call-assert', rule, {
val = await asyncTask(val);
assert.strictEqual(val, 3);
})).then(common.mustCall());
Promise.all(Object.keys(keys).map(async (val) => {
val = await asyncTask(val);
assert.strictEqual(val, 3);
})).then(common.mustCall());
}));
`,
`
@@ -106,6 +110,9 @@ tester.run('must-call-assert', rule, {
},
);
`,
'eval("(" + function() {} + ")()")',
// eslint-disable-next-line no-template-curly-in-string
'eval(`(${function() {}})()`)',
],
invalid: [
{
@@ -130,6 +137,14 @@ tester.run('must-call-assert', rule, {
code: 'process.once("message", (code) => {if(2+2 === 5) { assert.strictEqual(code, 0)} });',
errors: [{ message }],
},
{
code: 'process.once("message", (code) => { assert(code) });',
errors: [{ message }],
},
{
code: 'process.once("message", (code) => { setTimeout(mustCall()); });',
errors: [{ message }],
},
{
code: 'process.once("message", (code) => { (() => { assert.strictEqual(code, 0)})(); });',
errors: [{ message }],
@@ -1,5 +1,5 @@
'use strict';
require('../common');
const common = require('../common');
const Countdown = require('../common/countdown');
const assert = require('assert');
const { Worker } = require('worker_threads');
@@ -30,10 +30,10 @@ describe('Allocating uninitialized ArrayBuffers ...', () => {
w.on('online', fn);
const countdown = new Countdown(100, () => {
const countdown = new Countdown(100, common.mustCallAtLeast(() => {
w.terminate();
assert(fn.mock.calls.length > 0);
});
}));
w.on('message', (sum) => {
assert.strictEqual(sum, 0);
@@ -34,11 +34,11 @@ port2.onmessage = common.mustCall((message) => {
port1.close();
tick(10, () => {
tick(10, common.mustCall(() => {
const inspectedPort1 = util.inspect(port1);
const inspectedPort2 = util.inspect(port2);
assert(inspectedPort1.includes('active: false'), inspectedPort1);
assert(inspectedPort2.includes('active: false'), inspectedPort2);
});
}, 1));
});
port1.postMessage(2);
+6 -6
View File
@@ -43,20 +43,20 @@ const server = https.createServer(options, function(req, res) {
res.end();
});
server.listen(0, function() {
server.listen(0, common.mustCall(() => {
const req = https.request({
method: 'POST',
port: server.address().port,
rejectUnauthorized: false,
}, function(res) {
}, common.mustCall((res) => {
res.read(0);
setTimeout(function() {
setTimeout(common.mustCall(() => {
// Read buffer should be somewhere near high watermark
// (i.e. should not leak)
assert(res.readableLength < 100 * 1024);
process.exit(0);
}, 2000);
});
}), 2000);
}));
req.end();
});
}));
+2 -2
View File
@@ -135,10 +135,10 @@ function assertDirents(dirents) {
assert.strictEqual(dirents.length, expected.length);
dirents.sort((a, b) => (getDirentPath(a) < getDirentPath(b) ? -1 : 1));
assert.deepStrictEqual(
dirents.map((dirent) => {
dirents.map(common.mustCallAtLeast((dirent) => {
assert(dirent instanceof fs.Dirent);
return getDirentPath(dirent);
}),
})),
expected
);
}
@@ -26,12 +26,12 @@ const server = http.createServer(common.mustCall((req, res) => {
res.write(content);
res.end();
}));
server.on('timeout', () => {
server.on('timeout', common.mustCallAtLeast(() => {
// TODO(apapirovski): This test is faulty on certain Windows systems
// as no queue is ever created
assert(!socket._handle || socket._handle.writeQueueSize === 0,
'Should not timeout');
});
}, 0));
server.listen(0, common.mustCall(() => {
http.get({
@@ -102,7 +102,7 @@ server.listen(0, common.mustCall(() => {
request5.client.write(requestBodyPart2);
}, headersTimeout * 0.8);
setTimeout(() => {
setTimeout(common.mustCall(() => {
// After the first timeout, the first request should have been completed and second timedout
assert(request1.completed);
assert(request2.completed);
@@ -112,14 +112,14 @@ server.listen(0, common.mustCall(() => {
assert(request1.response.startsWith(responseOk));
assert(request2.response.startsWith(responseTimeout)); // It is expired due to headersTimeout
}, headersTimeout * 1.4);
}), headersTimeout * 1.4);
setTimeout(() => {
// Complete the body for the fourth request
request4.client.write(requestBodyPart3);
}, headersTimeout * 1.5);
setTimeout(() => {
setTimeout(common.mustCall(() => {
// All request should be completed now, either with 200 or 408
assert(request3.completed);
assert(request4.completed);
@@ -129,5 +129,5 @@ server.listen(0, common.mustCall(() => {
assert(request4.response.startsWith(responseOk));
assert(request5.response.startsWith(responseTimeout)); // It is expired due to requestTimeout
server.close();
}, headersTimeout * 3 + connectionsCheckingInterval);
}), headersTimeout * 3 + connectionsCheckingInterval);
}));
@@ -22,7 +22,7 @@ const handleRequest = (req, res) => {
res.end('hello world\n');
break;
default:
assert(false, `Unexpected path: ${path}`);
assert.fail(`Unexpected path: ${path}`);
}
};
@@ -23,7 +23,7 @@ const handleRequest = (req, res) => {
res.end('hello world\n');
break;
default:
assert(false, `Unexpected path: ${path}`);
assert.fail(`Unexpected path: ${path}`);
}
};
+1 -1
View File
@@ -22,7 +22,7 @@ const handleRequest = (req, res) => {
res.end('hello world\n');
break;
default:
assert(false, `Unexpected path: ${path}`);
assert.fail(`Unexpected path: ${path}`);
}
};
+19 -2
View File
@@ -7,6 +7,14 @@ const message =
const requireCall = 'CallExpression[callee.name="require"]';
const assertModuleSpecifier = '/^(node:)?assert(.strict)?$/';
const isObjectKeysOrEntries = (node) =>
node.type === 'CallExpression' &&
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'Identifier' &&
node.callee.object.name === 'Object' &&
node.callee.property.type === 'Identifier' &&
['keys', 'entries'].includes(node.callee.property.name);
const isPromiseAllCallArg = (node) =>
node.parent?.type === 'CallExpression' &&
node.parent.callee.type === 'MemberExpression' &&
@@ -26,7 +34,11 @@ function findEnclosingFunction(node) {
if (
node.parent.callee.type === 'MemberExpression' &&
(node.parent.callee.object.type === 'ArrayExpression' || node.parent.callee.object.type === 'Identifier') &&
(
node.parent.callee.object.type === 'ArrayExpression' ||
node.parent.callee.object.type === 'Identifier' ||
isObjectKeysOrEntries(node.parent.callee.object)
) &&
(
node.parent.callee.property.name === 'forEach' ||
(node.parent.callee.property.name === 'map' && isPromiseAllCallArg(node.parent))
@@ -62,13 +74,18 @@ module.exports = {
create: function(context) {
return {
[`:function CallExpression:matches(${[
'[callee.type="Identifier"][callee.value=/^mustCall(AtLeast)?$/]',
'[callee.type="Identifier"][callee.name=/^mustCall(AtLeast)?$/]',
'[callee.type="Identifier"][callee.name="assert"]',
'[callee.object.name="assert"][callee.property.name!="fail"]',
'[callee.object.name="common"][callee.property.name=/^mustCall(AtLeast)?$/]',
].join(',')})`]: (node) => {
const enclosingFn = findEnclosingFunction(node);
const parent = enclosingFn?.parent;
if (!parent) return; // Top-level
if (parent.type === 'BinaryExpression' && parent.operator === '+') {
// Function is stringified, e.g. to be passed to a child process or a worker.
return;
}
if (parent.type === 'CallExpression') {
switch (parent.callee.type) {
case 'MemberExpression':