diff --git a/test/js/node/test/parallel/test-als-defaultvalue.js b/test/js/node/test/parallel/test-als-defaultvalue.js index 2565983ed6b0..5b5b43b57a72 100644 --- a/test/js/node/test/parallel/test-als-defaultvalue.js +++ b/test/js/node/test/parallel/test-als-defaultvalue.js @@ -1,18 +1,21 @@ -"use strict"; +// Flags: --async-context-frame +'use strict'; -require("../common"); +require('../common'); -const { AsyncLocalStorage } = require("async_hooks"); +const { + AsyncLocalStorage, +} = require('async_hooks'); -const assert = require("assert"); +const assert = require('assert'); // ============================================================================ // The defaultValue option const als1 = new AsyncLocalStorage(); assert.strictEqual(als1.getStore(), undefined); -const als2 = new AsyncLocalStorage({ defaultValue: "default" }); -assert.strictEqual(als2.getStore(), "default"); +const als2 = new AsyncLocalStorage({ defaultValue: 'default' }); +assert.strictEqual(als2.getStore(), 'default'); const als3 = new AsyncLocalStorage({ defaultValue: 42 }); assert.strictEqual(als3.getStore(), 42); @@ -21,14 +24,14 @@ const als4 = new AsyncLocalStorage({ defaultValue: null }); assert.strictEqual(als4.getStore(), null); assert.throws(() => new AsyncLocalStorage(null), { - code: "ERR_INVALID_ARG_TYPE", + code: 'ERR_INVALID_ARG_TYPE', }); // ============================================================================ // The name option -const als5 = new AsyncLocalStorage({ name: "test" }); -assert.strictEqual(als5.name, "test"); +const als5 = new AsyncLocalStorage({ name: 'test' }); +assert.strictEqual(als5.name, 'test'); const als6 = new AsyncLocalStorage(); -assert.strictEqual(als6.name, ""); +assert.strictEqual(als6.name, ''); diff --git a/test/js/node/test/parallel/test-assert-async.js b/test/js/node/test/parallel/test-assert-async.js index bcf3d55622b8..3fc7e3c0a0ea 100644 --- a/test/js/node/test/parallel/test-assert-async.js +++ b/test/js/node/test/parallel/test-assert-async.js @@ -85,7 +85,7 @@ const invalidThenableFunc = () => { } { - const handler = (err) => { + const handler = common.mustCallAtLeast((err) => { assert(err instanceof assert.AssertionError, `${err.name} is not instance of AssertionError`); assert.strictEqual(err.code, 'ERR_ASSERTION'); @@ -94,7 +94,7 @@ const invalidThenableFunc = () => { assert.strictEqual(err.operator, 'rejects'); assert.ok(!err.stack.includes('at Function.rejects')); return true; - }; + }); let promise = assert.rejects(async () => {}, common.mustNotCall()); promises.push(assert.rejects(promise, common.mustCall(handler))); @@ -132,14 +132,14 @@ promises.push(assert.rejects( )); { - const handler = (generated, actual, err) => { + const handler = common.mustCallAtLeast((generated, actual, err) => { assert.strictEqual(err.generatedMessage, generated); assert.strictEqual(err.code, 'ERR_ASSERTION'); assert.strictEqual(err.actual, actual); assert.strictEqual(err.operator, 'rejects'); assert.match(err.stack, /rejects/); return true; - }; + }); const err = new Error(); promises.push(assert.rejects( assert.rejects(Promise.reject(null), { code: 'FOO' }), @@ -192,14 +192,14 @@ promises.push(assert.rejects( }) ); - const handler1 = (err) => { + const handler1 = common.mustCallAtLeast((err) => { assert(err instanceof assert.AssertionError, `${err.name} is not instance of AssertionError`); assert.strictEqual(err.code, 'ERR_ASSERTION'); assert.strictEqual(err.message, 'Failed'); return true; - }; - const handler2 = (err) => { + }); + const handler2 = common.mustCallAtLeast((err) => { assert(err instanceof assert.AssertionError, `${err.name} is not instance of AssertionError`); assert.strictEqual(err.code, 'ERR_ASSERTION'); @@ -209,7 +209,7 @@ promises.push(assert.rejects( assert.ok(err.stack); assert.ok(!err.stack.includes('at Function.doesNotReject')); return true; - }; + }); const rejectingFn = async () => assert.fail(); diff --git a/test/js/node/test/parallel/test-assert-checktag.js b/test/js/node/test/parallel/test-assert-checktag.js index b86a1bde7f09..b1c3660ab4a6 100644 --- a/test/js/node/test/parallel/test-assert-checktag.js +++ b/test/js/node/test/parallel/test-assert-checktag.js @@ -1,5 +1,5 @@ 'use strict'; -const { hasCrypto } = require('../common'); +const { hasCrypto, hasLocalStorage } = require('../common'); const { test } = require('node:test'); const assert = require('assert'); @@ -12,7 +12,7 @@ const assert = require('assert'); if (process.stdout.isTTY) process.env.NODE_DISABLE_COLORS = '1'; -test('', { skip: !hasCrypto }, () => { +test({ skip: !hasCrypto || !hasLocalStorage }, () => { // See https://github.com/nodejs/node/issues/10258 { const date = new Date('2016'); diff --git a/test/js/node/test/parallel/test-assert-deep-with-error.js b/test/js/node/test/parallel/test-assert-deep-with-error.js index f6bc5c6359cf..8cfb9ce1bf90 100644 --- a/test/js/node/test/parallel/test-assert-deep-with-error.js +++ b/test/js/node/test/parallel/test-assert-deep-with-error.js @@ -3,6 +3,13 @@ require('../common'); const assert = require('assert'); const { test } = require('node:test'); +// Disable colored output to prevent color codes from breaking assertion +// message comparisons. This should only be an issue when process.stdout +// is a TTY. +if (process.stdout.isTTY) { + process.env.NODE_DISABLE_COLORS = '1'; +} + const defaultStartMessage = 'Expected values to be strictly deep-equal:\n' + '+ actual - expected\n' + '\n'; diff --git a/test/js/node/test/parallel/test-assert-typedarray-deepequal.js b/test/js/node/test/parallel/test-assert-typedarray-deepequal.js index 7fb18c1886ba..0ca174ea96c3 100644 --- a/test/js/node/test/parallel/test-assert-typedarray-deepequal.js +++ b/test/js/node/test/parallel/test-assert-typedarray-deepequal.js @@ -20,6 +20,7 @@ suite('equalArrayPairs', () => { [new Int8Array(1e5), new Int8Array(1e5)], [new Int16Array(1e5), new Int16Array(1e5)], [new Int32Array(1e5), new Int32Array(1e5)], + [new Float16Array(1e5), new Float16Array(1e5)], [new Float32Array(1e5), new Float32Array(1e5)], [new Float64Array(1e5), new Float64Array(1e5)], [new Float32Array([+0.0]), new Float32Array([+0.0])], @@ -34,13 +35,19 @@ suite('equalArrayPairs', () => { test('', () => { // eslint-disable-next-line no-restricted-properties assert.deepEqual(arrayPair[0], arrayPair[1]); + // eslint-disable-next-line no-restricted-properties + assert.deepEqual(arrayPair[1], arrayPair[0]); assert.deepStrictEqual(arrayPair[0], arrayPair[1]); + assert.deepStrictEqual(arrayPair[1], arrayPair[0]); + assert.partialDeepStrictEqual(arrayPair[0], arrayPair[1]); + assert.partialDeepStrictEqual(arrayPair[1], arrayPair[0]); }); } }); suite('looseEqualArrayPairs', () => { const looseEqualArrayPairs = [ + [new Float16Array([+0.0]), new Float16Array([-0.0])], [new Float32Array([+0.0]), new Float32Array([-0.0])], [new Float64Array([+0.0]), new Float64Array([-0.0])], ]; @@ -49,10 +56,24 @@ suite('looseEqualArrayPairs', () => { test('', () => { // eslint-disable-next-line no-restricted-properties assert.deepEqual(arrayPair[0], arrayPair[1]); + // eslint-disable-next-line no-restricted-properties + assert.deepEqual(arrayPair[1], arrayPair[0]); assert.throws( makeBlock(assert.deepStrictEqual, arrayPair[0], arrayPair[1]), assert.AssertionError ); + assert.throws( + makeBlock(assert.deepStrictEqual, arrayPair[1], arrayPair[0]), + assert.AssertionError + ); + assert.throws( + makeBlock(assert.partialDeepStrictEqual, arrayPair[0], arrayPair[1]), + assert.AssertionError + ); + assert.throws( + makeBlock(assert.partialDeepStrictEqual, arrayPair[1], arrayPair[0]), + assert.AssertionError + ); }); } }); @@ -63,7 +84,7 @@ suite('notEqualArrayPairs', () => { [new Int16Array(256), new Uint16Array(256)], [new Int16Array([256]), new Uint16Array([256])], [new Float64Array([+0.0]), new Float32Array([-0.0])], - [new Uint8Array(2), new Uint8Array(3)], + [new Uint8Array(2), new Uint8Array(3), 'unequal length'], [new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])], [new Uint8ClampedArray([300, 2, 3]), new Uint8Array([300, 2, 3])], [new Uint16Array([2]), new Uint16Array([3])], @@ -71,16 +92,18 @@ suite('notEqualArrayPairs', () => { [new Int16Array([0]), new Uint16Array([256])], [new Int16Array([-256]), new Uint16Array([0xff00])], // same bits [new Int32Array([-256]), new Uint32Array([0xffffff00])], // ditto + [new Float16Array([0.1]), new Float16Array([0.0])], + [new Float16Array([0.1]), new Float16Array([0.1, 0.2]), 'unequal length'], [new Float32Array([0.1]), new Float32Array([0.0])], - [new Float32Array([0.1]), new Float32Array([0.1, 0.2])], + [new Float32Array([0.1]), new Float32Array([0.1, 0.2]), 'unequal length'], [new Float64Array([0.1]), new Float64Array([0.0])], [new Uint8Array([1, 2, 3]).buffer, new Uint8Array([4, 5, 6]).buffer], [ new Uint8Array(new SharedArrayBuffer(3)).fill(1).buffer, new Uint8Array(new SharedArrayBuffer(3)).fill(2).buffer, ], - [new ArrayBuffer(2), new ArrayBuffer(3)], - [new SharedArrayBuffer(2), new SharedArrayBuffer(3)], + [new ArrayBuffer(2), new ArrayBuffer(3), 'unequal length'], + [new SharedArrayBuffer(2), new SharedArrayBuffer(3), 'unequal length'], [new ArrayBuffer(2), new SharedArrayBuffer(3)], [ new Uint8Array(new ArrayBuffer(3)).fill(1).buffer, @@ -97,14 +120,31 @@ suite('notEqualArrayPairs', () => { makeBlock(assert.deepEqual, arrayPair[0], arrayPair[1]), assert.AssertionError ); + assert.throws( + // eslint-disable-next-line no-restricted-properties + makeBlock(assert.deepEqual, arrayPair[1], arrayPair[0]), + assert.AssertionError + ); assert.throws( makeBlock(assert.deepStrictEqual, arrayPair[0], arrayPair[1]), assert.AssertionError ); + assert.throws( + makeBlock(assert.deepStrictEqual, arrayPair[1], arrayPair[0]), + assert.AssertionError + ); assert.throws( makeBlock(assert.partialDeepStrictEqual, arrayPair[0], arrayPair[1]), assert.AssertionError ); + if (arrayPair[2]) { + assert.partialDeepStrictEqual(arrayPair[1], arrayPair[0]); + } else { + assert.throws( + makeBlock(assert.partialDeepStrictEqual, arrayPair[1], arrayPair[0]), + assert.AssertionError + ); + } }); } }); diff --git a/test/js/node/test/parallel/test-async-hooks-recursive-stack-runInAsyncScope.js b/test/js/node/test/parallel/test-async-hooks-recursive-stack-runInAsyncScope.js index bc4ac86e7f1c..d0d5ee76e9d1 100644 --- a/test/js/node/test/parallel/test-async-hooks-recursive-stack-runInAsyncScope.js +++ b/test/js/node/test/parallel/test-async-hooks-recursive-stack-runInAsyncScope.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const async_hooks = require('async_hooks'); @@ -7,14 +7,14 @@ const async_hooks = require('async_hooks'); function recurse(n) { const a = new async_hooks.AsyncResource('foobar'); - a.runInAsyncScope(() => { + a.runInAsyncScope(common.mustCall(() => { assert.strictEqual(a.asyncId(), async_hooks.executionAsyncId()); assert.strictEqual(a.triggerAsyncId(), async_hooks.triggerAsyncId()); if (n >= 0) recurse(n - 1); assert.strictEqual(a.asyncId(), async_hooks.executionAsyncId()); assert.strictEqual(a.triggerAsyncId(), async_hooks.triggerAsyncId()); - }); + })); } recurse(1000); diff --git a/test/js/node/test/parallel/test-async-local-storage-contexts.js b/test/js/node/test/parallel/test-async-local-storage-contexts.js index 9a6327133794..b63d383fecc4 100644 --- a/test/js/node/test/parallel/test-async-local-storage-contexts.js +++ b/test/js/node/test/parallel/test-async-local-storage-contexts.js @@ -1,6 +1,6 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const vm = require('vm'); const { AsyncLocalStorage } = require('async_hooks'); @@ -26,10 +26,10 @@ vm.runInContext(` const storage = new AsyncLocalStorage(); async function test() { - return storage.run({ test: 'main context' }, async () => { + return storage.run({ test: 'main context' }, common.mustCall(async () => { assert.strictEqual(storage.getStore().test, 'main context'); await 42; assert.strictEqual(storage.getStore().test, 'main context'); - }); + })); } test(); diff --git a/test/js/node/test/parallel/test-async-local-storage-snapshot.js b/test/js/node/test/parallel/test-async-local-storage-snapshot.js index 63e47ba3ce0a..169da60c3a32 100644 --- a/test/js/node/test/parallel/test-async-local-storage-snapshot.js +++ b/test/js/node/test/parallel/test-async-local-storage-snapshot.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -const { strictEqual } = require('assert'); +const assert = require('assert'); const { AsyncLocalStorage } = require('async_hooks'); const asyncLocalStorage = new AsyncLocalStorage(); @@ -13,4 +13,4 @@ const result = return asyncLocalStorage.getStore(); }); })); -strictEqual(result, 123); +assert.strictEqual(result, 123); diff --git a/test/js/node/test/parallel/test-blocklist-clone.js b/test/js/node/test/parallel/test-blocklist-clone.js index 4264b36f54ca..ea6471c7df87 100644 --- a/test/js/node/test/parallel/test-blocklist-clone.js +++ b/test/js/node/test/parallel/test-blocklist-clone.js @@ -6,10 +6,7 @@ const { BlockList, } = require('net'); -const { - ok, - notStrictEqual, -} = require('assert'); +const assert = require('assert'); const blocklist = new BlockList(); blocklist.addAddress('123.123.123.123'); @@ -17,13 +14,13 @@ blocklist.addAddress('123.123.123.123'); const mc = new MessageChannel(); mc.port1.onmessage = common.mustCall(({ data }) => { - notStrictEqual(data, blocklist); - ok(data.check('123.123.123.123')); - ok(!data.check('123.123.123.124')); + assert.notStrictEqual(data, blocklist); + assert.ok(data.check('123.123.123.123')); + assert.ok(!data.check('123.123.123.124')); data.addAddress('123.123.123.124'); - ok(blocklist.check('123.123.123.124')); - ok(data.check('123.123.123.124')); + assert.ok(blocklist.check('123.123.123.124')); + assert.ok(data.check('123.123.123.124')); mc.port1.close(); }); diff --git a/test/js/node/test/parallel/test-btoa-atob.js b/test/js/node/test/parallel/test-btoa-atob.js index abf05adeef10..a2c8d9e3134c 100644 --- a/test/js/node/test/parallel/test-btoa-atob.js +++ b/test/js/node/test/parallel/test-btoa-atob.js @@ -2,37 +2,37 @@ require('../common'); -const { strictEqual, throws } = require('assert'); +const assert = require('assert'); const buffer = require('buffer'); // Exported on the global object -strictEqual(globalThis.atob, buffer.atob); -strictEqual(globalThis.btoa, buffer.btoa); +assert.strictEqual(globalThis.atob, buffer.atob); +assert.strictEqual(globalThis.btoa, buffer.btoa); // Throws type error on no argument passed -throws(() => buffer.atob(), /TypeError/); -throws(() => buffer.btoa(), /TypeError/); +assert.throws(() => buffer.atob(), /TypeError/); +assert.throws(() => buffer.btoa(), /TypeError/); -strictEqual(atob(' '), ''); -strictEqual(atob(' Y\fW\tJ\njZ A=\r= '), 'abcd'); +assert.strictEqual(atob(' '), ''); +assert.strictEqual(atob(' Y\fW\tJ\njZ A=\r= '), 'abcd'); -strictEqual(atob(null), '\x9Eée'); -strictEqual(atob(NaN), '5£'); -strictEqual(atob(Infinity), '"wâ\x9E+r'); -strictEqual(atob(true), '¶»\x9E'); -strictEqual(atob(1234), '×mø'); -strictEqual(atob([]), ''); -strictEqual(atob({ toString: () => '' }), ''); -strictEqual(atob({ [Symbol.toPrimitive]: () => '' }), ''); +assert.strictEqual(atob(null), '\x9Eée'); +assert.strictEqual(atob(NaN), '5£'); +assert.strictEqual(atob(Infinity), '"wâ\x9E+r'); +assert.strictEqual(atob(true), '¶»\x9E'); +assert.strictEqual(atob(1234), '×mø'); +assert.strictEqual(atob([]), ''); +assert.strictEqual(atob({ toString: () => '' }), ''); +assert.strictEqual(atob({ [Symbol.toPrimitive]: () => '' }), ''); -throws(() => atob(Symbol()), /TypeError/); +assert.throws(() => atob(Symbol()), /TypeError/); [ undefined, false, () => {}, {}, [1], 0, 1, 0n, 1n, -Infinity, 'a', 'a\n\n\n', '\ra\r\r', ' a ', '\t\t\ta', 'a\f\f\f', '\ta\r \n\f', ].forEach((value) => // See #2 - https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob - throws(() => atob(value), { + assert.throws(() => atob(value), { constructor: DOMException, name: 'InvalidCharacterError', code: 5, diff --git a/test/js/node/test/parallel/test-child-process-can-write-to-stdout.js b/test/js/node/test/parallel/test-child-process-can-write-to-stdout.js index 069e07fb1602..68e1bff877ff 100644 --- a/test/js/node/test/parallel/test-child-process-can-write-to-stdout.js +++ b/test/js/node/test/parallel/test-child-process-can-write-to-stdout.js @@ -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'); -}); +})); diff --git a/test/js/node/test/parallel/test-child-process-cwd.js b/test/js/node/test/parallel/test-child-process-cwd.js index e876361b167f..847c666a9077 100644 --- a/test/js/node/test/parallel/test-child-process-cwd.js +++ b/test/js/node/test/parallel/test-child-process-cwd.js @@ -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'); })); diff --git a/test/js/node/test/parallel/test-child-process-disconnect.js b/test/js/node/test/parallel/test-child-process-disconnect.js index fb8a2dd0ea22..0e4f37ae61d5 100644 --- a/test/js/node/test/parallel/test-child-process-disconnect.js +++ b/test/js/node/test/parallel/test-child-process-disconnect.js @@ -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); diff --git a/test/js/node/test/parallel/test-child-process-exec-encoding.js b/test/js/node/test/parallel/test-child-process-exec-encoding.js index 059e300e4e76..21ab207fca8c 100644 --- a/test/js/node/test/parallel/test-child-process-exec-encoding.js +++ b/test/js/node/test/parallel/test-child-process-exec-encoding.js @@ -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); - }); + })); }); } diff --git a/test/js/node/test/parallel/test-child-process-flush-stdio.js b/test/js/node/test/parallel/test-child-process-flush-stdio.js index 7b9a2a049cb2..37e63e64990e 100644 --- a/test/js/node/test/parallel/test-child-process-flush-stdio.js +++ b/test/js/node/test/parallel/test-child-process-flush-stdio.js @@ -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); }); -}; +}); diff --git a/test/js/node/test/parallel/test-child-process-fork-abort-signal.js b/test/js/node/test/parallel/test-child-process-fork-abort-signal.js index b963306fb1be..1d170134f715 100644 --- a/test/js/node/test/parallel/test-child-process-fork-abort-signal.js +++ b/test/js/node/test/parallel/test-child-process-fork-abort-signal.js @@ -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'); })); } diff --git a/test/js/node/test/parallel/test-child-process-fork-closed-channel-segfault.js b/test/js/node/test/parallel/test-child-process-fork-closed-channel-segfault.js index 47eb87c45fd0..73bd118ddce3 100644 --- a/test/js/node/test/parallel/test-child-process-fork-closed-channel-segfault.js +++ b/test/js/node/test/parallel/test-child-process-fork-closed-channel-segfault.js @@ -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; } }); - }); - }); - }); + })); + })); + })); diff --git a/test/js/node/test/parallel/test-child-process-fork-ref.js b/test/js/node/test/parallel/test-child-process-fork-ref.js index bbf4432af808..ae025a72fa27 100644 --- a/test/js/node/test/parallel/test-child-process-fork-ref.js +++ b/test/js/node/test/parallel/test-child-process-fork-ref.js @@ -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'); - }); + })); } diff --git a/test/js/node/test/parallel/test-child-process-fork.js b/test/js/node/test/parallel/test-child-process-fork.js index ee9dd3fc9f47..3146c4fea182 100644 --- a/test/js/node/test/parallel/test-child-process-fork.js +++ b/test/js/node/test/parallel/test-child-process-fork.js @@ -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... diff --git a/test/js/node/test/parallel/test-child-process-reject-null-bytes.js b/test/js/node/test/parallel/test-child-process-reject-null-bytes.js index b5239cdddcdd..3b3a25d961a9 100644 --- a/test/js/node/test/parallel/test-child-process-reject-null-bytes.js +++ b/test/js/node/test/parallel/test-child-process-reject-null-bytes.js @@ -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', }); diff --git a/test/js/node/test/parallel/test-child-process-silent.js b/test/js/node/test/parallel/test-child-process-silent.js index 892c4527c9e2..3c0acf97555d 100644 --- a/test/js/node/test/parallel/test-child-process-silent.js +++ b/test/js/node/test/parallel/test-child-process-silent.js @@ -20,7 +20,7 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const childProcess = require('child_process'); @@ -44,9 +44,7 @@ if (process.argv[2] === 'pipe') { // Allow child process to self terminate child.disconnect(); - child.on('exit', function() { - process.exit(0); - }); + child.on('exit', common.mustCall()); } else { // Testcase | start primary && child IPC test diff --git a/test/js/node/test/parallel/test-child-process-spawnsync-args.js b/test/js/node/test/parallel/test-child-process-spawnsync-args.js index 4e65b22f6e45..997852cae118 100644 --- a/test/js/node/test/parallel/test-child-process-spawnsync-args.js +++ b/test/js/node/test/parallel/test-child-process-spawnsync-args.js @@ -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]); diff --git a/test/js/node/test/parallel/test-child-process-spawnsync-input.js b/test/js/node/test/parallel/test-child-process-spawnsync-input.js index 62ae476ae17c..f0c3d3d78978 100644 --- a/test/js/node/test/parallel/test-child-process-spawnsync-input.js +++ b/test/js/node/test/parallel/test-child-process-spawnsync-input.js @@ -65,7 +65,6 @@ if (process.argv.includes('spawnchild')) { checkSpawnSyncRet(ret); break; } - process.exit(0); return; } diff --git a/test/js/node/test/parallel/test-child-process-spawnsync-timeout.js b/test/js/node/test/parallel/test-child-process-spawnsync-timeout.js index 36f2555ac844..426ac05a4349 100644 --- a/test/js/node/test/parallel/test-child-process-spawnsync-timeout.js +++ b/test/js/node/test/parallel/test-child-process-spawnsync-timeout.js @@ -39,7 +39,6 @@ if (common.isWindows) { switch (process.argv[2]) { case 'child': - console.log('child started'); setTimeout(() => { debug('child fired'); process.exit(1); diff --git a/test/js/node/test/parallel/test-child-process-stdio-inherit.js b/test/js/node/test/parallel/test-child-process-stdio-inherit.js index 034a0770168b..73a5bc802c76 100644 --- a/test/js/node/test/parallel/test-child-process-stdio-inherit.js +++ b/test/js/node/test/parallel/test-child-process-stdio-inherit.js @@ -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() { diff --git a/test/js/node/test/parallel/test-child-process-stdout-flush-exit.js b/test/js/node/test/parallel/test-child-process-stdout-flush-exit.js index 90f746c39ef6..4c5de7d9a2b4 100644 --- a/test/js/node/test/parallel/test-child-process-stdout-flush-exit.js +++ b/test/js/node/test/parallel/test-child-process-stdout-flush-exit.js @@ -36,7 +36,6 @@ if (process.argv[2] === 'child') { console.log('filler'); } console.log('goodbye'); - process.exit(0); } else { // parent process const spawn = require('child_process').spawn; diff --git a/test/js/node/test/parallel/test-config-json-schema.js b/test/js/node/test/parallel/test-config-json-schema.js index ee97b84b41f4..82679660a30f 100644 --- a/test/js/node/test/parallel/test-config-json-schema.js +++ b/test/js/node/test/parallel/test-config-json-schema.js @@ -21,6 +21,14 @@ if (!common.hasIntl) { common.skip('missing Intl'); } +if (!common.hasQuic) { + common.skip('this test requires QUIC'); +} + +if (process.config.variables.icu_small) { + common.skip('this test assumes full ICU build'); +} + if (process.config.variables.node_quic) { common.skip('this test assumes default configuration options'); } diff --git a/test/js/node/test/parallel/test-crypto-certificate.js b/test/js/node/test/parallel/test-crypto-certificate.js index 6b02d07f3ce0..28d20ba61c75 100644 --- a/test/js/node/test/parallel/test-crypto-certificate.js +++ b/test/js/node/test/parallel/test-crypto-certificate.js @@ -103,22 +103,6 @@ function checkMethods(certificate) { checkMethods(Certificate); } -{ - const spkacText = spkacValid.toString('utf8').trimEnd(); - const padded = Buffer.alloc(Buffer.byteLength(spkacText) + 1); - padded.write(spkacText); - const zeroLengthView = padded.subarray(0, 0); - assert.strictEqual(Certificate.verifySpkac(zeroLengthView), false); - assert.strictEqual(Certificate.exportPublicKey(zeroLengthView), ''); - assert.strictEqual(Certificate.exportChallenge(zeroLengthView), ''); - - for (const input of [Buffer.alloc(0), Buffer.from(' \n\r\t'), '', ' \n\r\t']) { - assert.strictEqual(Certificate.verifySpkac(Buffer.from(input)), false); - assert.strictEqual(Certificate.exportPublicKey(input), ''); - assert.strictEqual(Certificate.exportChallenge(input), ''); - } -} - function stripLineEndings(obj) { return obj.replace(/\n/g, ''); } diff --git a/test/js/node/test/parallel/test-crypto-keyobject-brand-check.js b/test/js/node/test/parallel/test-crypto-keyobject-brand-check.js index fffd6e4a8885..ac0cf1b65f70 100644 --- a/test/js/node/test/parallel/test-crypto-keyobject-brand-check.js +++ b/test/js/node/test/parallel/test-crypto-keyobject-brand-check.js @@ -18,16 +18,6 @@ const { const { types: { isKeyObject } } = require('node:util'); const invalidThis = { code: 'ERR_INVALID_THIS', name: 'TypeError' }; -// A non-KeyObject receiver names "KeyObject"; a KeyObject of the wrong kind names the -// specific subclass the getter lives on. -const notKeyObject = { - ...invalidThis, - message: 'Value of "this" must be of type KeyObject', -}; -const wrongKind = (expected) => ({ - ...invalidThis, - message: `Value of "this" must be of type ${expected}`, -}); function getter(proto, name) { return Object.getOwnPropertyDescriptor(proto, name).get; @@ -62,25 +52,22 @@ function getter(proto, name) { for (const value of [{}, { __proto__: null }, 1, null, undefined, Buffer.alloc(1), function() {}]) { - assert.throws(() => type.call(value), notKeyObject); - assert.throws(() => symmetricKeySize.call(value), notKeyObject); - assert.throws(() => asymmetricKeyType.call(value), notKeyObject); - assert.throws(() => asymmetricKeyDetails.call(value), notKeyObject); + assert.throws(() => type.call(value), invalidThis); + assert.throws(() => symmetricKeySize.call(value), invalidThis); + assert.throws(() => asymmetricKeyType.call(value), invalidThis); + assert.throws(() => asymmetricKeyDetails.call(value), invalidThis); } - assert.throws(() => symmetricKeySize.call(publicKey), - wrongKind('SecretKeyObject')); - assert.throws(() => asymmetricKeyType.call(secret), - wrongKind('AsymmetricKeyObject')); - assert.throws(() => asymmetricKeyDetails.call(secret), - wrongKind('AsymmetricKeyObject')); + assert.throws(() => symmetricKeySize.call(publicKey), invalidThis); + assert.throws(() => asymmetricKeyType.call(secret), invalidThis); + assert.throws(() => asymmetricKeyDetails.call(secret), invalidThis); const spoofed = {}; Object.setPrototypeOf(spoofed, Object.getPrototypeOf(secret)); assert.strictEqual(spoofed instanceof KeyObject, true); assert.strictEqual(isKeyObject(spoofed), false); - assert.throws(() => type.call(spoofed), notKeyObject); - assert.throws(() => symmetricKeySize.call(spoofed), notKeyObject); + assert.throws(() => type.call(spoofed), invalidThis); + assert.throws(() => symmetricKeySize.call(spoofed), invalidThis); assert.throws(() => createHmac('sha256', spoofed), { code: 'ERR_INVALID_ARG_TYPE', }); @@ -95,10 +82,10 @@ function getter(proto, name) { const buf = Buffer.alloc(16); assert.strictEqual(buf instanceof KeyObject, true); assert.strictEqual(isKeyObject(buf), false); - assert.throws(() => type.call(buf), notKeyObject); - assert.throws(() => symmetricKeySize.call(buf), notKeyObject); - assert.throws(() => asymmetricKeyType.call(buf), notKeyObject); - assert.throws(() => asymmetricKeyDetails.call(buf), notKeyObject); + assert.throws(() => type.call(buf), invalidThis); + assert.throws(() => symmetricKeySize.call(buf), invalidThis); + assert.throws(() => asymmetricKeyType.call(buf), invalidThis); + assert.throws(() => asymmetricKeyDetails.call(buf), invalidThis); } finally { if (originalHasInstance === undefined) { delete KeyObject[Symbol.hasInstance]; diff --git a/test/js/node/test/parallel/test-crypto-rsa-dsa.js b/test/js/node/test/parallel/test-crypto-rsa-dsa.js index 2c28c28c2198..35ad67302077 100644 --- a/test/js/node/test/parallel/test-crypto-rsa-dsa.js +++ b/test/js/node/test/parallel/test-crypto-rsa-dsa.js @@ -234,6 +234,8 @@ function test_rsa(padding, encryptOaepHash, decryptOaepHash) { if (padding === constants.RSA_PKCS1_PADDING) { if (!process.config.variables.node_shared_openssl) { + // TODO(richardlau) remove check and else branch after deps/openssl + // is upgraded. if (hasOpenSSL(3, 2)) { let decryptedBuffer = crypto.privateDecrypt({ key: rsaKeyPem, diff --git a/test/js/node/test/parallel/test-debug-process.js b/test/js/node/test/parallel/test-debug-process.js index 0d10a15e2eef..4eb5ad7b4d5d 100644 --- a/test/js/node/test/parallel/test-debug-process.js +++ b/test/js/node/test/parallel/test-debug-process.js @@ -16,6 +16,6 @@ cp.on('exit', common.mustCall(function() { try { process._debugProcess(cp.pid); } catch (error) { - assert.strictEqual(error.message, 'The system cannot find the file specified.'); + assert.strictEqual(error.errno, 2); } })); diff --git a/test/js/node/test/parallel/test-debugger-backtrace.js b/test/js/node/test/parallel/test-debugger-backtrace.js index f66cc11d70a9..c189cb3f5b22 100644 --- a/test/js/node/test/parallel/test-debugger-backtrace.js +++ b/test/js/node/test/parallel/test-debugger-backtrace.js @@ -13,7 +13,7 @@ const path = require('path'); { const scriptFullPath = fixtures.path('debugger', 'backtrace.js'); const script = path.relative(process.cwd(), scriptFullPath); - const cli = startCLI(['--port=0', script]); + const cli = startCLI([script]); async function runTest() { try { diff --git a/test/js/node/test/parallel/test-debugger-exec.js b/test/js/node/test/parallel/test-debugger-exec.js index 536e0128ea2a..2b6c50ab61ff 100644 --- a/test/js/node/test/parallel/test-debugger-exec.js +++ b/test/js/node/test/parallel/test-debugger-exec.js @@ -8,7 +8,7 @@ const startCLI = require('../common/debugger'); const assert = require('assert'); -const cli = startCLI(['--port=0', fixtures.path('debugger/alive.js')]); +const cli = startCLI([fixtures.path('debugger/alive.js')]); async function waitInitialBreak() { try { diff --git a/test/js/node/test/parallel/test-debugger-invalid-json.mjs b/test/js/node/test/parallel/test-debugger-invalid-json.mjs index e4754a465fcf..1c2b4b475b7e 100644 --- a/test/js/node/test/parallel/test-debugger-invalid-json.mjs +++ b/test/js/node/test/parallel/test-debugger-invalid-json.mjs @@ -17,7 +17,7 @@ const host = '127.0.0.1'; server.listen(0, mustCall(async () => { const port = server.address().port; - const cli = startCLI([`${host}:${port}`]); + const cli = startCLI([`${host}:${port}`], [], {}, { randomPort: false }); try { const code = await cli.quit(); assert.strictEqual(code, 1); @@ -35,7 +35,7 @@ const host = '127.0.0.1'; server.listen(0, host, mustCall(async () => { const port = server.address().port; - const cli = startCLI([`${host}:${port}`]); + const cli = startCLI([`${host}:${port}`], [], {}, { randomPort: false }); try { const code = await cli.quit(); assert.strictEqual(code, 1); diff --git a/test/js/node/test/parallel/test-debugger-low-level.js b/test/js/node/test/parallel/test-debugger-low-level.js index 31f67849f547..93c8e1b62559 100644 --- a/test/js/node/test/parallel/test-debugger-low-level.js +++ b/test/js/node/test/parallel/test-debugger-low-level.js @@ -9,7 +9,7 @@ const assert = require('assert'); // Debugger agent direct access. { - const cli = startCLI(['--port=0', fixtures.path('debugger/three-lines.js')]); + const cli = startCLI([fixtures.path('debugger/three-lines.js')]); const scriptPattern = /^\* (\d+): \S+debugger(?:\/|\\)three-lines\.js/m; async function testDebuggerLowLevel() { diff --git a/test/js/node/test/parallel/test-debugger-repeat-last.js b/test/js/node/test/parallel/test-debugger-repeat-last.js index 9a9b8eecdc71..5b403035dc46 100644 --- a/test/js/node/test/parallel/test-debugger-repeat-last.js +++ b/test/js/node/test/parallel/test-debugger-repeat-last.js @@ -1,10 +1,10 @@ 'use strict'; const common = require('../common'); common.skipIfInspectorDisabled(); -const path = require('../common/fixtures').path; +const fixtures = require('../common/fixtures'); const spawn = require('child_process').spawn; const assert = require('assert'); -const fixture = path('debugger-repeat-last.js'); +const fixture = fixtures.path('debugger-repeat-last.js'); const args = [ 'inspect', diff --git a/test/js/node/test/parallel/test-debugger-restart-message.js b/test/js/node/test/parallel/test-debugger-restart-message.js index e4001b47ee2d..3f19e22f550e 100644 --- a/test/js/node/test/parallel/test-debugger-restart-message.js +++ b/test/js/node/test/parallel/test-debugger-restart-message.js @@ -14,23 +14,29 @@ const startCLI = require('../common/debugger'); // Using `restart` should result in only one "Connect/For help" message. { const script = fixtures.path('debugger', 'three-lines.js'); - const cli = startCLI(['--port=0', script]); + const cli = startCLI([script]); const listeningRegExp = /Debugger listening on/g; async function onWaitForInitialBreak() { try { - await cli.waitForInitialBreak(); + await cli.waitFor(/ ok\n/); await cli.waitForPrompt(); assert.strictEqual(cli.output.match(listeningRegExp).length, 1); for (let i = 0; i < RESTARTS; i++) { - await cli.stepCommand('restart'); + // For `restart`, sync on attach/prompt instead of BREAK_MESSAGE to avoid flaky races. + // https://github.com/nodejs/node/issues/61762 + await cli.command('restart'); + await cli.waitFor(/Debugger attached\./); + await cli.waitForPrompt(); assert.strictEqual(cli.output.match(listeningRegExp).length, 1); } } finally { await cli.quit(); } + + assert.doesNotMatch(cli.stderrOutput, /MaxListenersExceededWarning/); } onWaitForInitialBreak(); diff --git a/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-callback-error.js b/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-callback-error.js index 672500e76832..0767db3b7ad5 100644 --- a/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-callback-error.js +++ b/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-callback-error.js @@ -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); diff --git a/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-callback.js b/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-callback.js index d306f0f51b7c..dbe2406475ac 100644 --- a/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-callback.js +++ b/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-callback.js @@ -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); diff --git a/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-promise-error.js b/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-promise-error.js index f1f52d72f800..4a193b52a764 100644 --- a/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-promise-error.js +++ b/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-promise-error.js @@ -27,12 +27,10 @@ const handlers = { channel.subscribe(handlers); -channel.tracePromise(function(value) { - assert.deepStrictEqual(this, thisArg); - return Promise.reject(value); -}, input, thisArg, expectedError).then( - common.mustNotCall(), - common.mustCall((value) => { - assert.deepStrictEqual(value, expectedError); - }) -); +assert.rejects( + channel.tracePromise(common.mustCall(function(value) { + assert.deepStrictEqual(this, thisArg); + return Promise.reject(value); + }), input, thisArg, expectedError), + expectedError, +).then(common.mustCall()); diff --git a/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-promise.js b/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-promise.js index 20892ca40f59..1ac1a5649628 100644 --- a/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-promise.js +++ b/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-promise.js @@ -30,12 +30,11 @@ 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); }), - common.mustNotCall() ); diff --git a/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-sync-error.js b/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-sync-error.js index 0965bf3fb495..b7b5084bae61 100644 --- a/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-sync-error.js +++ b/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-sync-error.js @@ -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) { diff --git a/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-sync.js b/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-sync.js index b28b47256b75..1cc5feb6d0dc 100644 --- a/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-sync.js +++ b/test/js/node/test/parallel/test-diagnostics-channel-tracing-channel-sync.js @@ -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); diff --git a/test/js/node/test/parallel/test-dns-setservers-type-check.js b/test/js/node/test/parallel/test-dns-setservers-type-check.js index 7a19dc5eb067..007cae4f95d6 100644 --- a/test/js/node/test/parallel/test-dns-setservers-type-check.js +++ b/test/js/node/test/parallel/test-dns-setservers-type-check.js @@ -20,7 +20,8 @@ const promiseResolver = new dns.promises.Resolver(); const errObj = { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', - message: /^The "servers" argument must be an instance of Array\./ + message: 'The "servers" argument must be an instance of Array.' + + common.invalidArgTypeHelper(val) }; assert.throws( () => { @@ -59,7 +60,8 @@ const promiseResolver = new dns.promises.Resolver(); const errObj = { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', - message: /^The "servers\[0\]" argument must be of type string\./ + message: 'The "servers[0]" argument must be of type string.' + + common.invalidArgTypeHelper(val[0]) }; assert.throws( () => { @@ -108,7 +110,8 @@ const promiseResolver = new dns.promises.Resolver(); const errObj = { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', - message: /^The "servers\[0\]" argument must be of type string\./ + message: 'The "servers[0]" argument must be of type string.' + + common.invalidArgTypeHelper(val[0]) }; assert.throws(() => { setServers(val); diff --git a/test/js/node/test/parallel/test-domain-nested-throw.js b/test/js/node/test/parallel/test-domain-nested-throw.js index ec016ada7285..ee16d86f107e 100644 --- a/test/js/node/test/parallel/test-domain-nested-throw.js +++ b/test/js/node/test/parallel/test-domain-nested-throw.js @@ -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; diff --git a/test/js/node/test/parallel/test-domexception-cause.js b/test/js/node/test/parallel/test-domexception-cause.js index 179ef6d212ae..c5a9f61c234b 100644 --- a/test/js/node/test/parallel/test-domexception-cause.js +++ b/test/js/node/test/parallel/test-domexception-cause.js @@ -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); } diff --git a/test/js/node/test/parallel/test-event-emitter-add-listeners.js b/test/js/node/test/parallel/test-event-emitter-add-listeners.js index f42d1f248784..5d17fd0db085 100644 --- a/test/js/node/test/parallel/test-event-emitter-add-listeners.js +++ b/test/js/node/test/parallel/test-event-emitter-add-listeners.js @@ -46,11 +46,11 @@ const EventEmitter = require('events'); assert.strictEqual(b, 'b'); }); - ee.once('newListener', function(name, listener) { + ee.once('newListener', common.mustCall(function(name, listener) { assert.strictEqual(name, 'hello'); assert.strictEqual(listener, hello); assert.deepStrictEqual(this.listeners('hello'), []); - }); + })); ee.on('hello', hello); ee.once('foo', assert.fail); @@ -72,13 +72,13 @@ const EventEmitter = require('events'); const listen2 = () => {}; const ee = new EventEmitter(); - ee.once('newListener', function() { + ee.once('newListener', common.mustCall(() => { assert.deepStrictEqual(ee.listeners('hello'), []); - ee.once('newListener', function() { + ee.once('newListener', common.mustCall(() => { assert.deepStrictEqual(ee.listeners('hello'), []); - }); + })); ee.on('hello', listen2); - }); + })); ee.on('hello', listen1); // The order of listeners on an event is not always the order in which the // listeners were added. diff --git a/test/js/node/test/parallel/test-event-emitter-method-names.js b/test/js/node/test/parallel/test-event-emitter-method-names.js index 684024d02762..8ee44f41d588 100644 --- a/test/js/node/test/parallel/test-event-emitter-method-names.js +++ b/test/js/node/test/parallel/test-event-emitter-method-names.js @@ -28,8 +28,8 @@ const E = events.EventEmitter.prototype; assert.strictEqual(E.constructor.name, 'EventEmitter'); assert.strictEqual(E.on, E.addListener); // Same method. assert.strictEqual(E.off, E.removeListener); // Same method. -Object.getOwnPropertyNames(E).forEach(function(name) { +for (const name of Object.getOwnPropertyNames(E)) { if (name === 'constructor' || name === 'on' || name === 'off') return; if (typeof E[name] !== 'function') return; assert.strictEqual(E[name].name, name); -}); +} diff --git a/test/js/node/test/parallel/test-event-emitter-remove-all-listeners.js b/test/js/node/test/parallel/test-event-emitter-remove-all-listeners.js index c62183fd08c2..bca8f3eb1650 100644 --- a/test/js/node/test/parallel/test-event-emitter-remove-all-listeners.js +++ b/test/js/node/test/parallel/test-event-emitter-remove-all-listeners.js @@ -87,9 +87,9 @@ function expect(expected) { { const ee = new events.EventEmitter(); let expectLength = 2; - ee.on('removeListener', function(name, noop) { + ee.on('removeListener', common.mustCallAtLeast(function(name, noop) { assert.strictEqual(expectLength--, this.listeners('baz').length); - }); + })); ee.on('baz', common.mustNotCall()); ee.on('baz', common.mustNotCall()); ee.on('baz', common.mustNotCall()); diff --git a/test/js/node/test/parallel/test-event-emitter-remove-listeners.js b/test/js/node/test/parallel/test-event-emitter-remove-listeners.js index e9e4a74a5b63..7b94d31f45d2 100644 --- a/test/js/node/test/parallel/test-event-emitter-remove-listeners.js +++ b/test/js/node/test/parallel/test-event-emitter-remove-listeners.js @@ -144,19 +144,6 @@ function listener2() {} assert.deepStrictEqual(ee, ee.removeListener('foo', () => {})); } -{ - const ee = new EventEmitter(); - ee.on('persistent', listener1); - - for (let i = 0; i < 100; i++) { - const eventName = `event-${i}`; - ee.on(eventName, listener2); - ee.removeListener(eventName, listener2); - } - - assert.deepStrictEqual(Reflect.ownKeys(ee._events), ['persistent']); -} - { const ee = new EventEmitter(); const listener = () => {}; diff --git a/test/js/node/test/parallel/test-events-add-abort-listener.mjs b/test/js/node/test/parallel/test-events-add-abort-listener.mjs index f8de1e2e42a1..69b6a054e395 100644 --- a/test/js/node/test/parallel/test-events-add-abort-listener.mjs +++ b/test/js/node/test/parallel/test-events-add-abort-listener.mjs @@ -1,7 +1,7 @@ -import * as assert from 'node:assert'; +import * as common from '../common/index.mjs'; import * as events from 'node:events'; +import * as assert from 'node:assert'; import { describe, it } from 'node:test'; -import * as common from '../common/index.mjs'; describe('events.addAbortListener', () => { it('should throw if signal not provided', () => { @@ -52,4 +52,4 @@ describe('events.addAbortListener', () => { disposable[Symbol.dispose](); controller.abort(); }); -}); \ No newline at end of file +}); diff --git a/test/js/node/test/parallel/test-events-once.js b/test/js/node/test/parallel/test-events-once.js index d5eadeaca0e9..2a3d3c97ae20 100644 --- a/test/js/node/test/parallel/test-events-once.js +++ b/test/js/node/test/parallel/test-events-once.js @@ -1,14 +1,9 @@ 'use strict'; -// Flags: --expose-internals --no-warnings +// Flags: --no-warnings const common = require('../common'); const { once, EventEmitter, listenerCount } = require('events'); -const { - deepStrictEqual, - fail, - rejects, - strictEqual, -} = require('assert'); +const assert = require('assert'); async function onceAnEvent() { const ee = new EventEmitter(); @@ -18,16 +13,16 @@ async function onceAnEvent() { }); const [value] = await once(ee, 'myevent'); - strictEqual(value, 42); - strictEqual(ee.listenerCount('error'), 0); - strictEqual(ee.listenerCount('myevent'), 0); + assert.strictEqual(value, 42); + assert.strictEqual(ee.listenerCount('error'), 0); + assert.strictEqual(ee.listenerCount('myevent'), 0); } async function onceAnEventWithInvalidOptions() { const ee = new EventEmitter(); await Promise.all([1, 'hi', null, false, () => {}, Symbol(), 1n].map((options) => { - return rejects(once(ee, 'myevent', options), { + return assert.rejects(once(ee, 'myevent', options), { code: 'ERR_INVALID_ARG_TYPE', }); })); @@ -41,7 +36,7 @@ async function onceAnEventWithTwoArgs() { }); const value = await once(ee, 'myevent'); - deepStrictEqual(value, [42, 24]); + assert.deepStrictEqual(value, [42, 24]); } async function catchesErrors() { @@ -58,9 +53,9 @@ async function catchesErrors() { } catch (_e) { err = _e; } - strictEqual(err, expected); - strictEqual(ee.listenerCount('error'), 0); - strictEqual(ee.listenerCount('myevent'), 0); + assert.strictEqual(err, expected); + assert.strictEqual(ee.listenerCount('error'), 0); + assert.strictEqual(ee.listenerCount('myevent'), 0); } async function catchesErrorsWithAbortSignal() { @@ -76,17 +71,17 @@ async function catchesErrorsWithAbortSignal() { try { const promise = once(ee, 'myevent', { signal }); - strictEqual(ee.listenerCount('error'), 1); - strictEqual(listenerCount(signal, "abort"), 1); + assert.strictEqual(ee.listenerCount('error'), 1); + assert.strictEqual(listenerCount(signal, 'abort'), 1); await promise; } catch (e) { err = e; } - strictEqual(err, expected); - strictEqual(ee.listenerCount('error'), 0); - strictEqual(ee.listenerCount('myevent'), 0); - strictEqual(listenerCount(signal, "abort"), 0); + assert.strictEqual(err, expected); + assert.strictEqual(ee.listenerCount('error'), 0); + assert.strictEqual(ee.listenerCount('myevent'), 0); + assert.strictEqual(listenerCount(signal, 'abort'), 0); } async function stopListeningAfterCatchingError() { @@ -104,10 +99,9 @@ async function stopListeningAfterCatchingError() { } catch (_e) { err = _e; } - process.removeAllListeners('multipleResolves'); - strictEqual(err, expected); - strictEqual(ee.listenerCount('error'), 0); - strictEqual(ee.listenerCount('myevent'), 0); + assert.strictEqual(err, expected); + assert.strictEqual(ee.listenerCount('error'), 0); + assert.strictEqual(ee.listenerCount('myevent'), 0); } async function onceError() { @@ -119,11 +113,11 @@ async function onceError() { }); const promise = once(ee, 'error'); - strictEqual(ee.listenerCount('error'), 1); + assert.strictEqual(ee.listenerCount('error'), 1); const [ err ] = await promise; - strictEqual(err, expected); - strictEqual(ee.listenerCount('error'), 0); - strictEqual(ee.listenerCount('myevent'), 0); + assert.strictEqual(err, expected); + assert.strictEqual(ee.listenerCount('error'), 0); + assert.strictEqual(ee.listenerCount('myevent'), 0); } async function onceWithEventTarget() { @@ -133,7 +127,7 @@ async function onceWithEventTarget() { et.dispatchEvent(event); }); const [ value ] = await once(et, 'myevent'); - strictEqual(value, event); + assert.strictEqual(value, event); } async function onceWithEventTargetError() { @@ -144,20 +138,20 @@ async function onceWithEventTargetError() { }); const [ err ] = await once(et, 'error'); - strictEqual(err, error); + assert.strictEqual(err, error); } async function onceWithInvalidEventEmmiter() { const ac = new AbortController(); - return rejects(once(ac, 'myevent'), { + return assert.rejects(once(ac, 'myevent'), { code: 'ERR_INVALID_ARG_TYPE', }); } async function prioritizesEventEmitter() { const ee = new EventEmitter(); - ee.addEventListener = fail; - ee.removeAllListeners = fail; + ee.addEventListener = assert.fail; + ee.removeAllListeners = assert.fail; process.nextTick(() => ee.emit('foo')); await once(ee, 'foo'); } @@ -168,12 +162,12 @@ async function abortSignalBefore() { const abortedSignal = AbortSignal.abort(); await Promise.all([1, {}, 'hi', null, false].map((signal) => { - return rejects(once(ee, 'foo', { signal }), { + return assert.rejects(once(ee, 'foo', { signal }), { code: 'ERR_INVALID_ARG_TYPE', }); })); - return rejects(once(ee, 'foo', { signal: abortedSignal }), { + return assert.rejects(once(ee, 'foo', { signal: abortedSignal }), { name: 'AbortError', }); } @@ -182,7 +176,7 @@ async function abortSignalAfter() { const ee = new EventEmitter(); const ac = new AbortController(); ee.on('error', common.mustNotCall()); - const r = rejects(once(ee, 'foo', { signal: ac.signal }), { + const r = assert.rejects(once(ee, 'foo', { signal: ac.signal }), { name: 'AbortError', }); process.nextTick(() => ac.abort()); @@ -197,9 +191,9 @@ async function abortSignalAfterEvent() { ac.abort(); }); const promise = once(ee, 'foo', { signal: ac.signal }); - strictEqual(listenerCount(ac.signal, "abort"), 1); + assert.strictEqual(listenerCount(ac.signal, 'abort'), 1); await promise; - strictEqual(listenerCount(ac.signal, "abort"), 0); + assert.strictEqual(listenerCount(ac.signal, 'abort'), 0); } async function abortSignalRemoveListener() { @@ -210,8 +204,8 @@ async function abortSignalRemoveListener() { process.nextTick(() => ac.abort()); await once(ee, 'test', { signal: ac.signal }); } catch { - strictEqual(ee.listeners('test').length, 0); - strictEqual(ee.listeners('error').length, 0); + assert.strictEqual(ee.listeners('test').length, 0); + assert.strictEqual(ee.listeners('error').length, 0); } } @@ -220,33 +214,32 @@ async function eventTargetAbortSignalBefore() { const abortedSignal = AbortSignal.abort(); await Promise.all([1, {}, 'hi', null, false].map((signal) => { - return rejects(once(et, 'foo', { signal }), { + return assert.rejects(once(et, 'foo', { signal }), { code: 'ERR_INVALID_ARG_TYPE', }); })); - return rejects(once(et, 'foo', { signal: abortedSignal }), { + return assert.rejects(once(et, 'foo', { signal: abortedSignal }), { name: 'AbortError', }); } -// TODO: unskip -// async function eventTargetAbortSignalBeforeEvenWhenSignalPropagationStopped() { -// const et = new EventTarget(); -// const ac = new AbortController(); -// const { signal } = ac; -// signal.addEventListener('abort', (e) => e.stopImmediatePropagation(), { once: true }); - -// process.nextTick(() => ac.abort()); -// return rejects(once(et, 'foo', { signal }), { -// name: 'AbortError', -// }); -// } +async function eventTargetAbortSignalBeforeEvenWhenSignalPropagationStopped() { + const et = new EventTarget(); + const ac = new AbortController(); + const { signal } = ac; + signal.addEventListener('abort', (e) => e.stopImmediatePropagation(), { once: true }); + + process.nextTick(() => ac.abort()); + return assert.rejects(once(et, 'foo', { signal }), { + name: 'AbortError', + }); +} async function eventTargetAbortSignalAfter() { const et = new EventTarget(); const ac = new AbortController(); - const r = rejects(once(et, 'foo', { signal: ac.signal }), { + const r = assert.rejects(once(et, 'foo', { signal: ac.signal }), { name: 'AbortError', }); process.nextTick(() => ac.abort()); @@ -280,7 +273,7 @@ Promise.all([ abortSignalAfterEvent(), abortSignalRemoveListener(), eventTargetAbortSignalBefore(), - // eventTargetAbortSignalBeforeEvenWhenSignalPropagationStopped(), + eventTargetAbortSignalBeforeEvenWhenSignalPropagationStopped(), eventTargetAbortSignalAfter(), eventTargetAbortSignalAfterEvent(), ]).then(common.mustCall()); diff --git a/test/js/node/test/parallel/test-events-static-geteventlisteners.js b/test/js/node/test/parallel/test-events-static-geteventlisteners.js index 35b4e34325a8..2f450f076457 100644 --- a/test/js/node/test/parallel/test-events-static-geteventlisteners.js +++ b/test/js/node/test/parallel/test-events-static-geteventlisteners.js @@ -1,11 +1,9 @@ 'use strict'; // Flags: --expose-internals --no-warnings const common = require('../common'); +const { kWeakHandler } = require('internal/event_target'); -const { - deepStrictEqual, - throws, -} = require('assert'); +const assert = require('assert'); const { getEventListeners, EventEmitter } = require('events'); @@ -18,9 +16,9 @@ const { getEventListeners, EventEmitter } = require('events'); emitter.on('foo', fn2); emitter.on('baz', fn1); emitter.on('baz', fn1); - deepStrictEqual(getEventListeners(emitter, 'foo'), [fn1, fn2]); - deepStrictEqual(getEventListeners(emitter, 'bar'), []); - deepStrictEqual(getEventListeners(emitter, 'baz'), [fn1, fn1]); + assert.deepStrictEqual(getEventListeners(emitter, 'foo'), [fn1, fn2]); + assert.deepStrictEqual(getEventListeners(emitter, 'bar'), []); + assert.deepStrictEqual(getEventListeners(emitter, 'baz'), [fn1, fn1]); } // Test getEventListeners on EventTarget { @@ -31,21 +29,21 @@ const { getEventListeners, EventEmitter } = require('events'); target.addEventListener('foo', fn2); target.addEventListener('baz', fn1); target.addEventListener('baz', fn1); - deepStrictEqual(getEventListeners(target, 'foo'), [fn1, fn2]); - deepStrictEqual(getEventListeners(target, 'bar'), []); - deepStrictEqual(getEventListeners(target, 'baz'), [fn1]); + assert.deepStrictEqual(getEventListeners(target, 'foo'), [fn1, fn2]); + assert.deepStrictEqual(getEventListeners(target, 'bar'), []); + assert.deepStrictEqual(getEventListeners(target, 'baz'), [fn1]); } { - throws(() => { + assert.throws(() => { getEventListeners('INVALID_EMITTER'); }, /ERR_INVALID_ARG_TYPE/); } -// { -// // Test weak listeners -// const target = new EventTarget(); -// const fn = common.mustNotCall(); -// target.addEventListener('foo', fn, { [kWeakHandler]: {} }); -// const listeners = getEventListeners(target, 'foo'); -// deepStrictEqual(listeners, [fn]); -// } +{ + // Test weak listeners + const target = new EventTarget(); + const fn = common.mustNotCall(); + target.addEventListener('foo', fn, { [kWeakHandler]: {} }); + const listeners = getEventListeners(target, 'foo'); + assert.deepStrictEqual(listeners, [fn]); +} diff --git a/test/js/node/test/parallel/test-events-uncaught-exception-stack.js b/test/js/node/test/parallel/test-events-uncaught-exception-stack.js index 065bbd8a4be2..25fe9d6585f1 100644 --- a/test/js/node/test/parallel/test-events-uncaught-exception-stack.js +++ b/test/js/node/test/parallel/test-events-uncaught-exception-stack.js @@ -1,15 +1,14 @@ 'use strict'; const common = require('../common'); -if (common.isWindows) return; // TODO: BUN https://github.com/oven-sh/bun/issues/12827 const assert = require('assert'); const EventEmitter = require('events'); // Tests that the error stack where the exception was thrown is *not* appended. process.on('uncaughtException', common.mustCall((err) => { - const lines = err.stack.split('\n'); - assert.strictEqual(lines[0], 'Error'); - lines.slice(1).forEach((line) => { + const [firstLine, ...lines] = err.stack.split('\n'); + assert.strictEqual(firstLine, 'Error'); + lines.forEach((line) => { assert.match(line, /^ {4}at/); }); })); diff --git a/test/js/node/test/parallel/test-file-write-stream.js b/test/js/node/test/parallel/test-file-write-stream.js index 573cd409db3e..c334d89ccd4a 100644 --- a/test/js/node/test/parallel/test-file-write-stream.js +++ b/test/js/node/test/parallel/test-file-write-stream.js @@ -40,12 +40,12 @@ const callbacks = { }; file - .on('open', function(fd) { + .on('open', common.mustCall((fd) => { console.error('open!'); callbacks.open++; assert.strictEqual(typeof fd, 'number'); - }) - .on('drain', function() { + })) + .on('drain', common.mustCallAtLeast(() => { console.error('drain!', callbacks.drain); callbacks.drain++; if (callbacks.drain === -1) { @@ -55,8 +55,8 @@ file assert.strictEqual(fs.readFileSync(fn, 'utf8'), EXPECTED + EXPECTED); file.end(); } - }) - .on('close', function() { + })) + .on('close', common.mustCall(() => { console.error('close!'); assert.strictEqual(file.bytesWritten, EXPECTED.length * 2); @@ -69,7 +69,7 @@ file file.on('error', common.mustNotCall()); fs.unlinkSync(fn); - }); + })); for (let i = 0; i < 11; i++) { file.write(`${i}`); diff --git a/test/js/node/test/parallel/test-file-write-stream2.js b/test/js/node/test/parallel/test-file-write-stream2.js index ca52135ecf6c..79cdc41c8a26 100644 --- a/test/js/node/test/parallel/test-file-write-stream2.js +++ b/test/js/node/test/parallel/test-file-write-stream2.js @@ -20,7 +20,7 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const fs = require('fs'); @@ -68,13 +68,13 @@ const file = fs.createWriteStream(filepath, { highWaterMark: 11 }); -file.on('open', function(fd) { +file.on('open', common.mustCall((fd) => { console.error('open'); cb_occurred += 'open '; assert.strictEqual(typeof fd, 'number'); -}); +})); -file.on('drain', function() { +file.on('drain', common.mustCallAtLeast(() => { console.error('drain'); cb_occurred += 'drain '; ++countDrains; @@ -88,15 +88,15 @@ file.on('drain', function() { assert.strictEqual(fs.readFileSync(filepath, 'utf8'), EXPECTED + EXPECTED); file.end(); } -}); +})); -file.on('close', function() { +file.on('close', common.mustCall(() => { cb_occurred += 'close '; assert.strictEqual(file.bytesWritten, EXPECTED.length * 2); - file.write('should not work anymore', (err) => { + file.write('should not work anymore', common.mustCall((err) => { assert.ok(err.message.includes('write after end')); - }); -}); + })); +})); for (let i = 0; i < 11; i++) { const ret = file.write(String(i)); diff --git a/test/js/node/test/parallel/test-file-write-stream3.js b/test/js/node/test/parallel/test-file-write-stream3.js index 94ea9bcbc910..0670b078d086 100644 --- a/test/js/node/test/parallel/test-file-write-stream3.js +++ b/test/js/node/test/parallel/test-file-write-stream3.js @@ -65,7 +65,7 @@ function run_test_1() { cb_occurred += 'open '; }); - file.on('close', function() { + file.on('close', common.mustCall(() => { cb_occurred += 'close '; console.log(' (debug: bytesWritten ', file.bytesWritten); console.log(' (debug: start ', file.start); @@ -77,7 +77,7 @@ function run_test_1() { assert.strictEqual(fileData, fileDataExpected_1); run_test_2(); - }); + })); file.on('error', function(err) { cb_occurred += 'error '; @@ -107,7 +107,7 @@ function run_test_2() { cb_occurred += 'open '; }); - file.on('close', function() { + file.on('close', common.mustCall(() => { cb_occurred += 'close '; console.log(' (debug: bytesWritten ', file.bytesWritten); console.log(' (debug: start ', file.start); @@ -119,7 +119,7 @@ function run_test_2() { assert.strictEqual(fileData, fileDataExpected_2); run_test_3(); - }); + })); file.on('error', function(err) { cb_occurred += 'error '; @@ -148,7 +148,7 @@ function run_test_3() { cb_occurred += 'open '; }); - file.on('close', function() { + file.on('close', common.mustCall(() => { cb_occurred += 'close '; console.log(' (debug: bytesWritten ', file.bytesWritten); console.log(' (debug: start ', file.start); @@ -161,7 +161,7 @@ function run_test_3() { run_test_4(); run_test_5(); - }); + })); file.on('error', function(err) { cb_occurred += 'error '; diff --git a/test/js/node/test/parallel/test-filehandle-autoclose.mjs b/test/js/node/test/parallel/test-filehandle-autoclose.mjs index 1b19e968f714..bfc782be56cd 100644 --- a/test/js/node/test/parallel/test-filehandle-autoclose.mjs +++ b/test/js/node/test/parallel/test-filehandle-autoclose.mjs @@ -5,7 +5,7 @@ import assert from 'node:assert'; { const fh = await open(new URL(import.meta.url)); - // autoClose: true is passed explicitly until it becomes the default upstream + // TODO: remove autoClose option when it becomes default const readableStream = fh.readableWebStream({ autoClose: true }); // Consume the stream diff --git a/test/js/node/test/parallel/test-fs-copyfile.js b/test/js/node/test/parallel/test-fs-copyfile.js index 4541ef76b0cb..51d7153de025 100644 --- a/test/js/node/test/parallel/test-fs-copyfile.js +++ b/test/js/node/test/parallel/test-fs-copyfile.js @@ -1,13 +1,15 @@ +// Flags: --expose-internals 'use strict'; const common = require('../common'); const fixtures = require('../common/fixtures'); const tmpdir = require('../common/tmpdir'); const assert = require('assert'); const fs = require('fs'); +const { internalBinding } = require('internal/test/binding'); const { UV_ENOENT, UV_EEXIST -} = process.binding('uv'); +} = internalBinding('uv'); const src = fixtures.path('a.js'); const dest = tmpdir.resolve('copyfile.out'); const { diff --git a/test/js/node/test/parallel/test-fs-error-messages.js b/test/js/node/test/parallel/test-fs-error-messages.js index 270ab97398f0..6db11802f60e 100644 --- a/test/js/node/test/parallel/test-fs-error-messages.js +++ b/test/js/node/test/parallel/test-fs-error-messages.js @@ -42,6 +42,7 @@ fs.writeFileSync(existingFile2, 'test', 'utf-8'); const { COPYFILE_EXCL } = fs.constants; +const { internalBinding } = require('internal/test/binding'); const { UV_EBADF, UV_EEXIST, @@ -50,7 +51,7 @@ const { UV_ENOTDIR, UV_ENOTEMPTY, UV_EPERM -} = process.binding('uv'); +} = internalBinding('uv'); // Template tag function for escaping special characters in strings so that: // new RegExp(re`${str}`).test(str) === true diff --git a/test/js/node/test/parallel/test-fs-promises-file-handle-dispose.js b/test/js/node/test/parallel/test-fs-promises-file-handle-dispose.js index 406430eef4a2..fa1eba0138f6 100644 --- a/test/js/node/test/parallel/test-fs-promises-file-handle-dispose.js +++ b/test/js/node/test/parallel/test-fs-promises-file-handle-dispose.js @@ -1,12 +1,50 @@ 'use strict'; const common = require('../common'); -const { promises: fs } = require('fs'); +const assert = require('assert'); +const { opendirSync, promises: fs } = require('fs'); -async function doOpen() { +async function explicitCall() { const fh = await fs.open(__filename); fh.on('close', common.mustCall()); await fh[Symbol.asyncDispose](); + + const dh = await fs.opendir(__dirname); + await dh[Symbol.asyncDispose](); + // Repeat invocations should not reject + await dh[Symbol.asyncDispose](); + await assert.rejects(dh.read(), { code: 'ERR_DIR_CLOSED' }); + + const dhSync = opendirSync(__dirname); + dhSync[Symbol.dispose](); + // Repeat invocations should not throw + dhSync[Symbol.dispose](); + assert.throws(() => dhSync.readSync(), { code: 'ERR_DIR_CLOSED' }); +} + +async function implicitCall() { + let fh; + { + await using openHandle = await fs.open(__filename); + fh = openHandle; + fh.on('close', common.mustCall()); + } + assert.strictEqual(fh.fd, -1); + + let dh; + { + await using dirHandle = await fs.opendir(__dirname); + dh = dirHandle; + } + await assert.rejects(dh.read(), { code: 'ERR_DIR_CLOSED' }); + + let dhSync; + { + using dirHandleSync = opendirSync(__dirname); + dhSync = dirHandleSync; + } + assert.throws(() => dhSync.readSync(), { code: 'ERR_DIR_CLOSED' }); } -doOpen().then(common.mustCall()); +explicitCall().then(common.mustCall()); +implicitCall().then(common.mustCall()); diff --git a/test/js/node/test/parallel/test-fs-statfs.js b/test/js/node/test/parallel/test-fs-statfs.js index 5fd34f215bc3..4ff66a7d7c0f 100644 --- a/test/js/node/test/parallel/test-fs-statfs.js +++ b/test/js/node/test/parallel/test-fs-statfs.js @@ -7,7 +7,7 @@ function verifyStatFsObject(statfs, isBigint = false) { const valueType = isBigint ? 'bigint' : 'number'; [ - 'type', 'bsize', 'blocks', 'bfree', 'bavail', 'files', 'ffree', + 'type', 'bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files', 'ffree', ].forEach((k) => { assert.ok(Object.hasOwn(statfs, k)); assert.strictEqual(typeof statfs[k], valueType, @@ -20,11 +20,10 @@ fs.statfs(__filename, common.mustSucceed(function(stats) { assert.strictEqual(this, undefined); })); -fs.statfs(__filename, { bigint: true }, function(err, stats) { - assert.ifError(err); +fs.statfs(__filename, { bigint: true }, common.mustSucceed(function(stats) { verifyStatFsObject(stats, true); assert.strictEqual(this, undefined); -}); +})); // Synchronous { diff --git a/test/js/node/test/parallel/test-fs-utimes.js b/test/js/node/test/parallel/test-fs-utimes.js index e6ae75d4e33a..fc11c0791ddb 100644 --- a/test/js/node/test/parallel/test-fs-utimes.js +++ b/test/js/node/test/parallel/test-fs-utimes.js @@ -63,13 +63,18 @@ function expect_ok(syscall, resource, err, atime, mtime, statSync) { const mtime_diff = check_mtime(resource, mtime, statSync); assert( // Check up to single-second precision. - // Sub-second precision is OS and fs dependant. + // Sub-second precision is OS and fs dependent. !err && (mtime_diff < 2) || err && err.code === 'ENOSYS', `FAILED: expect_ok ${util.inspect(arguments)} check_mtime: ${mtime_diff}` ); } +function getExpectedMtime(mtime) { + // Negative numeric timestamps are normalized to "now" at call time. + return fs._toUnixTimestamp(mtime); +} + const stats = fs.statSync(tmpdir.path); const asPath = (path) => path; @@ -98,11 +103,13 @@ function runTests(iter) { // // test async code paths // + const expectedUtimesMtime = getExpectedMtime(mtime); fs.utimes(pathType(tmpdir.path), atime, mtime, common.mustCall((err) => { - expect_ok('utimes', tmpdir.path, err, atime, mtime); + expect_ok('utimes', tmpdir.path, err, atime, expectedUtimesMtime); + const expectedLutimesMtime = getExpectedMtime(mtime); fs.lutimes(pathType(lpath), atime, mtime, common.mustCall((err) => { - expect_ok('lutimes', lpath, err, atime, mtime, fs.lstatSync); + expect_ok('lutimes', lpath, err, atime, expectedLutimesMtime, fs.lstatSync); fs.utimes(pathType('foobarbaz'), atime, mtime, common.mustCall((err) => { expect_errno('utimes', 'foobarbaz', err, 'ENOENT'); @@ -114,8 +121,9 @@ function runTests(iter) { fd = fs.openSync(tmpdir.path, 'r'); } + const expectedFutimesMtime = getExpectedMtime(mtime); fs.futimes(fd, atime, mtime, common.mustCall((err) => { - expect_ok('futimes', fd, err, atime, mtime); + expect_ok('futimes', fd, err, atime, expectedFutimesMtime); syncTests(); @@ -129,17 +137,20 @@ function runTests(iter) { // test synchronized code paths, these functions throw on failure // function syncTests() { + const expectedUtimesMtime = getExpectedMtime(mtime); fs.utimesSync(pathType(tmpdir.path), atime, mtime); - expect_ok('utimesSync', tmpdir.path, undefined, atime, mtime); + expect_ok('utimesSync', tmpdir.path, undefined, atime, expectedUtimesMtime); + const expectedLutimesMtime = getExpectedMtime(mtime); fs.lutimesSync(pathType(lpath), atime, mtime); - expect_ok('lutimesSync', lpath, undefined, atime, mtime, fs.lstatSync); + expect_ok('lutimesSync', lpath, undefined, atime, expectedLutimesMtime, fs.lstatSync); // Some systems don't have futimes // if there's an error, it should be ENOSYS try { + const expectedFutimesMtime = getExpectedMtime(mtime); fs.futimesSync(fd, atime, mtime); - expect_ok('futimesSync', fd, undefined, atime, mtime); + expect_ok('futimesSync', fd, undefined, atime, expectedFutimesMtime); } catch (ex) { expect_errno('futimesSync', fd, ex, 'ENOSYS'); } diff --git a/test/js/node/test/parallel/test-fs-watch-enoent.js b/test/js/node/test/parallel/test-fs-watch-enoent.js index ef3c6b14008d..e363b3e9325c 100644 --- a/test/js/node/test/parallel/test-fs-watch-enoent.js +++ b/test/js/node/test/parallel/test-fs-watch-enoent.js @@ -12,10 +12,11 @@ const assert = require('assert'); const fs = require('fs'); const tmpdir = require('../common/tmpdir'); const nonexistentFile = tmpdir.resolve('non-existent'); +const { internalBinding } = require('internal/test/binding'); const { UV_ENODEV, UV_ENOENT -} = process.binding('uv'); +} = internalBinding('uv'); tmpdir.refresh(); diff --git a/test/js/node/test/parallel/test-fs-write-stream-flush.js b/test/js/node/test/parallel/test-fs-write-stream-flush.js index 8c1b60edd18f..452dd0a1051a 100644 --- a/test/js/node/test/parallel/test-fs-write-stream-flush.js +++ b/test/js/node/test/parallel/test-fs-write-stream-flush.js @@ -4,7 +4,7 @@ const tmpdir = require('../common/tmpdir'); const assert = require('node:assert'); const fs = require('node:fs'); const fsp = require('node:fs/promises'); -const { test, describe, jest } = require('bun:test'); +const test = require('node:test'); const data = 'foo'; let cnt = 0; @@ -22,10 +22,8 @@ test('validation', () => { } }); -test('performs flush', () => { - jest.restoreAllMocks(); - const { promise, resolve: done } = Promise.withResolvers(); - const spy = jest.spyOn(fs, 'fsync'); +test('performs flush', (t, done) => { + const spy = t.mock.method(fs, 'fsync'); const file = nextFile(); const stream = fs.createWriteStream(file, { flush: true }); @@ -33,21 +31,20 @@ test('performs flush', () => { stream.close(common.mustSucceed(() => { const calls = spy.mock.calls; assert.strictEqual(calls.length, 1); - assert.strictEqual(calls[0].length, 2); - assert.strictEqual(typeof calls[0][0], 'number'); - assert.strictEqual(typeof calls[0][1], 'function'); + assert.strictEqual(calls[0].result, undefined); + assert.strictEqual(calls[0].error, undefined); + assert.strictEqual(calls[0].arguments.length, 2); + assert.strictEqual(typeof calls[0].arguments[0], 'number'); + assert.strictEqual(typeof calls[0].arguments[1], 'function'); assert.strictEqual(fs.readFileSync(file, 'utf8'), data); done(); })); })); - return promise; }); -test('does not perform flush', () => { - jest.restoreAllMocks(); - const { promise, resolve: done } = Promise.withResolvers(); +test('does not perform flush', (t, done) => { const values = [undefined, null, false]; - const spy = jest.spyOn(fs, 'fsync'); + const spy = t.mock.method(fs, 'fsync'); let cnt = 0; for (const flush of values) { @@ -66,7 +63,6 @@ test('does not perform flush', () => { })); })); } - return promise; }); test('works with file handles', async () => { diff --git a/test/js/node/test/parallel/test-global-encoder.js b/test/js/node/test/parallel/test-global-encoder.js index 0e98bc806ca5..f86d0858ccde 100644 --- a/test/js/node/test/parallel/test-global-encoder.js +++ b/test/js/node/test/parallel/test-global-encoder.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -const { strictEqual } = require('assert'); +const assert = require('assert'); const util = require('util'); -strictEqual(TextDecoder, util.TextDecoder); -strictEqual(TextEncoder, util.TextEncoder); +assert.strictEqual(TextDecoder, util.TextDecoder); +assert.strictEqual(TextEncoder, util.TextEncoder); diff --git a/test/js/node/test/parallel/test-http-full-response.js b/test/js/node/test/parallel/test-http-full-response.js index d54743b69194..22693233cf43 100644 --- a/test/js/node/test/parallel/test-http-full-response.js +++ b/test/js/node/test/parallel/test-http-full-response.js @@ -21,7 +21,6 @@ 'use strict'; const common = require('../common'); -if (common.isWindows) return; // TODO: BUN no 'ab' installed const assert = require('assert'); // This test requires the program 'ab' const http = require('http'); @@ -41,7 +40,7 @@ const server = http.createServer(function(req, res) { function runAb(opts, callback) { const command = `ab ${opts} http://127.0.0.1:${server.address().port}/`; - exec(command, function(err, stdout, stderr) { + exec(command, common.mustCall(function(err, stdout, stderr) { if (err) { if (/ab|apr/i.test(stderr)) { common.printSkipMessage(`problem spawning \`ab\`.\n${stderr}`); @@ -63,7 +62,7 @@ function runAb(opts, callback) { assert.strictEqual(completeRequests * documentLength, htmlTransferred); if (callback) callback(); - }); + })); } server.listen(0, common.mustCall(function() { diff --git a/test/js/node/test/parallel/test-icu-stringwidth.js b/test/js/node/test/parallel/test-icu-stringwidth.js index 40ef7a42cd05..66142a8d6811 100644 --- a/test/js/node/test/parallel/test-icu-stringwidth.js +++ b/test/js/node/test/parallel/test-icu-stringwidth.js @@ -51,7 +51,7 @@ assert.strictEqual(getStringWidth(String.fromCharCode(0x20DD)), 0); // these fully. // See https://www.unicode.org/reports/tr51/tr51-16.html#Emoji_ZWJ_Sequences assert.strictEqual(getStringWidth('👩‍👩‍👧‍👧'), 8); -// Upstream note (BridgeAR): This should have a width of two and six. The heart contains +// TODO(BridgeAR): This should have a width of two and six. The heart contains // the \uFE0F variation selector that indicates that it should be displayed as // emoji instead of as text. Emojis are all full width characters when not being // rendered as text. diff --git a/test/js/node/test/parallel/test-kill-segfault-freebsd.js b/test/js/node/test/parallel/test-kill-segfault-freebsd.js index e17b00741bd9..baba07f3f151 100644 --- a/test/js/node/test/parallel/test-kill-segfault-freebsd.js +++ b/test/js/node/test/parallel/test-kill-segfault-freebsd.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); // This test ensures Node.js doesn't crash on hitting Ctrl+C in order to // terminate the currently running process (especially on FreeBSD). @@ -14,6 +14,6 @@ const cp = child_process.spawn(process.execPath, [ 'process.kill(process.pid, "SIGINT")', ]); -cp.on('exit', function(code) { +cp.on('exit', common.mustCall((code) => { assert.notStrictEqual(code, 0); -}); +})); diff --git a/test/js/node/test/parallel/test-listen-fd-detached-inherit.js b/test/js/node/test/parallel/test-listen-fd-detached-inherit.js index 2a8e70f0f942..3c87794d073a 100644 --- a/test/js/node/test/parallel/test-listen-fd-detached-inherit.js +++ b/test/js/node/test/parallel/test-listen-fd-detached-inherit.js @@ -58,12 +58,12 @@ function test() { server: 'localhost', port: child.port, path: '/', - }).on('response', function(res) { + }).on('response', common.mustCall((res) => { let s = ''; res.on('data', function(c) { s += c.toString(); }); - res.on('end', function() { + res.on('end', common.mustCall(() => { // Kill the subprocess before we start doing asserts. // It's really annoying when tests leave orphans! process.kill(child.pid, 'SIGKILL'); @@ -75,8 +75,8 @@ function test() { assert.strictEqual(s, 'hello from child\n'); assert.strictEqual(res.statusCode, 200); - }); - }); + })); + })); } } diff --git a/test/js/node/test/parallel/test-listen-fd-detached.js b/test/js/node/test/parallel/test-listen-fd-detached.js index fba96a112f89..4506bd4ab8f9 100644 --- a/test/js/node/test/parallel/test-listen-fd-detached.js +++ b/test/js/node/test/parallel/test-listen-fd-detached.js @@ -58,12 +58,12 @@ function test() { server: 'localhost', port: child.port, path: '/', - }).on('response', function(res) { + }).on('response', common.mustCall((res) => { let s = ''; res.on('data', function(c) { s += c.toString(); }); - res.on('end', function() { + res.on('end', common.mustCall(() => { // Kill the subprocess before we start doing asserts. // it's really annoying when tests leave orphans! process.kill(child.pid, 'SIGKILL'); @@ -75,8 +75,8 @@ function test() { assert.strictEqual(s, 'hello from child\n'); assert.strictEqual(res.statusCode, 200); - }); - }); + })); + })); } } diff --git a/test/js/node/test/parallel/test-microtask-queue-integration.js b/test/js/node/test/parallel/test-microtask-queue-integration.js index 69d55253a252..79a161dfa7d0 100644 --- a/test/js/node/test/parallel/test-microtask-queue-integration.js +++ b/test/js/node/test/parallel/test-microtask-queue-integration.js @@ -20,11 +20,12 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const implementations = [ function(fn) { + // eslint-disable-next-line node-core/must-call-assert Promise.resolve().then(fn); }, ]; @@ -40,16 +41,16 @@ function test(scheduleMicrotask) { let nextTickCalled = false; expected++; - scheduleMicrotask(function() { + scheduleMicrotask(common.mustCall(() => { process.nextTick(function() { nextTickCalled = true; }); - setTimeout(function() { + setTimeout(common.mustCall(() => { assert(nextTickCalled); done++; - }, 0); - }); + }), 0); + })); } // first tick case diff --git a/test/js/node/test/parallel/test-microtask-queue-run-immediate.js b/test/js/node/test/parallel/test-microtask-queue-run-immediate.js index 577391993bcc..52f4cd5bd7e3 100644 --- a/test/js/node/test/parallel/test-microtask-queue-run-immediate.js +++ b/test/js/node/test/parallel/test-microtask-queue-run-immediate.js @@ -24,6 +24,7 @@ require('../common'); const assert = require('assert'); function enqueueMicrotask(fn) { + // eslint-disable-next-line node-core/must-call-assert Promise.resolve().then(fn); } diff --git a/test/js/node/test/parallel/test-microtask-queue-run.js b/test/js/node/test/parallel/test-microtask-queue-run.js index 5281cb4f3c2e..4d3156affe96 100644 --- a/test/js/node/test/parallel/test-microtask-queue-run.js +++ b/test/js/node/test/parallel/test-microtask-queue-run.js @@ -24,6 +24,7 @@ require('../common'); const assert = require('assert'); function enqueueMicrotask(fn) { + // eslint-disable-next-line node-core/must-call-assert Promise.resolve().then(fn); } diff --git a/test/js/node/test/parallel/test-module-prototype-mutation.js b/test/js/node/test/parallel/test-module-prototype-mutation.js index d0149548600f..6d83533a5ed2 100644 --- a/test/js/node/test/parallel/test-module-prototype-mutation.js +++ b/test/js/node/test/parallel/test-module-prototype-mutation.js @@ -49,4 +49,4 @@ assert.strictEqual( ); import(fixtures.fileURL('es-module-specifiers', 'index.mjs')) - .then(common.mustCall((module) => assert.strictEqual(module.noMain, 'no main field'))); + .then(common.mustCall((module) => { assert.strictEqual(module.noMain, 'no main field'); })); diff --git a/test/js/node/test/parallel/test-module-run-main-monkey-patch.js b/test/js/node/test/parallel/test-module-run-main-monkey-patch.js index c9f189abb688..bafb91ffeffd 100644 --- a/test/js/node/test/parallel/test-module-run-main-monkey-patch.js +++ b/test/js/node/test/parallel/test-module-run-main-monkey-patch.js @@ -4,14 +4,14 @@ // TODO(joyeecheung): This probably should be deprecated. require('../common'); -const { path } = require('../common/fixtures'); +const fixtures = require('../common/fixtures'); const assert = require('assert'); const { spawnSync } = require('child_process'); const child = spawnSync(process.execPath, [ '--require', - path('monkey-patch-run-main.js'), - path('semicolon.js'), + fixtures.path('monkey-patch-run-main.js'), + fixtures.path('semicolon.js'), ]); assert.strictEqual(child.status, 0); diff --git a/test/js/node/test/parallel/test-module-stat.js b/test/js/node/test/parallel/test-module-stat.js index 0ab63f8edf95..a15365b784eb 100644 --- a/test/js/node/test/parallel/test-module-stat.js +++ b/test/js/node/test/parallel/test-module-stat.js @@ -6,7 +6,7 @@ require('../common'); const Module = require('module'); const fs = require('fs'); const tmpdir = require('../common/tmpdir'); -const { ok, strictEqual } = require('assert'); +const assert = require('assert'); const directory = tmpdir.resolve('directory'); const doesNotExist = tmpdir.resolve('does-not-exist'); @@ -16,9 +16,9 @@ tmpdir.refresh(); fs.writeFileSync(file, "module.exports = { a: 'b' }"); fs.mkdirSync(directory); -strictEqual(Module._stat(directory), 1); // Returns 1 for directories. -strictEqual(Module._stat(file), 0); // Returns 0 for files. -ok(Module._stat(doesNotExist) < 0); // Returns a negative integer for any other kind of strings. +assert.strictEqual(Module._stat(directory), 1); // Returns 1 for directories. +assert.strictEqual(Module._stat(file), 0); // Returns 0 for files. +assert.ok(Module._stat(doesNotExist) < 0); // Returns a negative integer for any other kind of strings. // TODO(RaisinTen): Add tests that make sure that Module._stat() does not crash when called // with a non-string data type. It crashes currently. diff --git a/test/js/node/test/parallel/test-net-autoselectfamily-default.js b/test/js/node/test/parallel/test-net-autoselectfamily-default.js index b0b41fb7037d..67977498c5a3 100644 --- a/test/js/node/test/parallel/test-net-autoselectfamily-default.js +++ b/test/js/node/test/parallel/test-net-autoselectfamily-default.js @@ -10,12 +10,12 @@ const autoSelectFamilyAttemptTimeout = common.defaultAutoSelectFamilyAttemptTime // Test that IPV4 is reached by default if IPV6 is not reachable and the default is enabled { - const ipv4Server = createServer((socket) => { + const ipv4Server = createServer(common.mustCall((socket) => { socket.on('data', common.mustCall(() => { socket.write('response-ipv4'); socket.end(); })); - }); + })); ipv4Server.listen(0, '127.0.0.1', common.mustCall(() => { setDefaultAutoSelectFamily(true); @@ -45,12 +45,12 @@ const autoSelectFamilyAttemptTimeout = common.defaultAutoSelectFamilyAttemptTime // Test that IPV4 is not reached by default if IPV6 is not reachable and the default is disabled { - const ipv4Server = createServer((socket) => { + const ipv4Server = createServer(common.mustCallAtLeast((socket) => { socket.on('data', common.mustCall(() => { socket.write('response-ipv4'); socket.end(); })); - }); + }, 0)); ipv4Server.listen(0, '127.0.0.1', common.mustCall(() => { setDefaultAutoSelectFamily(false); diff --git a/test/js/node/test/parallel/test-net-autoselectfamily-ipv4first.js b/test/js/node/test/parallel/test-net-autoselectfamily-ipv4first.js index f94af0d9eeeb..e7e788a0d219 100644 --- a/test/js/node/test/parallel/test-net-autoselectfamily-ipv4first.js +++ b/test/js/node/test/parallel/test-net-autoselectfamily-ipv4first.js @@ -8,12 +8,12 @@ const { createConnection, createServer } = require('net'); // Test that happy eyeballs algorithm is properly implemented when a A record is returned first. if (common.hasIPv6) { - const ipv4Server = createServer((socket) => { + const ipv4Server = createServer(common.mustCall((socket) => { socket.on('data', common.mustCall(() => { socket.write('response-ipv4'); socket.end(); })); - }); + })); const ipv6Server = createServer((socket) => { socket.on('data', common.mustNotCall(() => { diff --git a/test/js/node/test/parallel/test-net-blocklist.js b/test/js/node/test/parallel/test-net-blocklist.js index 901b9a4dfb7b..7048405aa97f 100644 --- a/test/js/node/test/parallel/test-net-blocklist.js +++ b/test/js/node/test/parallel/test-net-blocklist.js @@ -3,7 +3,6 @@ const common = require('../common'); const net = require('net'); const assert = require('assert'); - const blockList = new net.BlockList(); blockList.addAddress('127.0.0.1'); blockList.addAddress('127.0.0.2'); diff --git a/test/js/node/test/parallel/test-net-child-process-connect-reset.js b/test/js/node/test/parallel/test-net-child-process-connect-reset.js index 228ba8ed57fc..ef9245c910ed 100644 --- a/test/js/node/test/parallel/test-net-child-process-connect-reset.js +++ b/test/js/node/test/parallel/test-net-child-process-connect-reset.js @@ -35,10 +35,10 @@ if (process.argv[2] === 'child') { } }); - conn.on('error', (err) => { + conn.on('error', common.mustCallAtLeast((err) => { // Error emitted on Windows. assert.strictEqual(err.code, 'ECONNRESET'); - }); + }, 0)); conn.on('connect', common.mustCall(() => { cp.kill('SIGKILL'); diff --git a/test/js/node/test/parallel/test-net-connect-abort-controller.js b/test/js/node/test/parallel/test-net-connect-abort-controller.js index 9c259cc3fc2c..3d2b19615044 100644 --- a/test/js/node/test/parallel/test-net-connect-abort-controller.js +++ b/test/js/node/test/parallel/test-net-connect-abort-controller.js @@ -3,7 +3,7 @@ const common = require('../common'); const net = require('net'); const assert = require('assert'); const server = net.createServer(); -const { getEventListeners, once } = require('events'); +const { listenerCount, once } = require('events'); const liveConnections = new Set(); @@ -18,20 +18,20 @@ server.listen(0, common.mustCall(async () => { }); }); - const assertAbort = async (socket, testName) => { + const assertAbort = common.mustCallAtLeast(async (socket, testName) => { try { await once(socket, 'close'); assert.fail(`close ${testName} should have thrown`); } catch (err) { assert.strictEqual(err.name, 'AbortError'); } - }; + }); async function postAbort() { const ac = new AbortController(); const { signal } = ac; const socket = net.connect(socketOptions(signal)); - assert.strictEqual(getEventListeners(signal, 'abort').length, 1); + assert.strictEqual(listenerCount(signal, 'abort'), 1); ac.abort(); await assertAbort(socket, 'postAbort'); } @@ -41,7 +41,7 @@ server.listen(0, common.mustCall(async () => { const { signal } = ac; ac.abort(); const socket = net.connect(socketOptions(signal)); - assert.strictEqual(getEventListeners(signal, 'abort').length, 0); + assert.strictEqual(listenerCount(signal, 'abort'), 0); await assertAbort(socket, 'preAbort'); } @@ -50,7 +50,7 @@ server.listen(0, common.mustCall(async () => { const { signal } = ac; setImmediate(() => ac.abort()); const socket = net.connect(socketOptions(signal)); - assert.strictEqual(getEventListeners(signal, 'abort').length, 1); + assert.strictEqual(listenerCount(signal, 'abort'), 1); await assertAbort(socket, 'tickAbort'); } @@ -59,7 +59,7 @@ server.listen(0, common.mustCall(async () => { const { signal } = ac; ac.abort(); const socket = new net.Socket(socketOptions(signal)); - assert.strictEqual(getEventListeners(signal, 'abort').length, 0); + assert.strictEqual(listenerCount(signal, 'abort'), 0); await assertAbort(socket, 'testConstructor'); } @@ -67,7 +67,7 @@ server.listen(0, common.mustCall(async () => { const ac = new AbortController(); const { signal } = ac; const socket = new net.Socket(socketOptions(signal)); - assert.strictEqual(getEventListeners(signal, 'abort').length, 1); + assert.strictEqual(listenerCount(signal, 'abort'), 1); ac.abort(); await assertAbort(socket, 'testConstructorPost'); } @@ -76,7 +76,7 @@ server.listen(0, common.mustCall(async () => { const ac = new AbortController(); const { signal } = ac; const socket = new net.Socket(socketOptions(signal)); - assert.strictEqual(getEventListeners(signal, 'abort').length, 1); + assert.strictEqual(listenerCount(signal, 'abort'), 1); setImmediate(() => ac.abort()); await assertAbort(socket, 'testConstructorPostTick'); } diff --git a/test/js/node/test/parallel/test-net-connect-nodelay.js b/test/js/node/test/parallel/test-net-connect-nodelay.js index 6810e339e2b6..ede4ae480534 100644 --- a/test/js/node/test/parallel/test-net-connect-nodelay.js +++ b/test/js/node/test/parallel/test-net-connect-nodelay.js @@ -6,9 +6,6 @@ const net = require('net'); const truthyValues = [true, 1, 'true', {}, []]; const falseyValues = [false, 0, '']; -const genSetNoDelay = (desiredArg) => (enable) => { - assert.strictEqual(enable, desiredArg); -}; for (const value of truthyValues) { const server = net.createServer(); @@ -21,7 +18,9 @@ for (const value of truthyValues) { common.mustCall(() => client.end()) ); - client._handle.setNoDelay = common.mustCall(genSetNoDelay(true)); + client._handle.setNoDelay = common.mustCall((enable) => { + assert.strictEqual(enable, true); + }); client.on('end', common.mustCall(function() { server.close(); diff --git a/test/js/node/test/parallel/test-net-connect-options-invalid.js b/test/js/node/test/parallel/test-net-connect-options-invalid.js index 53ce89cac9aa..3c748b151610 100644 --- a/test/js/node/test/parallel/test-net-connect-options-invalid.js +++ b/test/js/node/test/parallel/test-net-connect-options-invalid.js @@ -35,6 +35,5 @@ const net = require('net'); }, { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', - message: 'The "options.host" property must be of type string. Received an instance of Array', }); } diff --git a/test/js/node/test/parallel/test-net-connect-options-ipv6.js b/test/js/node/test/parallel/test-net-connect-options-ipv6.js index 13381074ba46..610760851500 100644 --- a/test/js/node/test/parallel/test-net-connect-options-ipv6.js +++ b/test/js/node/test/parallel/test-net-connect-options-ipv6.js @@ -32,11 +32,11 @@ const net = require('net'); const hostAddrIPv6 = '::1'; const HOSTNAME = 'dummy'; -const server = net.createServer({ allowHalfOpen: true }, (socket) => { +const server = net.createServer({ allowHalfOpen: true }, common.mustCall((socket) => { socket.resume(); socket.on('end', common.mustCall()); socket.end(); -}); +})); function tryConnect() { const connectOpt = { @@ -51,17 +51,17 @@ function tryConnect() { }) }; // No `mustCall`, since test could skip, and it's the only path to `close`. - const client = net.connect(connectOpt, () => { + const client = net.connect(connectOpt, common.mustCall(() => { client.resume(); - client.on('end', () => { + client.on('end', common.mustCall(() => { // Wait for next uv tick and make sure the socket stream is writable. - setTimeout(function() { + setTimeout(common.mustCall(() => { assert(client.writable); client.end(); - }, 10); - }); + }), 10); + })); client.on('close', () => server.close()); - }); + })); } server.listen(0, hostAddrIPv6, tryConnect); diff --git a/test/js/node/test/parallel/test-net-connect-options-port.js b/test/js/node/test/parallel/test-net-connect-options-port.js index b62fe9457842..c46dbb88aa51 100644 --- a/test/js/node/test/parallel/test-net-connect-options-port.js +++ b/test/js/node/test/parallel/test-net-connect-options-port.js @@ -171,7 +171,7 @@ function syncFailToConnect(port, assertErr, optOnly) { } function canConnect(port) { - const noop = () => common.mustCall(); + const noop = common.mustCallAtLeast(() => common.mustCall()); const family = 4; // connect(port, cb) and connect(port) @@ -202,10 +202,10 @@ function canConnect(port) { } function asyncFailToConnect(port) { - const onError = () => common.mustCall((err) => { + const onError = common.mustCallAtLeast(() => common.mustCall((err) => { const regexp = /^Error: connect E\w+.+$/; assert.match(String(err), regexp); - }); + })); const dont = () => common.mustNotCall(); const family = 4; diff --git a/test/js/node/test/parallel/test-net-eaddrinuse.js b/test/js/node/test/parallel/test-net-eaddrinuse.js index 8bd790158e36..dd13ed1ee466 100644 --- a/test/js/node/test/parallel/test-net-eaddrinuse.js +++ b/test/js/node/test/parallel/test-net-eaddrinuse.js @@ -27,9 +27,9 @@ const net = require('net'); const server1 = net.createServer(common.mustNotCall()); const server2 = net.createServer(common.mustNotCall()); server1.listen(0, common.mustCall(function() { - server2.on('error', function(error) { - assert.strictEqual(error.code === 'EADDRINUSE', true); + server2.on('error', common.mustCall((error) => { + assert.strictEqual(error.message.includes('EADDRINUSE'), true); server1.close(); - }); + })); server2.listen(this.address().port); })); diff --git a/test/js/node/test/parallel/test-net-keepalive.js b/test/js/node/test/parallel/test-net-keepalive.js index d91ec625f882..26a4c5b3d648 100644 --- a/test/js/node/test/parallel/test-net-keepalive.js +++ b/test/js/node/test/parallel/test-net-keepalive.js @@ -26,7 +26,7 @@ const net = require('net'); let serverConnection; let clientConnection; -const echoServer = net.createServer(function(connection) { +const echoServer = net.createServer(common.mustCall((connection) => { serverConnection = connection; setTimeout(common.mustCall(function() { // Make sure both connections are still open @@ -43,7 +43,7 @@ const echoServer = net.createServer(function(connection) { connection.on('end', function() { connection.end(); }); -}); +})); echoServer.listen(0); echoServer.on('listening', function() { diff --git a/test/js/node/test/parallel/test-net-listen-exclusive-random-ports.js b/test/js/node/test/parallel/test-net-listen-exclusive-random-ports.js index 66dfb598204e..3604e2481ccd 100644 --- a/test/js/node/test/parallel/test-net-listen-exclusive-random-ports.js +++ b/test/js/node/test/parallel/test-net-listen-exclusive-random-ports.js @@ -1,6 +1,6 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const cluster = require('cluster'); const net = require('net'); @@ -8,19 +8,19 @@ const net = require('net'); if (cluster.isPrimary) { const worker1 = cluster.fork(); - worker1.on('message', function(port1) { + worker1.on('message', common.mustCall((port1) => { assert.strictEqual(port1, port1 | 0, `first worker could not listen on port ${port1}`); const worker2 = cluster.fork(); - worker2.on('message', function(port2) { + worker2.on('message', common.mustCall((port2) => { assert.strictEqual(port2, port2 | 0, `second worker could not listen on port ${port2}`); - assert.notStrictEqual(port1, port2, 'ports should not be equal'); + assert.notStrictEqual(port1, port2); worker1.kill(); worker2.kill(); - }); - }); + })); + })); } else { const server = net.createServer(() => {}); diff --git a/test/js/node/test/parallel/test-net-listen-invalid-port.js b/test/js/node/test/parallel/test-net-listen-invalid-port.js index 844878036646..220ca2ba30b0 100644 --- a/test/js/node/test/parallel/test-net-listen-invalid-port.js +++ b/test/js/node/test/parallel/test-net-listen-invalid-port.js @@ -10,13 +10,13 @@ const net = require('net'); const invalidPort = -1 >>> 0; -net.Server().listen(0, function() { +net.Server().listen(0, common.mustCall(function() { const address = this.address(); const key = `${address.family.slice(-1)}:${address.address}:0`; assert.strictEqual(this._connectionKey, key); this.close(); -}); +})); // The first argument is a configuration object assert.throws(() => { diff --git a/test/js/node/test/parallel/test-net-localerror.js b/test/js/node/test/parallel/test-net-localerror.js index 92095340512d..ab31c992556e 100644 --- a/test/js/node/test/parallel/test-net-localerror.js +++ b/test/js/node/test/parallel/test-net-localerror.js @@ -20,16 +20,16 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const net = require('net'); -const connect = (opts, code, type) => { +const connect = common.mustCall((opts, code, type) => { assert.throws( () => net.connect(opts), { code, name: type.name } ); -}; +}, 2); connect({ host: 'localhost', diff --git a/test/js/node/test/parallel/test-net-persistent-keepalive.js b/test/js/node/test/parallel/test-net-persistent-keepalive.js index b25162996e1b..8caf640a4bbe 100644 --- a/test/js/node/test/parallel/test-net-persistent-keepalive.js +++ b/test/js/node/test/parallel/test-net-persistent-keepalive.js @@ -1,29 +1,29 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const net = require('net'); let serverConnection; let clientConnection; -const echoServer = net.createServer(function(connection) { +const echoServer = net.createServer(common.mustCall((connection) => { serverConnection = connection; - setTimeout(function() { + setTimeout(common.mustCall(() => { // Make sure both connections are still open assert.strictEqual(serverConnection.readyState, 'open'); assert.strictEqual(clientConnection.readyState, 'open'); serverConnection.end(); clientConnection.end(); echoServer.close(); - }, 600); + }), 600); connection.setTimeout(0); assert.strictEqual(typeof connection.setKeepAlive, 'function'); connection.on('end', function() { connection.end(); }); -}); +})); echoServer.listen(0); -echoServer.on('listening', function() { +echoServer.on('listening', common.mustCall(function() { clientConnection = new net.Socket(); // Send a keepalive packet after 1000 ms // and make sure it persists @@ -31,4 +31,4 @@ echoServer.on('listening', function() { assert.ok(s instanceof net.Socket); clientConnection.connect(this.address().port); clientConnection.setTimeout(0); -}); +})); diff --git a/test/js/node/test/parallel/test-net-pipe-connect-errors.js b/test/js/node/test/parallel/test-net-pipe-connect-errors.js index fec4259b348d..33dc6a8a23b5 100644 --- a/test/js/node/test/parallel/test-net-pipe-connect-errors.js +++ b/test/js/node/test/parallel/test-net-pipe-connect-errors.js @@ -24,6 +24,7 @@ const common = require('../common'); const fixtures = require('../common/fixtures'); const fs = require('fs'); const net = require('net'); +const path = require('path'); const assert = require('assert'); // Test if ENOTSOCK is fired when trying to connect to a file which is not @@ -38,11 +39,11 @@ if (common.isWindows) { } else { const tmpdir = require('../common/tmpdir'); tmpdir.refresh(); - // Keep the file name very short so that we don't exceed the 108 char limit - // on CI for a POSIX socket. Even though this isn't actually a socket file, - // the error will be different from the one we are expecting if we exceed the - // limit. - emptyTxt = `${tmpdir.path}0.txt`; + // Use a short relative path so that we don't exceed the 108 byte limit for + // Unix socket paths in long or multibyte CI workspaces. Even though this + // isn't actually a socket file, the error will be different from the one we + // are expecting if the path is too long. + emptyTxt = path.join(path.relative(process.cwd(), tmpdir.path), '0.txt'); function cleanup() { try { diff --git a/test/js/node/test/parallel/test-net-reconnect.js b/test/js/node/test/parallel/test-net-reconnect.js index 233f5b01e544..2f7de82eb442 100644 --- a/test/js/node/test/parallel/test-net-reconnect.js +++ b/test/js/node/test/parallel/test-net-reconnect.js @@ -20,7 +20,7 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const net = require('net'); @@ -30,7 +30,7 @@ let client_recv_count = 0; let client_end_count = 0; let disconnect_count = 0; -const server = net.createServer(function(socket) { +const server = net.createServer(common.mustCallAtLeast((socket) => { console.error('SERVER: got socket connection'); socket.resume(); @@ -42,13 +42,13 @@ const server = net.createServer(function(socket) { socket.end(); }); - socket.on('close', (had_error) => { + socket.on('close', common.mustCall((had_error) => { console.log(`SERVER had_error: ${JSON.stringify(had_error)}`); assert.strictEqual(had_error, false); - }); -}); + })); +})); -server.listen(0, function() { +server.listen(0, common.mustCall(function() { console.log('SERVER listening'); const client = net.createConnection(this.address().port); @@ -58,28 +58,28 @@ server.listen(0, function() { console.error('CLIENT connected', client._writableState); }); - client.on('data', function(chunk) { + client.on('data', common.mustCallAtLeast((chunk) => { client_recv_count += 1; console.log(`client_recv_count ${client_recv_count}`); assert.strictEqual(chunk, 'hello\r\n'); console.error('CLIENT: calling end', client._writableState); client.end(); - }); + })); client.on('end', () => { console.error('CLIENT end'); client_end_count++; }); - client.on('close', (had_error) => { + client.on('close', common.mustCallAtLeast((had_error) => { console.log('CLIENT disconnect'); assert.strictEqual(had_error, false); if (disconnect_count++ < N) client.connect(server.address().port); // reconnect else server.close(); - }); -}); + })); +})); process.on('exit', () => { assert.strictEqual(disconnect_count, N + 1); diff --git a/test/js/node/test/parallel/test-net-remote-address-port.js b/test/js/node/test/parallel/test-net-remote-address-port.js index 615f22979c2f..7a3561950146 100644 --- a/test/js/node/test/parallel/test-net-remote-address-port.js +++ b/test/js/node/test/parallel/test-net-remote-address-port.js @@ -43,14 +43,14 @@ const server = net.createServer(common.mustCall(function(socket) { socket.on('end', function() { if (++conns_closed === 2) server.close(); }); - socket.on('close', function() { + socket.on('close', common.mustCall(() => { assert.ok(remoteAddrCandidates.includes(socket.remoteAddress)); assert.ok(remoteFamilyCandidates.includes(socket.remoteFamily)); - }); + })); socket.resume(); }, 2)); -server.listen(0, function() { +server.listen(0, common.mustCall(function() { const client = net.createConnection(this.address().port, '127.0.0.1'); const client2 = net.createConnection(this.address().port); @@ -61,24 +61,24 @@ server.listen(0, function() { assert.strictEqual(client2.remoteFamily, undefined); assert.strictEqual(client2.remotePort, undefined); - client.on('connect', function() { + client.on('connect', common.mustCall(() => { assert.ok(remoteAddrCandidates.includes(client.remoteAddress)); assert.ok(remoteFamilyCandidates.includes(client.remoteFamily)); assert.strictEqual(client.remotePort, server.address().port); client.end(); - }); - client.on('close', function() { + })); + client.on('close', common.mustCall(() => { assert.ok(remoteAddrCandidates.includes(client.remoteAddress)); assert.ok(remoteFamilyCandidates.includes(client.remoteFamily)); - }); - client2.on('connect', function() { + })); + client2.on('connect', common.mustCall(() => { assert.ok(remoteAddrCandidates.includes(client2.remoteAddress)); assert.ok(remoteFamilyCandidates.includes(client2.remoteFamily)); assert.strictEqual(client2.remotePort, server.address().port); client2.end(); - }); - client2.on('close', function() { + })); + client2.on('close', common.mustCall(() => { assert.ok(remoteAddrCandidates.includes(client2.remoteAddress)); assert.ok(remoteFamilyCandidates.includes(client2.remoteFamily)); - }); -}); + })); +})); diff --git a/test/js/node/test/parallel/test-net-remote-address.js b/test/js/node/test/parallel/test-net-remote-address.js index a116cb99d3bc..904e8dcccb56 100644 --- a/test/js/node/test/parallel/test-net-remote-address.js +++ b/test/js/node/test/parallel/test-net-remote-address.js @@ -2,18 +2,18 @@ const common = require('../common'); const net = require('net'); -const { strictEqual } = require('assert'); +const assert = require('assert'); const server = net.createServer(); server.listen(common.mustCall(function() { const socket = net.connect({ port: server.address().port }); - strictEqual(socket.connecting, true); - strictEqual(socket.remoteAddress, undefined); + assert.strictEqual(socket.connecting, true); + assert.strictEqual(socket.remoteAddress, undefined); socket.on('connect', common.mustCall(function() { - strictEqual(socket.remoteAddress !== undefined, true); + assert.strictEqual(socket.remoteAddress !== undefined, true); socket.end(); })); diff --git a/test/js/node/test/parallel/test-net-server-close.js b/test/js/node/test/parallel/test-net-server-close.js index 8291f70432ec..ff08150bbf17 100644 --- a/test/js/node/test/parallel/test-net-server-close.js +++ b/test/js/node/test/parallel/test-net-server-close.js @@ -26,7 +26,7 @@ const net = require('net'); const sockets = []; -const server = net.createServer(function(c) { +const server = net.createServer(common.mustCallAtLeast((c) => { c.on('close', common.mustCall()); sockets.push(c); @@ -35,7 +35,7 @@ const server = net.createServer(function(c) { assert.strictEqual(server.close(), server); sockets.forEach((c) => c.destroy()); } -}); +})); server.on('close', common.mustCall()); diff --git a/test/js/node/test/parallel/test-net-server-listen-remove-callback.js b/test/js/node/test/parallel/test-net-server-listen-remove-callback.js index a874099fb8c7..87bd7448aef1 100644 --- a/test/js/node/test/parallel/test-net-server-listen-remove-callback.js +++ b/test/js/node/test/parallel/test-net-server-listen-remove-callback.js @@ -20,18 +20,18 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const net = require('net'); // Server should only fire listen callback once const server = net.createServer(); -server.on('close', function() { +server.on('close', common.mustCall(() => { const listeners = server.listeners('listening'); console.log('Closed, listeners:', listeners.length); assert.strictEqual(listeners.length, 0); -}); +}, 2)); server.listen(0, function() { server.close(); diff --git a/test/js/node/test/parallel/test-net-server-max-connections-close-makes-more-available.js b/test/js/node/test/parallel/test-net-server-max-connections-close-makes-more-available.js index f607f28c10ea..408fb4a01ee3 100644 --- a/test/js/node/test/parallel/test-net-server-max-connections-close-makes-more-available.js +++ b/test/js/node/test/parallel/test-net-server-max-connections-close-makes-more-available.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const net = require('net'); @@ -28,10 +28,10 @@ function createConnection(index) { sent.push(msg); }); - connection.on('error', function(err) { + connection.on('error', common.mustCallAtLeast((err) => { assert.strictEqual(err.code, 'ECONNRESET'); resolve(); - }); + }, 0)); connection.on('data', function(e) { console.error(`connection ${index} received response`); @@ -67,15 +67,16 @@ const server = net.createServer(function(socket) { server.maxConnections = 1; -server.listen(0, function() { +server.listen(0, common.mustCall(() => { createConnection(0) .then(createConnection.bind(null, 1)) .then(closeConnection.bind(null, 0)) .then(createConnection.bind(null, 2)) .then(createConnection.bind(null, 3)) .then(server.close.bind(server)) - .then(closeConnection.bind(null, 2)); -}); + .then(closeConnection.bind(null, 2)) + .then(common.mustCall()); +})); process.on('exit', function() { // Confirm that all connections tried to send data... diff --git a/test/js/node/test/parallel/test-net-server-max-connections.js b/test/js/node/test/parallel/test-net-server-max-connections.js index ea9a8d29e9f1..4e347de7892c 100644 --- a/test/js/node/test/parallel/test-net-server-max-connections.js +++ b/test/js/node/test/parallel/test-net-server-max-connections.js @@ -49,12 +49,12 @@ function makeConnection(index) { const c = net.createConnection(server.address().port); let gotData = false; - c.on('connect', function() { + c.on('connect', common.mustCall(() => { if (index + 1 < N) { makeConnection(index + 1); } - c.on('close', function() { + c.on('close', common.mustCall(() => { console.error(`closed ${index}`); closes++; @@ -81,15 +81,15 @@ function makeConnection(index) { assert.strictEqual(gotData, false, `${index} got data, but shouldn't have`); } - }); - }); + })); + })); c.on('end', function() { c.end(); }); - c.on('data', function(b) { + c.on('data', common.mustCallAtLeast((b) => { gotData = true; assert.ok(b.length > 0); - }); + }, 0)); c.on('error', function(e) { // Retry if SmartOS and ECONNREFUSED. See diff --git a/test/js/node/test/parallel/test-net-server-pause-on-connect.js b/test/js/node/test/parallel/test-net-server-pause-on-connect.js index 59c39e8816cc..51bdec9ac641 100644 --- a/test/js/node/test/parallel/test-net-server-pause-on-connect.js +++ b/test/js/node/test/parallel/test-net-server-pause-on-connect.js @@ -28,8 +28,8 @@ let stopped = true; let server1Sock; -const server1ConnHandler = (socket) => { - socket.on('data', function(data) { +const server1ConnHandler = common.mustCall((socket) => { + socket.on('data', common.mustCall((data) => { if (stopped) { assert.fail('data event should not have happened yet'); } @@ -37,15 +37,15 @@ const server1ConnHandler = (socket) => { assert.strictEqual(data.toString(), msg); socket.end(); server1.close(); - }); + })); server1Sock = socket; -}; +}); const server1 = net.createServer({ pauseOnConnect: true }, server1ConnHandler); -const server2ConnHandler = (socket) => { - socket.on('data', function(data) { +const server2ConnHandler = common.mustCall((socket) => { + socket.on('data', common.mustCall((data) => { assert.strictEqual(data.toString(), msg); socket.end(); server2.close(); @@ -53,19 +53,19 @@ const server2ConnHandler = (socket) => { assert.strictEqual(server1Sock.bytesRead, 0); server1Sock.resume(); stopped = false; - }); -}; + })); +}); const server2 = net.createServer({ pauseOnConnect: false }, server2ConnHandler); -server1.listen(0, function() { +server1.listen(0, common.mustCall(function() { const clientHandler = common.mustCall(function() { server2.listen(0, function() { net.createConnection({ port: this.address().port }).write(msg); }); }); net.createConnection({ port: this.address().port }).write(msg, clientHandler); -}); +})); process.on('exit', function() { assert.strictEqual(stopped, false); diff --git a/test/js/node/test/parallel/test-net-settimeout.js b/test/js/node/test/parallel/test-net-settimeout.js index 581e27ec327d..5662a5cc4140 100644 --- a/test/js/node/test/parallel/test-net-settimeout.js +++ b/test/js/node/test/parallel/test-net-settimeout.js @@ -33,7 +33,7 @@ const server = net.createServer(common.mustCall((c) => { c.write('hello'); })); -server.listen(0, function() { +server.listen(0, common.mustCall(function() { const socket = net.createConnection(this.address().port, 'localhost'); const s = socket.setTimeout(T, common.mustNotCall()); @@ -47,4 +47,4 @@ server.listen(0, function() { })); socket.setTimeout(0); -}); +})); diff --git a/test/js/node/test/parallel/test-net-socket-close-after-end.js b/test/js/node/test/parallel/test-net-socket-close-after-end.js index 06bf55f89d6e..4b86849c1e83 100644 --- a/test/js/node/test/parallel/test-net-socket-close-after-end.js +++ b/test/js/node/test/parallel/test-net-socket-close-after-end.js @@ -6,7 +6,7 @@ const net = require('net'); const server = net.createServer(); -server.on('connection', (socket) => { +server.on('connection', common.mustCall((socket) => { let endEmitted = false; socket.once('readable', () => { @@ -17,12 +17,12 @@ server.on('connection', (socket) => { socket.on('end', () => { endEmitted = true; }); - socket.on('close', () => { + socket.on('close', common.mustCall(() => { assert(endEmitted); server.close(); - }); + })); socket.end('foo'); -}); +})); server.listen(common.mustCall(() => { const socket = net.createConnection(server.address().port, () => { diff --git a/test/js/node/test/parallel/test-net-socket-connecting.js b/test/js/node/test/parallel/test-net-socket-connecting.js index 21aa261192c1..222361a8843e 100644 --- a/test/js/node/test/parallel/test-net-socket-connecting.js +++ b/test/js/node/test/parallel/test-net-socket-connecting.js @@ -1,21 +1,21 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const net = require('net'); const server = net.createServer((conn) => { conn.end(); server.close(); -}).listen(0, () => { - const client = net.connect(server.address().port, () => { +}).listen(0, common.mustCall(() => { + const client = net.connect(server.address().port, common.mustCall(() => { assert.strictEqual(client.connecting, false); // Legacy getter assert.strictEqual(client._connecting, false); client.end(); - }); + })); assert.strictEqual(client.connecting, true); // Legacy getter assert.strictEqual(client._connecting, true); -}); +})); diff --git a/test/js/node/test/parallel/test-net-socket-no-halfopen-enforcer.js b/test/js/node/test/parallel/test-net-socket-no-halfopen-enforcer.js index 3df5b6d7b9c8..69ebd694e8fa 100644 --- a/test/js/node/test/parallel/test-net-socket-no-halfopen-enforcer.js +++ b/test/js/node/test/parallel/test-net-socket-no-halfopen-enforcer.js @@ -5,7 +5,7 @@ require('../common'); // enforcer from `stream.Duplex`. const { Socket } = require('net'); -const { strictEqual } = require('assert'); +const assert = require('assert'); const socket = new Socket({ allowHalfOpen: false }); -strictEqual(socket.listenerCount('end'), 1); +assert.strictEqual(socket.listenerCount('end'), 1); diff --git a/test/js/node/test/parallel/test-net-socket-write-error.js b/test/js/node/test/parallel/test-net-socket-write-error.js index e68db68c0d49..c181c9ce9011 100644 --- a/test/js/node/test/parallel/test-net-socket-write-error.js +++ b/test/js/node/test/parallel/test-net-socket-write-error.js @@ -7,7 +7,7 @@ const assert = require('assert'); const server = net.createServer().listen(0, connectToServer); function connectToServer() { - const client = net.createConnection(this.address().port, () => { + const client = net.createConnection(this.address().port, common.mustCall(() => { client.on('error', common.mustNotCall()); assert.throws(() => { client.write(1337); @@ -17,6 +17,6 @@ function connectToServer() { }); client.destroy(); - }) + })) .on('close', () => server.close()); } diff --git a/test/js/node/test/parallel/test-net-sync-cork.js b/test/js/node/test/parallel/test-net-sync-cork.js index 447f42ca91e7..49f68960ce63 100644 --- a/test/js/node/test/parallel/test-net-sync-cork.js +++ b/test/js/node/test/parallel/test-net-sync-cork.js @@ -9,10 +9,10 @@ const server = net.createServer(handle); const N = 100; const buf = Buffer.alloc(2, 'a'); -server.listen(0, function() { +server.listen(0, common.mustCall(function() { const conn = net.connect(this.address().port); - conn.on('connect', () => { + conn.on('connect', common.mustCall(() => { let res = true; let i = 0; for (; i < N && res; i++) { @@ -23,8 +23,8 @@ server.listen(0, function() { } assert.strictEqual(i, N); conn.end(); - }); -}); + })); +})); function handle(socket) { socket.resume(); diff --git a/test/js/node/test/parallel/test-net-throttle.js b/test/js/node/test/parallel/test-net-throttle.js index fd9e2be9aece..c9128ff85714 100644 --- a/test/js/node/test/parallel/test-net-throttle.js +++ b/test/js/node/test/parallel/test-net-throttle.js @@ -20,7 +20,7 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const net = require('net'); const debuglog = require('util').debuglog('test'); @@ -29,7 +29,7 @@ let chars_recved = 0; let npauses = 0; let totalLength = 0; -const server = net.createServer((connection) => { +const server = net.createServer(common.mustCallAtLeast((connection) => { const body = 'C'.repeat(1024); let n = 1; debuglog('starting write loop'); @@ -49,15 +49,15 @@ const server = net.createServer((connection) => { `writableLength: ${connection.writableLength}, totalLength: ${totalLength}`, ); connection.end(); -}); +})); -server.listen(0, () => { +server.listen(0, common.mustCall(() => { const port = server.address().port; debuglog(`server started on port ${port}`); let paused = false; const client = net.createConnection(port); client.setEncoding('ascii'); - client.on('data', (d) => { + client.on('data', common.mustCallAtLeast((d) => { chars_recved += d.length; debuglog(`got ${chars_recved}`); if (!paused) { @@ -66,20 +66,20 @@ server.listen(0, () => { paused = true; debuglog('pause'); const x = chars_recved; - setTimeout(() => { + setTimeout(common.mustCall(() => { assert.strictEqual(chars_recved, x); client.resume(); debuglog('resume'); paused = false; - }, 100); + }), 100); } - }); + })); client.on('end', () => { server.close(); client.end(); }); -}); +})); process.on('exit', () => { diff --git a/test/js/node/test/parallel/test-next-tick-errors.js b/test/js/node/test/parallel/test-next-tick-errors.js index 6fd079625afa..28df53c8bfc2 100644 --- a/test/js/node/test/parallel/test-next-tick-errors.js +++ b/test/js/node/test/parallel/test-next-tick-errors.js @@ -20,7 +20,7 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const order = []; @@ -57,7 +57,7 @@ testNextTickWith('str'); testNextTickWith({}); testNextTickWith([]); -process.on('uncaughtException', function(err, errorOrigin) { +process.on('uncaughtException', common.mustCall((err, errorOrigin) => { assert.strictEqual(errorOrigin, 'uncaughtException'); if (!exceptionHandled) { @@ -67,7 +67,7 @@ process.on('uncaughtException', function(err, errorOrigin) { // If we get here then the first process.nextTick got called twice order.push('OOPS!'); } -}); +})); process.on('exit', function() { assert.deepStrictEqual(order, ['A', 'B', 'C']); diff --git a/test/js/node/test/parallel/test-next-tick-fixed-queue-regression.js b/test/js/node/test/parallel/test-next-tick-fixed-queue-regression.js index 1fe82d02b109..82e04e371a72 100644 --- a/test/js/node/test/parallel/test-next-tick-fixed-queue-regression.js +++ b/test/js/node/test/parallel/test-next-tick-fixed-queue-regression.js @@ -14,5 +14,5 @@ process.nextTick(() => { process.nextTick(common.mustCall()); const immediate = setImmediate(common.mustNotCall()); process.nextTick(common.mustCall(() => clearImmediate(immediate))); - }); + }).then(common.mustCall()); }); diff --git a/test/js/node/test/parallel/test-os.js b/test/js/node/test/parallel/test-os.js index 3d9fe5c1a60e..f15499d692e1 100644 --- a/test/js/node/test/parallel/test-os.js +++ b/test/js/node/test/parallel/test-os.js @@ -27,16 +27,16 @@ const path = require('path'); const { inspect } = require('util'); const is = { - number: (value, key) => { + number: common.mustCallAtLeast((value, key) => { assert(!Number.isNaN(value), `${key} should not be NaN`); assert.strictEqual(typeof value, 'number'); - }, - string: (value) => { assert.strictEqual(typeof value, 'string'); }, - array: (value) => { assert.ok(Array.isArray(value)); }, - object: (value) => { + }), + string: common.mustCallAtLeast((value) => { assert.strictEqual(typeof value, 'string'); }), + array: common.mustCallAtLeast((value) => { assert.ok(Array.isArray(value)); }), + object: common.mustCallAtLeast((value) => { assert.strictEqual(typeof value, 'object'); assert.notStrictEqual(value, null); - } + }), }; process.env.TMPDIR = '/tmpdir'; @@ -181,15 +181,13 @@ const netmaskToCIDRSuffixMap = new Map(Object.entries({ 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff': 128 })); -Object.values(interfaces) - .flat(Infinity) - .map((v) => ({ v, mask: netmaskToCIDRSuffixMap.get(v.netmask) })) - .forEach(({ v, mask }) => { - assert.ok('cidr' in v, `"cidr" prop not found in ${inspect(v)}`); - if (mask) { - assert.strictEqual(v.cidr, `${v.address}/${mask}`); - } - }); +for (const v of Object.values(interfaces).flat(Infinity)) { + assert.ok('cidr' in v, `"cidr" prop not found in ${inspect(v)}`); + const mask = netmaskToCIDRSuffixMap.get(v.netmask); + if (mask) { + assert.strictEqual(v.cidr, `${v.address}/${mask}`); + } +} const EOL = os.EOL; if (common.isWindows) { diff --git a/test/js/node/test/parallel/test-performance-measure.js b/test/js/node/test/parallel/test-performance-measure.js index 949258f96e1b..443dd90ca9bb 100644 --- a/test/js/node/test/parallel/test-performance-measure.js +++ b/test/js/node/test/parallel/test-performance-measure.js @@ -9,10 +9,10 @@ const ALLOWED_MARGIN = 10; const expected = ['Start to Now', 'A to Now', 'A to B']; const obs = new PerformanceObserver(common.mustCall((items) => { - items.getEntries().forEach(({ name, duration }) => { + for (const { name, duration } of items.getEntries()) { assert.ok(duration > (DELAY - ALLOWED_MARGIN)); assert.strictEqual(expected.shift(), name); - }); + } })); obs.observe({ entryTypes: ['measure'] }); diff --git a/test/js/node/test/parallel/test-permission-fs-supported.js b/test/js/node/test/parallel/test-permission-fs-supported.js index bf5127efd91a..0c0da9500f25 100644 --- a/test/js/node/test/parallel/test-permission-fs-supported.js +++ b/test/js/node/test/parallel/test-permission-fs-supported.js @@ -82,7 +82,22 @@ const ignoreList = [ 'unwatchFile', ...syncAndAsyncAPI('lstat'), ...syncAndAsyncAPI('realpath'), - // fd required methods + // File descriptor–based metadata operations + // + // The kernel does not allow opening a file descriptor for an inode + // with write access if the inode itself is read-only. However, it still + // permits modifying the inode’s metadata (e.g., permission bits, ownership, + // timestamps) because you own the file. These changes can be made either + // by referring to the file by name (e.g., chmod) or through any existing + // file descriptor that identifies the same inode (e.g., fchmod). + // + // If the kernel required write access to change metadata, it would be + // impossible to modify the permissions of a file once it was made read-only. + // For that reason, syscalls such as fchmod, fchown, and futimes bypass + // the file descriptor’s access mode. Even a read-only ('r') descriptor + // can still update metadata. To prevent unintended modifications, + // these APIs are therefore blocked by default when permission model is + // enabled. ...syncAndAsyncAPI('close'), ...syncAndAsyncAPI('fchown'), ...syncAndAsyncAPI('fchmod'), diff --git a/test/js/node/test/parallel/test-pipe-address.js b/test/js/node/test/parallel/test-pipe-address.js index 77ada78670de..3550434932e9 100644 --- a/test/js/node/test/parallel/test-pipe-address.js +++ b/test/js/node/test/parallel/test-pipe-address.js @@ -1,6 +1,5 @@ 'use strict'; const common = require('../common'); -if (common.isWindows) return; // TODO: BUN const assert = require('assert'); const net = require('net'); const server = net.createServer(common.mustNotCall()); diff --git a/test/js/node/test/parallel/test-pipe-file-to-http.js b/test/js/node/test/parallel/test-pipe-file-to-http.js index ffbab21f71fd..2242d81095c5 100644 --- a/test/js/node/test/parallel/test-pipe-file-to-http.js +++ b/test/js/node/test/parallel/test-pipe-file-to-http.js @@ -31,7 +31,7 @@ tmpdir.refresh(); const filename = tmpdir.resolve('big'); let count = 0; -const server = http.createServer((req, res) => { +const server = http.createServer(common.mustCall((req, res) => { assert.strictEqual(req.method, 'POST'); req.pause(); @@ -50,7 +50,7 @@ const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(); }); -}); +})); server.listen(0); server.on('listening', () => { diff --git a/test/js/node/test/parallel/test-pipe-writev.js b/test/js/node/test/parallel/test-pipe-writev.js index 5e5b42e6a78d..ba02dd82b82b 100644 --- a/test/js/node/test/parallel/test-pipe-writev.js +++ b/test/js/node/test/parallel/test-pipe-writev.js @@ -10,7 +10,7 @@ const net = require('net'); const tmpdir = require('../common/tmpdir'); tmpdir.refresh(); -const server = net.createServer((connection) => { +const server = net.createServer(common.mustCallAtLeast((connection) => { connection.on('error', (err) => { throw err; }); @@ -22,13 +22,13 @@ const server = net.createServer((connection) => { connection.write('pi'); connection.write('ng'); connection.end(); -}); +})); server.on('error', (err) => { throw err; }); -server.listen(common.PIPE, () => { +server.listen(common.PIPE, common.mustCall(() => { const client = net.connect(common.PIPE); client.on('error', (err) => { @@ -42,4 +42,4 @@ server.listen(common.PIPE, () => { client.on('end', () => { server.close(); }); -}); +})); diff --git a/test/js/node/test/parallel/test-process-config.js b/test/js/node/test/parallel/test-process-config.js index 20ebc36a9963..3d3c3cc6b8f0 100644 --- a/test/js/node/test/parallel/test-process-config.js +++ b/test/js/node/test/parallel/test-process-config.js @@ -49,8 +49,7 @@ let config = fs.readFileSync(configPath, 'utf8'); // Clean up comment at the first line. config = config.split('\n').slice(1).join('\n'); -config = config.replace(/"/g, '\\"'); -config = config.replace(/'/g, '"'); +// Turn pseudo-booleans strings into booleans. config = JSON.parse(config, (key, value) => { if (value === 'true') return true; if (value === 'false') return false; diff --git a/test/js/node/test/parallel/test-process-exception-capture-should-abort-on-uncaught.js b/test/js/node/test/parallel/test-process-exception-capture-should-abort-on-uncaught.js index fd7443153f66..f9e685a86ea2 100644 --- a/test/js/node/test/parallel/test-process-exception-capture-should-abort-on-uncaught.js +++ b/test/js/node/test/parallel/test-process-exception-capture-should-abort-on-uncaught.js @@ -1,7 +1,6 @@ // Flags: --abort-on-uncaught-exception 'use strict'; const common = require('../common'); -if (common.isWindows) return; // TODO: BUN https://github.com/oven-sh/bun/issues/12827 const assert = require('assert'); assert.strictEqual(process.hasUncaughtExceptionCaptureCallback(), false); diff --git a/test/js/node/test/parallel/test-process-exception-capture.js b/test/js/node/test/parallel/test-process-exception-capture.js index 3b382473592c..c84d3459e231 100644 --- a/test/js/node/test/parallel/test-process-exception-capture.js +++ b/test/js/node/test/parallel/test-process-exception-capture.js @@ -1,7 +1,6 @@ // Flags: --abort-on-uncaught-exception 'use strict'; const common = require('../common'); -if (common.isWindows) return; // TODO: BUN https://github.com/oven-sh/bun/issues/12827 const assert = require('assert'); assert.strictEqual(process.hasUncaughtExceptionCaptureCallback(), false); diff --git a/test/js/node/test/parallel/test-process-execve-on-exit.js b/test/js/node/test/parallel/test-process-execve-on-exit.js index ff01b0b50e25..77d0cd467455 100644 --- a/test/js/node/test/parallel/test-process-execve-on-exit.js +++ b/test/js/node/test/parallel/test-process-execve-on-exit.js @@ -1,7 +1,7 @@ 'use strict'; const { mustNotCall, skip, isWindows, isIBMi } = require('../common'); -const { strictEqual } = require('assert'); +const assert = require('assert'); const { isMainThread } = require('worker_threads'); if (!isMainThread) { @@ -11,7 +11,7 @@ if (!isMainThread) { } if (process.argv[2] === 'replaced') { - strictEqual(process.argv[2], 'replaced'); + assert.strictEqual(process.argv[2], 'replaced'); } else { process.on('exit', mustNotCall()); process.execve(process.execPath, [process.execPath, __filename, 'replaced'], process.env); diff --git a/test/js/node/test/parallel/test-process-execve-permission-granted.js b/test/js/node/test/parallel/test-process-execve-permission-granted.js index f4d36d83f07a..fcafe5df1b96 100644 --- a/test/js/node/test/parallel/test-process-execve-permission-granted.js +++ b/test/js/node/test/parallel/test-process-execve-permission-granted.js @@ -3,7 +3,7 @@ 'use strict'; const { skip, isWindows, isIBMi } = require('../common'); -const { deepStrictEqual } = require('assert'); +const assert = require('assert'); const { isMainThread } = require('worker_threads'); if (!isMainThread) { @@ -13,7 +13,7 @@ if (!isMainThread) { } if (process.argv[2] === 'replaced') { - deepStrictEqual(process.argv, [process.execPath, __filename, 'replaced']); + assert.deepStrictEqual(process.argv, [process.execPath, __filename, 'replaced']); } else { process.execve(process.execPath, [process.execPath, __filename, 'replaced'], process.env); } diff --git a/test/js/node/test/parallel/test-process-execve-socket.js b/test/js/node/test/parallel/test-process-execve-socket.js index d113f690a09a..c229e4781c0f 100644 --- a/test/js/node/test/parallel/test-process-execve-socket.js +++ b/test/js/node/test/parallel/test-process-execve-socket.js @@ -1,7 +1,7 @@ 'use strict'; const { mustCall, mustNotCall, skip, isWindows, isIBMi } = require('../common'); -const { fail, ok } = require('assert'); +const assert = require('assert'); const { createServer } = require('net'); const { isMainThread } = require('worker_threads'); @@ -13,7 +13,7 @@ if (!isMainThread) { if (process.argv[2] === 'replaced') { const port = parseInt(process.env.PORT, 10); - ok(Number.isInteger(port)); + assert.ok(Number.isInteger(port)); const server = createServer(); server.on('error', mustNotCall()); @@ -39,11 +39,11 @@ if (process.argv[2] === 'replaced') { ); // If process.execve succeed, this should never be executed. - fail('process.execve failed'); + assert.fail('process.execve failed'); })); server2.listen(port, mustCall(() => { - fail('server2.listen unexpectedly succeeded'); + assert.fail('server2.listen unexpectedly succeeded'); })); })); } diff --git a/test/js/node/test/parallel/test-process-execve-worker-threads.js b/test/js/node/test/parallel/test-process-execve-worker-threads.js index 551f6f7ac306..2d86befa08eb 100644 --- a/test/js/node/test/parallel/test-process-execve-worker-threads.js +++ b/test/js/node/test/parallel/test-process-execve-worker-threads.js @@ -1,7 +1,7 @@ 'use strict'; const { isWindows, isIBMi, mustCall, skip } = require('../common'); -const { throws } = require('assert'); +const assert = require('assert'); const { isMainThread, Worker } = require('worker_threads'); if (isWindows || isIBMi) { @@ -11,7 +11,7 @@ if (isWindows || isIBMi) { if (isMainThread) { new Worker(__filename); } else { - throws(mustCall(() => { + assert.throws(mustCall(() => { process.execve( process.execPath, [__filename, 'replaced'], diff --git a/test/js/node/test/parallel/test-process-execve.js b/test/js/node/test/parallel/test-process-execve.js index b0d4bc05158f..577de22a1887 100644 --- a/test/js/node/test/parallel/test-process-execve.js +++ b/test/js/node/test/parallel/test-process-execve.js @@ -1,7 +1,7 @@ 'use strict'; const { isWindows, isIBMi, skip } = require('../common'); -const { deepStrictEqual, fail, strictEqual } = require('assert'); +const assert = require('assert'); const { isMainThread } = require('worker_threads'); if (!isMainThread) { @@ -11,10 +11,10 @@ if (!isMainThread) { } if (process.argv[2] === 'replaced') { - deepStrictEqual(process.argv, [process.execPath, __filename, 'replaced']); - strictEqual(process.env.CWD, process.cwd()); - strictEqual(process.env.EXECVE_A, 'FIRST'); - strictEqual(process.env.EXECVE_B, 'SECOND'); + assert.deepStrictEqual(process.argv, [process.execPath, __filename, 'replaced']); + assert.strictEqual(process.env.CWD, process.cwd()); + assert.strictEqual(process.env.EXECVE_A, 'FIRST'); + assert.strictEqual(process.env.EXECVE_B, 'SECOND'); } else { process.execve( process.execPath, @@ -23,5 +23,5 @@ if (process.argv[2] === 'replaced') { ); // If process.execve succeed, this should never be executed. - fail('process.execve failed'); + assert.fail('process.execve failed'); } diff --git a/test/js/node/test/parallel/test-process-getgroups.js b/test/js/node/test/parallel/test-process-getgroups.js index 28df13205f44..a5fd23ae26d8 100644 --- a/test/js/node/test/parallel/test-process-getgroups.js +++ b/test/js/node/test/parallel/test-process-getgroups.js @@ -34,13 +34,12 @@ if (typeof process.getgroups === 'function') { const groups = unique(process.getgroups()); assert(Array.isArray(groups)); assert(groups.length > 0); - exec('id -G', function(err, stdout) { - assert.ifError(err); + exec('id -G', common.mustSucceed((stdout) => { const real_groups = unique(stdout.match(/\d+/g).map(Number)); assert.deepStrictEqual(groups, real_groups); check(groups, real_groups); check(real_groups, groups); - }); + })); } function check(a, b) { diff --git a/test/js/node/test/parallel/test-process-ref-unref.js b/test/js/node/test/parallel/test-process-ref-unref.js index 19665703cfe3..b80085d559af 100644 --- a/test/js/node/test/parallel/test-process-ref-unref.js +++ b/test/js/node/test/parallel/test-process-ref-unref.js @@ -7,9 +7,7 @@ const { it, } = require('node:test'); -const { - strictEqual, -} = require('node:assert'); +const assert = require('node:assert'); class Foo { refCalled = 0; @@ -43,18 +41,18 @@ describe('process.ref/unref work as expected', () => { process.unref(foo1); process.ref(foo2); process.unref(foo2); - strictEqual(foo1.refCalled, 1); - strictEqual(foo1.unrefCalled, 1); - strictEqual(foo2.refCalled, 1); - strictEqual(foo2.unrefCalled, 1); + assert.strictEqual(foo1.refCalled, 1); + assert.strictEqual(foo1.unrefCalled, 1); + assert.strictEqual(foo2.refCalled, 1); + assert.strictEqual(foo2.unrefCalled, 1); // Objects that implement the legacy API also just work. const i = setInterval(() => {}, 1000); - strictEqual(i.hasRef(), true); + assert.strictEqual(i.hasRef(), true); process.unref(i); - strictEqual(i.hasRef(), false); + assert.strictEqual(i.hasRef(), false); process.ref(i); - strictEqual(i.hasRef(), true); + assert.strictEqual(i.hasRef(), true); clearInterval(i); }); }); diff --git a/test/js/node/test/parallel/test-process-release.js b/test/js/node/test/parallel/test-process-release.js index ae4a02aa850e..c23aba990223 100644 --- a/test/js/node/test/parallel/test-process-release.js +++ b/test/js/node/test/parallel/test-process-release.js @@ -29,6 +29,8 @@ if (versionParts[0] === '4' && versionParts[1] >= 2) { assert.strictEqual(process.release.lts, 'Iron'); } else if (versionParts[0] === '22' && versionParts[1] >= 11) { assert.strictEqual(process.release.lts, 'Jod'); +} else if (versionParts[0] === '24' && versionParts[1] >= 11) { + assert.strictEqual(process.release.lts, 'Krypton'); } else { assert.strictEqual(process.release.lts, undefined); } diff --git a/test/js/node/test/parallel/test-process-title-cli.js b/test/js/node/test/parallel/test-process-title-cli.js index 98b3da003f77..35d3693c0690 100644 --- a/test/js/node/test/parallel/test-process-title-cli.js +++ b/test/js/node/test/parallel/test-process-title-cli.js @@ -2,7 +2,6 @@ 'use strict'; const common = require('../common'); -if (common.isWindows) return; // TODO: BUN if (common.isSunOS) common.skip(`Unsupported platform [${process.platform}]`); diff --git a/test/js/node/test/parallel/test-process-uptime.js b/test/js/node/test/parallel/test-process-uptime.js index eabb6cf2661c..017fa06c71c6 100644 --- a/test/js/node/test/parallel/test-process-uptime.js +++ b/test/js/node/test/parallel/test-process-uptime.js @@ -20,7 +20,7 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); console.error(process.uptime()); @@ -31,7 +31,7 @@ assert.ok(process.uptime() <= 15); const original = process.uptime(); -setTimeout(function() { +setTimeout(common.mustCall(() => { const uptime = process.uptime(); assert.ok(original < uptime); -}, 10); +}), 10); diff --git a/test/js/node/test/parallel/test-promises-unhandled-rejections.js b/test/js/node/test/parallel/test-promises-unhandled-rejections.js index 761923c5cc30..bfdd2cf44982 100644 --- a/test/js/node/test/parallel/test-promises-unhandled-rejections.js +++ b/test/js/node/test/parallel/test-promises-unhandled-rejections.js @@ -4,7 +4,7 @@ const common = require('../common'); const assert = require('assert'); const { inspect } = require('util'); -const asyncTest = (function() { +const test = (function() { let asyncTestsEnabled = false; let asyncTestLastCheck; const asyncTestQueue = []; @@ -107,32 +107,32 @@ function onUnhandledFail(done) { }, 10); } -asyncTest('synchronously rejected promise should trigger' + +test('synchronously rejected promise should trigger' + ' unhandledRejection', function(done) { const e = new Error(); - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, e); - }); + })); Promise.reject(e); }); -asyncTest('synchronously rejected promise should trigger' + +test('synchronously rejected promise should trigger' + ' unhandledRejection', function(done) { const e = new Error(); - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, e); - }); + })); new Promise(function(_, reject) { reject(e); }); }); -asyncTest('Promise rejected after setImmediate should trigger' + +test('Promise rejected after setImmediate should trigger' + ' unhandledRejection', function(done) { const e = new Error(); - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, e); - }); + })); new Promise(function(_, reject) { setImmediate(function() { reject(e); @@ -140,12 +140,12 @@ asyncTest('Promise rejected after setImmediate should trigger' + }); }); -asyncTest('Promise rejected after setTimeout(,1) should trigger' + +test('Promise rejected after setTimeout(,1) should trigger' + ' unhandled rejection', function(done) { const e = new Error(); - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, e); - }); + })); new Promise(function(_, reject) { setTimeout(function() { reject(e); @@ -153,55 +153,56 @@ asyncTest('Promise rejected after setTimeout(,1) should trigger' + }); }); -asyncTest('Catching a promise rejection after setImmediate is not' + +test('Catching a promise rejection after setImmediate is not' + ' soon enough to stop unhandledRejection', function(done) { const e = new Error(); - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, e); - }); + })); let _reject; const promise = new Promise(function(_, reject) { _reject = reject; }); _reject(e); setImmediate(function() { + // eslint-disable-next-line node-core/must-call-assert promise.then(assert.fail, function() {}); }); }); -asyncTest('When re-throwing new errors in a promise catch, only the' + +test('When re-throwing new errors in a promise catch, only the' + ' re-thrown error should hit unhandledRejection', function(done) { const e = new Error(); const e2 = new Error(); - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, e2); assert.strictEqual(promise, promise2); - }); + })); const promise2 = Promise.reject(e).then(assert.fail, function(reason) { assert.strictEqual(reason, e); throw e2; }); }); -asyncTest('Test params of unhandledRejection for a synchronously-rejected ' + +test('Test params of unhandledRejection for a synchronously-rejected ' + 'promise', function(done) { const e = new Error(); - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, e); assert.strictEqual(promise, promise); - }); + })); Promise.reject(e); }); -asyncTest('When re-throwing new errors in a promise catch, only the ' + +test('When re-throwing new errors in a promise catch, only the ' + 're-thrown error should hit unhandledRejection: original promise' + ' rejected async with setTimeout(,1)', function(done) { const e = new Error(); const e2 = new Error(); - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, e2); assert.strictEqual(promise, promise2); - }); + })); const promise2 = new Promise(function(_, reject) { setTimeout(function() { reject(e); @@ -212,15 +213,15 @@ asyncTest('When re-throwing new errors in a promise catch, only the ' + }); }); -asyncTest('When re-throwing new errors in a promise catch, only the re-thrown' + +test('When re-throwing new errors in a promise catch, only the re-thrown' + ' error should hit unhandledRejection: promise catch attached a' + ' process.nextTick after rejection', function(done) { const e = new Error(); const e2 = new Error(); - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, e2); assert.strictEqual(promise, promise2); - }); + })); const promise = new Promise(function(_, reject) { setTimeout(function() { reject(e); @@ -235,39 +236,42 @@ asyncTest('When re-throwing new errors in a promise catch, only the re-thrown' + let promise2; }); -asyncTest( +test( 'unhandledRejection should not be triggered if a promise catch is' + ' attached synchronously upon the promise\'s creation', function(done) { const e = new Error(); onUnhandledFail(done); + // eslint-disable-next-line node-core/must-call-assert Promise.reject(e).then(assert.fail, function() {}); } ); -asyncTest( +test( 'unhandledRejection should not be triggered if a promise catch is' + ' attached synchronously upon the promise\'s creation', function(done) { const e = new Error(); onUnhandledFail(done); + // eslint-disable-next-line node-core/must-call-assert new Promise(function(_, reject) { reject(e); }).then(assert.fail, function() {}); } ); -asyncTest('Attaching a promise catch in a process.nextTick is soon enough to' + +test('Attaching a promise catch in a process.nextTick is soon enough to' + ' prevent unhandledRejection', function(done) { const e = new Error(); onUnhandledFail(done); const promise = Promise.reject(e); process.nextTick(function() { + // eslint-disable-next-line node-core/must-call-assert promise.then(assert.fail, function() {}); }); }); -asyncTest('Attaching a promise catch in a process.nextTick is soon enough to' + +test('Attaching a promise catch in a process.nextTick is soon enough to' + ' prevent unhandledRejection', function(done) { const e = new Error(); onUnhandledFail(done); @@ -275,11 +279,12 @@ asyncTest('Attaching a promise catch in a process.nextTick is soon enough to' + reject(e); }); process.nextTick(function() { + // eslint-disable-next-line node-core/must-call-assert promise.then(assert.fail, function() {}); }); }); -asyncTest('While inside setImmediate, catching a rejected promise derived ' + +test('While inside setImmediate, catching a rejected promise derived ' + 'from returning a rejected promise in a fulfillment handler ' + 'prevents unhandledRejection', function(done) { onUnhandledFail(done); @@ -295,11 +300,12 @@ asyncTest('While inside setImmediate, catching a rejected promise derived ' + }); // State adaptation tests -asyncTest('catching a promise which is asynchronously rejected (via ' + +test('catching a promise which is asynchronously rejected (via ' + 'resolution to an asynchronously-rejected promise) prevents' + ' unhandledRejection', function(done) { const e = new Error(); onUnhandledFail(done); + // eslint-disable-next-line node-core/must-call-assert Promise.resolve().then(function() { return new Promise(function(_, reject) { setTimeout(function() { @@ -311,10 +317,11 @@ asyncTest('catching a promise which is asynchronously rejected (via ' + }); }); -asyncTest('Catching a rejected promise derived from throwing in a' + +test('Catching a rejected promise derived from throwing in a' + ' fulfillment handler prevents unhandledRejection', function(done) { const e = new Error(); onUnhandledFail(done); + // eslint-disable-next-line node-core/must-call-assert Promise.resolve().then(function() { throw e; }).then(assert.fail, function(reason) { @@ -322,11 +329,12 @@ asyncTest('Catching a rejected promise derived from throwing in a' + }); }); -asyncTest('Catching a rejected promise derived from returning a' + +test('Catching a rejected promise derived from returning a' + ' synchronously-rejected promise in a fulfillment handler' + ' prevents unhandledRejection', function(done) { const e = new Error(); onUnhandledFail(done); + // eslint-disable-next-line node-core/must-call-assert Promise.resolve().then(function() { return Promise.reject(e); }).then(assert.fail, function(reason) { @@ -334,14 +342,14 @@ asyncTest('Catching a rejected promise derived from returning a' + }); }); -asyncTest('A rejected promise derived from returning an' + +test('A rejected promise derived from returning an' + ' asynchronously-rejected promise in a fulfillment handler' + ' does trigger unhandledRejection', function(done) { const e = new Error(); - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, e); assert.strictEqual(promise, _promise); - }); + })); const _promise = Promise.resolve().then(function() { return new Promise(function(_, reject) { setTimeout(function() { @@ -351,27 +359,27 @@ asyncTest('A rejected promise derived from returning an' + }); }); -asyncTest('A rejected promise derived from throwing in a fulfillment handler' + +test('A rejected promise derived from throwing in a fulfillment handler' + ' does trigger unhandledRejection', function(done) { const e = new Error(); - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, e); assert.strictEqual(promise, _promise); - }); + })); const _promise = Promise.resolve().then(function() { throw e; }); }); -asyncTest( +test( 'A rejected promise derived from returning a synchronously-rejected' + ' promise in a fulfillment handler does trigger unhandledRejection', function(done) { const e = new Error(); - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, e); assert.strictEqual(promise, _promise); - }); + })); const _promise = Promise.resolve().then(function() { return Promise.reject(e); }); @@ -379,14 +387,15 @@ asyncTest( ); // Combinations with Promise.all -asyncTest('Catching the Promise.all() of a collection that includes a ' + +test('Catching the Promise.all() of a collection that includes a ' + 'rejected promise prevents unhandledRejection', function(done) { const e = new Error(); onUnhandledFail(done); + // eslint-disable-next-line node-core/must-call-assert Promise.all([Promise.reject(e)]).then(assert.fail, function() {}); }); -asyncTest( +test( 'Catching the Promise.all() of a collection that includes a ' + 'nextTick-async rejected promise prevents unhandledRejection', function(done) { @@ -399,49 +408,51 @@ asyncTest( }); p = Promise.all([p]); process.nextTick(function() { + // eslint-disable-next-line node-core/must-call-assert p.then(assert.fail, function() {}); }); } ); -asyncTest('Failing to catch the Promise.all() of a collection that includes' + +test('Failing to catch the Promise.all() of a collection that includes' + ' a rejected promise triggers unhandledRejection for the returned' + ' promise, not the passed promise', function(done) { const e = new Error(); - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, e); assert.strictEqual(promise, p); - }); + })); const p = Promise.all([Promise.reject(e)]); }); -asyncTest('Waiting setTimeout(, 10) to catch a promise causes an' + +test('Waiting setTimeout(, 10) to catch a promise causes an' + ' unhandledRejection + rejectionHandled pair', function(done) { clean(); const unhandledPromises = []; const e = new Error(); - process.on('unhandledRejection', function(reason, promise) { + process.on('unhandledRejection', common.mustCall((reason, promise) => { assert.strictEqual(reason, e); unhandledPromises.push(promise); - }); - process.on('rejectionHandled', function(promise) { + })); + process.on('rejectionHandled', common.mustCall((promise) => { assert.strictEqual(unhandledPromises.length, 1); assert.strictEqual(unhandledPromises[0], promise); assert.strictEqual(promise, thePromise); done(); - }); + })); const thePromise = new Promise(function() { throw e; }); setTimeout(function() { + // eslint-disable-next-line node-core/must-call-assert thePromise.then(assert.fail, function(reason) { assert.strictEqual(reason, e); }); }, 10); }); -asyncTest('Waiting for some combination of process.nextTick + promise' + +test('Waiting for some combination of process.nextTick + promise' + ' microtasks to attach a catch handler is still soon enough to' + ' prevent unhandledRejection', function(done) { const e = new Error(); @@ -450,57 +461,57 @@ asyncTest('Waiting for some combination of process.nextTick + promise' + const a = Promise.reject(e); process.nextTick(function() { - Promise.resolve().then(function() { + Promise.resolve().then(common.mustCall(() => { process.nextTick(function() { - Promise.resolve().then(function() { + Promise.resolve().then(common.mustCall(() => { a.catch(function() {}); - }); + })); }); - }); + })); }); }); -asyncTest('Waiting for some combination of process.nextTick + promise' + +test('Waiting for some combination of process.nextTick + promise' + ' microtasks to attach a catch handler is still soon enough to ' + 'prevent unhandledRejection: inside setImmediate', function(done) { const e = new Error(); onUnhandledFail(done); - setImmediate(function() { + setImmediate(common.mustCall(() => { const a = Promise.reject(e); process.nextTick(function() { - Promise.resolve().then(function() { + Promise.resolve().then(common.mustCall(() => { process.nextTick(function() { - Promise.resolve().then(function() { + Promise.resolve().then(common.mustCall(() => { a.catch(function() {}); - }); + })); }); - }); + })); }); - }); + })); }); -asyncTest('Waiting for some combination of process.nextTick + promise ' + +test('Waiting for some combination of process.nextTick + promise ' + 'microtasks to attach a catch handler is still soon enough to ' + 'prevent unhandledRejection: inside setTimeout', function(done) { const e = new Error(); onUnhandledFail(done); - setTimeout(function() { + setTimeout(common.mustCall(() => { const a = Promise.reject(e); process.nextTick(function() { - Promise.resolve().then(function() { + Promise.resolve().then(common.mustCall(() => { process.nextTick(function() { - Promise.resolve().then(function() { + Promise.resolve().then(common.mustCall(() => { a.catch(function() {}); - }); + })); }); - }); + })); }); - }, 0); + }), 0); }); -asyncTest('Waiting for some combination of promise microtasks + ' + +test('Waiting for some combination of promise microtasks + ' + 'process.nextTick to attach a catch handler is still soon enough' + ' to prevent unhandledRejection', function(done) { const e = new Error(); @@ -508,18 +519,18 @@ asyncTest('Waiting for some combination of promise microtasks + ' + const a = Promise.reject(e); - Promise.resolve().then(function() { + Promise.resolve().then(common.mustCall(() => { process.nextTick(function() { - Promise.resolve().then(function() { + Promise.resolve().then(common.mustCall(() => { process.nextTick(function() { a.catch(function() {}); }); - }); + })); }); - }); + })); }); -asyncTest( +test( 'Waiting for some combination of promise microtasks +' + ' process.nextTick to attach a catch handler is still soon enough' + ' to prevent unhandledRejection: inside setImmediate', @@ -527,128 +538,128 @@ asyncTest( const e = new Error(); onUnhandledFail(done); - setImmediate(function() { + setImmediate(common.mustCall(() => { const a = Promise.reject(e); - Promise.resolve().then(function() { + Promise.resolve().then(common.mustCall(() => { process.nextTick(function() { - Promise.resolve().then(function() { + Promise.resolve().then(common.mustCall(() => { process.nextTick(function() { a.catch(function() {}); }); - }); + })); }); - }); - }); + })); + })); } ); -asyncTest('Waiting for some combination of promise microtasks +' + +test('Waiting for some combination of promise microtasks +' + ' process.nextTick to attach a catch handler is still soon enough' + ' to prevent unhandledRejection: inside setTimeout', function(done) { const e = new Error(); onUnhandledFail(done); - setTimeout(function() { + setTimeout(common.mustCall(() => { const a = Promise.reject(e); - Promise.resolve().then(function() { + Promise.resolve().then(common.mustCall(() => { process.nextTick(function() { - Promise.resolve().then(function() { + Promise.resolve().then(common.mustCall(() => { process.nextTick(function() { a.catch(function() {}); }); - }); + })); }); - }); - }, 0); + })); + }), 0); }); -asyncTest('setImmediate + promise microtasks is too late to attach a catch' + +test('setImmediate + promise microtasks is too late to attach a catch' + ' handler; unhandledRejection will be triggered in that case.' + ' (setImmediate before promise creation/rejection)', function(done) { const e = new Error(); - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, e); assert.strictEqual(promise, p); - }); + })); const p = Promise.reject(e); - setImmediate(function() { - Promise.resolve().then(function() { + setImmediate(common.mustCall(() => { + Promise.resolve().then(common.mustCall(() => { p.catch(function() {}); - }); - }); + })); + })); }); -asyncTest('setImmediate + promise microtasks is too late to attach a catch' + +test('setImmediate + promise microtasks is too late to attach a catch' + ' handler; unhandledRejection will be triggered in that case' + ' (setImmediate before promise creation/rejection)', function(done) { - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, undefined); assert.strictEqual(promise, p); - }); - setImmediate(function() { - Promise.resolve().then(function() { - Promise.resolve().then(function() { - Promise.resolve().then(function() { - Promise.resolve().then(function() { + })); + setImmediate(common.mustCall(() => { + Promise.resolve().then(common.mustCall(() => { + Promise.resolve().then(common.mustCall(() => { + Promise.resolve().then(common.mustCall(() => { + Promise.resolve().then(common.mustCall(() => { p.catch(function() {}); - }); - }); - }); - }); - }); + })); + })); + })); + })); + })); const p = Promise.reject(); }); -asyncTest('setImmediate + promise microtasks is too late to attach a catch' + +test('setImmediate + promise microtasks is too late to attach a catch' + ' handler; unhandledRejection will be triggered in that case' + ' (setImmediate after promise creation/rejection)', function(done) { - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, undefined); assert.strictEqual(promise, p); - }); + })); const p = Promise.reject(); - setImmediate(function() { - Promise.resolve().then(function() { - Promise.resolve().then(function() { - Promise.resolve().then(function() { - Promise.resolve().then(function() { + setImmediate(common.mustCall(() => { + Promise.resolve().then(common.mustCall(() => { + Promise.resolve().then(common.mustCall(() => { + Promise.resolve().then(common.mustCall(() => { + Promise.resolve().then(common.mustCall(() => { p.catch(function() {}); - }); - }); - }); - }); - }); + })); + })); + })); + })); + })); }); -asyncTest('nextTick is immediately scheduled when called inside an event' + +test('nextTick is immediately scheduled when called inside an event' + ' handler', function(done) { clean(); const e = new Error('error'); - process.on('unhandledRejection', function(reason, promise) { + process.on('unhandledRejection', common.mustCall((reason, promise) => { const order = []; process.nextTick(function() { order.push(1); }); - setTimeout(function() { + setTimeout(common.mustCall(() => { order.push(2); assert.deepStrictEqual([1, 2], order); done(); - }, 1); - }); + }), 1); + })); Promise.reject(e); }); -asyncTest('Throwing an error inside a rejectionHandled handler goes to' + +test('Throwing an error inside a rejectionHandled handler goes to' + ' unhandledException, and does not cause .catch() to throw an ' + 'exception', function(done) { clean(); const e = new Error(); const e2 = new Error(); - const tearDownException = setupException(function(err) { + const tearDownException = setupException(common.mustCall((err) => { assert.strictEqual(err, e2); tearDownException(); done(); - }); + })); process.on('rejectionHandled', function() { throw e2; }); @@ -662,20 +673,20 @@ asyncTest('Throwing an error inside a rejectionHandled handler goes to' + }, 1); }); -asyncTest('Rejected promise inside unhandledRejection allows nextTick loop' + +test('Rejected promise inside unhandledRejection allows nextTick loop' + ' to proceed first', function(done) { clean(); Promise.reject(0); let didCall = false; - process.on('unhandledRejection', () => { + process.on('unhandledRejection', common.mustCall(() => { assert(!didCall); didCall = true; const promise = Promise.reject(0); process.nextTick(() => promise.catch(() => done())); - }); + })); }); -asyncTest( +test( 'Promise rejection triggers unhandledRejection immediately', function(done) { clean(); @@ -693,12 +704,12 @@ asyncTest( ); // https://github.com/nodejs/node/issues/30953 -asyncTest( +test( 'Catching a promise should not take effect on previous promises', function(done) { - onUnhandledSucceed(done, function(reason, promise) { + onUnhandledSucceed(done, common.mustCall((reason, promise) => { assert.strictEqual(reason, '1'); - }); + })); Promise.reject('1'); Promise.reject('2').catch(function() {}); } diff --git a/test/js/node/test/parallel/test-promises-warning-on-unhandled-rejection.js b/test/js/node/test/parallel/test-promises-warning-on-unhandled-rejection.js index 0d6a74854217..71aeb9bd5c2d 100644 --- a/test/js/node/test/parallel/test-promises-warning-on-unhandled-rejection.js +++ b/test/js/node/test/parallel/test-promises-warning-on-unhandled-rejection.js @@ -18,11 +18,7 @@ process.on('warning', common.mustCall((warning) => { case 1: // Warning about rejection not being handled (will be next tick) assert.strictEqual(warning.name, 'UnhandledPromiseRejectionWarning'); - assert( - /Unhandled promise rejection/.test(warning.message), - 'Expected warning message to contain "Unhandled promise rejection" ' + - `but did not. Had "${warning.message}" instead.` - ); + assert.match(warning.message, /Unhandled promise rejection/); break; case 2: // Number rejection error displayed. Note it's been stringified @@ -31,17 +27,12 @@ process.on('warning', common.mustCall((warning) => { case 3: // Unhandled rejection warning (won't be handled next tick) assert.strictEqual(warning.name, 'UnhandledPromiseRejectionWarning'); - assert( - /Unhandled promise rejection/.test(warning.message), - 'Expected warning message to contain "Unhandled promise rejection" ' + - `but did not. Had "${warning.message}" instead.` - ); + assert.match(warning.message, /Unhandled promise rejection/); break; case 4: // Rejection handled asynchronously. assert.strictEqual(warning.name, 'PromiseRejectionHandledWarning'); - assert(/Promise rejection was handled asynchronously/ - .test(warning.message)); + assert.match(warning.message, /Promise rejection was handled asynchronously/); } }, 5)); diff --git a/test/js/node/test/parallel/test-queue-microtask.js b/test/js/node/test/parallel/test-queue-microtask.js index 7504843d33e0..d25bfab96287 100644 --- a/test/js/node/test/parallel/test-queue-microtask.js +++ b/test/js/node/test/parallel/test-queue-microtask.js @@ -32,7 +32,7 @@ queueMicrotask(common.mustCall(function() { { const q = []; - Promise.resolve().then(() => q.push('a')); + Promise.resolve().then(() => q.push('a')).then(common.mustCall()); queueMicrotask(common.mustCall(() => q.push('b'))); Promise.reject().catch(() => q.push('c')); @@ -50,7 +50,7 @@ process.on('exit', () => { assert.strictEqual(eq.length, 2); assert.strictEqual(eq[0].message, 'E1'); assert.strictEqual( - eq[1].message, 'Cannot call a class constructor without |new|'); + eq[1].message, 'Class constructor cannot be invoked without \'new\''); }); queueMicrotask(common.mustCall(() => { diff --git a/test/js/node/test/parallel/test-readable-from-iterator-closing.js b/test/js/node/test/parallel/test-readable-from-iterator-closing.js index 02252ffe5685..ef7e54821ace 100644 --- a/test/js/node/test/parallel/test-readable-from-iterator-closing.js +++ b/test/js/node/test/parallel/test-readable-from-iterator-closing.js @@ -2,7 +2,7 @@ const { mustCall, mustNotCall } = require('../common'); const { Readable } = require('stream'); -const { strictEqual } = require('assert'); +const assert = require('assert'); async function asyncSupport() { const finallyMustCall = mustCall(); @@ -20,7 +20,7 @@ async function asyncSupport() { for await (const chunk of stream) { bodyMustCall(); - strictEqual(chunk, 'a'); + assert.strictEqual(chunk, 'a'); break; } } @@ -41,7 +41,7 @@ async function syncSupport() { for await (const chunk of stream) { bodyMustCall(); - strictEqual(chunk, 'a'); + assert.strictEqual(chunk, 'a'); break; } } @@ -66,7 +66,7 @@ async function syncPromiseSupport() { for await (const chunk of stream) { bodyMustCall(); - strictEqual(chunk, 'a'); + assert.strictEqual(chunk, 'a'); break; } } @@ -130,7 +130,6 @@ async function noReturnAfterThrow() { async function closeStreamWhileNextIsPending() { const finallyMustCall = mustCall(); - const dataMustCall = mustCall(); let resolveDestroy; const destroyed = @@ -153,20 +152,18 @@ async function closeStreamWhileNextIsPending() { const stream = Readable.from(infiniteGenerate()); - stream.on('data', (data) => { - dataMustCall(); - strictEqual(data, 'a'); - }); + stream.on('data', mustCall((data) => { + assert.strictEqual(data, 'a'); + })); yielded.then(() => { stream.destroy(); resolveDestroy(); - }); + }).then(mustCall()); } async function closeAfterNullYielded() { const finallyMustCall = mustCall(); - const dataMustCall = mustCall(3); function* generate() { try { @@ -180,10 +177,9 @@ async function closeAfterNullYielded() { const stream = Readable.from(generate()); - stream.on('data', (chunk) => { - dataMustCall(); - strictEqual(chunk, 'a'); - }); + stream.on('data', mustCall((chunk) => { + assert.strictEqual(chunk, 'a'); + }, 3)); } Promise.all([ diff --git a/test/js/node/test/parallel/test-readable-from-web-enqueue-then-close.js b/test/js/node/test/parallel/test-readable-from-web-enqueue-then-close.js index e96df70c9eb9..67b861596741 100644 --- a/test/js/node/test/parallel/test-readable-from-web-enqueue-then-close.js +++ b/test/js/node/test/parallel/test-readable-from-web-enqueue-then-close.js @@ -1,7 +1,7 @@ 'use strict'; const { mustCall } = require('../common'); const { Readable, Duplex } = require('stream'); -const { strictEqual } = require('assert'); +const assert = require('assert'); function start(controller) { controller.enqueue(new Uint8Array(1)); @@ -10,7 +10,7 @@ function start(controller) { Readable.fromWeb(new ReadableStream({ start })) .on('data', mustCall((d) => { - strictEqual(d.length, 1); + assert.strictEqual(d.length, 1); })) .on('end', mustCall()) .resume(); @@ -20,7 +20,7 @@ Duplex.fromWeb({ writable: new WritableStream({ write(chunk) {} }) }) .on('data', mustCall((d) => { - strictEqual(d.length, 1); + assert.strictEqual(d.length, 1); })) .on('end', mustCall()) .resume(); diff --git a/test/js/node/test/parallel/test-readable-from.js b/test/js/node/test/parallel/test-readable-from.js index b844574dc9e3..1d812ade3f23 100644 --- a/test/js/node/test/parallel/test-readable-from.js +++ b/test/js/node/test/parallel/test-readable-from.js @@ -3,11 +3,11 @@ const { mustCall } = require('../common'); const { once } = require('events'); const { Readable } = require('stream'); -const { strictEqual, throws } = require('assert'); +const assert = require('assert'); const common = require('../common'); { - throws(() => { + assert.throws(() => { Readable.from(null); }, /ERR_INVALID_ARG_TYPE/); } @@ -24,7 +24,7 @@ async function toReadableBasicSupport() { const expected = ['a', 'b', 'c']; for await (const chunk of stream) { - strictEqual(chunk, expected.shift()); + assert.strictEqual(chunk, expected.shift()); } } @@ -40,7 +40,7 @@ async function toReadableSyncIterator() { const expected = ['a', 'b', 'c']; for await (const chunk of stream) { - strictEqual(chunk, expected.shift()); + assert.strictEqual(chunk, expected.shift()); } } @@ -56,7 +56,7 @@ async function toReadablePromises() { const expected = ['a', 'b', 'c']; for await (const chunk of stream) { - strictEqual(chunk, expected.shift()); + assert.strictEqual(chunk, expected.shift()); } } @@ -66,7 +66,7 @@ async function toReadableString() { const expected = ['abc']; for await (const chunk of stream) { - strictEqual(chunk, expected.shift()); + assert.strictEqual(chunk, expected.shift()); } } @@ -76,7 +76,7 @@ async function toReadableBuffer() { const expected = ['abc']; for await (const chunk of stream) { - strictEqual(chunk.toString(), expected.shift()); + assert.strictEqual(chunk.toString(), expected.shift()); } } @@ -92,14 +92,14 @@ async function toReadableOnData() { let iterations = 0; const expected = ['a', 'b', 'c']; - stream.on('data', (chunk) => { + stream.on('data', common.mustCallAtLeast((chunk) => { iterations++; - strictEqual(chunk, expected.shift()); - }); + assert.strictEqual(chunk, expected.shift()); + })); await once(stream, 'end'); - strictEqual(iterations, 3); + assert.strictEqual(iterations, 3); } async function toReadableOnDataNonObject() { @@ -114,15 +114,15 @@ async function toReadableOnDataNonObject() { let iterations = 0; const expected = ['a', 'b', 'c']; - stream.on('data', (chunk) => { + stream.on('data', common.mustCallAtLeast((chunk) => { iterations++; - strictEqual(chunk instanceof Buffer, true); - strictEqual(chunk.toString(), expected.shift()); - }); + assert.strictEqual(chunk instanceof Buffer, true); + assert.strictEqual(chunk.toString(), expected.shift()); + })); await once(stream, 'end'); - strictEqual(iterations, 3); + assert.strictEqual(iterations, 3); } async function destroysTheStreamWhenThrowing() { @@ -135,8 +135,8 @@ async function destroysTheStreamWhenThrowing() { stream.read(); const [err] = await once(stream, 'error'); - strictEqual(err.message, 'kaboom'); - strictEqual(stream.destroyed, true); + assert.strictEqual(err.message, 'kaboom'); + assert.strictEqual(stream.destroyed, true); } @@ -162,7 +162,7 @@ async function asTransformStream() { const expected = ['A', 'B', 'C']; for await (const chunk of stream) { - strictEqual(chunk, expected.shift()); + assert.strictEqual(chunk, expected.shift()); } } @@ -179,18 +179,18 @@ async function endWithError() { try { for await (const chunk of stream) { - strictEqual(chunk, expected.shift()); + assert.strictEqual(chunk, expected.shift()); } throw new Error(); } catch (err) { - strictEqual(expected.length, 0); - strictEqual(err, 'Boum'); + assert.strictEqual(expected.length, 0); + assert.strictEqual(err, 'Boum'); } } async function destroyingStreamWithErrorThrowsInGenerator() { const validateError = common.mustCall((e) => { - strictEqual(e, 'Boum'); + assert.strictEqual(e, 'Boum'); }); async function* generate() { try { diff --git a/test/js/node/test/parallel/test-readline-async-iterators.js b/test/js/node/test/parallel/test-readline-async-iterators.js index 32fa32a1284a..a88c550c07ef 100644 --- a/test/js/node/test/parallel/test-readline-async-iterators.js +++ b/test/js/node/test/parallel/test-readline-async-iterators.js @@ -17,6 +17,7 @@ const testContents = [ 'line 1', 'line 1\nline 2 南越国是前203年至前111年存在于岭南地区的一个国家\nline 3\ntrailing', 'line 1\nline 2\nline 3 ends with newline\n', + Array(1e4).fill(0).map((_, i) => i).join('\n'), // More that 2 * highWaterMark ]; async function testSimple() { @@ -43,6 +44,29 @@ async function testSimple() { } } +// Same as testSimple, but with Readable.from() instead of fs.createReadStream +async function testReadableFrom() { + for (const fileContent of testContents) { + const readable = Readable.from([fileContent]); + const rli = readline.createInterface({ + input: readable, + crlfDelay: Infinity + }); + + const iteratedLines = []; + for await (const k of rli) { + iteratedLines.push(k); + } + + const expectedLines = fileContent.split('\n'); + if (expectedLines[expectedLines.length - 1] === '') { + expectedLines.pop(); + } + assert.deepStrictEqual(iteratedLines, expectedLines); + assert.strictEqual(iteratedLines.join(''), fileContent.replace(/\n/g, '')); + } +} + async function testMutual() { for (const fileContent of testContents) { fs.writeFileSync(filename, fileContent); @@ -115,6 +139,7 @@ async function testSlowStreamForLeaks() { } testSimple() + .then(testReadableFrom) .then(testMutual) .then(testSlowStreamForLeaks) .then(common.mustCall()); diff --git a/test/js/node/test/parallel/test-readline-keys.js b/test/js/node/test/parallel/test-readline-keys.js index 28b5846d4eb5..4379193b82f1 100644 --- a/test/js/node/test/parallel/test-readline-keys.js +++ b/test/js/node/test/parallel/test-readline-keys.js @@ -49,9 +49,9 @@ function addTest(sequences, expectedKeys) { // (addKeyIntervalTest(..)(noop)))() // where noop is a terminal function(() => {}). -const addKeyIntervalTest = (sequences, expectedKeys, interval = 550, - assertDelay = 550) => { - const fn = common.mustCall((next) => () => { +function addKeyIntervalTest(sequences, expectedKeys, interval = 550, + assertDelay = 550) { + const fn = common.mustCall((next) => common.mustCall(() => { if (!Array.isArray(sequences)) { sequences = [ sequences ]; @@ -66,21 +66,21 @@ const addKeyIntervalTest = (sequences, expectedKeys, interval = 550, const keys = []; fi.on('keypress', (s, k) => keys.push(k)); - const emitKeys = ([head, ...tail]) => { + const emitKeys = common.mustCallAtLeast(([head, ...tail]) => { if (head) { fi.write(head); setTimeout(() => emitKeys(tail), interval); } else { - setTimeout(() => { + setTimeout(common.mustCall(() => { next(); assert.deepStrictEqual(keys, expectedKeys); - }, assertDelay); + }), assertDelay); } - }; + }); emitKeys(sequences); - }); + })); return fn; -}; +} // Regular alphanumerics addTest('io.JS', [ diff --git a/test/js/node/test/parallel/test-readline-set-raw-mode.js b/test/js/node/test/parallel/test-readline-set-raw-mode.js index de47d14b03de..57015077781f 100644 --- a/test/js/node/test/parallel/test-readline-set-raw-mode.js +++ b/test/js/node/test/parallel/test-readline-set-raw-mode.js @@ -20,7 +20,7 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const readline = require('readline'); const Stream = require('stream'); @@ -31,10 +31,10 @@ let rawModeCalled = false; let resumeCalled = false; let pauseCalled = false; -stream.setRawMode = function(mode) { +stream.setRawMode = common.mustCallAtLeast(function(mode) { rawModeCalled = true; assert.strictEqual(mode, expectedRawMode); -}; +}); stream.resume = function() { resumeCalled = true; }; diff --git a/test/js/node/test/parallel/test-repl-dynamic-import.js b/test/js/node/test/parallel/test-repl-dynamic-import.js index a043e31bf5b2..3ce21d662f6f 100644 --- a/test/js/node/test/parallel/test-repl-dynamic-import.js +++ b/test/js/node/test/parallel/test-repl-dynamic-import.js @@ -14,7 +14,7 @@ setTimeout(() => { child.stdin.write('\nimport("fs");\n'); child.stdin.write('\nprocess.exit(0);\n'); }, common.platformTimeout(50)); -child.on('exit', (code, signal) => { +child.on('exit', common.mustCall((code, signal) => { assert.strictEqual(code, 0); assert.strictEqual(signal, null); -}); +})); diff --git a/test/js/node/test/parallel/test-repl-syntax-error-handling.js b/test/js/node/test/parallel/test-repl-syntax-error-handling.js index 91a8614d1deb..2b57af8c8011 100644 --- a/test/js/node/test/parallel/test-repl-syntax-error-handling.js +++ b/test/js/node/test/parallel/test-repl-syntax-error-handling.js @@ -20,7 +20,7 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); switch (process.argv[2]) { @@ -47,15 +47,15 @@ function parent() { child.stdout.on('data', function(c) { out += c; }); - child.stdout.on('end', function() { + child.stdout.on('end', common.mustCall(() => { assert.strictEqual(out, '10\n'); console.log('ok - got expected output'); - }); + })); - child.on('exit', function(c) { + child.on('exit', common.mustCall((c) => { assert(!c); console.log('ok - exit success'); - }); + })); } function child() { diff --git a/test/js/node/test/parallel/test-require-nul.js b/test/js/node/test/parallel/test-require-nul.js index 5429f06f759b..7756a2d4e2db 100644 --- a/test/js/node/test/parallel/test-require-nul.js +++ b/test/js/node/test/parallel/test-require-nul.js @@ -5,7 +5,7 @@ const assert = require('assert'); // Nul bytes should throw, not abort. /* eslint-disable no-control-regex */ -assert.throws(() => require('\u0000ab'), /'\u0000ab'/); -assert.throws(() => require('a\u0000b'), /'a\u0000b'/); -assert.throws(() => require('ab\u0000'), /'ab\u0000'/); +assert.throws(() => require('\u0000ab'), /Cannot find module '\u0000ab'/); +assert.throws(() => require('a\u0000b'), /Cannot find module 'a\u0000b'/); +assert.throws(() => require('ab\u0000'), /Cannot find module 'ab\u0000'/); /* eslint-enable no-control-regex */ diff --git a/test/js/node/test/parallel/test-require-symlink.js b/test/js/node/test/parallel/test-require-symlink.js index 9ca543e8d64c..6e3035171710 100644 --- a/test/js/node/test/parallel/test-require-symlink.js +++ b/test/js/node/test/parallel/test-require-symlink.js @@ -76,19 +76,19 @@ function test() { // Load symlinked-script as main const node = process.execPath; const child = spawn(node, ['--preserve-symlinks', linkScript]); - child.on('close', function(code, signal) { + child.on('close', common.mustCall((code, signal) => { assert.strictEqual(code, 0); assert(!signal); - }); + })); // Also verify that symlinks works for setting preserve via env variables const childEnv = spawn(node, [linkScript], { env: { ...process.env, NODE_PRESERVE_SYMLINKS: '1' } }); - childEnv.on('close', function(code, signal) { + childEnv.on('close', common.mustCall((code, signal) => { assert.strictEqual(code, 0); assert(!signal); - }); + })); // Also verify that symlinks works for setting preserve via env variables in // Workers. diff --git a/test/js/node/test/parallel/test-runner-mock-timers.js b/test/js/node/test/parallel/test-runner-mock-timers.js index ad63344f7d02..25510fe023d0 100644 --- a/test/js/node/test/parallel/test-runner-mock-timers.js +++ b/test/js/node/test/parallel/test-runner-mock-timers.js @@ -133,6 +133,7 @@ describe('Mock Timers Test Suite', () => { t.mock.timers.enable(); const fn = t.mock.fn(); globalThis.setTimeout(fn, 1000); + // TODO(benjamingr) refactor to `using` t.mock.timers[Symbol.dispose](); assert.throws(() => { t.mock.timers.tick(1000); diff --git a/test/js/node/test/parallel/test-safe-get-env.js b/test/js/node/test/parallel/test-safe-get-env.js index 01bd6423b2c8..f57dcb566d67 100644 --- a/test/js/node/test/parallel/test-safe-get-env.js +++ b/test/js/node/test/parallel/test-safe-get-env.js @@ -6,7 +6,7 @@ const assert = require('assert'); const { internalBinding } = require('internal/test/binding'); const { safeGetenv } = internalBinding('credentials'); -// Upstream note (joyeecheung): this test is not entirely useful. To properly +// FIXME(joyeecheung): this test is not entirely useful. To properly // test this we could create a mismatch between the effective/real // group/user id of a Node.js process and see if the environment variables // are no longer available - but that might be tricky to set up reliably. diff --git a/test/js/node/test/parallel/test-spawn-cmd-named-pipe.js b/test/js/node/test/parallel/test-spawn-cmd-named-pipe.js index bfc3ce4a39fe..e9eb206b1b1f 100644 --- a/test/js/node/test/parallel/test-spawn-cmd-named-pipe.js +++ b/test/js/node/test/parallel/test-spawn-cmd-named-pipe.js @@ -3,7 +3,6 @@ const common = require('../common'); // This test is intended for Windows only if (!common.isWindows) common.skip('this test is Windows-specific.'); -if (common.isWindows) return; // TODO: BUN const assert = require('assert'); @@ -17,22 +16,22 @@ if (!process.argv[2]) { const stdinPipeName = `\\\\.\\pipe\\${pipeNamePrefix}.stdin`; const stdoutPipeName = `\\\\.\\pipe\\${pipeNamePrefix}.stdout`; - const stdinPipeServer = net.createServer(function(c) { + const stdinPipeServer = net.createServer(common.mustCall((c) => { c.on('end', common.mustCall()); c.end('hello'); - }); + })); stdinPipeServer.listen(stdinPipeName); const output = []; - const stdoutPipeServer = net.createServer(function(c) { + const stdoutPipeServer = net.createServer(common.mustCallAtLeast((c) => { c.on('data', function(x) { output.push(x); }); c.on('end', common.mustCall(function() { assert.strictEqual(output.join(''), 'hello'); })); - }); + })); stdoutPipeServer.listen(stdoutPipeName); const args = diff --git a/test/js/node/test/parallel/test-stdin-pipe-resume.js b/test/js/node/test/parallel/test-stdin-pipe-resume.js index e9000933a37c..90e41b95405b 100644 --- a/test/js/node/test/parallel/test-stdin-pipe-resume.js +++ b/test/js/node/test/parallel/test-stdin-pipe-resume.js @@ -1,6 +1,6 @@ 'use strict'; // This tests that piping stdin will cause it to resume() as well. -require('../common'); +const common = require('../common'); const assert = require('assert'); if (process.argv[2] === 'child') { @@ -12,11 +12,11 @@ if (process.argv[2] === 'child') { child.stdout.on('data', function(c) { buffers.push(c); }); - child.stdout.on('close', function() { + child.stdout.on('close', common.mustCall(() => { const b = Buffer.concat(buffers).toString(); assert.strictEqual(b, 'Hello, world\n'); console.log('ok'); - }); + })); child.stdin.write('Hel'); child.stdin.write('lo,'); child.stdin.write(' wo'); diff --git a/test/js/node/test/parallel/test-stdio-pipe-stderr.js b/test/js/node/test/parallel/test-stdio-pipe-stderr.js index c914877062c4..ba4d2b71772c 100644 --- a/test/js/node/test/parallel/test-stdio-pipe-stderr.js +++ b/test/js/node/test/parallel/test-stdio-pipe-stderr.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const tmpdir = require('../common/tmpdir'); const assert = require('assert'); const fs = require('fs'); @@ -19,7 +19,7 @@ const stream = fs.createWriteStream(stderrOutputPath); // non-built-in module. fs.writeFileSync(fakeModulePath, '', 'utf8'); -stream.on('open', () => { +stream.on('open', common.mustCall(() => { spawnSync(process.execPath, { input: `require(${JSON.stringify(fakeModulePath)})`, stdio: ['pipe', 'pipe', stream] @@ -33,4 +33,4 @@ stream.on('open', () => { stream.end(); fs.unlinkSync(stderrOutputPath); fs.unlinkSync(fakeModulePath); -}); +})); diff --git a/test/js/node/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js b/test/js/node/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js index 7cd4b90c008a..ac2a8706890e 100644 --- a/test/js/node/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js +++ b/test/js/node/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); if (process.argv[2] === 'child') @@ -23,10 +23,10 @@ function parent() { err += c; }); - child.on('close', function(code, signal) { + child.on('close', common.mustCall((code, signal) => { assert.strictEqual(code, 0); assert.strictEqual(err, ''); assert.strictEqual(out, 'foo'); console.log('ok'); - }); + })); } diff --git a/test/js/node/test/parallel/test-stream-readable-infinite-read.js b/test/js/node/test/parallel/test-stream-readable-infinite-read.js index 9d39b1fc6cdb..8360df52ed7d 100644 --- a/test/js/node/test/parallel/test-stream-readable-infinite-read.js +++ b/test/js/node/test/parallel/test-stream-readable-infinite-read.js @@ -17,12 +17,9 @@ let i = 0; readable.on('readable', common.mustCall(function() { if (i++ === 10) { - // We will just terminate now. readable.removeAllListeners('readable'); return; } - const data = readable.read(); - // read() with no size returns a single buffered chunk at a time. - assert.strictEqual(data.length, 8192); + assert.strictEqual(readable.read().length, 8192); }, 11)); diff --git a/test/js/node/test/parallel/test-stream-typedarray.js b/test/js/node/test/parallel/test-stream-typedarray.js index 55d92aa31eda..5ef2733a91bd 100644 --- a/test/js/node/test/parallel/test-stream-typedarray.js +++ b/test/js/node/test/parallel/test-stream-typedarray.js @@ -83,12 +83,19 @@ const views = common.getArrayBufferViews(buffer); readable.push(views[2]); readable.unshift(views[0]); - // read() with no size returns one buffered chunk at a time. - const buf = readable.read(); + let buf; + + buf = readable.read(); assert(buf instanceof Buffer); assert.deepStrictEqual([...buf], [...views[0]]); - assert.deepStrictEqual([...readable.read()], [...views[1]]); - assert.deepStrictEqual([...readable.read()], [...views[2]]); + + buf = readable.read(); + assert(buf instanceof Buffer); + assert.deepStrictEqual([...buf], [...views[1]]); + + buf = readable.read(); + assert(buf instanceof Buffer); + assert.deepStrictEqual([...buf], [...views[2]]); } { diff --git a/test/js/node/test/parallel/test-stream-uint8array.js b/test/js/node/test/parallel/test-stream-uint8array.js index 5ffdbbbc54b4..a34f6e1e5a48 100644 --- a/test/js/node/test/parallel/test-stream-uint8array.js +++ b/test/js/node/test/parallel/test-stream-uint8array.js @@ -80,11 +80,15 @@ const GHI = new Uint8Array([0x47, 0x48, 0x49]); readable.push(DEF); readable.unshift(ABC); - // read() with no size returns one buffered chunk at a time. - const buf = readable.read(); + let buf; + + buf = readable.read(); assert(buf instanceof Buffer); assert.deepStrictEqual([...buf], [...ABC]); - assert.deepStrictEqual([...readable.read()], [...DEF]); + + buf = readable.read(); + assert(buf instanceof Buffer); + assert.deepStrictEqual([...buf], [...DEF]); } { diff --git a/test/js/node/test/parallel/test-stream2-transform.js b/test/js/node/test/parallel/test-stream2-transform.js index a7d0f236d787..457001fd8869 100644 --- a/test/js/node/test/parallel/test-stream2-transform.js +++ b/test/js/node/test/parallel/test-stream2-transform.js @@ -282,7 +282,6 @@ const { PassThrough, Transform } = require('stream'); pt.write(Buffer.from('ef'), common.mustCall(function() { pt.end(); })); - // read() with no size returns one buffered chunk at a time. assert.strictEqual(pt.read().toString(), 'abc'); assert.strictEqual(pt.read().toString(), 'd'); assert.strictEqual(pt.read().toString(), 'ef'); diff --git a/test/js/node/test/parallel/test-timers-immediate-queue.js b/test/js/node/test/parallel/test-timers-immediate-queue.js index d67b98a431f2..8b433ddedbf4 100644 --- a/test/js/node/test/parallel/test-timers-immediate-queue.js +++ b/test/js/node/test/parallel/test-timers-immediate-queue.js @@ -39,10 +39,7 @@ function run() { if (hit === 0) { setTimeout(() => { ticked = true; }, 1); const now = Date.now(); - // BUN: blocking duration changed from 2ms to 20ms as our Date.now() is slightly less precise - // than Node on Windows, and setTimeout() uses a different clock than Date.now(), so sometimes - // this loop will finish blocking for 2ms but the setTimeout() will not fire yet - while (Date.now() - now < 20); + while (Date.now() - now < 2); } if (ticked) return; diff --git a/test/js/node/test/parallel/test-timers-nan-duration-warning-promises.js b/test/js/node/test/parallel/test-timers-nan-duration-warning-promises.js index 2a7cbeb2fb7d..ae2f8e1234b9 100644 --- a/test/js/node/test/parallel/test-timers-nan-duration-warning-promises.js +++ b/test/js/node/test/parallel/test-timers-nan-duration-warning-promises.js @@ -8,4 +8,4 @@ process.once('warning', common.mustCall((warning) => { assert.strictEqual(warning.name, 'TimeoutNaNWarning'); })); -setTimeout(NaN).then(common.mustCall(), common.mustNotCall()); +setTimeout(NaN).then(common.mustCall()); diff --git a/test/js/node/test/parallel/test-timers-promises.js b/test/js/node/test/parallel/test-timers-promises.js index 4df8d7444713..6729bf12caf3 100644 --- a/test/js/node/test/parallel/test-timers-promises.js +++ b/test/js/node/test/parallel/test-timers-promises.js @@ -5,5 +5,8 @@ const common = require('../common'); const timer = require('node:timers'); const timerPromises = require('node:timers/promises'); const assert = require('assert'); +const { test } = require('node:test'); -assert.deepStrictEqual(timerPromises, timer.promises); +test('(node:timers/promises) is equal to (node:timers).promises', common.mustCall(() => { + assert.deepStrictEqual(timerPromises, timer.promises); +})); diff --git a/test/js/node/test/parallel/test-timers-unref-throw-then-ref.js b/test/js/node/test/parallel/test-timers-unref-throw-then-ref.js index 1dd5fdd0ad27..d9f23ea19284 100644 --- a/test/js/node/test/parallel/test-timers-unref-throw-then-ref.js +++ b/test/js/node/test/parallel/test-timers-unref-throw-then-ref.js @@ -9,11 +9,11 @@ process.once('uncaughtException', common.mustCall((err) => { })); let called = false; -const t = setTimeout(() => { +const t = setTimeout(common.mustCall(() => { assert(!called); called = true; t.ref(); throw new Error('Timeout Error'); -}, 1).unref(); +}), 1).unref(); setTimeout(common.mustCall(), 1); diff --git a/test/js/node/test/parallel/test-timers-user-call.js b/test/js/node/test/parallel/test-timers-user-call.js index 4ff24e688b5a..9ebb6896d042 100644 --- a/test/js/node/test/parallel/test-timers-user-call.js +++ b/test/js/node/test/parallel/test-timers-user-call.js @@ -25,12 +25,12 @@ const common = require('../common'); } { - const testInterval = (...args) => { + const testInterval = common.mustCall((...args) => { const fn = common.mustCall(() => { clearInterval(interval); }); fn.call = 'not a function'; fn.apply = 'also not a function'; const interval = setInterval(fn, 1, ...args); - }; + }, 5); testInterval(); testInterval('oneArg'); diff --git a/test/js/node/test/parallel/test-tty-stdin-pipe.js b/test/js/node/test/parallel/test-tty-stdin-pipe.js index 9e9415320603..f0bb614e7ae8 100644 --- a/test/js/node/test/parallel/test-tty-stdin-pipe.js +++ b/test/js/node/test/parallel/test-tty-stdin-pipe.js @@ -20,29 +20,20 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; -require('../common'); +const common = require('../common'); // This test ensures piping from `stdin` isn't broken. // https://github.com/nodejs/node/issues/5927 -const assert = require('assert'); const readline = require('readline'); const rl = readline.createInterface(process.stdin, process.stdout); rl.resume(); -let hasPaused = false; - const origPause = rl.pause; -rl.pause = function() { - hasPaused = true; - origPause.apply(this, arguments); -}; - -const origSetRawMode = rl._setRawMode; -rl._setRawMode = function(mode) { - assert.ok(hasPaused); - origSetRawMode.apply(this, arguments); -}; +rl.pause = common.mustCall(function pause() { + Reflect.apply(origPause, this, arguments); +}); +rl._setRawMode = common.mustNotCall(); rl.close(); diff --git a/test/js/node/test/parallel/test-tz-version.js b/test/js/node/test/parallel/test-tz-version.js index 6e4b14e1ac18..e08c12fdd6e5 100644 --- a/test/js/node/test/parallel/test-tz-version.js +++ b/test/js/node/test/parallel/test-tz-version.js @@ -21,8 +21,8 @@ const fixtures = require('../common/fixtures'); // This test ensures the correctness of the automated timezone upgrade PRs. -const { strictEqual } = require('assert'); +const assert = require('assert'); const { readFileSync } = require('fs'); const expectedVersion = readFileSync(fixtures.path('tz-version.txt'), 'utf8').trim(); -strictEqual(process.versions.tz, expectedVersion); +assert.strictEqual(process.versions.tz, expectedVersion); diff --git a/test/js/node/test/parallel/test-url-domain-ascii-unicode.js b/test/js/node/test/parallel/test-url-domain-ascii-unicode.js index 737294c241fb..ebbeba427ee6 100644 --- a/test/js/node/test/parallel/test-url-domain-ascii-unicode.js +++ b/test/js/node/test/parallel/test-url-domain-ascii-unicode.js @@ -1,14 +1,10 @@ 'use strict'; -const common = require('../common'); -if (!common.hasIntl) - common.skip('missing Intl'); +const { hasIntl } = require('../common'); -const strictEqual = require('assert').strictEqual; -const url = require('url'); - -const domainToASCII = url.domainToASCII; -const domainToUnicode = url.domainToUnicode; +const assert = require('node:assert'); +const { domainToASCII, domainToUnicode } = require('node:url'); +const { test } = require('node:test'); const domainWithASCII = [ ['ıíd', 'xn--d-iga7r'], @@ -21,11 +17,11 @@ const domainWithASCII = [ ['भारत.org', 'xn--h2brj9c.org'], ]; -domainWithASCII.forEach((pair) => { - const domain = pair[0]; - const ascii = pair[1]; - const domainConvertedToASCII = domainToASCII(domain); - strictEqual(domainConvertedToASCII, ascii); - const asciiConvertedToUnicode = domainToUnicode(ascii); - strictEqual(asciiConvertedToUnicode, domain); +test('domainToASCII and domainToUnicode', { skip: !hasIntl }, () => { + for (const [domain, ascii] of domainWithASCII) { + const domainConvertedToASCII = domainToASCII(domain); + assert.strictEqual(domainConvertedToASCII, ascii); + const asciiConvertedToUnicode = domainToUnicode(ascii); + assert.strictEqual(asciiConvertedToUnicode, domain); + } }); diff --git a/test/js/node/test/parallel/test-url-format-invalid-input.js b/test/js/node/test/parallel/test-url-format-invalid-input.js index ac3d28c841dc..4395ececfe64 100644 --- a/test/js/node/test/parallel/test-url-format-invalid-input.js +++ b/test/js/node/test/parallel/test-url-format-invalid-input.js @@ -18,8 +18,7 @@ test('format invalid input', () => { ]; for (const urlObject of throwsObjsAndReportTypes) { - console.log(urlObject) - assert.throws(function runFormat() { + assert.throws(() => { url.format(urlObject); }, { code: 'ERR_INVALID_ARG_TYPE', diff --git a/test/js/node/test/parallel/test-url-format-whatwg.js b/test/js/node/test/parallel/test-url-format-whatwg.js index bf9f8eaac632..12594335d6bd 100644 --- a/test/js/node/test/parallel/test-url-format-whatwg.js +++ b/test/js/node/test/parallel/test-url-format-whatwg.js @@ -1,147 +1,157 @@ 'use strict'; -const common = require('../common'); -if (!common.hasIntl) - common.skip('missing Intl'); +const { hasIntl } = require('../common'); -const assert = require('assert'); -const url = require('url'); +const assert = require('node:assert'); +const url = require('node:url'); +const { test } = require('node:test'); const myURL = new URL('http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c'); -assert.strictEqual( - url.format(myURL), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' -); +test('should format', { skip: !hasIntl }, () => { + assert.strictEqual( + url.format(myURL), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' + ); -assert.strictEqual( - url.format(myURL, {}), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' -); + assert.strictEqual( + url.format(myURL, {}), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' + ); +}); -{ - [true, 1, 'test', Infinity].forEach((value) => { +test('handle invalid arguments', { skip: !hasIntl }, () => { + for (const value of [true, 1, 'test', Infinity]) { assert.throws( () => url.format(myURL, value), { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', - message: 'The "options" argument must be of type object.' + - common.invalidArgTypeHelper(value) } ); - }); -} - -// Any falsy value other than undefined will be treated as false. -// Any truthy value will be treated as true. - -assert.strictEqual( - url.format(myURL, { auth: false }), - 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' -); - -assert.strictEqual( - url.format(myURL, { auth: '' }), - 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' -); - -assert.strictEqual( - url.format(myURL, { auth: 0 }), - 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' -); - -assert.strictEqual( - url.format(myURL, { auth: 1 }), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' -); - -assert.strictEqual( - url.format(myURL, { auth: {} }), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' -); - -assert.strictEqual( - url.format(myURL, { fragment: false }), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b' -); - -assert.strictEqual( - url.format(myURL, { fragment: '' }), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b' -); - -assert.strictEqual( - url.format(myURL, { fragment: 0 }), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b' -); - -assert.strictEqual( - url.format(myURL, { fragment: 1 }), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' -); - -assert.strictEqual( - url.format(myURL, { fragment: {} }), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' -); - -assert.strictEqual( - url.format(myURL, { search: false }), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a#c' -); - -assert.strictEqual( - url.format(myURL, { search: '' }), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a#c' -); - -assert.strictEqual( - url.format(myURL, { search: 0 }), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a#c' -); - -assert.strictEqual( - url.format(myURL, { search: 1 }), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' -); - -assert.strictEqual( - url.format(myURL, { search: {} }), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' -); - -assert.strictEqual( - url.format(myURL, { unicode: true }), - 'http://user:pass@理容ナカムラ.com/a?a=b#c' -); - -assert.strictEqual( - url.format(myURL, { unicode: 1 }), - 'http://user:pass@理容ナカムラ.com/a?a=b#c' -); - -assert.strictEqual( - url.format(myURL, { unicode: {} }), - 'http://user:pass@理容ナカムラ.com/a?a=b#c' -); - -assert.strictEqual( - url.format(myURL, { unicode: false }), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' -); - -assert.strictEqual( - url.format(myURL, { unicode: 0 }), - 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' -); - -assert.strictEqual( - url.format(new URL('http://user:pass@xn--0zwm56d.com:8080/path'), { unicode: true }), - 'http://user:pass@测试.com:8080/path' -); - -assert.strictEqual( - url.format(new URL('tel:123')), - url.format(new URL('tel:123'), { unicode: true }) -); + } +}); + +test('any falsy value other than undefined will be treated as false', { skip: !hasIntl }, () => { + assert.strictEqual( + url.format(myURL, { auth: false }), + 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' + ); + + assert.strictEqual( + url.format(myURL, { auth: '' }), + 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' + ); + + assert.strictEqual( + url.format(myURL, { auth: 0 }), + 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' + ); + + assert.strictEqual( + url.format(myURL, { auth: 1 }), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' + ); + + assert.strictEqual( + url.format(myURL, { auth: {} }), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' + ); + + assert.strictEqual( + url.format(myURL, { fragment: false }), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b' + ); + + assert.strictEqual( + url.format(myURL, { fragment: '' }), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b' + ); + + assert.strictEqual( + url.format(myURL, { fragment: 0 }), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b' + ); + + assert.strictEqual( + url.format(myURL, { fragment: 1 }), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' + ); + + assert.strictEqual( + url.format(myURL, { fragment: {} }), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' + ); + + assert.strictEqual( + url.format(myURL, { search: false }), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a#c' + ); + + assert.strictEqual( + url.format(myURL, { search: '' }), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a#c' + ); + + assert.strictEqual( + url.format(myURL, { search: 0 }), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a#c' + ); + + assert.strictEqual( + url.format(myURL, { search: 1 }), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' + ); + + assert.strictEqual( + url.format(myURL, { search: {} }), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' + ); + + assert.strictEqual( + url.format(myURL, { unicode: true }), + 'http://user:pass@理容ナカムラ.com/a?a=b#c' + ); + + assert.strictEqual( + url.format(myURL, { unicode: 1 }), + 'http://user:pass@理容ナカムラ.com/a?a=b#c' + ); + + assert.strictEqual( + url.format(myURL, { unicode: {} }), + 'http://user:pass@理容ナカムラ.com/a?a=b#c' + ); + + assert.strictEqual( + url.format(myURL, { unicode: false }), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' + ); + + assert.strictEqual( + url.format(myURL, { unicode: 0 }), + 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' + ); +}); + +test('should format with unicode: true', { skip: !hasIntl }, () => { + assert.strictEqual( + url.format(new URL('http://user:pass@xn--0zwm56d.com:8080/path'), { unicode: true }), + 'http://user:pass@测试.com:8080/path' + ); +}); + +test('should format tel: prefix', { skip: !hasIntl }, () => { + assert.strictEqual( + url.format(new URL('tel:123')), + url.format(new URL('tel:123'), { unicode: true }) + ); +}); + +// Regression test: url.format should not crash on URLs that ada::url_aggregator +// can parse but ada::url cannot (e.g. special scheme URLs with opaque paths). +test('should not crash on URLs with invalid IDN hostnames', () => { + const u = new URL('ws:xn-\u022B'); + // doesNotThrow + url.format(u, { fragment: false, unicode: false, auth: false, search: false }); +}); diff --git a/test/js/node/test/parallel/test-url-format.js b/test/js/node/test/parallel/test-url-format.js index 883d060ac2a1..4de8f51ef27e 100644 --- a/test/js/node/test/parallel/test-url-format.js +++ b/test/js/node/test/parallel/test-url-format.js @@ -1,277 +1,278 @@ 'use strict'; -const common = require('../common'); -const assert = require('assert'); -const url = require('url'); -if (!common.hasIntl) - common.skip('missing Intl'); +const { hasIntl } = require('../common'); -// Formatting tests to verify that it'll format slightly wonky content to a -// valid URL. -const formatTests = { - 'http://example.com?': { - href: 'http://example.com/?', - protocol: 'http:', - slashes: true, - host: 'example.com', - hostname: 'example.com', - search: '?', - query: {}, - pathname: '/' - }, - 'http://example.com?foo=bar#frag': { - href: 'http://example.com/?foo=bar#frag', - protocol: 'http:', - host: 'example.com', - hostname: 'example.com', - hash: '#frag', - search: '?foo=bar', - query: 'foo=bar', - pathname: '/' - }, - 'http://example.com?foo=@bar#frag': { - href: 'http://example.com/?foo=@bar#frag', - protocol: 'http:', - host: 'example.com', - hostname: 'example.com', - hash: '#frag', - search: '?foo=@bar', - query: 'foo=@bar', - pathname: '/' - }, - 'http://example.com?foo=/bar/#frag': { - href: 'http://example.com/?foo=/bar/#frag', - protocol: 'http:', - host: 'example.com', - hostname: 'example.com', - hash: '#frag', - search: '?foo=/bar/', - query: 'foo=/bar/', - pathname: '/' - }, - 'http://example.com?foo=?bar/#frag': { - href: 'http://example.com/?foo=?bar/#frag', - protocol: 'http:', - host: 'example.com', - hostname: 'example.com', - hash: '#frag', - search: '?foo=?bar/', - query: 'foo=?bar/', - pathname: '/' - }, - 'http://example.com#frag=?bar/#frag': { - href: 'http://example.com/#frag=?bar/#frag', - protocol: 'http:', - host: 'example.com', - hostname: 'example.com', - hash: '#frag=?bar/#frag', - pathname: '/' - }, - 'http://google.com" onload="alert(42)/': { - href: 'http://google.com/%22%20onload=%22alert(42)/', - protocol: 'http:', - host: 'google.com', - pathname: '/%22%20onload=%22alert(42)/' - }, - 'http://a.com/a/b/c?s#h': { - href: 'http://a.com/a/b/c?s#h', - protocol: 'http', - host: 'a.com', - pathname: 'a/b/c', - hash: 'h', - search: 's' - }, - 'xmpp:isaacschlueter@jabber.org': { - href: 'xmpp:isaacschlueter@jabber.org', - protocol: 'xmpp:', - host: 'jabber.org', - auth: 'isaacschlueter', - hostname: 'jabber.org' - }, - 'http://atpass:foo%40bar@127.0.0.1/': { - href: 'http://atpass:foo%40bar@127.0.0.1/', - auth: 'atpass:foo@bar', - hostname: '127.0.0.1', - protocol: 'http:', - pathname: '/' - }, - 'http://atslash%2F%40:%2F%40@foo/': { - href: 'http://atslash%2F%40:%2F%40@foo/', - auth: 'atslash/@:/@', - hostname: 'foo', - protocol: 'http:', - pathname: '/' - }, - 'svn+ssh://foo/bar': { - href: 'svn+ssh://foo/bar', - hostname: 'foo', - protocol: 'svn+ssh:', - pathname: '/bar', - slashes: true - }, - 'dash-test://foo/bar': { - href: 'dash-test://foo/bar', - hostname: 'foo', - protocol: 'dash-test:', - pathname: '/bar', - slashes: true - }, - 'dash-test:foo/bar': { - href: 'dash-test:foo/bar', - hostname: 'foo', - protocol: 'dash-test:', - pathname: '/bar' - }, - 'dot.test://foo/bar': { - href: 'dot.test://foo/bar', - hostname: 'foo', - protocol: 'dot.test:', - pathname: '/bar', - slashes: true - }, - 'dot.test:foo/bar': { - href: 'dot.test:foo/bar', - hostname: 'foo', - protocol: 'dot.test:', - pathname: '/bar' - }, - // IPv6 support - 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature': { - href: 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature', - protocol: 'coap:', - auth: 'u:p', - hostname: '::1', - port: '61616', - pathname: '/.well-known/r', - search: 'n=Temperature' - }, - 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton': { - href: 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton', - protocol: 'coap', - host: '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616', - pathname: '/s/stopButton' - }, - 'http://[::]/': { - href: 'http://[::]/', - protocol: 'http:', - hostname: '[::]', - pathname: '/' - }, +const assert = require('node:assert'); +const url = require('node:url'); +const { test } = require('node:test'); - // Encode context-specific delimiters in path and query, but do not touch - // other non-delimiter chars like `%`. - // +test('format slightly wonky content to a valid URL', { skip: !hasIntl }, () => { + const formatTests = { + 'http://example.com?': { + href: 'http://example.com/?', + protocol: 'http:', + slashes: true, + host: 'example.com', + hostname: 'example.com', + search: '?', + query: {}, + pathname: '/' + }, + 'http://example.com?foo=bar#frag': { + href: 'http://example.com/?foo=bar#frag', + protocol: 'http:', + host: 'example.com', + hostname: 'example.com', + hash: '#frag', + search: '?foo=bar', + query: 'foo=bar', + pathname: '/' + }, + 'http://example.com?foo=@bar#frag': { + href: 'http://example.com/?foo=@bar#frag', + protocol: 'http:', + host: 'example.com', + hostname: 'example.com', + hash: '#frag', + search: '?foo=@bar', + query: 'foo=@bar', + pathname: '/' + }, + 'http://example.com?foo=/bar/#frag': { + href: 'http://example.com/?foo=/bar/#frag', + protocol: 'http:', + host: 'example.com', + hostname: 'example.com', + hash: '#frag', + search: '?foo=/bar/', + query: 'foo=/bar/', + pathname: '/' + }, + 'http://example.com?foo=?bar/#frag': { + href: 'http://example.com/?foo=?bar/#frag', + protocol: 'http:', + host: 'example.com', + hostname: 'example.com', + hash: '#frag', + search: '?foo=?bar/', + query: 'foo=?bar/', + pathname: '/' + }, + 'http://example.com#frag=?bar/#frag': { + href: 'http://example.com/#frag=?bar/#frag', + protocol: 'http:', + host: 'example.com', + hostname: 'example.com', + hash: '#frag=?bar/#frag', + pathname: '/' + }, + 'http://google.com" onload="alert(42)/': { + href: 'http://google.com/%22%20onload=%22alert(42)/', + protocol: 'http:', + host: 'google.com', + pathname: '/%22%20onload=%22alert(42)/' + }, + 'http://a.com/a/b/c?s#h': { + href: 'http://a.com/a/b/c?s#h', + protocol: 'http', + host: 'a.com', + pathname: 'a/b/c', + hash: 'h', + search: 's' + }, + 'xmpp:isaacschlueter@jabber.org': { + href: 'xmpp:isaacschlueter@jabber.org', + protocol: 'xmpp:', + host: 'jabber.org', + auth: 'isaacschlueter', + hostname: 'jabber.org' + }, + 'http://atpass:foo%40bar@127.0.0.1/': { + href: 'http://atpass:foo%40bar@127.0.0.1/', + auth: 'atpass:foo@bar', + hostname: '127.0.0.1', + protocol: 'http:', + pathname: '/' + }, + 'http://atslash%2F%40:%2F%40@foo/': { + href: 'http://atslash%2F%40:%2F%40@foo/', + auth: 'atslash/@:/@', + hostname: 'foo', + protocol: 'http:', + pathname: '/' + }, + 'svn+ssh://foo/bar': { + href: 'svn+ssh://foo/bar', + hostname: 'foo', + protocol: 'svn+ssh:', + pathname: '/bar', + slashes: true + }, + 'dash-test://foo/bar': { + href: 'dash-test://foo/bar', + hostname: 'foo', + protocol: 'dash-test:', + pathname: '/bar', + slashes: true + }, + 'dash-test:foo/bar': { + href: 'dash-test:foo/bar', + hostname: 'foo', + protocol: 'dash-test:', + pathname: '/bar' + }, + 'dot.test://foo/bar': { + href: 'dot.test://foo/bar', + hostname: 'foo', + protocol: 'dot.test:', + pathname: '/bar', + slashes: true + }, + 'dot.test:foo/bar': { + href: 'dot.test:foo/bar', + hostname: 'foo', + protocol: 'dot.test:', + pathname: '/bar' + }, + // IPv6 support + 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature': { + href: 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature', + protocol: 'coap:', + auth: 'u:p', + hostname: '::1', + port: '61616', + pathname: '/.well-known/r', + search: 'n=Temperature' + }, + 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton': { + href: 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton', + protocol: 'coap', + host: '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616', + pathname: '/s/stopButton' + }, + 'http://[::]/': { + href: 'http://[::]/', + protocol: 'http:', + hostname: '[::]', + pathname: '/' + }, + + // Encode context-specific delimiters in path and query, but do not touch + // other non-delimiter chars like `%`. + // - // `#`,`?` in path - '/path/to/%%23%3F+=&.txt?foo=theA1#bar': { - href: '/path/to/%%23%3F+=&.txt?foo=theA1#bar', - pathname: '/path/to/%#?+=&.txt', - query: { - foo: 'theA1' + // `#`,`?` in path + '/path/to/%%23%3F+=&.txt?foo=theA1#bar': { + href: '/path/to/%%23%3F+=&.txt?foo=theA1#bar', + pathname: '/path/to/%#?+=&.txt', + query: { + foo: 'theA1' + }, + hash: '#bar' }, - hash: '#bar' - }, - // `#`,`?` in path + `#` in query - '/path/to/%%23%3F+=&.txt?foo=the%231#bar': { - href: '/path/to/%%23%3F+=&.txt?foo=the%231#bar', - pathname: '/path/to/%#?+=&.txt', - query: { - foo: 'the#1' + // `#`,`?` in path + `#` in query + '/path/to/%%23%3F+=&.txt?foo=the%231#bar': { + href: '/path/to/%%23%3F+=&.txt?foo=the%231#bar', + pathname: '/path/to/%#?+=&.txt', + query: { + foo: 'the#1' + }, + hash: '#bar' }, - hash: '#bar' - }, - // `#` in path end + `#` in query - '/path/to/%%23?foo=the%231#bar': { - href: '/path/to/%%23?foo=the%231#bar', - pathname: '/path/to/%#', - query: { - foo: 'the#1' + // `#` in path end + `#` in query + '/path/to/%%23?foo=the%231#bar': { + href: '/path/to/%%23?foo=the%231#bar', + pathname: '/path/to/%#', + query: { + foo: 'the#1' + }, + hash: '#bar' }, - hash: '#bar' - }, - // `?` and `#` in path and search - 'http://ex.com/foo%3F100%m%23r?abc=the%231?&foo=bar#frag': { - href: 'http://ex.com/foo%3F100%m%23r?abc=the%231?&foo=bar#frag', - protocol: 'http:', - hostname: 'ex.com', - hash: '#frag', - search: '?abc=the#1?&foo=bar', - pathname: '/foo?100%m#r', - }, + // `?` and `#` in path and search + 'http://ex.com/foo%3F100%m%23r?abc=the%231?&foo=bar#frag': { + href: 'http://ex.com/foo%3F100%m%23r?abc=the%231?&foo=bar#frag', + protocol: 'http:', + hostname: 'ex.com', + hash: '#frag', + search: '?abc=the#1?&foo=bar', + pathname: '/foo?100%m#r', + }, - // `?` and `#` in search only - 'http://ex.com/fooA100%mBr?abc=the%231?&foo=bar#frag': { - href: 'http://ex.com/fooA100%mBr?abc=the%231?&foo=bar#frag', - protocol: 'http:', - hostname: 'ex.com', - hash: '#frag', - search: '?abc=the#1?&foo=bar', - pathname: '/fooA100%mBr', - }, + // `?` and `#` in search only + 'http://ex.com/fooA100%mBr?abc=the%231?&foo=bar#frag': { + href: 'http://ex.com/fooA100%mBr?abc=the%231?&foo=bar#frag', + protocol: 'http:', + hostname: 'ex.com', + hash: '#frag', + search: '?abc=the#1?&foo=bar', + pathname: '/fooA100%mBr', + }, + + // Multiple `#` in search + 'http://example.com/?foo=bar%231%232%233&abc=%234%23%235#frag': { + href: 'http://example.com/?foo=bar%231%232%233&abc=%234%23%235#frag', + protocol: 'http:', + slashes: true, + host: 'example.com', + hostname: 'example.com', + hash: '#frag', + search: '?foo=bar#1#2#3&abc=#4##5', + query: {}, + pathname: '/' + }, - // Multiple `#` in search - 'http://example.com/?foo=bar%231%232%233&abc=%234%23%235#frag': { - href: 'http://example.com/?foo=bar%231%232%233&abc=%234%23%235#frag', - protocol: 'http:', - slashes: true, - host: 'example.com', - hostname: 'example.com', - hash: '#frag', - search: '?foo=bar#1#2#3&abc=#4##5', - query: {}, - pathname: '/' - }, + // More than 255 characters in hostname which exceeds the limit + [`http://${'a'.repeat(255)}.com/node`]: { + href: 'http:///node', + protocol: 'http:', + slashes: true, + host: '', + hostname: '', + pathname: '/node', + path: '/node' + }, - // More than 255 characters in hostname which exceeds the limit - [`http://${'a'.repeat(255)}.com/node`]: { - href: 'http:///node', - protocol: 'http:', - slashes: true, - host: '', - hostname: '', - pathname: '/node', - path: '/node' - }, + // Greater than or equal to 63 characters after `.` in hostname + [`http://www.${'z'.repeat(63)}example.com/node`]: { + href: `http://www.${'z'.repeat(63)}example.com/node`, + protocol: 'http:', + slashes: true, + host: `www.${'z'.repeat(63)}example.com`, + hostname: `www.${'z'.repeat(63)}example.com`, + pathname: '/node', + path: '/node' + }, - // Greater than or equal to 63 characters after `.` in hostname - [`http://www.${'z'.repeat(63)}example.com/node`]: { - href: `http://www.${'z'.repeat(63)}example.com/node`, - protocol: 'http:', - slashes: true, - host: `www.${'z'.repeat(63)}example.com`, - hostname: `www.${'z'.repeat(63)}example.com`, - pathname: '/node', - path: '/node' - }, + // https://github.com/nodejs/node/issues/3361 + 'file:///home/user': { + href: 'file:///home/user', + protocol: 'file', + pathname: '/home/user', + path: '/home/user' + }, - // https://github.com/nodejs/node/issues/3361 - 'file:///home/user': { - href: 'file:///home/user', - protocol: 'file', - pathname: '/home/user', - path: '/home/user' - }, + // surrogate in auth + 'http://%F0%9F%98%80@www.example.com/': { + href: 'http://%F0%9F%98%80@www.example.com/', + protocol: 'http:', + auth: '\uD83D\uDE00', + hostname: 'www.example.com', + pathname: '/' + } + }; - // surrogate in auth - 'http://%F0%9F%98%80@www.example.com/': { - href: 'http://%F0%9F%98%80@www.example.com/', - protocol: 'http:', - auth: '\uD83D\uDE00', - hostname: 'www.example.com', - pathname: '/' + for (const u in formatTests) { + const expect = formatTests[u].href; + delete formatTests[u].href; + const actual = url.format(u); + const actualObj = url.format(formatTests[u]); + assert.strictEqual(actual, expect, + `wonky format(${u}) == ${expect}\nactual:${actual}`); + assert.strictEqual(actualObj, expect, + `wonky format(${JSON.stringify(formatTests[u])}) == ${ + expect}\nactual: ${actualObj}`); } -}; -for (const u in formatTests) { - const expect = formatTests[u].href; - delete formatTests[u].href; - const actual = url.format(u); - const actualObj = url.format(formatTests[u]); - assert.strictEqual(actual, expect, - `wonky format(${u}) == ${expect}\nactual:${actual}`); - assert.strictEqual(actualObj, expect, - `wonky format(${JSON.stringify(formatTests[u])}) == ${ - expect}\nactual: ${actualObj}`); -} +}); diff --git a/test/js/node/test/parallel/test-url-parse-format.js b/test/js/node/test/parallel/test-url-parse-format.js index f8761514a30b..405625410fde 100644 --- a/test/js/node/test/parallel/test-url-parse-format.js +++ b/test/js/node/test/parallel/test-url-parse-format.js @@ -1,13 +1,10 @@ 'use strict'; -const common = require('../common'); +const { hasIntl } = require('../common'); -if (!common.hasIntl) - common.skip('missing Intl'); - -const assert = require('assert'); -const inspect = require('util').inspect; - -const url = require('url'); +const assert = require('node:assert'); +const { inspect } = require('node:util'); +const url = require('node:url'); +const { test } = require('node:test'); // URLs to parse, and expected data // { url : parsed } @@ -865,22 +862,6 @@ const parseTests = { href: 'http://a%22%20%3C\'b:b@cd/e?f' }, - // Git urls used by npm - 'git+ssh://git@github.com:npm/npm': { - protocol: 'git+ssh:', - slashes: true, - auth: 'git', - host: 'github.com', - port: null, - hostname: 'github.com', - hash: null, - search: null, - query: null, - pathname: '/:npm/npm', - path: '/:npm/npm', - href: 'git+ssh://git@github.com/:npm/npm' - }, - 'https://*': { protocol: 'https:', slashes: true, @@ -1025,36 +1006,38 @@ const parseTests = { } }; -for (const u in parseTests) { - let actual = url.parse(u); - const spaced = url.parse(` \t ${u}\n\t`); - let expected = Object.assign(new url.Url(), parseTests[u]); - - Object.keys(actual).forEach(function(i) { - if (expected[i] === undefined && actual[i] === null) { - expected[i] = null; - } - }); +test('should parse and format', { skip: !hasIntl }, () => { + for (const u in parseTests) { + let actual = url.parse(u); + const spaced = url.parse(` \t ${u}\n\t`); + let expected = Object.assign(new url.Url(), parseTests[u]); + + Object.keys(actual).forEach(function(i) { + if (expected[i] === undefined && actual[i] === null) { + expected[i] = null; + } + }); + + assert.deepStrictEqual( + actual, + expected, + `parsing ${u} and expected ${inspect(expected)} but got ${inspect(actual)}` + ); + assert.deepStrictEqual( + spaced, + expected, + `expected ${inspect(expected)}, got ${inspect(spaced)}` + ); + + expected = parseTests[u].href; + actual = url.format(parseTests[u]); + + assert.strictEqual(actual, expected, + `format(${u}) == ${u}\nactual:${actual}`); + } +}); - assert.deepStrictEqual( - actual, - expected, - `parsing ${u} and expected ${inspect(expected)} but got ${inspect(actual)}` - ); - assert.deepStrictEqual( - spaced, - expected, - `expected ${inspect(expected)}, got ${inspect(spaced)}` - ); - - expected = parseTests[u].href; - actual = url.format(parseTests[u]); - - assert.strictEqual(actual, expected, - `format(${u}) == ${u}\nactual:${actual}`); -} - -{ +test('parse result should equal new url.Url()', { skip: !hasIntl }, () => { const parsed = url.parse('http://nodejs.org/') .resolveObject('jAvascript:alert(1);a=\x27@white-listed.com\x27'); @@ -1074,4 +1057,4 @@ for (const u in parseTests) { }); assert.deepStrictEqual(parsed, expected); -} +}); diff --git a/test/js/node/test/parallel/test-url-parse-query.js b/test/js/node/test/parallel/test-url-parse-query.js index 9cb21486c126..ac05ed10aa7a 100644 --- a/test/js/node/test/parallel/test-url-parse-query.js +++ b/test/js/node/test/parallel/test-url-parse-query.js @@ -12,18 +12,11 @@ function createWithNoPrototype(properties = []) { } function check(actual, expected) { - // NOTE: Node creates a new object with no prototype when parsing queries. - // Their query parsing logic is written in JS. We re-use URLSearchParams - // from WebCore, which is spec-compliant with newer standards. - // assert.notStrictEqual(Object.getPrototypeOf(actual), Object.prototype); + assert.notStrictEqual(Object.getPrototypeOf(actual), Object.prototype); assert.deepStrictEqual(Object.keys(actual).sort(), Object.keys(expected).sort()); Object.keys(expected).forEach(function(key) { - assert.deepStrictEqual( - actual[key], - expected[key], - `actual[${key}] !== expected[${key}]: ${actual[key]} !== ${expected[key]}` - ); + assert.deepStrictEqual(actual[key], expected[key]); }); } @@ -91,11 +84,7 @@ for (const u in parseTestsWithQueryString) { if (property === 'query') { check(actual[property], expected[property]); } else { - assert.deepStrictEqual( - actual[property], - expected[property], - `${u}\n\nactual['${property}'] !== expected['${property}']: ${actual[property]} !== ${expected[property]}` - ); + assert.deepStrictEqual(actual[property], expected[property]); } }); } diff --git a/test/js/node/test/parallel/test-util-stripvtcontrolcharacters.js b/test/js/node/test/parallel/test-util-stripvtcontrolcharacters.js index a201c78976c0..a33d18d26dbc 100644 --- a/test/js/node/test/parallel/test-util-stripvtcontrolcharacters.js +++ b/test/js/node/test/parallel/test-util-stripvtcontrolcharacters.js @@ -2,7 +2,7 @@ require('../common'); const util = require('util'); -const assert = require('node:assert'); +const { test } = require('node:test'); // Ref: https://github.com/chalk/ansi-regex/blob/main/test.js const tests = [ @@ -21,6 +21,8 @@ for (const ST of ['\u0007', '\u001B\u005C', '\u009C']) { ); } -for (const [before, expected] of tests) { - assert.strictEqual(util.stripVTControlCharacters(before), expected); -} +test('util.stripVTControlCharacters', (t) => { + for (const [before, expected] of tests) { + t.assert.strictEqual(util.stripVTControlCharacters(before), expected); + } +}); diff --git a/test/js/node/test/parallel/test-util-text-decoder.js b/test/js/node/test/parallel/test-util-text-decoder.js index 3f349ec63b07..adf52241c391 100644 --- a/test/js/node/test/parallel/test-util-text-decoder.js +++ b/test/js/node/test/parallel/test-util-text-decoder.js @@ -1,13 +1,63 @@ 'use strict'; -require('../common'); +const common = require('../common'); + +const test = require('node:test'); const assert = require('node:assert'); -const latin1Bytes = new Uint8Array([0xc1, 0xe9, 0xf3]); +test('TextDecoder correctly decodes windows-1252 encoded data', { skip: !common.hasIntl }, () => { + const latin1Bytes = new Uint8Array([0xc1, 0xe9, 0xf3]); + + const expectedString = 'Áéó'; + + const decoder = new TextDecoder('windows-1252'); + const decodedString = decoder.decode(latin1Bytes); + + assert.strictEqual(decodedString, expectedString); +}); + +// Test for the difference between Latin1 and Windows-1252 in the 128-159 +// range +// Ref: https://github.com/nodejs/node/issues/60888 +test('TextDecoder correctly decodes windows-1252 special characters in ' + + '128-159 range', { skip: !common.hasIntl }, () => { + const decoder = new TextDecoder('windows-1252'); -const expectedString = 'Áéó'; + // Test specific characters that differ between Latin1 and Windows-1252. + // € Euro sign + assert.strictEqual(decoder.decode(Uint8Array.of(128)).codePointAt(0), + 8364); + // ‚ Single low-9 quotation mark + assert.strictEqual(decoder.decode(Uint8Array.of(130)).codePointAt(0), + 8218); + // Latin small letter f with hook (ƒ) + assert.strictEqual(decoder.decode(Uint8Array.of(131)).codePointAt(0), + 402); + // Ÿ Latin capital letter Y with diaeresis + assert.strictEqual(decoder.decode(Uint8Array.of(159)).codePointAt(0), + 376); -const decoder = new TextDecoder('windows-1252'); -const decodedString = decoder.decode(latin1Bytes); + // Test the full range to ensure no character is treated as Latin1 + // Directly. + const expectedMappings = [ + [128, 8364], [129, 129], [130, 8218], [131, 402], [132, 8222], + [133, 8230], [134, 8224], [135, 8225], [136, 710], [137, 8240], + [138, 352], [139, 8249], [140, 338], [141, 141], [142, 381], + [143, 143], [144, 144], [145, 8216], [146, 8217], [147, 8220], + [148, 8221], [149, 8226], [150, 8211], [151, 8212], [152, 732], + [153, 8482], [154, 353], [155, 8250], [156, 339], [157, 157], + [158, 382], [159, 376], + ]; -assert.strictEqual(decodedString, expectedString); + for (const [byte, expectedCodePoint] of expectedMappings) { + const result = decoder.decode(Uint8Array.of(byte)); + const actualCodePoint = result.codePointAt(0); + assert.strictEqual( + actualCodePoint, + expectedCodePoint, + `Byte 0x${byte.toString(16)} should decode to ` + + `U+${expectedCodePoint.toString(16)} but got ` + + `U+${actualCodePoint.toString(16)}` + ); + } +}); diff --git a/test/js/node/test/parallel/test-weakref.js b/test/js/node/test/parallel/test-weakref.js index ca7485aaa6a4..f8f37bc2ed72 100644 --- a/test/js/node/test/parallel/test-weakref.js +++ b/test/js/node/test/parallel/test-weakref.js @@ -2,12 +2,12 @@ // Flags: --expose-gc -require('../common'); +const common = require('../common'); const assert = require('assert'); const w = new globalThis.WeakRef({}); -setTimeout(() => { +setTimeout(common.mustCall(() => { globalThis.gc(); assert.strictEqual(w.deref(), undefined); -}, 200); +}), 200); diff --git a/test/js/node/test/parallel/test-whatwg-events-add-event-listener-options-passive.js b/test/js/node/test/parallel/test-whatwg-events-add-event-listener-options-passive.js index 97984bd9aff8..7f37ecc497f9 100644 --- a/test/js/node/test/parallel/test-whatwg-events-add-event-listener-options-passive.js +++ b/test/js/node/test/parallel/test-whatwg-events-add-event-listener-options-passive.js @@ -1,15 +1,11 @@ 'use strict'; -const common = require('../common'); +require('../common'); // Manually converted from https://github.com/web-platform-tests/wpt/blob/master/dom/events/AddEventListenerOptions-passive.html // in order to define the `document` ourselves -const { - fail, - ok, - strictEqual -} = require('assert'); +const assert = require('assert'); { const document = new EventTarget(); @@ -20,17 +16,17 @@ const { return false; }, get dummy() { - fail('dummy value getter invoked'); + assert.fail('dummy value getter invoked'); return false; } }; document.addEventListener('test_event', null, query_options); - ok(supportsPassive); + assert.ok(supportsPassive); supportsPassive = false; document.removeEventListener('test_event', null, query_options); - strictEqual(supportsPassive, false); + assert.strictEqual(supportsPassive, false); } { function testPassiveValue(optionsValue, expectedDefaultPrevented) { @@ -38,7 +34,7 @@ const { let defaultPrevented; function handler(e) { if (e.defaultPrevented) { - fail('Event prematurely marked defaultPrevented'); + assert.fail('Event prematurely marked defaultPrevented'); } e.preventDefault(); defaultPrevented = e.defaultPrevented; @@ -49,8 +45,8 @@ const { const ev = new Event('test', { bubbles: true, cancelable: true }); const uncanceled = document.dispatchEvent(ev); - strictEqual(defaultPrevented, expectedDefaultPrevented); - strictEqual(uncanceled, !expectedDefaultPrevented); + assert.strictEqual(defaultPrevented, expectedDefaultPrevented); + assert.strictEqual(uncanceled, !expectedDefaultPrevented); document.removeEventListener('test', handler, optionsValue); } @@ -58,7 +54,6 @@ const { testPassiveValue({}, true); testPassiveValue({ passive: false }, true); - common.skip('TODO: passive listeners is still broken'); testPassiveValue({ passive: 1 }, false); testPassiveValue({ passive: true }, false); testPassiveValue({ passive: 0 }, true); diff --git a/test/js/node/test/parallel/test-whatwg-events-add-event-listener-options-signal.js b/test/js/node/test/parallel/test-whatwg-events-add-event-listener-options-signal.js index 460d2ee3f276..27aa5c62a4c0 100644 --- a/test/js/node/test/parallel/test-whatwg-events-add-event-listener-options-signal.js +++ b/test/js/node/test/parallel/test-whatwg-events-add-event-listener-options-signal.js @@ -1,11 +1,8 @@ 'use strict'; -require('../common'); +const common = require('../common'); -const { - strictEqual, - throws, -} = require('assert'); +const assert = require('node:assert'); // Manually ported from: wpt@dom/events/AddEventListenerOptions-signal.any.js @@ -13,134 +10,98 @@ const { // Passing an AbortSignal to addEventListener does not prevent // removeEventListener let count = 0; - function handler() { + const handler = common.mustCall(() => { count++; - } + }, 2); const et = new EventTarget(); const controller = new AbortController(); et.addEventListener('test', handler, { signal: controller.signal }); et.dispatchEvent(new Event('test')); - strictEqual(count, 1, 'Adding a signal still adds a listener'); + assert.strictEqual(count, 1); et.dispatchEvent(new Event('test')); - strictEqual(count, 2, 'The listener was not added with the once flag'); controller.abort(); et.dispatchEvent(new Event('test')); - strictEqual(count, 2, 'Aborting on the controller removes the listener'); // See: https://github.com/nodejs/node/pull/37696 , adding an event listener // should always return undefined. - strictEqual( + assert.strictEqual( et.addEventListener('test', handler, { signal: controller.signal }), undefined); et.dispatchEvent(new Event('test')); - strictEqual(count, 2, 'Passing an aborted signal never adds the handler'); } { // Passing an AbortSignal to addEventListener works with the once flag - let count = 0; - function handler() { - count++; - } + const handler = common.mustNotCall(); const et = new EventTarget(); const controller = new AbortController(); et.addEventListener('test', handler, { signal: controller.signal }); et.removeEventListener('test', handler); et.dispatchEvent(new Event('test')); - strictEqual(count, 0, 'The listener was still removed'); } { // Removing a once listener works with a passed signal - let count = 0; - function handler() { - count++; - } const et = new EventTarget(); const controller = new AbortController(); const options = { signal: controller.signal, once: true }; - et.addEventListener('test', handler, options); + et.addEventListener('test', common.mustNotCall(), options); controller.abort(); et.dispatchEvent(new Event('test')); - strictEqual(count, 0, 'The listener was still removed'); } { - let count = 0; - function handler() { - count++; - } + const handler = common.mustNotCall(); const et = new EventTarget(); const controller = new AbortController(); const options = { signal: controller.signal, once: true }; et.addEventListener('test', handler, options); et.removeEventListener('test', handler); et.dispatchEvent(new Event('test')); - strictEqual(count, 0, 'The listener was still removed'); } { // Passing an AbortSignal to multiple listeners - let count = 0; - function handler() { - count++; - } const et = new EventTarget(); const controller = new AbortController(); const options = { signal: controller.signal, once: true }; - et.addEventListener('first', handler, options); - et.addEventListener('second', handler, options); + et.addEventListener('first', common.mustNotCall(), options); + et.addEventListener('second', common.mustNotCall(), options); controller.abort(); et.dispatchEvent(new Event('first')); et.dispatchEvent(new Event('second')); - strictEqual(count, 0, 'The listener was still removed'); } { // Passing an AbortSignal to addEventListener works with the capture flag - let count = 0; - function handler() { - count++; - } const et = new EventTarget(); const controller = new AbortController(); const options = { signal: controller.signal, capture: true }; - et.addEventListener('test', handler, options); + et.addEventListener('test', common.mustNotCall(), options); controller.abort(); et.dispatchEvent(new Event('test')); - strictEqual(count, 0, 'The listener was still removed'); } { // Aborting from a listener does not call future listeners - let count = 0; - function handler() { - count++; - } const et = new EventTarget(); const controller = new AbortController(); const options = { signal: controller.signal }; et.addEventListener('test', () => { controller.abort(); }, options); - et.addEventListener('test', handler, options); + et.addEventListener('test', common.mustNotCall(), options); et.dispatchEvent(new Event('test')); - strictEqual(count, 0, 'The listener was still removed'); } { // Adding then aborting a listener in another listener does not call it - let count = 0; - function handler() { - count++; - } const et = new EventTarget(); const controller = new AbortController(); - et.addEventListener('test', () => { - et.addEventListener('test', handler, { signal: controller.signal }); + et.addEventListener('test', common.mustCall(() => { + et.addEventListener('test', common.mustNotCall(), { signal: controller.signal }); controller.abort(); - }, { signal: controller.signal }); + }), { signal: controller.signal }); et.dispatchEvent(new Event('test')); - strictEqual(count, 0, 'The listener was still removed'); } { @@ -161,7 +122,7 @@ const { { const et = new EventTarget(); [1, 1n, {}, [], null, true, 'hi', Symbol(), () => {}].forEach((signal) => { - throws(() => et.addEventListener('foo', () => {}, { signal }), { + assert.throws(() => et.addEventListener('foo', () => {}, { signal }), { name: 'TypeError', }); }); diff --git a/test/js/node/test/parallel/test-whatwg-events-customevent.js b/test/js/node/test/parallel/test-whatwg-events-customevent.js index e21ea1783f89..75650e47a41f 100644 --- a/test/js/node/test/parallel/test-whatwg-events-customevent.js +++ b/test/js/node/test/parallel/test-whatwg-events-customevent.js @@ -2,7 +2,7 @@ const common = require('../common'); -const { strictEqual, throws, equal } = require('assert'); +const assert = require('assert'); // Manually converted from https://github.com/web-platform-tests/wpt/blob/master/dom/events/CustomEvent.html // in order to define the `document` ourselves @@ -12,22 +12,22 @@ const { strictEqual, throws, equal } = require('assert'); const target = new EventTarget(); target.addEventListener(type, common.mustCall((evt) => { - strictEqual(evt.type, type); + assert.strictEqual(evt.type, type); })); target.dispatchEvent(new Event(type)); } { - throws(() => { + assert.throws(() => { new Event(); }, TypeError); } { const event = new Event('foo'); - equal(event.type, 'foo'); - equal(event.bubbles, false); - equal(event.cancelable, false); - equal(event.detail, null); + assert.strictEqual(event.type, 'foo'); + assert.strictEqual(event.bubbles, false); + assert.strictEqual(event.cancelable, false); + assert.strictEqual(event.detail, undefined); } diff --git a/test/js/node/test/parallel/test-worker-heap-snapshot.js b/test/js/node/test/parallel/test-worker-heap-snapshot.js index 5358f2effca5..20ff3d540f98 100644 --- a/test/js/node/test/parallel/test-worker-heap-snapshot.js +++ b/test/js/node/test/parallel/test-worker-heap-snapshot.js @@ -10,7 +10,8 @@ const { once } = require('events'); const worker = new Worker('setInterval(() => {}, 1000);', { eval: true }); await once(worker, 'online'); const stream = await worker.getHeapSnapshot(); - assert.ok(JSON.parse(stream.read())); + stream.read(0); // Trigger the stream to start flowing + assert.ok(JSON.parse(stream.read(stream.readableLength))); await worker.terminate(); })().then(common.mustCall()); diff --git a/test/js/node/test/parallel/test-worker-message-event.js b/test/js/node/test/parallel/test-worker-message-event.js index 5768514f715a..7bf3b73c0884 100644 --- a/test/js/node/test/parallel/test-worker-message-event.js +++ b/test/js/node/test/parallel/test-worker-message-event.js @@ -79,13 +79,13 @@ const dummyPort = new MessageChannel().port1; new MessageEvent('message', { ports: [ null ] }); }, { name: 'TypeError', - message: /MessageEvent constructor: Expected eventInitDict\.ports\[0\] \("null"\) to be an instance of MessagePort\./, + message: /MessageEvent constructor: Expected eventInitDict\.ports(\[0\])? \("null"\) to be an instance of MessagePort\./, }); assert.throws(() => { new MessageEvent('message', { ports: [ {} ] }); }, { name: 'TypeError', - message: /MessageEvent constructor: Expected eventInitDict\.ports\[0\] \("\{\}"\) to be an instance of MessagePort\./, + message: /MessageEvent constructor: Expected eventInitDict\.ports(\[0\])? \("\{\}"\) to be an instance of MessagePort\./, }); } diff --git a/test/js/node/test/parallel/test-zlib-brotli-16GB.js b/test/js/node/test/parallel/test-zlib-brotli-16GB.js index 9b894320e91e..7bd5a137f908 100644 --- a/test/js/node/test/parallel/test-zlib-brotli-16GB.js +++ b/test/js/node/test/parallel/test-zlib-brotli-16GB.js @@ -2,7 +2,7 @@ const common = require('../common'); const { createBrotliDecompress } = require('node:zlib'); -const strictEqual = require('node:assert').strictEqual; +const assert = require('node:assert'); const { getDefaultHighWaterMark } = require('stream'); // This tiny HEX string is a 16GB file. @@ -19,5 +19,5 @@ decoder.end(buf); // to process the data and the buffer is not empty. setTimeout(common.mustCall(() => { // There is only one chunk in the buffer - strictEqual(decoder._readableState.buffer.length, getDefaultHighWaterMark() / (16 * 1024)); + assert.strictEqual(decoder._readableState.buffer.length, getDefaultHighWaterMark() / (16 * 1024)); }), common.platformTimeout(500)); diff --git a/test/js/node/test/parallel/test-zlib-brotli-kmaxlength-rangeerror.js b/test/js/node/test/parallel/test-zlib-brotli-kmaxlength-rangeerror.js index 6a59ad34b0a1..69f23542cb9a 100644 --- a/test/js/node/test/parallel/test-zlib-brotli-kmaxlength-rangeerror.js +++ b/test/js/node/test/parallel/test-zlib-brotli-kmaxlength-rangeerror.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); // This test ensures that zlib throws a RangeError if the final buffer needs to // be larger than kMaxLength and concatenation fails. @@ -18,9 +18,9 @@ buffer.kMaxLength = oldkMaxLength; const encoded = Buffer.from('G38A+CXCIrFAIAM=', 'base64'); // Async -zlib.brotliDecompress(encoded, function(err) { +zlib.brotliDecompress(encoded, common.mustCall((err) => { assert.ok(err instanceof RangeError); -}); +})); // Sync assert.throws(function() { diff --git a/test/js/node/test/parallel/test-zlib-deflate-constructors.js b/test/js/node/test/parallel/test-zlib-deflate-constructors.js index 4c735c78d000..492048d3d0a1 100644 --- a/test/js/node/test/parallel/test-zlib-deflate-constructors.js +++ b/test/js/node/test/parallel/test-zlib-deflate-constructors.js @@ -1,6 +1,6 @@ 'use strict'; -const common = require('../common'); +require('../common'); const zlib = require('zlib'); const assert = require('assert'); @@ -18,7 +18,8 @@ assert.throws( { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', - message: 'The "options.chunkSize" property must be of type number.' + common.invalidArgTypeHelper('test') + message: 'The "options.chunkSize" property must be of type number. ' + + "Received type string ('test')" } ); @@ -51,7 +52,8 @@ assert.throws( { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', - message: 'The "options.windowBits" property must be of type number.' + common.invalidArgTypeHelper('test') + message: 'The "options.windowBits" property must be of type number. ' + + "Received type string ('test')" } ); @@ -91,7 +93,8 @@ assert.throws( { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', - message: 'The "options.level" property must be of type number.' + common.invalidArgTypeHelper('test') + message: 'The "options.level" property must be of type number. ' + + "Received type string ('test')" } ); @@ -131,7 +134,8 @@ assert.throws( { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', - message: 'The "level" argument must be of type number.' + common.invalidArgTypeHelper('test') + message: 'The "level" argument must be of type number. ' + + "Received type string ('test')" } ); @@ -171,7 +175,8 @@ assert.throws( { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', - message: 'The "options.memLevel" property must be of type number.' + common.invalidArgTypeHelper('test') + message: 'The "options.memLevel" property must be of type number. ' + + "Received type string ('test')" } ); @@ -218,7 +223,8 @@ assert.throws( { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', - message: 'The "options.strategy" property must be of type number.' + common.invalidArgTypeHelper('test') + message: 'The "options.strategy" property must be of type number. ' + + "Received type string ('test')" } ); @@ -258,7 +264,8 @@ assert.throws( { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', - message: 'The "strategy" argument must be of type number.' + common.invalidArgTypeHelper('test') + message: 'The "strategy" argument must be of type number. ' + + "Received type string ('test')" } ); @@ -298,5 +305,8 @@ assert.throws( { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', + message: 'The "options.dictionary" property must be an instance of Buffer' + + ', TypedArray, DataView, or ArrayBuffer. Received type string ' + + "('not a buffer')" } ); diff --git a/test/js/node/test/parallel/test-zlib-flush.js b/test/js/node/test/parallel/test-zlib-flush.js index 557775d5091a..ba3f8019fd81 100644 --- a/test/js/node/test/parallel/test-zlib-flush.js +++ b/test/js/node/test/parallel/test-zlib-flush.js @@ -1,36 +1,38 @@ 'use strict'; + require('../common'); -const assert = require('assert'); -const zlib = require('zlib'); -const fixtures = require('../common/fixtures'); -const file = fixtures.readSync('person.jpg'); -const chunkSize = 16; -const opts = { level: 0 }; -const deflater = zlib.createDeflate(opts); +const assert = require('node:assert'); +const zlib = require('node:zlib'); +const { test } = require('node:test'); + +test('zlib flush', async () => { + const { promise, resolve } = Promise.withResolvers(); -const chunk = file.slice(0, chunkSize); -const expectedNone = Buffer.from([0x78, 0x01]); -const blkhdr = Buffer.from([0x00, 0x10, 0x00, 0xef, 0xff]); -const adler32 = Buffer.from([0x00, 0x00, 0x00, 0xff, 0xff]); -const expectedFull = Buffer.concat([blkhdr, chunk, adler32]); -let actualNone; -let actualFull; + const opts = { level: 0 }; + const deflater = zlib.createDeflate(opts); + const chunk = Buffer.from('/9j/4AAQSkZJRgABAQEASA==', 'base64'); + const expectedNone = Buffer.from([0x78, 0x01]); + const blkhdr = Buffer.from([0x00, 0x10, 0x00, 0xef, 0xff]); + const adler32 = Buffer.from([0x00, 0x00, 0x00, 0xff, 0xff]); + const expectedFull = Buffer.concat([blkhdr, chunk, adler32]); + let actualNone; + let actualFull; -deflater.write(chunk, function() { - deflater.flush(zlib.constants.Z_NO_FLUSH, function() { - actualNone = deflater.read(); - deflater.flush(function() { - const bufs = []; - let buf; - while ((buf = deflater.read()) !== null) - bufs.push(buf); - actualFull = Buffer.concat(bufs); + deflater.write(chunk, function() { + deflater.flush(zlib.constants.Z_NO_FLUSH, function() { + actualNone = deflater.read(); + deflater.flush(function() { + const bufs = []; + let buf; + while ((buf = deflater.read()) !== null) + bufs.push(buf); + actualFull = Buffer.concat(bufs); + resolve(); + }); }); }); -}); - -process.once('exit', function() { + await promise; assert.deepStrictEqual(actualNone, expectedNone); assert.deepStrictEqual(actualFull, expectedFull); }); diff --git a/test/js/node/test/parallel/test-zlib-from-concatenated-gzip.js b/test/js/node/test/parallel/test-zlib-from-concatenated-gzip.js index 1de36dacf95f..31985aa2bbe7 100644 --- a/test/js/node/test/parallel/test-zlib-from-concatenated-gzip.js +++ b/test/js/node/test/parallel/test-zlib-from-concatenated-gzip.js @@ -47,9 +47,7 @@ const pmmResultBuffers = []; fs.createReadStream(pmmFileGz) .pipe(zlib.createGunzip()) - .on('error', (err) => { - assert.ifError(err); - }) + .on('error', common.mustNotCall()) .on('data', (data) => pmmResultBuffers.push(data)) .on('finish', common.mustCall(() => { // Result should match original random garbage @@ -61,9 +59,7 @@ fs.createReadStream(pmmFileGz) const resultBuffers = []; const unzip = zlib.createGunzip() - .on('error', (err) => { - assert.ifError(err); - }) + .on('error', common.mustNotCall()) .on('data', (data) => resultBuffers.push(data)) .on('finish', common.mustCall(() => { assert.strictEqual( diff --git a/test/js/node/test/parallel/test-zlib-kmaxlength-rangeerror.js b/test/js/node/test/parallel/test-zlib-kmaxlength-rangeerror.js index 9803630214eb..bae49a6530a9 100644 --- a/test/js/node/test/parallel/test-zlib-kmaxlength-rangeerror.js +++ b/test/js/node/test/parallel/test-zlib-kmaxlength-rangeerror.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); // This test ensures that zlib throws a RangeError if the final buffer needs to // be larger than kMaxLength and concatenation fails. @@ -18,9 +18,9 @@ buffer.kMaxLength = oldkMaxLength; const encoded = Buffer.from('H4sIAAAAAAAAA0tMHFgAAIw2K/GAAAAA', 'base64'); // Async -zlib.gunzip(encoded, function(err) { +zlib.gunzip(encoded, common.mustCall((err) => { assert.ok(err instanceof RangeError); -}); +})); // Sync assert.throws(function() { diff --git a/test/js/node/test/parallel/test-zlib-maxOutputLength.js b/test/js/node/test/parallel/test-zlib-maxOutputLength.js index 9af0b3736f88..ec293aabe7fc 100644 --- a/test/js/node/test/parallel/test-zlib-maxOutputLength.js +++ b/test/js/node/test/parallel/test-zlib-maxOutputLength.js @@ -17,9 +17,7 @@ assert.throws(function() { }, RangeError); // Async -zlib.brotliDecompress(encoded, { maxOutputLength: 256 }, function(err) { - assert.strictEqual(err, null); -}); +zlib.brotliDecompress(encoded, { maxOutputLength: 256 }, common.mustSucceed()); // Sync zlib.brotliDecompressSync(encoded, { maxOutputLength: 256 }); diff --git a/test/js/node/test/parallel/test-zlib-reset-before-write.js b/test/js/node/test/parallel/test-zlib-reset-before-write.js index afa207f12c1b..05c1cdce2c49 100644 --- a/test/js/node/test/parallel/test-zlib-reset-before-write.js +++ b/test/js/node/test/parallel/test-zlib-reset-before-write.js @@ -21,9 +21,7 @@ for (const fn of [ const output = []; inflate - .on('error', (err) => { - assert.ifError(err); - }) + .on('error', common.mustNotCall()) .on('data', (chunk) => output.push(chunk)) .on('end', common.mustCall( () => assert.strictEqual(Buffer.concat(output).toString(), 'abc'))); diff --git a/test/js/node/test/parallel/test-zlib-truncated.js b/test/js/node/test/parallel/test-zlib-truncated.js index 94bc0e21cb7a..c489388a674e 100644 --- a/test/js/node/test/parallel/test-zlib-truncated.js +++ b/test/js/node/test/parallel/test-zlib-truncated.js @@ -1,7 +1,7 @@ 'use strict'; // Tests zlib streams with truncated compressed input -require('../common'); +const common = require('../common'); const assert = require('assert'); const zlib = require('zlib'); @@ -23,8 +23,7 @@ const errMessage = /unexpected end of file/; { comp: 'deflate', decomp: 'inflate', decompSync: 'inflateSync' }, { comp: 'deflateRaw', decomp: 'inflateRaw', decompSync: 'inflateRawSync' }, ].forEach(function(methods) { - zlib[methods.comp](inputString, function(err, compressed) { - assert.ifError(err); + zlib[methods.comp](inputString, common.mustSucceed((compressed) => { const truncated = compressed.slice(0, compressed.length / 2); const toUTF8 = (buffer) => buffer.toString('utf-8'); @@ -33,10 +32,9 @@ const errMessage = /unexpected end of file/; assert.strictEqual(toUTF8(decompressed), inputString); // async sanity - zlib[methods.decomp](compressed, function(err, result) { - assert.ifError(err); + zlib[methods.decomp](compressed, common.mustSucceed((result) => { assert.strictEqual(toUTF8(result), inputString); - }); + })); // Sync truncated input test assert.throws(function() { @@ -44,9 +42,9 @@ const errMessage = /unexpected end of file/; }, errMessage); // Async truncated input test - zlib[methods.decomp](truncated, function(err, result) { + zlib[methods.decomp](truncated, common.mustCall((err) => { assert.match(err.message, errMessage); - }); + })); const syncFlushOpt = { finishFlush: zlib.constants.Z_SYNC_FLUSH }; @@ -55,10 +53,9 @@ const errMessage = /unexpected end of file/; assert.strictEqual(result, inputString.slice(0, result.length)); // Async truncated input test, finishFlush = Z_SYNC_FLUSH - zlib[methods.decomp](truncated, syncFlushOpt, function(err, decompressed) { - assert.ifError(err); + zlib[methods.decomp](truncated, syncFlushOpt, common.mustSucceed((decompressed) => { const result = toUTF8(decompressed); assert.strictEqual(result, inputString.slice(0, result.length)); - }); - }); + })); + })); }); diff --git a/test/js/node/test/parallel/test-zlib-unzip-one-byte-chunks.js b/test/js/node/test/parallel/test-zlib-unzip-one-byte-chunks.js index 51af5153a4dd..8fb8bcd39a7a 100644 --- a/test/js/node/test/parallel/test-zlib-unzip-one-byte-chunks.js +++ b/test/js/node/test/parallel/test-zlib-unzip-one-byte-chunks.js @@ -1,7 +1,9 @@ 'use strict'; + const common = require('../common'); -const assert = require('assert'); -const zlib = require('zlib'); + +const assert = require('node:assert'); +const zlib = require('node:zlib'); const data = Buffer.concat([ zlib.gzipSync('abc'), @@ -11,15 +13,13 @@ const data = Buffer.concat([ const resultBuffers = []; const unzip = zlib.createUnzip() - .on('error', (err) => { - assert.ifError(err); - }) + .on('error', common.mustNotCall()) .on('data', (data) => resultBuffers.push(data)) .on('finish', common.mustCall(() => { const unzipped = Buffer.concat(resultBuffers).toString(); assert.strictEqual(unzipped, 'abcdef', `'${unzipped}' should match 'abcdef' after zipping ` + - 'and unzipping'); + 'and unzipping'); })); for (let i = 0; i < data.length; i++) { diff --git a/test/js/node/test/parallel/test-zlib-write-after-close.js b/test/js/node/test/parallel/test-zlib-write-after-close.js index eb8ff4353963..6b2b1c8cd017 100644 --- a/test/js/node/test/parallel/test-zlib-write-after-close.js +++ b/test/js/node/test/parallel/test-zlib-write-after-close.js @@ -20,15 +20,18 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; + const common = require('../common'); -const zlib = require('zlib'); -zlib.gzip('hello', common.mustCall(function(err, out) { +const zlib = require('node:zlib'); +const assert = require('node:assert'); + +zlib.gzip('hello', common.mustCall(() => { const unzip = zlib.createGunzip(); unzip.close(common.mustCall()); - unzip.write('asd', common.expectsError({ - code: 'ERR_STREAM_DESTROYED', - name: 'Error', - message: 'Cannot call write after a stream was destroyed' + unzip.write('asd', common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_STREAM_DESTROYED'); + assert.strictEqual(err.name, 'Error'); + assert.strictEqual(err.message, 'Cannot call write after a stream was destroyed'); })); })); diff --git a/test/js/node/test/parallel/test-zlib-write-after-end.js b/test/js/node/test/parallel/test-zlib-write-after-end.js index 2b31ff30dc85..2017e7f7d9cc 100644 --- a/test/js/node/test/parallel/test-zlib-write-after-end.js +++ b/test/js/node/test/parallel/test-zlib-write-after-end.js @@ -1,16 +1,22 @@ 'use strict'; -const common = require('../common'); -const zlib = require('zlib'); -// Regression test for https://github.com/nodejs/node/issues/30976 -// Writes to a stream should finish even after the readable side has been ended. - -const data = zlib.deflateRawSync('Welcome'); +require('../common'); -const inflate = zlib.createInflateRaw(); +const assert = require('node:assert'); +const zlib = require('node:zlib'); +const { test } = require('node:test'); -inflate.resume(); -inflate.write(data, common.mustCall()); -inflate.write(Buffer.from([0x00]), common.mustCall()); -inflate.write(Buffer.from([0x00]), common.mustCall()); -inflate.flush(common.mustCall()); +// Regression test for https://github.com/nodejs/node/issues/30976 +test('Writes to a stream should finish even after the readable side has been ended.', async (t) => { + const { promise, resolve } = Promise.withResolvers(); + const data = zlib.deflateRawSync('Welcome'); + const inflate = zlib.createInflateRaw(); + const writeCallback = t.mock.fn(); + inflate.resume(); + inflate.write(data, writeCallback); + inflate.write(Buffer.from([0x00]), writeCallback); + inflate.write(Buffer.from([0x00]), writeCallback); + inflate.flush(resolve); + await promise; + assert.strictEqual(writeCallback.mock.callCount(), 3); +}); diff --git a/test/js/node/test/parallel/test-zlib-write-after-flush.js b/test/js/node/test/parallel/test-zlib-write-after-flush.js index 57988191f84c..9449ab46823b 100644 --- a/test/js/node/test/parallel/test-zlib-write-after-flush.js +++ b/test/js/node/test/parallel/test-zlib-write-after-flush.js @@ -20,9 +20,11 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; + const common = require('../common'); -const assert = require('assert'); -const zlib = require('zlib'); + +const assert = require('node:assert'); +const zlib = require('node:zlib'); for (const [ createCompress, createDecompress ] of [ [ zlib.createGzip, zlib.createGunzip ], @@ -37,6 +39,7 @@ for (const [ createCompress, createDecompress ] of [ let output = ''; const input = 'A line of data\n'; gunz.setEncoding('utf8'); + gunz.on('error', common.mustNotCall()); gunz.on('data', (c) => output += c); gunz.on('end', common.mustCall(() => { assert.strictEqual(output, input); diff --git a/test/js/node/test/parallel/test-zlib-zero-byte.js b/test/js/node/test/parallel/test-zlib-zero-byte.js index d61750912b01..c3e56bd180ec 100644 --- a/test/js/node/test/parallel/test-zlib-zero-byte.js +++ b/test/js/node/test/parallel/test-zlib-zero-byte.js @@ -20,9 +20,11 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; + const common = require('../common'); -const assert = require('assert'); -const zlib = require('zlib'); + +const assert = require('node:assert'); +const zlib = require('node:zlib'); const compressors = [ [zlib.Gzip, 20], @@ -37,12 +39,11 @@ for (const [Compressor, expected] of compressors) { gz.on('data', function(c) { received += c.length; }); - - gz.on('end', common.mustCall(function() { + gz.on('error', common.mustNotCall()); + gz.on('end', common.mustCall(() => { assert.strictEqual(received, expected, `${received}, ${expected}, ${Compressor.name}`); })); - gz.on('finish', common.mustCall()); gz.write(emptyBuffer); gz.end(); } diff --git a/test/js/node/test/parallel/test-zlib-zero-windowBits.js b/test/js/node/test/parallel/test-zlib-zero-windowBits.js index a27fd6734a54..220bbf8a4023 100644 --- a/test/js/node/test/parallel/test-zlib-zero-windowBits.js +++ b/test/js/node/test/parallel/test-zlib-zero-windowBits.js @@ -1,33 +1,30 @@ 'use strict'; require('../common'); -const assert = require('assert'); -const zlib = require('zlib'); +const assert = require('node:assert'); +const zlib = require('node:zlib'); +const { test } = require('node:test'); // windowBits is a special case in zlib. On the compression side, 0 is invalid. // On the decompression side, it indicates that zlib should use the value from // the header of the compressed stream. -{ +test('zlib should support zero windowBits', (t) => { const inflate = zlib.createInflate({ windowBits: 0 }); - assert(inflate instanceof zlib.Inflate); -} + assert.ok(inflate instanceof zlib.Inflate); -{ const gunzip = zlib.createGunzip({ windowBits: 0 }); - assert(gunzip instanceof zlib.Gunzip); -} + assert.ok(gunzip instanceof zlib.Gunzip); -{ const unzip = zlib.createUnzip({ windowBits: 0 }); - assert(unzip instanceof zlib.Unzip); -} + assert.ok(unzip instanceof zlib.Unzip); +}); -{ +test('windowBits should be valid', () => { assert.throws(() => zlib.createGzip({ windowBits: 0 }), { code: 'ERR_OUT_OF_RANGE', name: 'RangeError', message: 'The value of "options.windowBits" is out of range. ' + - 'It must be >= 9 and <= 15. Received 0' + 'It must be >= 9 and <= 15. Received 0' }); -} +}); diff --git a/test/js/node/test/parallel/test-zlib-zstd-kmaxlength-rangeerror.js b/test/js/node/test/parallel/test-zlib-zstd-kmaxlength-rangeerror.js index 58ad8ff2c98d..4537f1637014 100644 --- a/test/js/node/test/parallel/test-zlib-zstd-kmaxlength-rangeerror.js +++ b/test/js/node/test/parallel/test-zlib-zstd-kmaxlength-rangeerror.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); // This test ensures that zlib throws a RangeError if the final buffer needs to // be larger than kMaxLength and concatenation fails. @@ -19,9 +19,9 @@ buffer.kMaxLength = oldkMaxLength; const encoded = Buffer.from('KLUv/SCARQAAEGFhAQA7BVg=', 'base64'); // Async -zlib.zstdDecompress(encoded, function(err) { +zlib.zstdDecompress(encoded, common.mustCall((err) => { assert.ok(err instanceof RangeError); -}); +})); // Sync assert.throws(function() { diff --git a/test/js/node/test/sequential/test-child-process-exit.js b/test/js/node/test/sequential/test-child-process-exit.js index 318b6451dd4e..54dc6c1c90f9 100644 --- a/test/js/node/test/sequential/test-child-process-exit.js +++ b/test/js/node/test/sequential/test-child-process-exit.js @@ -40,7 +40,7 @@ if (gen === maxGen) { } const child = ch.spawn(process.execPath, [__filename, gen + 1], { - stdio: [ 'ignore', 'pipe', 'ignore' ] + stdio: [ 'ignore', 'pipe', 'ignore' ], }); assert.ok(!child.stdin); assert.ok(child.stdout); diff --git a/test/js/node/test/sequential/test-crypto-timing-safe-equal.js b/test/js/node/test/sequential/test-crypto-timing-safe-equal.js index c76b22444f9d..2025291daa0f 100644 --- a/test/js/node/test/sequential/test-crypto-timing-safe-equal.js +++ b/test/js/node/test/sequential/test-crypto-timing-safe-equal.js @@ -1,4 +1,4 @@ -// Flags: --expose-internals --no-warnings --allow-natives-syntax +// Flags: --no-warnings 'use strict'; const common = require('../common'); if (!common.hasCrypto) @@ -51,20 +51,20 @@ assert.strictEqual( test(new Float32Array([NaN]), new Float32Array([NaN]), { equal: false, sameValue: true, - timingSafeEqual: true + timingSafeEqual: true, }); test(new Float64Array([0]), new Float64Array([-0]), { equal: true, sameValue: false, - timingSafeEqual: false + timingSafeEqual: false, }); const x = new BigInt64Array([0x7ff0000000000001n, 0xfff0000000000001n]); test(new Float64Array(x.buffer), new Float64Array([NaN, NaN]), { equal: false, sameValue: true, - timingSafeEqual: false + timingSafeEqual: false, }); } @@ -73,7 +73,7 @@ assert.throws( { code: 'ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH', name: 'RangeError', - message: 'Input buffers must have the same byte length' + message: 'Input buffers must have the same byte length', } ); @@ -92,28 +92,3 @@ assert.throws( name: 'TypeError', } ); - -if (typeof Bun === 'undefined') { - // V8 Fast API - const foo = Buffer.from('foo'); - const bar = Buffer.from('bar'); - const longer = Buffer.from('longer'); - function testFastPath(buf1, buf2) { - return crypto.timingSafeEqual(buf1, buf2); - } - eval('%PrepareFunctionForOptimization(testFastPath)'); - assert.strictEqual(testFastPath(foo, bar), false); - eval('%OptimizeFunctionOnNextCall(testFastPath)'); - assert.strictEqual(testFastPath(foo, bar), false); - assert.strictEqual(testFastPath(foo, foo), true); - assert.throws(() => testFastPath(foo, longer), { - code: 'ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH', - }); - - if (common.isDebug) { - const { internalBinding } = require('internal/test/binding'); - const { getV8FastApiCallCount } = internalBinding('debug'); - assert.strictEqual(getV8FastApiCallCount('crypto.timingSafeEqual.ok'), 2); - assert.strictEqual(getV8FastApiCallCount('crypto.timingSafeEqual.error'), 1); - } -} diff --git a/test/js/node/test/sequential/test-init.js b/test/js/node/test/sequential/test-init.js index 7195369e0e4f..dd5db5640d1f 100644 --- a/test/js/node/test/sequential/test-init.js +++ b/test/js/node/test/sequential/test-init.js @@ -24,9 +24,11 @@ const common = require('../common'); const assert = require('assert'); const child = require('child_process'); const fixtures = require('../common/fixtures'); +const { isMainThread } = require('worker_threads'); -if (!common.isMainThread) +if (!isMainThread) { common.skip('process.chdir is not available in Workers'); +} if (process.env.TEST_INIT) { return process.stdout.write('Loaded successfully!'); diff --git a/test/js/node/test/sequential/test-net-GH-5504.js b/test/js/node/test/sequential/test-net-GH-5504.js index ebe987d0443b..3bdd76b6260f 100644 --- a/test/js/node/test/sequential/test-net-GH-5504.js +++ b/test/js/node/test/sequential/test-net-GH-5504.js @@ -61,7 +61,7 @@ function client() { const net = require('net'); const client = net.connect({ host: common.localhostIPv4, - port: common.PORT + port: common.PORT, }, function() { client.destroy(); }); @@ -73,8 +73,8 @@ function parent() { const s = spawn(node, [__filename, 'server'], { env: Object.assign(process.env, { - NODE_DEBUG: 'net' - }) + NODE_DEBUG: 'net', + }), }); wrap(s.stderr, process.stderr, 'SERVER 2>'); diff --git a/test/js/node/test/sequential/test-net-connect-econnrefused.js b/test/js/node/test/sequential/test-net-connect-econnrefused.js index c55a9ebe24cc..67f5820221c5 100644 --- a/test/js/node/test/sequential/test-net-connect-econnrefused.js +++ b/test/js/node/test/sequential/test-net-connect-econnrefused.js @@ -40,7 +40,7 @@ const server = net.createServer().listen(0, common.mustCall(() => { function pummel() { let pending; for (pending = 0; pending < ATTEMPTS_PER_ROUND; pending++) { - net.createConnection({ port, autoSelectFamily: false }).on('error', function(error) { + net.createConnection({ port, autoSelectFamily: false }).on('error', common.mustCallAtLeast((error) => { // Family autoselection might be skipped if only a single address is returned by DNS. const actualError = Array.isArray(error.errors) ? error.errors[0] : error; @@ -50,7 +50,7 @@ function pummel() { if (rounds === ROUNDS) return check(); rounds++; pummel(); - }); + }, 0)); reqs++; } } diff --git a/test/js/node/test/sequential/test-net-server-bind.js b/test/js/node/test/sequential/test-net-server-bind.js index 56216d0ed606..f1f274a01d09 100644 --- a/test/js/node/test/sequential/test-net-server-bind.js +++ b/test/js/node/test/sequential/test-net-server-bind.js @@ -20,7 +20,7 @@ const net = require('net'); server.listen(common.PORT); - setTimeout(function() { + setTimeout(common.mustCall(() => { const address = server.address(); assert.strictEqual(address.port, common.PORT); @@ -30,7 +30,7 @@ const net = require('net'); assert.strictEqual(server._connectionKey, `4:0.0.0.0:${address.port}`); server.close(); - }, 100); + }), 100); } // Callback to listen() diff --git a/test/js/node/test/sequential/test-require-cache-without-stat.js b/test/js/node/test/sequential/test-require-cache-without-stat.js index 3064bf3f3dda..f87911e7db43 100644 --- a/test/js/node/test/sequential/test-require-cache-without-stat.js +++ b/test/js/node/test/sequential/test-require-cache-without-stat.js @@ -26,7 +26,7 @@ require('../common'); const fs = require('fs'); const assert = require('assert'); -const { fixturesDir } = require('../common/fixtures'); +const fixtures = require('../common/fixtures'); let counter = 0; @@ -47,7 +47,7 @@ fs.stat = function() { }; // Load the module 'a' and 'http' once. It should become cached. -require(`${fixturesDir}/a`); +require(`${fixtures.fixturesDir}/a`); require('../fixtures/a.js'); require('./../fixtures/a.js'); require('http'); @@ -58,7 +58,7 @@ const counterBefore = counter; // Now load the module a bunch of times with equivalent paths. // stat should not be called. for (let i = 0; i < 100; i++) { - require(`${fixturesDir}/a`); + require(`${fixtures.fixturesDir}/a`); require('../fixtures/a.js'); require('./../fixtures/a.js'); } diff --git a/test/js/node/test/sequential/test-stream2-fs.js b/test/js/node/test/sequential/test-stream2-fs.js index 3d06abc92140..10414eaab336 100644 --- a/test/js/node/test/sequential/test-stream2-fs.js +++ b/test/js/node/test/sequential/test-stream2-fs.js @@ -20,7 +20,7 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; -require('../common'); +const common = require('../common'); const fixtures = require('../common/fixtures'); const assert = require('assert'); @@ -58,13 +58,13 @@ class TestWriter extends Stream { const r = new FSReadable(file); const w = new TestWriter(); -w.on('results', function(res) { +w.on('results', common.mustCall((res) => { console.error(res, w.length); assert.strictEqual(w.length, size); assert.deepStrictEqual(res.map(function(c) { return c.length; }), expectLengths); console.log('ok'); -}); +})); r.pipe(w);