diff --git a/.gitignore b/.gitignore index dad5a3efd8bcae..4ab96c80544963 100644 --- a/.gitignore +++ b/.gitignore @@ -135,3 +135,5 @@ deps/v8/gypfiles/Release/ deps/v8/third_party/eu-strip/ .DS_Store + +node_modules diff --git a/package.json b/package.json new file mode 100644 index 00000000000000..34a811578e24cd --- /dev/null +++ b/package.json @@ -0,0 +1,9 @@ +{ + "scripts": { + "format": "prettier --write \"{src,test}/**/*.{js,ts}\"", + "format:check": "prettier --list-different \"{src,test}/**/*.{js,ts}\"" + }, + "dependencies": { + "prettier": "^1.15.2" + } +} diff --git a/test/abort/test-abort-backtrace.js b/test/abort/test-abort-backtrace.js index 7f87ef0e7f4559..0d1e1106d56f16 100644 --- a/test/abort/test-abort-backtrace.js +++ b/test/abort/test-abort-backtrace.js @@ -12,7 +12,10 @@ if (process.argv[2] === 'child') { assert.strictEqual(child.stdout.toString(), ''); // stderr will be empty for systems that don't support backtraces. if (stderr !== '') { - const frames = stderr.trimRight().split('\n').map((s) => s.trim()); + const frames = stderr + .trimRight() + .split('\n') + .map((s) => s.trim()); if (!frames.every((frame, index) => frame.startsWith(`${index + 1}:`))) { assert.fail(`Each frame should start with a frame number:\n${stderr}`); diff --git a/test/abort/test-abort-uncaught-exception.js b/test/abort/test-abort-uncaught-exception.js index 718f456c9733c6..6c26e39c87f27b 100644 --- a/test/abort/test-abort-uncaught-exception.js +++ b/test/abort/test-abort-uncaught-exception.js @@ -14,27 +14,30 @@ if (process.argv[2] === 'child') { new vm.Script('[', {}); } else { run('', 'child', null); - run('--abort-on-uncaught-exception', 'child', - ['SIGABRT', 'SIGTRAP', 'SIGILL']); + run('--abort-on-uncaught-exception', 'child', [ + 'SIGABRT', + 'SIGTRAP', + 'SIGILL' + ]); run('--abort-on-uncaught-exception', 'vm', ['SIGABRT', 'SIGTRAP', 'SIGILL']); } function run(flags, argv2, signals) { const args = [__filename, argv2]; - if (flags) - args.unshift(flags); + if (flags) args.unshift(flags); const child = spawn(node, args); - child.on('exit', common.mustCall(function(code, sig) { - if (common.isWindows) { - if (signals) - assert.strictEqual(code, 0xC0000005); - else - assert.strictEqual(code, 1); - } else if (signals) { - assert(signals.includes(sig), `Unexpected signal ${sig}`); - } else { - assert.strictEqual(sig, null); - } - })); + child.on( + 'exit', + common.mustCall(function(code, sig) { + if (common.isWindows) { + if (signals) assert.strictEqual(code, 0xc0000005); + else assert.strictEqual(code, 1); + } else if (signals) { + assert(signals.includes(sig), `Unexpected signal ${sig}`); + } else { + assert.strictEqual(sig, null); + } + }) + ); } diff --git a/test/abort/test-addon-uv-handle-leak.js b/test/abort/test-addon-uv-handle-leak.js index 96608f8dda95fd..188bf04dc8665e 100644 --- a/test/abort/test-addon-uv-handle-leak.js +++ b/test/abort/test-addon-uv-handle-leak.js @@ -11,23 +11,33 @@ const { spawnSync } = require('child_process'); // This is a sibling test to test/addons/uv-handle-leak. const bindingPath = path.resolve( - __dirname, '..', 'addons', 'uv-handle-leak', 'build', - `${common.buildType}/binding.node`); + __dirname, + '..', + 'addons', + 'uv-handle-leak', + 'build', + `${common.buildType}/binding.node` +); -if (!fs.existsSync(bindingPath)) - common.skip('binding not built yet'); +if (!fs.existsSync(bindingPath)) common.skip('binding not built yet'); if (process.argv[2] === 'child') { - new Worker(` + new Worker( + ` const binding = require(${JSON.stringify(bindingPath)}); binding.leakHandle(); binding.leakHandle(0); binding.leakHandle(0x42); - `, { eval: true }); + `, + { eval: true } + ); } else { - const child = cp.spawnSync(process.execPath, - ['--experimental-worker', __filename, 'child']); + const child = cp.spawnSync(process.execPath, [ + '--experimental-worker', + __filename, + 'child' + ]); const stderr = child.stderr.toString(); assert.strictEqual(child.stdout.toString(), ''); @@ -53,23 +63,27 @@ if (process.argv[2] === 'child') { function isGlibc() { try { const lddOut = spawnSync('ldd', [process.execPath]).stdout; - const libcInfo = lddOut.toString().split('\n').map( - (line) => line.match(/libc\.so.+=>\s*(\S+)\s/)).filter((info) => info); - if (libcInfo.length === 0) - return false; + const libcInfo = lddOut + .toString() + .split('\n') + .map((line) => line.match(/libc\.so.+=>\s*(\S+)\s/)) + .filter((info) => info); + if (libcInfo.length === 0) return false; const nmOut = spawnSync('nm', ['-D', libcInfo[0][1]]).stdout; - if (/gnu_get_libc_version/.test(nmOut)) - return true; + if (/gnu_get_libc_version/.test(nmOut)) return true; } catch { return false; } } - - if (!(common.isFreeBSD || - common.isAIX || - (common.isLinux && !isGlibc()) || - common.isWindows)) { + if ( + !( + common.isFreeBSD || + common.isAIX || + (common.isLinux && !isGlibc()) || + common.isWindows + ) + ) { assert(stderr.includes('ExampleOwnerClass'), stderr); assert(stderr.includes('CloseCallback'), stderr); assert(stderr.includes('example_instance'), stderr); diff --git a/test/abort/test-http-parser-consume.js b/test/abort/test-http-parser-consume.js index 13dc93874a226f..c4fcb5e359e022 100644 --- a/test/abort/test-http-parser-consume.js +++ b/test/abort/test-http-parser-consume.js @@ -7,27 +7,39 @@ const { spawn } = require('child_process'); if (process.argv[2] === 'child') { // sub-process const server = createServer(common.mustCall((_, res) => res.end('h'))); - server.listen(0, common.mustCall(() => { - const rr = get({ port: server.address().port }, common.mustCall(() => { - // This bad input (0) should abort the parser and the process - rr.parser.consume(0); - // This line should be unreachable. - assert.fail('this should be unreachable'); - })); - })); + server.listen( + 0, + common.mustCall(() => { + const rr = get( + { port: server.address().port }, + common.mustCall(() => { + // This bad input (0) should abort the parser and the process + rr.parser.consume(0); + // This line should be unreachable. + assert.fail('this should be unreachable'); + }) + ); + }) + ); } else { // super-process const child = spawn(process.execPath, [__filename, 'child']); child.stdout.on('data', common.mustNotCall()); let stderr = ''; - child.stderr.on('data', common.mustCallAtLeast((data) => { - assert(Buffer.isBuffer(data)); - stderr += data.toString('utf8'); - }, 1)); - child.on('exit', common.mustCall((code, signal) => { - assert(stderr.includes('failed'), `stderr: ${stderr}`); - const didAbort = common.nodeProcessAborted(code, signal); - assert(didAbort, `process did not abort, code:${code} signal:${signal}`); - })); + child.stderr.on( + 'data', + common.mustCallAtLeast((data) => { + assert(Buffer.isBuffer(data)); + stderr += data.toString('utf8'); + }, 1) + ); + child.on( + 'exit', + common.mustCall((code, signal) => { + assert(stderr.includes('failed'), `stderr: ${stderr}`); + const didAbort = common.nodeProcessAborted(code, signal); + assert(didAbort, `process did not abort, code:${code} signal:${signal}`); + }) + ); } diff --git a/test/abort/test-process-abort-exitcode.js b/test/abort/test-process-abort-exitcode.js index 2aa44024ec05b9..8dec3a2c0d9001 100644 --- a/test/abort/test-process-abort-exitcode.js +++ b/test/abort/test-process-abort-exitcode.js @@ -12,13 +12,16 @@ if (process.argv[2] === 'child') { process.abort(); } else { const child = spawn(process.execPath, [__filename, 'child']); - child.on('exit', common.mustCall((code, signal) => { - if (common.isWindows) { - assert.strictEqual(code, 134); - assert.strictEqual(signal, null); - } else { - assert.strictEqual(code, null); - assert.strictEqual(signal, 'SIGABRT'); - } - })); + child.on( + 'exit', + common.mustCall((code, signal) => { + if (common.isWindows) { + assert.strictEqual(code, 134); + assert.strictEqual(signal, null); + } else { + assert.strictEqual(code, null); + assert.strictEqual(signal, 'SIGABRT'); + } + }) + ); } diff --git a/test/abort/test-zlib-invalid-internals-usage.js b/test/abort/test-zlib-invalid-internals-usage.js index c218a5ee956f19..14a5c2576d10a6 100644 --- a/test/abort/test-zlib-invalid-internals-usage.js +++ b/test/abort/test-zlib-invalid-internals-usage.js @@ -6,15 +6,18 @@ const cp = require('child_process'); if (process.argv[2] === 'child') { // This is the heart of the test. - new (process.binding('zlib').Zlib)(0).init(1, 2, 3, 4, 5); + new (process.binding('zlib')).Zlib(0).init(1, 2, 3, 4, 5); } else { const child = cp.spawnSync(`${process.execPath}`, [`${__filename}`, 'child']); assert.strictEqual(child.stdout.toString(), ''); - assert.ok(child.stderr.includes( - 'WARNING: You are likely using a version of node-tar or npm that ' + - `is incompatible with this version of Node.js.${os.EOL}` + - 'Please use either the version of npm that is bundled with Node.js, or ' + - 'a version of npm (> 5.5.1 or < 5.4.0) or node-tar (> 4.0.1) that is ' + - `compatible with Node.js 9 and above.${os.EOL}`)); + assert.ok( + child.stderr.includes( + 'WARNING: You are likely using a version of node-tar or npm that ' + + `is incompatible with this version of Node.js.${os.EOL}` + + 'Please use either the version of npm that is bundled with Node.js, or ' + + 'a version of npm (> 5.5.1 or < 5.4.0) or node-tar (> 4.0.1) that is ' + + `compatible with Node.js 9 and above.${os.EOL}` + ) + ); } diff --git a/test/addons-napi/test_array/test.js b/test/addons-napi/test_array/test.js index 75c181d9da8269..061947b319aa64 100644 --- a/test/addons-napi/test_array/test.js +++ b/test/addons-napi/test_array/test.js @@ -12,32 +12,21 @@ const array = [ 13493, 9459324, { name: 'hello' }, - [ - 'world', - 'node', - 'abi' - ] + ['world', 'node', 'abi'] ]; -assert.throws( - () => { - test_array.TestGetElement(array, array.length + 1); - }, - /^Error: assertion \(\(\(uint32_t\)index < length\)\) failed: Index out of bounds!$/ -); +assert.throws(() => { + test_array.TestGetElement(array, array.length + 1); +}, /^Error: assertion \(\(\(uint32_t\)index < length\)\) failed: Index out of bounds!$/); -assert.throws( - () => { - test_array.TestGetElement(array, -2); - }, - /^Error: assertion \(index >= 0\) failed: Invalid index\. Expects a positive integer\.$/ -); +assert.throws(() => { + test_array.TestGetElement(array, -2); +}, /^Error: assertion \(index >= 0\) failed: Invalid index\. Expects a positive integer\.$/); array.forEach(function(element, index) { assert.strictEqual(test_array.TestGetElement(array, index), element); }); - assert.deepStrictEqual(test_array.New(array), array); assert(test_array.TestHasElement(array, 0)); diff --git a/test/addons-napi/test_async/test-async-hooks.js b/test/addons-napi/test_async/test-async-hooks.js index db6e0cbd1679e6..e683183c918844 100644 --- a/test/addons-napi/test_async/test-async-hooks.js +++ b/test/addons-napi/test_async/test-async-hooks.js @@ -8,49 +8,57 @@ const events = []; let testId; const initAsyncId = async_hooks.executionAsyncId(); -async_hooks.createHook({ - init(id, provider, triggerAsyncId, resource) { - if (provider === 'TestResource') { - testId = id; - events.push({ type: 'init', id, provider, triggerAsyncId, resource }); +async_hooks + .createHook({ + init(id, provider, triggerAsyncId, resource) { + if (provider === 'TestResource') { + testId = id; + events.push({ type: 'init', id, provider, triggerAsyncId, resource }); + } + }, + before(id) { + if (testId === id) { + events.push({ type: 'before', id }); + } + }, + after(id) { + if (testId === id) { + events.push({ type: 'after', id }); + } + }, + destroy(id) { + if (testId === id) { + events.push({ type: 'destroy', id }); + } } - }, - before(id) { - if (testId === id) { - events.push({ type: 'before', id }); - } - }, - after(id) { - if (testId === id) { - events.push({ type: 'after', id }); - } - }, - destroy(id) { - if (testId === id) { - events.push({ type: 'destroy', id }); - } - } -}).enable(); + }) + .enable(); const resource = { foo: 'foo' }; events.push({ type: 'start' }); -test_async.Test(5, resource, common.mustCall(function(err, val) { - assert.strictEqual(err, null); - assert.strictEqual(val, 10); - events.push({ type: 'complete' }); - process.nextTick(common.mustCall()); -})); +test_async.Test( + 5, + resource, + common.mustCall(function(err, val) { + assert.strictEqual(err, null); + assert.strictEqual(val, 10); + events.push({ type: 'complete' }); + process.nextTick(common.mustCall()); + }) +); events.push({ type: 'scheduled' }); process.on('exit', () => { assert.deepStrictEqual(events, [ { type: 'start' }, - { type: 'init', + { + type: 'init', id: testId, provider: 'TestResource', triggerAsyncId: initAsyncId, - resource }, + resource + }, { type: 'scheduled' }, { type: 'before', id: testId }, { type: 'complete' }, diff --git a/test/addons-napi/test_async/test-uncaught.js b/test/addons-napi/test_async/test-uncaught.js index fdcb3203f54410..4c9b42c7f55366 100644 --- a/test/addons-napi/test_async/test-uncaught.js +++ b/test/addons-napi/test_async/test-uncaught.js @@ -3,16 +3,23 @@ const common = require('../../common'); const assert = require('assert'); const test_async = require(`./build/${common.buildType}/test_async`); -process.on('uncaughtException', common.mustCall(function(err) { - try { - throw new Error('should not fail'); - } catch (err) { - assert.strictEqual(err.message, 'should not fail'); - } - assert.strictEqual(err.message, 'uncaught'); -})); +process.on( + 'uncaughtException', + common.mustCall(function(err) { + try { + throw new Error('should not fail'); + } catch (err) { + assert.strictEqual(err.message, 'should not fail'); + } + assert.strictEqual(err.message, 'uncaught'); + }) +); // Successful async execution and completion callback. -test_async.Test(5, {}, common.mustCall(function() { - throw new Error('uncaught'); -})); +test_async.Test( + 5, + {}, + common.mustCall(function() { + throw new Error('uncaught'); + }) +); diff --git a/test/addons-napi/test_async/test.js b/test/addons-napi/test_async/test.js index 34ecae08e67f2e..600ae73faecfef 100644 --- a/test/addons-napi/test_async/test.js +++ b/test/addons-napi/test_async/test.js @@ -9,22 +9,29 @@ const testException = 'test_async_cb_exception'; // Exception thrown from async completion callback. // (Tested in a spawned process because the exception is fatal.) if (process.argv[2] === 'child') { - test_async.Test(1, {}, common.mustCall(function() { - throw new Error(testException); - })); + test_async.Test( + 1, + {}, + common.mustCall(function() { + throw new Error(testException); + }) + ); return; } -const p = child_process.spawnSync( - process.execPath, [ __filename, 'child' ]); +const p = child_process.spawnSync(process.execPath, [__filename, 'child']); assert.ifError(p.error); assert.ok(p.stderr.toString().includes(testException)); // Successful async execution and completion callback. -test_async.Test(5, {}, common.mustCall(function(err, val) { - assert.strictEqual(err, null); - assert.strictEqual(val, 10); - process.nextTick(common.mustCall()); -})); +test_async.Test( + 5, + {}, + common.mustCall(function(err, val) { + assert.strictEqual(err, null); + assert.strictEqual(val, 10); + process.nextTick(common.mustCall()); + }) +); // Async work item cancellation with callback. test_async.TestCancel(common.mustCall()); diff --git a/test/addons-napi/test_bigint/test.js b/test/addons-napi/test_bigint/test.js index b92c810459321b..f4ff7c1abc9e92 100644 --- a/test/addons-napi/test_bigint/test.js +++ b/test/addons-napi/test_bigint/test.js @@ -6,7 +6,7 @@ const { TestInt64, TestUint64, TestWords, - CreateTooBigBigInt, + CreateTooBigBigInt } = require(`./build/${common.buildType}/test_bigint`); [ @@ -20,7 +20,7 @@ const { 986583n, -976675n, 98765432213456789876546896323445679887645323232436587988766545658n, - -4350987086545760976737453646576078997096876957864353245245769809n, + -4350987086545760976737453646576078997096876957864353245245769809n ].forEach((num) => { if (num > -(2n ** 63n) && num < 2n ** 63n) { assert.strictEqual(TestInt64(num), num); @@ -41,5 +41,5 @@ const { assert.throws(CreateTooBigBigInt, { name: 'RangeError', - message: 'Maximum BigInt size exceeded', + message: 'Maximum BigInt size exceeded' }); diff --git a/test/addons-napi/test_callback_scope/test-async-hooks.js b/test/addons-napi/test_callback_scope/test-async-hooks.js index 1a11bf60398f9b..c347205ae7a133 100644 --- a/test/addons-napi/test_callback_scope/test-async-hooks.js +++ b/test/addons-napi/test_callback_scope/test-async-hooks.js @@ -13,16 +13,18 @@ process.emitWarning = () => {}; const { runInCallbackScope } = require(`./build/${common.buildType}/binding`); let insideHook = false; -async_hooks.createHook({ - before: common.mustCall((id) => { - assert.strictEqual(id, 1000); - insideHook = true; - }), - after: common.mustCall((id) => { - assert.strictEqual(id, 1000); - insideHook = false; +async_hooks + .createHook({ + before: common.mustCall((id) => { + assert.strictEqual(id, 1000); + insideHook = true; + }), + after: common.mustCall((id) => { + assert.strictEqual(id, 1000); + insideHook = false; + }) }) -}).enable(); + .enable(); runInCallbackScope({}, 1000, 1000, () => { assert(insideHook); diff --git a/test/addons-napi/test_callback_scope/test.js b/test/addons-napi/test_callback_scope/test.js index 2f2efe5f47b98a..a2158fd5bcea2b 100644 --- a/test/addons-napi/test_callback_scope/test.js +++ b/test/addons-napi/test_callback_scope/test.js @@ -7,9 +7,12 @@ const { runInCallbackScope } = require(`./build/${common.buildType}/binding`); assert.strictEqual(runInCallbackScope({}, 0, 0, () => 42), 42); { - process.once('uncaughtException', common.mustCall((err) => { - assert.strictEqual(err.message, 'foo'); - })); + process.once( + 'uncaughtException', + common.mustCall((err) => { + assert.strictEqual(err.message, 'foo'); + }) + ); runInCallbackScope({}, 0, 0, () => { throw new Error('foo'); diff --git a/test/addons-napi/test_cleanup_hook/test.js b/test/addons-napi/test_cleanup_hook/test.js index 354f4449045c17..41a69572ff8234 100644 --- a/test/addons-napi/test_cleanup_hook/test.js +++ b/test/addons-napi/test_cleanup_hook/test.js @@ -6,7 +6,9 @@ const child_process = require('child_process'); if (process.argv[2] === 'child') { require(`./build/${common.buildType}/binding`); } else { - const { stdout } = - child_process.spawnSync(process.execPath, [__filename, 'child']); + const { stdout } = child_process.spawnSync(process.execPath, [ + __filename, + 'child' + ]); assert.strictEqual(stdout.toString().trim(), 'cleanup(42)'); } diff --git a/test/addons-napi/test_constructor/test.js b/test/addons-napi/test_constructor/test.js index 616ba6c2a2927e..6ab04bfab9af1b 100644 --- a/test/addons-napi/test_constructor/test.js +++ b/test/addons-napi/test_constructor/test.js @@ -13,8 +13,9 @@ assert.strictEqual(test_object.readwriteValue, 1); test_object.readwriteValue = 2; assert.strictEqual(test_object.readwriteValue, 2); -assert.throws(() => { test_object.readonlyValue = 3; }, - /^TypeError: Cannot assign to read only property 'readonlyValue' of object '#'$/); +assert.throws(() => { + test_object.readonlyValue = 3; +}, /^TypeError: Cannot assign to read only property 'readonlyValue' of object '#'$/); assert.ok(test_object.hiddenValue); @@ -36,13 +37,15 @@ assert.ok(!propertyNames.includes('readonlyAccessor2')); test_object.readwriteAccessor1 = 1; assert.strictEqual(test_object.readwriteAccessor1, 1); assert.strictEqual(test_object.readonlyAccessor1, 1); -assert.throws(() => { test_object.readonlyAccessor1 = 3; }, - /^TypeError: Cannot assign to read only property 'readonlyAccessor1' of object '#'$/); +assert.throws(() => { + test_object.readonlyAccessor1 = 3; +}, /^TypeError: Cannot assign to read only property 'readonlyAccessor1' of object '#'$/); test_object.readwriteAccessor2 = 2; assert.strictEqual(test_object.readwriteAccessor2, 2); assert.strictEqual(test_object.readonlyAccessor2, 2); -assert.throws(() => { test_object.readonlyAccessor2 = 3; }, - /^TypeError: Cannot assign to read only property 'readonlyAccessor2' of object '#'$/); +assert.throws(() => { + test_object.readonlyAccessor2 = 3; +}, /^TypeError: Cannot assign to read only property 'readonlyAccessor2' of object '#'$/); // validate that static properties are on the class as opposed // to the instance diff --git a/test/addons-napi/test_constructor/test2.js b/test/addons-napi/test_constructor/test2.js index 64c03cbc684ac3..5d6e4a08e6c3d7 100644 --- a/test/addons-napi/test_constructor/test2.js +++ b/test/addons-napi/test_constructor/test2.js @@ -3,6 +3,7 @@ const common = require('../../common'); const assert = require('assert'); // Testing api calls for a constructor that defines properties -const TestConstructor = - require(`./build/${common.buildType}/test_constructor_name`); +const TestConstructor = require(`./build/${ + common.buildType +}/test_constructor_name`); assert.strictEqual(TestConstructor.name, 'MyObject'); diff --git a/test/addons-napi/test_conversions/test.js b/test/addons-napi/test_conversions/test.js index b9e43da0c5ed20..66477c7b47d007 100644 --- a/test/addons-napi/test_conversions/test.js +++ b/test/addons-napi/test_conversions/test.js @@ -109,9 +109,9 @@ assert.ok(Number.isNaN(test.toNumber(undefined))); assert.throws(() => test.toNumber(testSym), TypeError); assert.deepStrictEqual({}, test.toObject({})); -assert.deepStrictEqual({ 'test': 1 }, test.toObject({ 'test': 1 })); +assert.deepStrictEqual({ test: 1 }, test.toObject({ test: 1 })); assert.deepStrictEqual([], test.toObject([])); -assert.deepStrictEqual([ 1, 2, 3 ], test.toObject([ 1, 2, 3 ])); +assert.deepStrictEqual([1, 2, 3], test.toObject([1, 2, 3])); assert.deepStrictEqual(new Boolean(false), test.toObject(false)); assert.deepStrictEqual(new Boolean(true), test.toObject(true)); assert.deepStrictEqual(new String(''), test.toObject('')); @@ -136,5 +136,5 @@ assert.strictEqual(test.toString(Number.NaN), 'NaN'); assert.strictEqual(test.toString({}), '[object Object]'); assert.strictEqual(test.toString({ toString: () => 'test' }), 'test'); assert.strictEqual(test.toString([]), ''); -assert.strictEqual(test.toString([ 1, 2, 3 ]), '1,2,3'); +assert.strictEqual(test.toString([1, 2, 3]), '1,2,3'); assert.throws(() => test.toString(testSym), TypeError); diff --git a/test/addons-napi/test_dataview/test.js b/test/addons-napi/test_dataview/test.js index a6be58494069e5..5e7049374c64c7 100644 --- a/test/addons-napi/test_dataview/test.js +++ b/test/addons-napi/test_dataview/test.js @@ -11,8 +11,10 @@ const test_dataview = require(`./build/${common.buildType}/test_dataview`); const template = Reflect.construct(DataView, [buffer]); const theDataview = test_dataview.CreateDataViewFromJSDataView(template); - assert.ok(theDataview instanceof DataView, - `Expect ${theDataview} to be a DataView`); + assert.ok( + theDataview instanceof DataView, + `Expect ${theDataview} to be a DataView` + ); } // Test for creating dataview with invalid range diff --git a/test/addons-napi/test_env_sharing/test.js b/test/addons-napi/test_env_sharing/test.js index 6e21bf4c638b80..7ab9fd26570db6 100644 --- a/test/addons-napi/test_env_sharing/test.js +++ b/test/addons-napi/test_env_sharing/test.js @@ -5,6 +5,8 @@ const storeEnv = require(`./build/${common.buildType}/store_env`); const compareEnv = require(`./build/${common.buildType}/compare_env`); const assert = require('assert'); -assert.strictEqual(compareEnv(storeEnv), true, - 'N-API environment pointers in two different modules have ' + - 'the same value'); +assert.strictEqual( + compareEnv(storeEnv), + true, + 'N-API environment pointers in two different modules have ' + 'the same value' +); diff --git a/test/addons-napi/test_error/test.js b/test/addons-napi/test_error/test.js index d4b1d8a971ee09..ba9311a30dd2c2 100644 --- a/test/addons-napi/test_error/test.js +++ b/test/addons-napi/test_error/test.js @@ -11,7 +11,7 @@ const theReferenceError = new ReferenceError('Some reference error'); const theURIError = new URIError('Some URI error'); const theEvalError = new EvalError('Some eval error'); -class MyError extends Error { } +class MyError extends Error {} const myError = new MyError('Some MyError'); // Test that native error object is correctly classed @@ -66,7 +66,8 @@ function testThrowArbitrary(value) { (err) => { assert.strictEqual(err, value); return true; - }); + } + ); } testThrowArbitrary(42); @@ -79,39 +80,37 @@ testThrowArbitrary(undefined); testThrowArbitrary(null); testThrowArbitrary(NaN); -common.expectsError( - () => test_error.throwErrorCode(), - { - code: 'ERR_TEST_CODE', - message: 'Error [error]' - }); - -common.expectsError( - () => test_error.throwRangeErrorCode(), - { - code: 'ERR_TEST_CODE', - message: 'RangeError [range error]' - }); - -common.expectsError( - () => test_error.throwTypeErrorCode(), - { - code: 'ERR_TEST_CODE', - message: 'TypeError [type error]' - }); +common.expectsError(() => test_error.throwErrorCode(), { + code: 'ERR_TEST_CODE', + message: 'Error [error]' +}); + +common.expectsError(() => test_error.throwRangeErrorCode(), { + code: 'ERR_TEST_CODE', + message: 'RangeError [range error]' +}); + +common.expectsError(() => test_error.throwTypeErrorCode(), { + code: 'ERR_TEST_CODE', + message: 'TypeError [type error]' +}); let error = test_error.createError(); assert.ok(error instanceof Error, 'expected error to be an instance of Error'); assert.strictEqual(error.message, 'error'); error = test_error.createRangeError(); -assert.ok(error instanceof RangeError, - 'expected error to be an instance of RangeError'); +assert.ok( + error instanceof RangeError, + 'expected error to be an instance of RangeError' +); assert.strictEqual(error.message, 'range error'); error = test_error.createTypeError(); -assert.ok(error instanceof TypeError, - 'expected error to be an instance of TypeError'); +assert.ok( + error instanceof TypeError, + 'expected error to be an instance of TypeError' +); assert.strictEqual(error.message, 'type error'); error = test_error.createErrorCode(); @@ -121,15 +120,19 @@ assert.strictEqual(error.message, 'Error [error]'); assert.strictEqual(error.name, 'Error [ERR_TEST_CODE]'); error = test_error.createRangeErrorCode(); -assert.ok(error instanceof RangeError, - 'expected error to be an instance of RangeError'); +assert.ok( + error instanceof RangeError, + 'expected error to be an instance of RangeError' +); assert.strictEqual(error.message, 'RangeError [range error]'); assert.strictEqual(error.code, 'ERR_TEST_CODE'); assert.strictEqual(error.name, 'RangeError [ERR_TEST_CODE]'); error = test_error.createTypeErrorCode(); -assert.ok(error instanceof TypeError, - 'expected error to be an instance of TypeError'); +assert.ok( + error instanceof TypeError, + 'expected error to be an instance of TypeError' +); assert.strictEqual(error.message, 'TypeError [type error]'); assert.strictEqual(error.code, 'ERR_TEST_CODE'); assert.strictEqual(error.name, 'TypeError [ERR_TEST_CODE]'); diff --git a/test/addons-napi/test_exception/test.js b/test/addons-napi/test_exception/test.js index b9311add6c92d7..7f3eaea7e20c32 100644 --- a/test/addons-napi/test_exception/test.js +++ b/test/addons-napi/test_exception/test.js @@ -22,7 +22,9 @@ const test_exception = (function() { })(); { - const throwTheError = () => { throw theError; }; + const throwTheError = () => { + throw theError; + }; // Test that the native side successfully captures the exception let returnedError = test_exception.returnException(throwTheError); @@ -30,22 +32,30 @@ const test_exception = (function() { // Test that the native side passes the exception through assert.throws( - () => { test_exception.allowException(throwTheError); }, + () => { + test_exception.allowException(throwTheError); + }, (err) => err === theError ); // Test that the exception thrown above was marked as pending // before it was handled on the JS side const exception_pending = test_exception.wasPending(); - assert.strictEqual(exception_pending, true, - 'Exception not pending as expected,' + - ` .wasPending() returned ${exception_pending}`); + assert.strictEqual( + exception_pending, + true, + 'Exception not pending as expected,' + + ` .wasPending() returned ${exception_pending}` + ); // Test that the native side does not capture a non-existing exception returnedError = test_exception.returnException(common.mustCall()); - assert.strictEqual(returnedError, undefined, - 'Returned error should be undefined when no exception is' + - ` thrown, but ${returnedError} was passed`); + assert.strictEqual( + returnedError, + undefined, + 'Returned error should be undefined when no exception is' + + ` thrown, but ${returnedError} was passed` + ); } { @@ -56,22 +66,30 @@ const test_exception = (function() { } catch (anError) { caughtError = anError; } - assert.strictEqual(caughtError, undefined, - 'No exception originated on the native side, but' + - ` ${caughtError} was passed`); + assert.strictEqual( + caughtError, + undefined, + 'No exception originated on the native side, but' + + ` ${caughtError} was passed` + ); // Test that the exception state remains clear when no exception is thrown const exception_pending = test_exception.wasPending(); - assert.strictEqual(exception_pending, false, - 'Exception state did not remain clear as expected,' + - ` .wasPending() returned ${exception_pending}`); + assert.strictEqual( + exception_pending, + false, + 'Exception state did not remain clear as expected,' + + ` .wasPending() returned ${exception_pending}` + ); } // Make sure that exceptions that occur during finalization are propagated. function testFinalize(binding) { let x = test_exception[binding](); x = null; - assert.throws(() => { global.gc(); }, /Error during Finalize/); + assert.throws(() => { + global.gc(); + }, /Error during Finalize/); // To assuage the linter's concerns. (function() {})(x); diff --git a/test/addons-napi/test_fatal/test.js b/test/addons-napi/test_fatal/test.js index 7ff9a395635dce..dac5546a5b2ab9 100644 --- a/test/addons-napi/test_fatal/test.js +++ b/test/addons-napi/test_fatal/test.js @@ -11,8 +11,8 @@ if (process.argv[2] === 'child') { return; } -const p = child_process.spawnSync( - process.execPath, [ __filename, 'child' ]); +const p = child_process.spawnSync(process.execPath, [__filename, 'child']); assert.ifError(p.error); -assert.ok(p.stderr.toString().includes( - 'FATAL ERROR: test_fatal::Test fatal message')); +assert.ok( + p.stderr.toString().includes('FATAL ERROR: test_fatal::Test fatal message') +); diff --git a/test/addons-napi/test_fatal/test2.js b/test/addons-napi/test_fatal/test2.js index b9bde8f13016cc..e2628446fc65cc 100644 --- a/test/addons-napi/test_fatal/test2.js +++ b/test/addons-napi/test_fatal/test2.js @@ -11,8 +11,12 @@ if (process.argv[2] === 'child') { return; } -const p = child_process.spawnSync( - process.execPath, [ '--napi-modules', __filename, 'child' ]); +const p = child_process.spawnSync(process.execPath, [ + '--napi-modules', + __filename, + 'child' +]); assert.ifError(p.error); -assert.ok(p.stderr.toString().includes( - 'FATAL ERROR: test_fatal::Test fatal message')); +assert.ok( + p.stderr.toString().includes('FATAL ERROR: test_fatal::Test fatal message') +); diff --git a/test/addons-napi/test_fatal_exception/test.js b/test/addons-napi/test_fatal_exception/test.js index f02b9bce1e8169..97c2af027b0ac2 100644 --- a/test/addons-napi/test_fatal_exception/test.js +++ b/test/addons-napi/test_fatal_exception/test.js @@ -3,9 +3,12 @@ const common = require('../../common'); const assert = require('assert'); const test_fatal = require(`./build/${common.buildType}/test_fatal_exception`); -process.on('uncaughtException', common.mustCall(function(err) { - assert.strictEqual(err.message, 'fatal error'); -})); +process.on( + 'uncaughtException', + common.mustCall(function(err) { + assert.strictEqual(err.message, 'fatal error'); + }) +); const err = new Error('fatal error'); test_fatal.Test(err); diff --git a/test/addons-napi/test_general/test.js b/test/addons-napi/test_general/test.js index fe38c1b9a2828c..a1be853bf02270 100644 --- a/test/addons-napi/test_general/test.js +++ b/test/addons-napi/test_general/test.js @@ -9,11 +9,9 @@ const val1 = '1'; const val2 = 1; const val3 = 1; -class BaseClass { -} +class BaseClass {} -class ExtendedClass extends BaseClass { -} +class ExtendedClass extends BaseClass {} const baseObject = new BaseClass(); const extendedObject = new ExtendedClass(); @@ -24,21 +22,29 @@ assert.strictEqual(test_general.testStrictEquals(val1, val2), false); assert.ok(test_general.testStrictEquals(val2, val3)); // test napi_get_prototype -assert.strictEqual(test_general.testGetPrototype(baseObject), - Object.getPrototypeOf(baseObject)); -assert.strictEqual(test_general.testGetPrototype(extendedObject), - Object.getPrototypeOf(extendedObject)); +assert.strictEqual( + test_general.testGetPrototype(baseObject), + Object.getPrototypeOf(baseObject) +); +assert.strictEqual( + test_general.testGetPrototype(extendedObject), + Object.getPrototypeOf(extendedObject) +); // Prototypes for base and extended should be different. -assert.notStrictEqual(test_general.testGetPrototype(baseObject), - test_general.testGetPrototype(extendedObject)); +assert.notStrictEqual( + test_general.testGetPrototype(baseObject), + test_general.testGetPrototype(extendedObject) +); // test version management functions // expected version is currently 3 assert.strictEqual(test_general.testGetVersion(), 3); -const [ major, minor, patch, release ] = test_general.testGetNodeVersion(); -assert.strictEqual(process.version.split('-')[0], - `v${major}.${minor}.${patch}`); +const [major, minor, patch, release] = test_general.testGetNodeVersion(); +assert.strictEqual( + process.version.split('-')[0], + `v${major}.${minor}.${patch}` +); assert.strictEqual(release, process.release.name); [ @@ -64,17 +70,21 @@ test_general.wrap(w); w = null; global.gc(); const derefItemWasCalled = test_general.derefItemWasCalled(); -assert.strictEqual(derefItemWasCalled, true, - 'deref_item() was called upon garbage collecting a ' + - 'wrapped object. test_general.derefItemWasCalled() ' + - `returned ${derefItemWasCalled}`); - +assert.strictEqual( + derefItemWasCalled, + true, + 'deref_item() was called upon garbage collecting a ' + + 'wrapped object. test_general.derefItemWasCalled() ' + + `returned ${derefItemWasCalled}` +); // Assert that wrapping twice fails. const x = {}; test_general.wrap(x); -common.expectsError(() => test_general.wrap(x), - { type: Error, message: 'Invalid argument' }); +common.expectsError(() => test_general.wrap(x), { + type: Error, + message: 'Invalid argument' +}); // Ensure that wrapping, removing the wrap, and then wrapping again works. const y = {}; @@ -91,10 +101,13 @@ test_general.removeWrap(z); z = null; global.gc(); const finalizeWasCalled = test_general.finalizeWasCalled(); -assert.strictEqual(finalizeWasCalled, false, - 'finalize callback was not called upon garbage collection.' + - ' test_general.finalizeWasCalled() ' + - `returned ${finalizeWasCalled}`); +assert.strictEqual( + finalizeWasCalled, + false, + 'finalize callback was not called upon garbage collection.' + + ' test_general.finalizeWasCalled() ' + + `returned ${finalizeWasCalled}` +); // test napi_adjust_external_memory const adjustedValue = test_general.testAdjustExternalMemory(); diff --git a/test/addons-napi/test_general/testFinalizer.js b/test/addons-napi/test_general/testFinalizer.js index b440ed5e501ad8..5be89135ee9012 100644 --- a/test/addons-napi/test_general/testFinalizer.js +++ b/test/addons-napi/test_general/testFinalizer.js @@ -13,12 +13,16 @@ test_general.addFinalizerOnly(finalized, callback); test_general.addFinalizerOnly(finalized, callback); // Ensure attached items cannot be retrieved. -common.expectsError(() => test_general.unwrap(finalized), - { type: Error, message: 'Invalid argument' }); +common.expectsError(() => test_general.unwrap(finalized), { + type: Error, + message: 'Invalid argument' +}); // Ensure attached items cannot be removed. -common.expectsError(() => test_general.removeWrap(finalized), - { type: Error, message: 'Invalid argument' }); +common.expectsError(() => test_general.removeWrap(finalized), { + type: Error, + message: 'Invalid argument' +}); finalized = null; global.gc(); diff --git a/test/addons-napi/test_general/testInstanceOf.js b/test/addons-napi/test_general/testInstanceOf.js index 53455a0025a0e2..58a7a81c572332 100644 --- a/test/addons-napi/test_general/testInstanceOf.js +++ b/test/addons-napi/test_general/testInstanceOf.js @@ -10,8 +10,16 @@ const addon = require(`./build/${common.buildType}/test_general`); const path = require('path'); // This test depends on a number of V8 tests. -const v8TestsDir = path.resolve(__dirname, '..', '..', '..', 'deps', 'v8', - 'test', 'mjsunit'); +const v8TestsDir = path.resolve( + __dirname, + '..', + '..', + '..', + 'deps', + 'v8', + 'test', + 'mjsunit' +); const v8TestsDirExists = fs.existsSync(v8TestsDir); // The following assert functions are referenced by v8's unit tests @@ -41,15 +49,18 @@ function assertThrows(statement) { function testFile(fileName) { try { const contents = fs.readFileSync(fileName, { encoding: 'utf8' }); - eval(contents.replace(/[(]([^\s(]+)\s+instanceof\s+([^)]+)[)]/g, - '(addon.doInstanceOf($1, $2))')); + eval( + contents.replace( + /[(]([^\s(]+)\s+instanceof\s+([^)]+)[)]/g, + '(addon.doInstanceOf($1, $2))' + ) + ); } catch (err) { // This test depends on V8 test files, which may not exist in downloaded // archives. Emit a warning if the tests cannot be found instead of failing. if (err.code === 'ENOENT' && !v8TestsDirExists) process.emitWarning(`test file ${fileName} does not exist.`); - else - throw err; + else throw err; } } @@ -57,13 +68,15 @@ testFile(path.join(v8TestsDir, 'instanceof.js')); testFile(path.join(v8TestsDir, 'instanceof-2.js')); // We can only perform this test if we have a working Symbol.hasInstance -if (typeof Symbol !== 'undefined' && 'hasInstance' in Symbol && - typeof Symbol.hasInstance === 'symbol') { - +if ( + typeof Symbol !== 'undefined' && + 'hasInstance' in Symbol && + typeof Symbol.hasInstance === 'symbol' +) { function compareToNative(theObject, theConstructor) { assert.strictEqual( addon.doInstanceOf(theObject, theConstructor), - (theObject instanceof theConstructor) + theObject instanceof theConstructor ); } diff --git a/test/addons-napi/test_handle_scope/test.js b/test/addons-napi/test_handle_scope/test.js index 53abfe178c8d7d..6bbd3906aa66be 100644 --- a/test/addons-napi/test_handle_scope/test.js +++ b/test/addons-napi/test_handle_scope/test.js @@ -3,8 +3,9 @@ const common = require('../../common'); const assert = require('assert'); // testing handle scope api calls -const testHandleScope = - require(`./build/${common.buildType}/test_handle_scope`); +const testHandleScope = require(`./build/${ + common.buildType +}/test_handle_scope`); testHandleScope.NewScope(); @@ -12,8 +13,8 @@ assert.ok(testHandleScope.NewScopeEscape() instanceof Object); testHandleScope.NewScopeEscapeTwice(); -assert.throws( - () => { - testHandleScope.NewScopeWithException(() => { throw new RangeError(); }); - }, - RangeError); +assert.throws(() => { + testHandleScope.NewScopeWithException(() => { + throw new RangeError(); + }); +}, RangeError); diff --git a/test/addons-napi/test_make_callback/test-async-hooks.js b/test/addons-napi/test_make_callback/test-async-hooks.js index 755a2389c68591..def05c7e69797f 100644 --- a/test/addons-napi/test_make_callback/test-async-hooks.js +++ b/test/addons-napi/test_make_callback/test-async-hooks.js @@ -12,7 +12,7 @@ const hook_result = { init_called: false, before_called: false, after_called: false, - destroy_called: false, + destroy_called: false }; const test_hook = async_hooks.createHook({ init: (id, type) => { @@ -29,7 +29,7 @@ const test_hook = async_hooks.createHook({ }, destroy: (id) => { if (id === hook_result.id) hook_result.destroy_called = true; - }, + } }); test_hook.enable(); diff --git a/test/addons-napi/test_make_callback/test.js b/test/addons-napi/test_make_callback/test.js index f409bbc9d127d6..ea09f58fd0208e 100644 --- a/test/addons-napi/test_make_callback/test.js +++ b/test/addons-napi/test_make_callback/test.js @@ -13,21 +13,36 @@ function myMultiArgFunc(arg1, arg2, arg3) { return 42; } -assert.strictEqual(makeCallback(process, common.mustCall(function() { - assert.strictEqual(arguments.length, 0); - assert.strictEqual(this, process); - return 42; -})), 42); +assert.strictEqual( + makeCallback( + process, + common.mustCall(function() { + assert.strictEqual(arguments.length, 0); + assert.strictEqual(this, process); + return 42; + }) + ), + 42 +); -assert.strictEqual(makeCallback(process, common.mustCall(function(x) { - assert.strictEqual(arguments.length, 1); - assert.strictEqual(this, process); - assert.strictEqual(x, 1337); - return 42; -}), 1337), 42); +assert.strictEqual( + makeCallback( + process, + common.mustCall(function(x) { + assert.strictEqual(arguments.length, 1); + assert.strictEqual(this, process); + assert.strictEqual(x, 1337); + return 42; + }), + 1337 + ), + 42 +); -assert.strictEqual(makeCallback(this, - common.mustCall(myMultiArgFunc), 1, 2, 3), 42); +assert.strictEqual( + makeCallback(this, common.mustCall(myMultiArgFunc), 1, 2, 3), + 42 +); // TODO(node-api): napi_make_callback needs to support // strings passed for the func argument @@ -73,8 +88,7 @@ const forward = vm.runInNewContext(` // Runs in outer context. function endpoint($Object) { - if (Object === $Object) - throw new Error('bad'); + if (Object === $Object) throw new Error('bad'); return Object; } diff --git a/test/addons-napi/test_make_callback_recurse/test.js b/test/addons-napi/test_make_callback_recurse/test.js index f948103de1f4ec..4ca490390b89bb 100644 --- a/test/addons-napi/test_make_callback_recurse/test.js +++ b/test/addons-napi/test_make_callback_recurse/test.js @@ -9,7 +9,6 @@ const makeCallback = binding.makeCallback; // Make sure this is run in the future. const mustCallCheckDomains = common.mustCall(checkDomains); - // Make sure that using MakeCallback allows the error to propagate. assert.throws(function() { makeCallback({}, function() { @@ -17,7 +16,6 @@ assert.throws(function() { }); }, /^Error: hi from domain error$/); - // Check the execution order of the nextTickQueue and MicrotaskQueue in // relation to running multiple MakeCallback's from bootstrap, // node::MakeCallback() and node::AsyncWrap::MakeCallback(). @@ -28,116 +26,164 @@ assert.throws(function() { // Processing of the MicrotaskQueue is manually handled by node. They are not // processed until after the nextTickQueue has been processed. - Promise.resolve(1).then(common.mustCall(function() { - results.push(7); - })); + Promise.resolve(1).then( + common.mustCall(function() { + results.push(7); + }) + ); // The nextTick should run after all immediately invoked calls. - process.nextTick(common.mustCall(function() { - results.push(3); - - // Run same test again but while processing the nextTickQueue to make sure - // the following MakeCallback call breaks in the middle of processing the - // queue and allows the script to run normally. - process.nextTick(common.mustCall(function() { - results.push(6); - })); - - makeCallback({}, common.mustCall(function() { - results.push(4); - })); - - results.push(5); - })); + process.nextTick( + common.mustCall(function() { + results.push(3); + + // Run same test again but while processing the nextTickQueue to make sure + // the following MakeCallback call breaks in the middle of processing the + // queue and allows the script to run normally. + process.nextTick( + common.mustCall(function() { + results.push(6); + }) + ); + + makeCallback( + {}, + common.mustCall(function() { + results.push(4); + }) + ); + + results.push(5); + }) + ); results.push(0); // MakeCallback is calling the function immediately, but should then detect // that a script is already in the middle of execution and return before // either the nextTickQueue or MicrotaskQueue are processed. - makeCallback({}, common.mustCall(function() { - results.push(1); - })); + makeCallback( + {}, + common.mustCall(function() { + results.push(1); + }) + ); // This should run before either the nextTickQueue or MicrotaskQueue are // processed. Previously MakeCallback would not detect this circumstance // and process them immediately. results.push(2); - setImmediate(common.mustCall(function() { - for (let i = 0; i < results.length; i++) { - assert.strictEqual(results[i], i, - `verifyExecutionOrder(${arg}) results: ${results}`); - } - if (arg === 1) { - // The tests are first run on bootstrap during LoadEnvironment() in - // src/node.cc. Now run the tests through node::MakeCallback(). - setImmediate(function() { - makeCallback({}, common.mustCall(function() { - verifyExecutionOrder(2); - })); - }); - } else if (arg === 2) { - // Make sure there are no conflicts using node::MakeCallback() - // within timers. - setTimeout(common.mustCall(function() { - verifyExecutionOrder(3); - }), 10); - } else if (arg === 3) { - mustCallCheckDomains(); - } else { - throw new Error('UNREACHABLE'); - } - })); -}(1)); - + setImmediate( + common.mustCall(function() { + for (let i = 0; i < results.length; i++) { + assert.strictEqual( + results[i], + i, + `verifyExecutionOrder(${arg}) results: ${results}` + ); + } + if (arg === 1) { + // The tests are first run on bootstrap during LoadEnvironment() in + // src/node.cc. Now run the tests through node::MakeCallback(). + setImmediate(function() { + makeCallback( + {}, + common.mustCall(function() { + verifyExecutionOrder(2); + }) + ); + }); + } else if (arg === 2) { + // Make sure there are no conflicts using node::MakeCallback() + // within timers. + setTimeout( + common.mustCall(function() { + verifyExecutionOrder(3); + }), + 10 + ); + } else if (arg === 3) { + mustCallCheckDomains(); + } else { + throw new Error('UNREACHABLE'); + } + }) + ); +})(1); function checkDomains() { // Check that domains are properly entered/exited when called in multiple // levels from both node::MakeCallback() and AsyncWrap::MakeCallback - setImmediate(common.mustCall(function() { - const d1 = domain.create(); - const d2 = domain.create(); - const d3 = domain.create(); - - makeCallback({ domain: d1 }, common.mustCall(function() { - assert.strictEqual(d1, process.domain); - makeCallback({ domain: d2 }, common.mustCall(function() { - assert.strictEqual(d2, process.domain); - makeCallback({ domain: d3 }, common.mustCall(function() { - assert.strictEqual(d3, process.domain); - })); - assert.strictEqual(d2, process.domain); - })); - assert.strictEqual(d1, process.domain); - })); - })); - - setTimeout(common.mustCall(function() { - const d1 = domain.create(); - const d2 = domain.create(); - const d3 = domain.create(); - - makeCallback({ domain: d1 }, common.mustCall(function() { - assert.strictEqual(d1, process.domain); - makeCallback({ domain: d2 }, common.mustCall(function() { - assert.strictEqual(d2, process.domain); - makeCallback({ domain: d3 }, common.mustCall(function() { - assert.strictEqual(d3, process.domain); - })); - assert.strictEqual(d2, process.domain); - })); - assert.strictEqual(d1, process.domain); - })); - }), 1); + setImmediate( + common.mustCall(function() { + const d1 = domain.create(); + const d2 = domain.create(); + const d3 = domain.create(); + + makeCallback( + { domain: d1 }, + common.mustCall(function() { + assert.strictEqual(d1, process.domain); + makeCallback( + { domain: d2 }, + common.mustCall(function() { + assert.strictEqual(d2, process.domain); + makeCallback( + { domain: d3 }, + common.mustCall(function() { + assert.strictEqual(d3, process.domain); + }) + ); + assert.strictEqual(d2, process.domain); + }) + ); + assert.strictEqual(d1, process.domain); + }) + ); + }) + ); + + setTimeout( + common.mustCall(function() { + const d1 = domain.create(); + const d2 = domain.create(); + const d3 = domain.create(); + + makeCallback( + { domain: d1 }, + common.mustCall(function() { + assert.strictEqual(d1, process.domain); + makeCallback( + { domain: d2 }, + common.mustCall(function() { + assert.strictEqual(d2, process.domain); + makeCallback( + { domain: d3 }, + common.mustCall(function() { + assert.strictEqual(d3, process.domain); + }) + ); + assert.strictEqual(d2, process.domain); + }) + ); + assert.strictEqual(d1, process.domain); + }) + ); + }), + 1 + ); function testTimer(id) { // Make sure nextTick, setImmediate and setTimeout can all recover properly // after a thrown makeCallback call. const d = domain.create(); - d.on('error', common.mustCall(function(e) { - assert.strictEqual(e.message, `throw from domain ${id}`); - })); + d.on( + 'error', + common.mustCall(function(e) { + assert.strictEqual(e.message, `throw from domain ${id}`); + }) + ); makeCallback({ domain: d }, function() { throw new Error(`throw from domain ${id}`); }); diff --git a/test/addons-napi/test_new_target/test.js b/test/addons-napi/test_new_target/test.js index 702e8ca8b4387d..7849d1f4f813b9 100644 --- a/test/addons-napi/test_new_target/test.js +++ b/test/addons-napi/test_new_target/test.js @@ -18,4 +18,5 @@ assert.ok(new Class() instanceof binding.BaseClass); assert.ok(new Class().ok); assert.ok(binding.OrdinaryFunction()); assert.ok( - new binding.Constructor(binding.Constructor) instanceof binding.Constructor); + new binding.Constructor(binding.Constructor) instanceof binding.Constructor +); diff --git a/test/addons-napi/test_null_init/test.js b/test/addons-napi/test_null_init/test.js index 6e6bf51839bed0..ebbf6e2c9b8ca9 100644 --- a/test/addons-napi/test_null_init/test.js +++ b/test/addons-napi/test_null_init/test.js @@ -4,4 +4,5 @@ const assert = require('assert'); assert.throws( () => require(`./build/${common.buildType}/test_null_init`), - /Module has no declared entry point[.]/); + /Module has no declared entry point[.]/ +); diff --git a/test/addons-napi/test_number/test.js b/test/addons-napi/test_number/test.js index 34f48aee578ac6..06a34fee4b6cd2 100644 --- a/test/addons-napi/test_number/test.js +++ b/test/addons-napi/test_number/test.js @@ -3,7 +3,6 @@ const common = require('../../common'); const assert = require('assert'); const test_number = require(`./build/${common.buildType}/test_number`); - // testing api calls for number function testNumber(num) { assert.strictEqual(num, test_number.Test(num)); @@ -19,10 +18,8 @@ testNumber(-1233); testNumber(986583); testNumber(-976675); -testNumber( - 98765432213456789876546896323445679887645323232436587988766545658); -testNumber( - -4350987086545760976737453646576078997096876957864353245245769809); +testNumber(98765432213456789876546896323445679887645323232436587988766545658); +testNumber(-4350987086545760976737453646576078997096876957864353245245769809); testNumber(Number.MIN_SAFE_INTEGER); testNumber(Number.MAX_SAFE_INTEGER); testNumber(Number.MAX_SAFE_INTEGER + 10); @@ -84,8 +81,8 @@ testInt32(-Number.MAX_VALUE, 0); testInt32(Number.MAX_VALUE, 0); // Test outside int64_t range -testInt32(-Math.pow(2, 63) + (Math.pow(2, 9)), 0); -testInt32(Math.pow(2, 63) - (Math.pow(2, 9)), 0); +testInt32(-Math.pow(2, 63) + Math.pow(2, 9), 0); +testInt32(Math.pow(2, 63) - Math.pow(2, 9), 0); // Test non-finite numbers testInt32(Number.POSITIVE_INFINITY, 0); @@ -122,8 +119,8 @@ testInt64(-Number.MAX_VALUE, RANGEERROR_NEGATIVE); testInt64(Number.MAX_VALUE, RANGEERROR_POSITIVE); // Test outside int64_t range -testInt64(-Math.pow(2, 63) + (Math.pow(2, 9)), RANGEERROR_NEGATIVE); -testInt64(Math.pow(2, 63) - (Math.pow(2, 9)), RANGEERROR_POSITIVE); +testInt64(-Math.pow(2, 63) + Math.pow(2, 9), RANGEERROR_NEGATIVE); +testInt64(Math.pow(2, 63) - Math.pow(2, 9), RANGEERROR_POSITIVE); // Test non-finite numbers testInt64(Number.POSITIVE_INFINITY, 0); diff --git a/test/addons-napi/test_object/test.js b/test/addons-napi/test_object/test.js index 8e44a1b5ed647f..4920322970ce7f 100644 --- a/test/addons-napi/test_object/test.js +++ b/test/addons-napi/test_object/test.js @@ -5,22 +5,25 @@ const assert = require('assert'); // Testing api calls for objects const test_object = require(`./build/${common.buildType}/test_object`); - const object = { hello: 'world', - array: [ - 1, 94, 'str', 12.321, { test: 'obj in arr' } - ], + array: [1, 94, 'str', 12.321, { test: 'obj in arr' }], newObject: { test: 'obj in obj' } }; assert.strictEqual(test_object.Get(object, 'hello'), 'world'); -assert.deepStrictEqual(test_object.Get(object, 'array'), - [ 1, 94, 'str', 12.321, { test: 'obj in arr' } ]); -assert.deepStrictEqual(test_object.Get(object, 'newObject'), - { test: 'obj in obj' }); +assert.deepStrictEqual(test_object.Get(object, 'array'), [ + 1, + 94, + 'str', + 12.321, + { test: 'obj in arr' } +]); +assert.deepStrictEqual(test_object.Get(object, 'newObject'), { + test: 'obj in obj' +}); assert(test_object.Has(object, 'hello')); assert(test_object.Has(object, 'array')); @@ -46,8 +49,10 @@ assert.strictEqual(newObject.test_string, 'test string'); assert.strictEqual(test_object.Get(obj, 'foo'), 42); assert.strictEqual(test_object.Get(obj, 'bar'), 43); assert.strictEqual(test_object.Get(obj, 'baz'), 45); - assert.strictEqual(test_object.Get(obj, 'toString'), - Object.prototype.toString); + assert.strictEqual( + test_object.Get(obj, 'toString'), + Object.prototype.toString + ); } { @@ -96,8 +101,12 @@ assert.strictEqual(newObject.test_string, 'test string'); assert.deepStrictEqual(test_object.Inflate(cube), { x: 12, y: 12, z: 12 }); assert.deepStrictEqual(test_object.Inflate(cube), { x: 13, y: 13, z: 13 }); cube.t = 13; - assert.deepStrictEqual( - test_object.Inflate(cube), { x: 14, y: 14, z: 14, t: 14 }); + assert.deepStrictEqual(test_object.Inflate(cube), { + x: 14, + y: 14, + z: 14, + t: 14 + }); const sym1 = Symbol('1'); const sym2 = Symbol('2'); diff --git a/test/addons-napi/test_promise/test.js b/test/addons-napi/test_promise/test.js index feaa4ebfef688a..ae92136b2e6ac3 100644 --- a/test/addons-napi/test_promise/test.js +++ b/test/addons-napi/test_promise/test.js @@ -15,19 +15,21 @@ const test_promise = require(`./build/${common.buildType}/test_promise`); common.mustCall(function(result) { assert.strictEqual(result, expected_result); }), - common.mustNotCall()); + common.mustNotCall() + ); test_promise.concludeCurrentPromise(expected_result, true); } // A rejection { - const expected_result = 'It\'s not you, it\'s me.'; + const expected_result = "It's not you, it's me."; const promise = test_promise.createPromise(); promise.then( common.mustNotCall(), common.mustCall(function(result) { assert.strictEqual(result, expected_result); - })); + }) + ); test_promise.concludeCurrentPromise(expected_result, false); } @@ -39,7 +41,8 @@ const test_promise = require(`./build/${common.buildType}/test_promise`); common.mustCall(function(result) { assert.strictEqual(result, expected_result); }), - common.mustNotCall()); + common.mustNotCall() + ); test_promise.concludeCurrentPromise(Promise.resolve('chained answer'), true); } diff --git a/test/addons-napi/test_properties/test.js b/test/addons-napi/test_properties/test.js index 13a546c7b87f81..baff489895ddd4 100644 --- a/test/addons-napi/test_properties/test.js +++ b/test/addons-napi/test_properties/test.js @@ -1,8 +1,7 @@ 'use strict'; const common = require('../../common'); const assert = require('assert'); -const readonlyErrorRE = - /^TypeError: Cannot assign to read only property '.*' of object '#'$/; +const readonlyErrorRE = /^TypeError: Cannot assign to read only property '.*' of object '#'$/; // Testing api calls for defining properties const test_object = require(`./build/${common.buildType}/test_properties`); @@ -14,7 +13,9 @@ assert.strictEqual(test_object.readwriteValue, 1); test_object.readwriteValue = 2; assert.strictEqual(test_object.readwriteValue, 2); -assert.throws(() => { test_object.readonlyValue = 3; }, readonlyErrorRE); +assert.throws(() => { + test_object.readonlyValue = 3; +}, readonlyErrorRE); assert.ok(test_object.hiddenValue); @@ -36,22 +37,31 @@ assert.ok(!propertyNames.includes('readonlyAccessor2')); // validate property created with symbol const start = 'Symbol('.length; const end = start + 'NameKeySymbol'.length; -const symbolDescription = - String(Object.getOwnPropertySymbols(test_object)[0]).slice(start, end); +const symbolDescription = String( + Object.getOwnPropertySymbols(test_object)[0] +).slice(start, end); assert.strictEqual(symbolDescription, 'NameKeySymbol'); // The napi_writable attribute should be ignored for accessors. test_object.readwriteAccessor1 = 1; assert.strictEqual(test_object.readwriteAccessor1, 1); assert.strictEqual(test_object.readonlyAccessor1, 1); -assert.throws(() => { test_object.readonlyAccessor1 = 3; }, readonlyErrorRE); +assert.throws(() => { + test_object.readonlyAccessor1 = 3; +}, readonlyErrorRE); test_object.readwriteAccessor2 = 2; assert.strictEqual(test_object.readwriteAccessor2, 2); assert.strictEqual(test_object.readonlyAccessor2, 2); -assert.throws(() => { test_object.readonlyAccessor2 = 3; }, readonlyErrorRE); +assert.throws(() => { + test_object.readonlyAccessor2 = 3; +}, readonlyErrorRE); assert.strictEqual(test_object.hasNamedProperty(test_object, 'echo'), true); -assert.strictEqual(test_object.hasNamedProperty(test_object, 'hiddenValue'), - true); -assert.strictEqual(test_object.hasNamedProperty(test_object, 'doesnotexist'), - false); +assert.strictEqual( + test_object.hasNamedProperty(test_object, 'hiddenValue'), + true +); +assert.strictEqual( + test_object.hasNamedProperty(test_object, 'doesnotexist'), + false +); diff --git a/test/addons-napi/test_reference/test.js b/test/addons-napi/test_reference/test.js index 14932a74ca70b0..c052732d7cfca3 100644 --- a/test/addons-napi/test_reference/test.js +++ b/test/addons-napi/test_reference/test.js @@ -33,7 +33,6 @@ function runTests(i, title, tests) { } } runTests(0, undefined, [ - 'External value without a finalizer', () => { const value = test_reference.createExternal(); @@ -116,5 +115,5 @@ runTests(0, undefined, [ () => { // Value was already GC'd assert.strictEqual(test_reference.finalizeCount, 1); - }, + } ]); diff --git a/test/addons-napi/test_symbol/test3.js b/test/addons-napi/test_symbol/test3.js index a7c6c18c025480..03f1d4759f6a53 100644 --- a/test/addons-napi/test_symbol/test3.js +++ b/test/addons-napi/test_symbol/test3.js @@ -13,7 +13,7 @@ const foo1 = test_symbol.New('foo'); const foo2 = test_symbol.New('foo'); const object = { [foo1]: 1, - [foo2]: 2, + [foo2]: 2 }; assert.strictEqual(object[foo1], 1); assert.strictEqual(object[foo2], 2); diff --git a/test/addons-napi/test_threadsafe_function/test.js b/test/addons-napi/test_threadsafe_function/test.js index cfd00285308f5d..cdff346f2070f9 100644 --- a/test/addons-napi/test_threadsafe_function/test.js +++ b/test/addons-napi/test_threadsafe_function/test.js @@ -17,13 +17,18 @@ const expectedArray = (function(arrayLength) { // process to exit and the environment cleanup handler to be invoked. if (process.argv[2] === 'child') { let callCount = 0; - binding.StartThread((value) => { - callCount++; - console.log(value); - if (callCount === 2) { - binding.Unref(); - } - }, false /* abort */, true /* launchSecondary */, +process.argv[3]); + binding.StartThread( + (value) => { + callCount++; + console.log(value); + if (callCount === 2) { + binding.Unref(); + } + }, + false /* abort */, + true /* launchSecondary */, + +process.argv[3] + ); // Release the thread-safe function from the main thread so that it may be // torn down via the environment cleanup handler. @@ -36,19 +41,28 @@ function testWithJSMarshaller({ quitAfter, abort, maxQueueSize, - launchSecondary }) { + launchSecondary +}) { return new Promise((resolve) => { const array = []; - binding[threadStarter](function testCallback(value) { - array.push(value); - if (array.length === quitAfter) { - setImmediate(() => { - binding.StopThread(common.mustCall(() => { - resolve(array); - }), !!abort); - }); - } - }, !!abort, !!launchSecondary, maxQueueSize); + binding[threadStarter]( + function testCallback(value) { + array.push(value); + if (array.length === quitAfter) { + setImmediate(() => { + binding.StopThread( + common.mustCall(() => { + resolve(array); + }), + !!abort + ); + }); + } + }, + !!abort, + !!launchSecondary, + maxQueueSize + ); if (threadStarter === 'StartThreadNonblocking') { // Let's make this thread really busy for a short while to ensure that // the queue fills and the thread receives a napi_queue_full. @@ -72,135 +86,164 @@ function testUnref(queueSize) { } }); child.stdout.on('data', (data) => (output += data.toString())); - }) - .then((result) => assert.strictEqual(result.indexOf(0), -1)); + }).then((result) => assert.strictEqual(result.indexOf(0), -1)); } new Promise(function testWithoutJSMarshaller(resolve) { let callCount = 0; - binding.StartThreadNoNative(function testCallback() { - callCount++; - - // The default call-into-JS implementation passes no arguments. - assert.strictEqual(arguments.length, 0); - if (callCount === binding.ARRAY_LENGTH) { - setImmediate(() => { - binding.StopThread(common.mustCall(() => { - resolve(); - }), false); - }); - } - }, false /* abort */, false /* launchSecondary */, binding.MAX_QUEUE_SIZE); + binding.StartThreadNoNative( + function testCallback() { + callCount++; + + // The default call-into-JS implementation passes no arguments. + assert.strictEqual(arguments.length, 0); + if (callCount === binding.ARRAY_LENGTH) { + setImmediate(() => { + binding.StopThread( + common.mustCall(() => { + resolve(); + }), + false + ); + }); + } + }, + false /* abort */, + false /* launchSecondary */, + binding.MAX_QUEUE_SIZE + ); }) -// Start the thread in blocking mode, and assert that all values are passed. -// Quit after it's done. -.then(() => testWithJSMarshaller({ - threadStarter: 'StartThread', - maxQueueSize: binding.MAX_QUEUE_SIZE, - quitAfter: binding.ARRAY_LENGTH -})) -.then((result) => assert.deepStrictEqual(result, expectedArray)) - -// Start the thread in blocking mode with an infinite queue, and assert that all -// values are passed. Quit after it's done. -.then(() => testWithJSMarshaller({ - threadStarter: 'StartThread', - maxQueueSize: 0, - quitAfter: binding.ARRAY_LENGTH -})) -.then((result) => assert.deepStrictEqual(result, expectedArray)) - -// Start the thread in non-blocking mode, and assert that all values are passed. -// Quit after it's done. -.then(() => testWithJSMarshaller({ - threadStarter: 'StartThreadNonblocking', - maxQueueSize: binding.MAX_QUEUE_SIZE, - quitAfter: binding.ARRAY_LENGTH -})) -.then((result) => assert.deepStrictEqual(result, expectedArray)) - -// Start the thread in blocking mode, and assert that all values are passed. -// Quit early, but let the thread finish. -.then(() => testWithJSMarshaller({ - threadStarter: 'StartThread', - maxQueueSize: binding.MAX_QUEUE_SIZE, - quitAfter: 1 -})) -.then((result) => assert.deepStrictEqual(result, expectedArray)) - -// Start the thread in blocking mode with an infinite queue, and assert that all -// values are passed. Quit early, but let the thread finish. -.then(() => testWithJSMarshaller({ - threadStarter: 'StartThread', - maxQueueSize: 0, - quitAfter: 1 -})) -.then((result) => assert.deepStrictEqual(result, expectedArray)) - -// Start the thread in non-blocking mode, and assert that all values are passed. -// Quit early, but let the thread finish. -.then(() => testWithJSMarshaller({ - threadStarter: 'StartThreadNonblocking', - maxQueueSize: binding.MAX_QUEUE_SIZE, - quitAfter: 1 -})) -.then((result) => assert.deepStrictEqual(result, expectedArray)) - -// Start the thread in blocking mode, and assert that all values are passed. -// Quit early, but let the thread finish. Launch a secondary thread to test the -// reference counter incrementing functionality. -.then(() => testWithJSMarshaller({ - threadStarter: 'StartThread', - quitAfter: 1, - maxQueueSize: binding.MAX_QUEUE_SIZE, - launchSecondary: true -})) -.then((result) => assert.deepStrictEqual(result, expectedArray)) - -// Start the thread in non-blocking mode, and assert that all values are passed. -// Quit early, but let the thread finish. Launch a secondary thread to test the -// reference counter incrementing functionality. -.then(() => testWithJSMarshaller({ - threadStarter: 'StartThreadNonblocking', - quitAfter: 1, - maxQueueSize: binding.MAX_QUEUE_SIZE, - launchSecondary: true -})) -.then((result) => assert.deepStrictEqual(result, expectedArray)) - -// Start the thread in blocking mode, and assert that it could not finish. -// Quit early by aborting. -.then(() => testWithJSMarshaller({ - threadStarter: 'StartThread', - quitAfter: 1, - maxQueueSize: binding.MAX_QUEUE_SIZE, - abort: true -})) -.then((result) => assert.strictEqual(result.indexOf(0), -1)) - -// Start the thread in blocking mode with an infinite queue, and assert that it -// could not finish. Quit early by aborting. -.then(() => testWithJSMarshaller({ - threadStarter: 'StartThread', - quitAfter: 1, - maxQueueSize: 0, - abort: true -})) -.then((result) => assert.strictEqual(result.indexOf(0), -1)) - -// Start the thread in non-blocking mode, and assert that it could not finish. -// Quit early and aborting. -.then(() => testWithJSMarshaller({ - threadStarter: 'StartThreadNonblocking', - quitAfter: 1, - maxQueueSize: binding.MAX_QUEUE_SIZE, - abort: true -})) -.then((result) => assert.strictEqual(result.indexOf(0), -1)) - -// Start a child process to test rapid teardown -.then(() => testUnref(binding.MAX_QUEUE_SIZE)) - -// Start a child process with an infinite queue to test rapid teardown -.then(() => testUnref(0)); + // Start the thread in blocking mode, and assert that all values are passed. + // Quit after it's done. + .then(() => + testWithJSMarshaller({ + threadStarter: 'StartThread', + maxQueueSize: binding.MAX_QUEUE_SIZE, + quitAfter: binding.ARRAY_LENGTH + }) + ) + .then((result) => assert.deepStrictEqual(result, expectedArray)) + + // Start the thread in blocking mode with an infinite queue, and assert that all + // values are passed. Quit after it's done. + .then(() => + testWithJSMarshaller({ + threadStarter: 'StartThread', + maxQueueSize: 0, + quitAfter: binding.ARRAY_LENGTH + }) + ) + .then((result) => assert.deepStrictEqual(result, expectedArray)) + + // Start the thread in non-blocking mode, and assert that all values are passed. + // Quit after it's done. + .then(() => + testWithJSMarshaller({ + threadStarter: 'StartThreadNonblocking', + maxQueueSize: binding.MAX_QUEUE_SIZE, + quitAfter: binding.ARRAY_LENGTH + }) + ) + .then((result) => assert.deepStrictEqual(result, expectedArray)) + + // Start the thread in blocking mode, and assert that all values are passed. + // Quit early, but let the thread finish. + .then(() => + testWithJSMarshaller({ + threadStarter: 'StartThread', + maxQueueSize: binding.MAX_QUEUE_SIZE, + quitAfter: 1 + }) + ) + .then((result) => assert.deepStrictEqual(result, expectedArray)) + + // Start the thread in blocking mode with an infinite queue, and assert that all + // values are passed. Quit early, but let the thread finish. + .then(() => + testWithJSMarshaller({ + threadStarter: 'StartThread', + maxQueueSize: 0, + quitAfter: 1 + }) + ) + .then((result) => assert.deepStrictEqual(result, expectedArray)) + + // Start the thread in non-blocking mode, and assert that all values are passed. + // Quit early, but let the thread finish. + .then(() => + testWithJSMarshaller({ + threadStarter: 'StartThreadNonblocking', + maxQueueSize: binding.MAX_QUEUE_SIZE, + quitAfter: 1 + }) + ) + .then((result) => assert.deepStrictEqual(result, expectedArray)) + + // Start the thread in blocking mode, and assert that all values are passed. + // Quit early, but let the thread finish. Launch a secondary thread to test the + // reference counter incrementing functionality. + .then(() => + testWithJSMarshaller({ + threadStarter: 'StartThread', + quitAfter: 1, + maxQueueSize: binding.MAX_QUEUE_SIZE, + launchSecondary: true + }) + ) + .then((result) => assert.deepStrictEqual(result, expectedArray)) + + // Start the thread in non-blocking mode, and assert that all values are passed. + // Quit early, but let the thread finish. Launch a secondary thread to test the + // reference counter incrementing functionality. + .then(() => + testWithJSMarshaller({ + threadStarter: 'StartThreadNonblocking', + quitAfter: 1, + maxQueueSize: binding.MAX_QUEUE_SIZE, + launchSecondary: true + }) + ) + .then((result) => assert.deepStrictEqual(result, expectedArray)) + + // Start the thread in blocking mode, and assert that it could not finish. + // Quit early by aborting. + .then(() => + testWithJSMarshaller({ + threadStarter: 'StartThread', + quitAfter: 1, + maxQueueSize: binding.MAX_QUEUE_SIZE, + abort: true + }) + ) + .then((result) => assert.strictEqual(result.indexOf(0), -1)) + + // Start the thread in blocking mode with an infinite queue, and assert that it + // could not finish. Quit early by aborting. + .then(() => + testWithJSMarshaller({ + threadStarter: 'StartThread', + quitAfter: 1, + maxQueueSize: 0, + abort: true + }) + ) + .then((result) => assert.strictEqual(result.indexOf(0), -1)) + + // Start the thread in non-blocking mode, and assert that it could not finish. + // Quit early and aborting. + .then(() => + testWithJSMarshaller({ + threadStarter: 'StartThreadNonblocking', + quitAfter: 1, + maxQueueSize: binding.MAX_QUEUE_SIZE, + abort: true + }) + ) + .then((result) => assert.strictEqual(result.indexOf(0), -1)) + + // Start a child process to test rapid teardown + .then(() => testUnref(binding.MAX_QUEUE_SIZE)) + + // Start a child process with an infinite queue to test rapid teardown + .then(() => testUnref(0)); diff --git a/test/addons-napi/test_typedarray/test.js b/test/addons-napi/test_typedarray/test.js index 2a8cf18feb866c..7c2eee345b4154 100644 --- a/test/addons-napi/test_typedarray/test.js +++ b/test/addons-napi/test_typedarray/test.js @@ -40,18 +40,30 @@ assert.strictEqual(externalResult[2], 2); // validate creation of all kinds of TypedArrays const buffer = new ArrayBuffer(128); -const arrayTypes = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, - Uint16Array, Int32Array, Uint32Array, Float32Array, - Float64Array, BigInt64Array, BigUint64Array ]; +const arrayTypes = [ + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + BigInt64Array, + BigUint64Array +]; arrayTypes.forEach((currentType) => { const template = Reflect.construct(currentType, buffer); const theArray = test_typedarray.CreateTypedArray(template, buffer); - assert.ok(theArray instanceof currentType, - 'Type of new array should match that of the template. ' + - `Expected type: ${currentType.name}, ` + - `actual type: ${template.constructor.name}`); + assert.ok( + theArray instanceof currentType, + 'Type of new array should match that of the template. ' + + `Expected type: ${currentType.name}, ` + + `actual type: ${template.constructor.name}` + ); assert.notStrictEqual(theArray, template); assert.strictEqual(theArray.buffer, buffer); }); @@ -63,14 +75,25 @@ arrayTypes.forEach((currentType) => { }, RangeError); }); -const nonByteArrayTypes = [ Int16Array, Uint16Array, Int32Array, Uint32Array, - Float32Array, Float64Array, - BigInt64Array, BigUint64Array ]; +const nonByteArrayTypes = [ + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + BigInt64Array, + BigUint64Array +]; nonByteArrayTypes.forEach((currentType) => { const template = Reflect.construct(currentType, buffer); assert.throws(() => { - test_typedarray.CreateTypedArray(template, buffer, - currentType.BYTES_PER_ELEMENT + 1, 1); + test_typedarray.CreateTypedArray( + template, + buffer, + currentType.BYTES_PER_ELEMENT + 1, + 1 + ); console.log(`start of offset ${currentType}`); }, RangeError); }); diff --git a/test/addons/async-hello-world/test-makecallback-uncaught.js b/test/addons/async-hello-world/test-makecallback-uncaught.js index c207f535bee6eb..a7f73a73726e75 100644 --- a/test/addons/async-hello-world/test-makecallback-uncaught.js +++ b/test/addons/async-hello-world/test-makecallback-uncaught.js @@ -4,6 +4,9 @@ const { runMakeCallback } = require(`./build/${common.buildType}/binding`); process.on('uncaughtException', common.mustCall()); -runMakeCallback(5, common.mustCall(() => { - throw new Error('foo'); -})); +runMakeCallback( + 5, + common.mustCall(() => { + throw new Error('foo'); + }) +); diff --git a/test/addons/async-hello-world/test-makecallback.js b/test/addons/async-hello-world/test-makecallback.js index 0edf052e8c34fc..1a9f8b8a2d86c0 100644 --- a/test/addons/async-hello-world/test-makecallback.js +++ b/test/addons/async-hello-world/test-makecallback.js @@ -3,8 +3,11 @@ const common = require('../../common'); const assert = require('assert'); const { runMakeCallback } = require(`./build/${common.buildType}/binding`); -runMakeCallback(5, common.mustCall(function(err, val) { - assert.strictEqual(err, null); - assert.strictEqual(val, 10); - process.nextTick(common.mustCall()); -})); +runMakeCallback( + 5, + common.mustCall(function(err, val) { + assert.strictEqual(err, null); + assert.strictEqual(val, 10); + process.nextTick(common.mustCall()); + }) +); diff --git a/test/addons/async-hello-world/test.js b/test/addons/async-hello-world/test.js index f24071087c0629..24295f74c46d56 100644 --- a/test/addons/async-hello-world/test.js +++ b/test/addons/async-hello-world/test.js @@ -3,8 +3,11 @@ const common = require('../../common'); const assert = require('assert'); const { runCall } = require(`./build/${common.buildType}/binding`); -runCall(5, common.mustCall(function(err, val) { - assert.strictEqual(err, null); - assert.strictEqual(val, 10); - process.nextTick(common.mustCall()); -})); +runCall( + 5, + common.mustCall(function(err, val) { + assert.strictEqual(err, null); + assert.strictEqual(val, 10); + process.nextTick(common.mustCall()); + }) +); diff --git a/test/addons/async-hooks-id/test.js b/test/addons/async-hooks-id/test.js index e6c3cf612cacd5..714c4ebfcb1d00 100644 --- a/test/addons/async-hooks-id/test.js +++ b/test/addons/async-hooks-id/test.js @@ -9,18 +9,17 @@ assert.strictEqual( binding.getExecutionAsyncId(), async_hooks.executionAsyncId() ); -assert.strictEqual( - binding.getTriggerAsyncId(), - async_hooks.triggerAsyncId() -); +assert.strictEqual(binding.getTriggerAsyncId(), async_hooks.triggerAsyncId()); -process.nextTick(common.mustCall(function() { - assert.strictEqual( - binding.getExecutionAsyncId(), - async_hooks.executionAsyncId() - ); - assert.strictEqual( - binding.getTriggerAsyncId(), - async_hooks.triggerAsyncId() - ); -})); +process.nextTick( + common.mustCall(function() { + assert.strictEqual( + binding.getExecutionAsyncId(), + async_hooks.executionAsyncId() + ); + assert.strictEqual( + binding.getTriggerAsyncId(), + async_hooks.triggerAsyncId() + ); + }) +); diff --git a/test/addons/async-hooks-promise/test.js b/test/addons/async-hooks-promise/test.js index a6c48e94a34f07..dbcd2c452d795d 100644 --- a/test/addons/async-hooks-promise/test.js +++ b/test/addons/async-hooks-promise/test.js @@ -11,30 +11,26 @@ if (process.env.NODE_TEST_WITH_ASYNC_HOOKS) { } // Baseline to make sure the internal field isn't being set. -assert.strictEqual( - binding.getPromiseField(Promise.resolve(1)), - 0); +assert.strictEqual(binding.getPromiseField(Promise.resolve(1)), 0); const hook0 = async_hooks.createHook({}).enable(); // Check that no PromiseWrap is created when there are no hook callbacks. -assert.strictEqual( - binding.getPromiseField(Promise.resolve(1)), - 0); +assert.strictEqual(binding.getPromiseField(Promise.resolve(1)), 0); hook0.disable(); let pwrap = null; -const hook1 = async_hooks.createHook({ - init(id, type, tid, resource) { - pwrap = resource; - } -}).enable(); +const hook1 = async_hooks + .createHook({ + init(id, type, tid, resource) { + pwrap = resource; + } + }) + .enable(); // Check that the internal field returns the same PromiseWrap passed to init(). -assert.strictEqual( - binding.getPromiseField(Promise.resolve(1)), - pwrap); +assert.strictEqual(binding.getPromiseField(Promise.resolve(1)), pwrap); hook1.disable(); @@ -42,7 +38,5 @@ hook1.disable(); // a bit because the `disable()` call only schedules disabling the hook in a // future microtask. setImmediate(() => { - assert.strictEqual( - binding.getPromiseField(Promise.resolve(1)), - 0); + assert.strictEqual(binding.getPromiseField(Promise.resolve(1)), 0); }); diff --git a/test/addons/async-resource/test.js b/test/addons/async-resource/test.js index c37d4df83d0103..bb00dab035ec4d 100644 --- a/test/addons/async-resource/test.js +++ b/test/addons/async-resource/test.js @@ -16,34 +16,38 @@ let before = 0; let after = 0; let destroy = 0; -async_hooks.createHook({ - init(id, type, triggerAsyncId, resource) { - assert.strictEqual(typeof id, 'number'); - assert.strictEqual(typeof resource, 'object'); - assert(id > 1); - if (type === 'foobär') { - assert.strictEqual(resource.kObjectTag, kObjectTag); - assert.strictEqual(triggerAsyncId, expectedTriggerId); - bindingUids.push(id); - } - }, +async_hooks + .createHook({ + init(id, type, triggerAsyncId, resource) { + assert.strictEqual(typeof id, 'number'); + assert.strictEqual(typeof resource, 'object'); + assert(id > 1); + if (type === 'foobär') { + assert.strictEqual(resource.kObjectTag, kObjectTag); + assert.strictEqual(triggerAsyncId, expectedTriggerId); + bindingUids.push(id); + } + }, - before(id) { - if (bindingUids.includes(id)) before++; - }, + before(id) { + if (bindingUids.includes(id)) before++; + }, - after(id) { - if (bindingUids.includes(id)) after++; - }, + after(id) { + if (bindingUids.includes(id)) after++; + }, - destroy(id) { - if (bindingUids.includes(id)) destroy++; - } -}).enable(); + destroy(id) { + if (bindingUids.includes(id)) destroy++; + } + }) + .enable(); -for (const call of [binding.callViaFunction, - binding.callViaString, - binding.callViaUtf8Name]) { +for (const call of [ + binding.callViaFunction, + binding.callViaString, + binding.callViaUtf8Name +]) { for (const passedTriggerId of [undefined, 12345]) { let uid; const object = { @@ -56,10 +60,8 @@ for (const call of [binding.callViaFunction, kObjectTag }; - if (passedTriggerId === undefined) - expectedTriggerId = rootAsyncId; - else - expectedTriggerId = passedTriggerId; + if (passedTriggerId === undefined) expectedTriggerId = rootAsyncId; + else expectedTriggerId = passedTriggerId; const resource = binding.createAsyncResource(object, passedTriggerId); uid = bindingUids[bindingUids.length - 1]; @@ -74,9 +76,11 @@ for (const call of [binding.callViaFunction, } } -setImmediate(common.mustCall(() => { - assert.strictEqual(bindingUids.length, 6); - assert.strictEqual(before, bindingUids.length); - assert.strictEqual(after, bindingUids.length); - assert.strictEqual(destroy, bindingUids.length); -})); +setImmediate( + common.mustCall(() => { + assert.strictEqual(bindingUids.length, 6); + assert.strictEqual(before, bindingUids.length); + assert.strictEqual(after, bindingUids.length); + assert.strictEqual(destroy, bindingUids.length); + }) +); diff --git a/test/addons/callback-scope/test-async-hooks.js b/test/addons/callback-scope/test-async-hooks.js index 94b53efc53d78e..e2d86a7d6fe453 100644 --- a/test/addons/callback-scope/test-async-hooks.js +++ b/test/addons/callback-scope/test-async-hooks.js @@ -6,16 +6,18 @@ const async_hooks = require('async_hooks'); const { runInCallbackScope } = require(`./build/${common.buildType}/binding`); let insideHook = false; -async_hooks.createHook({ - before: common.mustCall((id) => { - assert.strictEqual(id, 1000); - insideHook = true; - }), - after: common.mustCall((id) => { - assert.strictEqual(id, 1000); - insideHook = false; +async_hooks + .createHook({ + before: common.mustCall((id) => { + assert.strictEqual(id, 1000); + insideHook = true; + }), + after: common.mustCall((id) => { + assert.strictEqual(id, 1000); + insideHook = false; + }) }) -}).enable(); + .enable(); runInCallbackScope({}, 1000, 1000, () => { assert(insideHook); diff --git a/test/addons/callback-scope/test-resolve-async.js b/test/addons/callback-scope/test-resolve-async.js index c2942397737359..dbec805cd8164e 100644 --- a/test/addons/callback-scope/test-resolve-async.js +++ b/test/addons/callback-scope/test-resolve-async.js @@ -7,6 +7,10 @@ const { testResolveAsync } = require(`./build/${common.buildType}/binding`); // Checks that resolving promises from C++ works. let called = false; -testResolveAsync().then(() => { called = true; }); +testResolveAsync().then(() => { + called = true; +}); -process.on('beforeExit', () => { assert(called); }); +process.on('beforeExit', () => { + assert(called); +}); diff --git a/test/addons/callback-scope/test.js b/test/addons/callback-scope/test.js index 2f2efe5f47b98a..a2158fd5bcea2b 100644 --- a/test/addons/callback-scope/test.js +++ b/test/addons/callback-scope/test.js @@ -7,9 +7,12 @@ const { runInCallbackScope } = require(`./build/${common.buildType}/binding`); assert.strictEqual(runInCallbackScope({}, 0, 0, () => 42), 42); { - process.once('uncaughtException', common.mustCall((err) => { - assert.strictEqual(err.message, 'foo'); - })); + process.once( + 'uncaughtException', + common.mustCall((err) => { + assert.strictEqual(err.message, 'foo'); + }) + ); runInCallbackScope({}, 0, 0, () => { throw new Error('foo'); diff --git a/test/addons/dlopen-ping-pong/test.js b/test/addons/dlopen-ping-pong/test.js index c533593496090a..1576e2e43a43d0 100644 --- a/test/addons/dlopen-ping-pong/test.js +++ b/test/addons/dlopen-ping-pong/test.js @@ -9,8 +9,11 @@ const path = require('path'); const os = require('os'); const bindingPath = require.resolve(`./build/${common.buildType}/binding`); -process.dlopen(module, bindingPath, - os.constants.dlopen.RTLD_NOW | os.constants.dlopen.RTLD_GLOBAL); +process.dlopen( + module, + bindingPath, + os.constants.dlopen.RTLD_NOW | os.constants.dlopen.RTLD_GLOBAL +); module.exports.load(`${path.dirname(bindingPath)}/ping.so`); assert.strictEqual(module.exports.ping(), 'pong'); diff --git a/test/addons/hello-world-esm/test.js b/test/addons/hello-world-esm/test.js index d0faf655400f13..c1c35d98220115 100644 --- a/test/addons/hello-world-esm/test.js +++ b/test/addons/hello-world-esm/test.js @@ -8,11 +8,15 @@ const { join } = require('path'); const buildDir = join(__dirname, 'build'); -copyFileSync(join(buildDir, common.buildType, 'binding.node'), - join(buildDir, 'binding.node')); +copyFileSync( + join(buildDir, common.buildType, 'binding.node'), + join(buildDir, 'binding.node') +); -const result = spawnSync(process.execPath, - ['--experimental-modules', `${__dirname}/test.mjs`]); +const result = spawnSync(process.execPath, [ + '--experimental-modules', + `${__dirname}/test.mjs` +]); assert.ifError(result.error); // TODO: Uncomment this once ESM is no longer experimental. diff --git a/test/addons/load-long-path/test.js b/test/addons/load-long-path/test.js index 7d1a37bd96055e..23a8edcb068351 100644 --- a/test/addons/load-long-path/test.js +++ b/test/addons/load-long-path/test.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../../common'); -if (common.isWindows && (process.env.PROCESSOR_ARCHITEW6432 !== undefined)) - common.skip('doesn\'t work on WOW64'); +if (common.isWindows && process.env.PROCESSOR_ARCHITEW6432 !== undefined) + common.skip("doesn't work on WOW64"); const fs = require('fs'); const path = require('path'); @@ -20,10 +20,12 @@ for (let i = 0; i < 10; i++) { fs.mkdirSync(addonDestinationDir); } -const addonPath = path.join(__dirname, - 'build', - common.buildType, - 'binding.node'); +const addonPath = path.join( + __dirname, + 'build', + common.buildType, + 'binding.node' +); const addonDestinationPath = path.join(addonDestinationDir, 'binding.node'); // Copy binary to long path destination diff --git a/test/addons/make-callback-domain-warning/test.js b/test/addons/make-callback-domain-warning/test.js index 2ea3c3f3d14b2b..9375d20ad4289e 100644 --- a/test/addons/make-callback-domain-warning/test.js +++ b/test/addons/make-callback-domain-warning/test.js @@ -17,19 +17,30 @@ process.on('warning', function(warning) { const d = domain.create(); // When domain is disabled, no warning will be emitted -makeCallback({ domain: d }, common.mustCall(function() { - assert.strictEqual(latestWarning, null); +makeCallback( + { domain: d }, + common.mustCall(function() { + assert.strictEqual(latestWarning, null); - d.run(common.mustCall(function() { - // No warning will be emitted when no domain property is applied - makeCallback({}, common.mustCall(function() { - assert.strictEqual(latestWarning, null); + d.run( + common.mustCall(function() { + // No warning will be emitted when no domain property is applied + makeCallback( + {}, + common.mustCall(function() { + assert.strictEqual(latestWarning, null); - // Warning is emitted when domain property is used and domain is enabled - makeCallback({ domain: d }, common.mustCall(function() { - assert.strictEqual(latestWarning.name, 'DeprecationWarning'); - assert.strictEqual(latestWarning.code, 'DEP0097'); - })); - })); - })); -})); + // Warning is emitted when domain property is used and domain is enabled + makeCallback( + { domain: d }, + common.mustCall(function() { + assert.strictEqual(latestWarning.name, 'DeprecationWarning'); + assert.strictEqual(latestWarning.code, 'DEP0097'); + }) + ); + }) + ); + }) + ); + }) +); diff --git a/test/addons/make-callback-recurse/test.js b/test/addons/make-callback-recurse/test.js index 102890cc964d2a..4ca490390b89bb 100644 --- a/test/addons/make-callback-recurse/test.js +++ b/test/addons/make-callback-recurse/test.js @@ -16,7 +16,6 @@ assert.throws(function() { }); }, /^Error: hi from domain error$/); - // Check the execution order of the nextTickQueue and MicrotaskQueue in // relation to running multiple MakeCallback's from bootstrap, // node::MakeCallback() and node::AsyncWrap::MakeCallback(). @@ -27,116 +26,164 @@ assert.throws(function() { // Processing of the MicrotaskQueue is manually handled by node. They are not // processed until after the nextTickQueue has been processed. - Promise.resolve(1).then(common.mustCall(function() { - results.push(7); - })); + Promise.resolve(1).then( + common.mustCall(function() { + results.push(7); + }) + ); // The nextTick should run after all immediately invoked calls. - process.nextTick(common.mustCall(function() { - results.push(3); - - // Run same test again but while processing the nextTickQueue to make sure - // the following MakeCallback call breaks in the middle of processing the - // queue and allows the script to run normally. - process.nextTick(common.mustCall(function() { - results.push(6); - })); - - makeCallback({}, common.mustCall(function() { - results.push(4); - })); - - results.push(5); - })); + process.nextTick( + common.mustCall(function() { + results.push(3); + + // Run same test again but while processing the nextTickQueue to make sure + // the following MakeCallback call breaks in the middle of processing the + // queue and allows the script to run normally. + process.nextTick( + common.mustCall(function() { + results.push(6); + }) + ); + + makeCallback( + {}, + common.mustCall(function() { + results.push(4); + }) + ); + + results.push(5); + }) + ); results.push(0); // MakeCallback is calling the function immediately, but should then detect // that a script is already in the middle of execution and return before // either the nextTickQueue or MicrotaskQueue are processed. - makeCallback({}, common.mustCall(function() { - results.push(1); - })); + makeCallback( + {}, + common.mustCall(function() { + results.push(1); + }) + ); // This should run before either the nextTickQueue or MicrotaskQueue are // processed. Previously MakeCallback would not detect this circumstance // and process them immediately. results.push(2); - setImmediate(common.mustCall(function() { - for (let i = 0; i < results.length; i++) { - assert.strictEqual(results[i], i, - `verifyExecutionOrder(${arg}) results: ${results}`); - } - if (arg === 1) { - // The tests are first run on bootstrap during LoadEnvironment() in - // src/node.cc. Now run the tests through node::MakeCallback(). - setImmediate(function() { - makeCallback({}, common.mustCall(function() { - verifyExecutionOrder(2); - })); - }); - } else if (arg === 2) { - // Make sure there are no conflicts using node::MakeCallback() - // within timers. - setTimeout(common.mustCall(function() { - verifyExecutionOrder(3); - }), 10); - } else if (arg === 3) { - mustCallCheckDomains(); - } else { - throw new Error('UNREACHABLE'); - } - })); -}(1)); - + setImmediate( + common.mustCall(function() { + for (let i = 0; i < results.length; i++) { + assert.strictEqual( + results[i], + i, + `verifyExecutionOrder(${arg}) results: ${results}` + ); + } + if (arg === 1) { + // The tests are first run on bootstrap during LoadEnvironment() in + // src/node.cc. Now run the tests through node::MakeCallback(). + setImmediate(function() { + makeCallback( + {}, + common.mustCall(function() { + verifyExecutionOrder(2); + }) + ); + }); + } else if (arg === 2) { + // Make sure there are no conflicts using node::MakeCallback() + // within timers. + setTimeout( + common.mustCall(function() { + verifyExecutionOrder(3); + }), + 10 + ); + } else if (arg === 3) { + mustCallCheckDomains(); + } else { + throw new Error('UNREACHABLE'); + } + }) + ); +})(1); function checkDomains() { // Check that domains are properly entered/exited when called in multiple // levels from both node::MakeCallback() and AsyncWrap::MakeCallback - setImmediate(common.mustCall(function() { - const d1 = domain.create(); - const d2 = domain.create(); - const d3 = domain.create(); - - makeCallback({ domain: d1 }, common.mustCall(function() { - assert.strictEqual(d1, process.domain); - makeCallback({ domain: d2 }, common.mustCall(function() { - assert.strictEqual(d2, process.domain); - makeCallback({ domain: d3 }, common.mustCall(function() { - assert.strictEqual(d3, process.domain); - })); - assert.strictEqual(d2, process.domain); - })); - assert.strictEqual(d1, process.domain); - })); - })); - - setTimeout(common.mustCall(function() { - const d1 = domain.create(); - const d2 = domain.create(); - const d3 = domain.create(); - - makeCallback({ domain: d1 }, common.mustCall(function() { - assert.strictEqual(d1, process.domain); - makeCallback({ domain: d2 }, common.mustCall(function() { - assert.strictEqual(d2, process.domain); - makeCallback({ domain: d3 }, common.mustCall(function() { - assert.strictEqual(d3, process.domain); - })); - assert.strictEqual(d2, process.domain); - })); - assert.strictEqual(d1, process.domain); - })); - }), 1); + setImmediate( + common.mustCall(function() { + const d1 = domain.create(); + const d2 = domain.create(); + const d3 = domain.create(); + + makeCallback( + { domain: d1 }, + common.mustCall(function() { + assert.strictEqual(d1, process.domain); + makeCallback( + { domain: d2 }, + common.mustCall(function() { + assert.strictEqual(d2, process.domain); + makeCallback( + { domain: d3 }, + common.mustCall(function() { + assert.strictEqual(d3, process.domain); + }) + ); + assert.strictEqual(d2, process.domain); + }) + ); + assert.strictEqual(d1, process.domain); + }) + ); + }) + ); + + setTimeout( + common.mustCall(function() { + const d1 = domain.create(); + const d2 = domain.create(); + const d3 = domain.create(); + + makeCallback( + { domain: d1 }, + common.mustCall(function() { + assert.strictEqual(d1, process.domain); + makeCallback( + { domain: d2 }, + common.mustCall(function() { + assert.strictEqual(d2, process.domain); + makeCallback( + { domain: d3 }, + common.mustCall(function() { + assert.strictEqual(d3, process.domain); + }) + ); + assert.strictEqual(d2, process.domain); + }) + ); + assert.strictEqual(d1, process.domain); + }) + ); + }), + 1 + ); function testTimer(id) { // Make sure nextTick, setImmediate and setTimeout can all recover properly // after a thrown makeCallback call. const d = domain.create(); - d.on('error', common.mustCall(function(e) { - assert.strictEqual(e.message, `throw from domain ${id}`); - })); + d.on( + 'error', + common.mustCall(function(e) { + assert.strictEqual(e.message, `throw from domain ${id}`); + }) + ); makeCallback({ domain: d }, function() { throw new Error(`throw from domain ${id}`); }); diff --git a/test/addons/make-callback/test.js b/test/addons/make-callback/test.js index c5a71b5ab7a3e0..85f0e47793e5a1 100644 --- a/test/addons/make-callback/test.js +++ b/test/addons/make-callback/test.js @@ -6,18 +6,31 @@ const vm = require('vm'); const binding = require(`./build/${common.buildType}/binding`); const makeCallback = binding.makeCallback; -assert.strictEqual(makeCallback(process, common.mustCall(function() { - assert.strictEqual(arguments.length, 0); - assert.strictEqual(process, this); - return 42; -})), 42); +assert.strictEqual( + makeCallback( + process, + common.mustCall(function() { + assert.strictEqual(arguments.length, 0); + assert.strictEqual(process, this); + return 42; + }) + ), + 42 +); -assert.strictEqual(makeCallback(process, common.mustCall(function(x) { - assert.strictEqual(arguments.length, 1); - assert.strictEqual(process, this); - assert.strictEqual(x, 1337); - return 42; -}), 1337), 42); +assert.strictEqual( + makeCallback( + process, + common.mustCall(function(x) { + assert.strictEqual(arguments.length, 1); + assert.strictEqual(process, this); + assert.strictEqual(x, 1337); + return 42; + }), + 1337 + ), + 42 +); const recv = { one: common.mustCall(function() { @@ -30,7 +43,7 @@ const recv = { assert.strictEqual(recv, this); assert.strictEqual(x, 1337); return 42; - }), + }) }; assert.strictEqual(makeCallback(recv, 'one'), 42); @@ -58,8 +71,7 @@ const forward = vm.runInNewContext(` `); // Runs in outer context. function endpoint($Object) { - if (Object === $Object) - throw new Error('bad'); + if (Object === $Object) throw new Error('bad'); return Object; } assert.strictEqual(makeCallback(process, forward, endpoint), Object); diff --git a/test/addons/node-module-version/test.js b/test/addons/node-module-version/test.js index 002e38134d76b6..00c19b4aa8ff47 100644 --- a/test/addons/node-module-version/test.js +++ b/test/addons/node-module-version/test.js @@ -4,11 +4,12 @@ const common = require('../../common'); const assert = require('assert'); const re = new RegExp( - '^Error: The module \'.+\'\n' + - 'was compiled against a different Node\\.js version using\n' + - 'NODE_MODULE_VERSION 42\\. This version of Node\\.js requires\n' + - `NODE_MODULE_VERSION ${process.versions.modules}\\. ` + - 'Please try re-compiling or re-installing\n' + - 'the module \\(for instance, using `npm rebuild` or `npm install`\\)\\.$'); + "^Error: The module '.+'\n" + + 'was compiled against a different Node\\.js version using\n' + + 'NODE_MODULE_VERSION 42\\. This version of Node\\.js requires\n' + + `NODE_MODULE_VERSION ${process.versions.modules}\\. ` + + 'Please try re-compiling or re-installing\n' + + 'the module \\(for instance, using `npm rebuild` or `npm install`\\)\\.$' +); assert.throws(() => require(`./build/${common.buildType}/binding`), re); diff --git a/test/addons/non-node-context/test-make-buffer.js b/test/addons/non-node-context/test-make-buffer.js index 9b17fa4ee930ae..a373537bae86b7 100644 --- a/test/addons/non-node-context/test-make-buffer.js +++ b/test/addons/non-node-context/test-make-buffer.js @@ -2,9 +2,9 @@ const common = require('../../common'); const assert = require('assert'); -const { - makeBufferInNewContext -} = require(`./build/${common.buildType}/binding`); +const { makeBufferInNewContext } = require(`./build/${ + common.buildType +}/binding`); // Because the `Buffer` function and its protoype property only (currently) // exist in a Node.js instance’s main context, trying to create buffers from @@ -17,6 +17,8 @@ try { assert(!(exception.constructor instanceof Error)); assert.strictEqual(exception.code, 'ERR_BUFFER_CONTEXT_NOT_AVAILABLE'); - assert.strictEqual(exception.message, - 'Buffer is not available for the current Context'); + assert.strictEqual( + exception.message, + 'Buffer is not available for the current Context' + ); } diff --git a/test/addons/non-node-context/test-perf-hooks-timerify.js b/test/addons/non-node-context/test-perf-hooks-timerify.js index 10a9ab8064227e..edf9470d078e12 100644 --- a/test/addons/non-node-context/test-perf-hooks-timerify.js +++ b/test/addons/non-node-context/test-perf-hooks-timerify.js @@ -8,10 +8,13 @@ const { performance } = require('perf_hooks'); // Check that performance.timerify() works when called from another context, // for a function created in another context. -const check = runInNewContext(` +const check = runInNewContext( + ` const { performance, assert } = data; const timerified = performance.timerify(function() { return []; }); assert.strictEqual(timerified().constructor, Array); 'success'; -`, { performance, assert }); +`, + { performance, assert } +); assert.strictEqual(check, 'success'); diff --git a/test/addons/openssl-binding/test.js b/test/addons/openssl-binding/test.js index 1e6c57ffd1e081..b88a36063429c9 100644 --- a/test/addons/openssl-binding/test.js +++ b/test/addons/openssl-binding/test.js @@ -1,8 +1,7 @@ 'use strict'; const common = require('../../common'); -if (!common.hasCrypto) - common.skip('missing crypto'); +if (!common.hasCrypto) common.skip('missing crypto'); const assert = require('assert'); const binding = require(`./build/${common.buildType}/binding`); diff --git a/test/addons/openssl-client-cert-engine/test.js b/test/addons/openssl-client-cert-engine/test.js index 1c0e4564a5c3e9..414eb3b8b3f430 100644 --- a/test/addons/openssl-client-cert-engine/test.js +++ b/test/addons/openssl-client-cert-engine/test.js @@ -2,17 +2,17 @@ const common = require('../../common'); const fixture = require('../../common/fixtures'); -if (!common.hasCrypto) - common.skip('missing crypto'); +if (!common.hasCrypto) common.skip('missing crypto'); const fs = require('fs'); const path = require('path'); -const engine = path.join(__dirname, - `/build/${common.buildType}/testengine.engine`); +const engine = path.join( + __dirname, + `/build/${common.buildType}/testengine.engine` +); -if (!fs.existsSync(engine)) - common.skip('no client cert engine'); +if (!fs.existsSync(engine)) common.skip('no client cert engine'); const assert = require('assert'); const https = require('https'); @@ -29,32 +29,40 @@ const serverOptions = { rejectUnauthorized: true }; -const server = https.createServer(serverOptions, (req, res) => { - res.writeHead(200); - res.end('hello world'); -}).listen(0, common.localhostIPv4, () => { - const clientOptions = { - method: 'GET', - host: common.localhostIPv4, - port: server.address().port, - path: '/test', - clientCertEngine: engine, // engine will provide key+cert - rejectUnauthorized: false, // prevent failing on self-signed certificates - headers: {} - }; - - const req = https.request(clientOptions, common.mustCall(function(response) { - let body = ''; - response.setEncoding('utf8'); - response.on('data', function(chunk) { - body += chunk; - }); - - response.on('end', common.mustCall(function() { - assert.strictEqual(body, 'hello world'); - server.close(); - })); - })); - - req.end(); -}); +const server = https + .createServer(serverOptions, (req, res) => { + res.writeHead(200); + res.end('hello world'); + }) + .listen(0, common.localhostIPv4, () => { + const clientOptions = { + method: 'GET', + host: common.localhostIPv4, + port: server.address().port, + path: '/test', + clientCertEngine: engine, // engine will provide key+cert + rejectUnauthorized: false, // prevent failing on self-signed certificates + headers: {} + }; + + const req = https.request( + clientOptions, + common.mustCall(function(response) { + let body = ''; + response.setEncoding('utf8'); + response.on('data', function(chunk) { + body += chunk; + }); + + response.on( + 'end', + common.mustCall(function() { + assert.strictEqual(body, 'hello world'); + server.close(); + }) + ); + }) + ); + + req.end(); + }); diff --git a/test/addons/repl-domain-abort/test.js b/test/addons/repl-domain-abort/test.js index 2049fe6e6a23f5..ba738b9e274d38 100644 --- a/test/addons/repl-domain-abort/test.js +++ b/test/addons/repl-domain-abort/test.js @@ -27,8 +27,7 @@ const stream = require('stream'); const path = require('path'); let buildPath = path.join(__dirname, 'build', common.buildType, 'binding'); // On Windows, escape backslashes in the path before passing it to REPL. -if (common.isWindows) - buildPath = buildPath.replace(/\\/g, '/'); +if (common.isWindows) buildPath = buildPath.replace(/\\/g, '/'); let cb_ran = false; process.on('exit', function() { @@ -39,9 +38,9 @@ process.on('exit', function() { const lines = [ // This line shouldn't cause an assertion error. `require('${buildPath}')` + - // Log output to double check callback ran. - '.method(function(v1, v2) {' + - 'console.log(\'cb_ran\'); return v1 === true && v2 === false; });', + // Log output to double check callback ran. + '.method(function(v1, v2) {' + + "console.log('cb_ran'); return v1 === true && v2 === false; });" ]; const dInput = new stream.Readable(); @@ -49,13 +48,11 @@ const dOutput = new stream.Writable(); dInput._read = function _read() { while (lines.length > 0 && this.push(lines.shift())); - if (lines.length === 0) - this.push(null); + if (lines.length === 0) this.push(null); }; dOutput._write = function _write(chunk, encoding, cb) { - if (chunk.toString().startsWith('cb_ran')) - cb_ran = true; + if (chunk.toString().startsWith('cb_ran')) cb_ran = true; cb(); }; diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-at-max.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-at-max.js index 820f71ec9e7a01..7caf36551dd252 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-at-max.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-at-max.js @@ -4,8 +4,7 @@ const common = require('../../common'); const { internalBinding } = require('internal/test/binding'); const skipMessage = 'intensive toString tests due to memory confinements'; -if (!common.enoughTestMem) - common.skip(skipMessage); +if (!common.enoughTestMem) common.skip(skipMessage); const binding = require(`./build/${common.buildType}/binding`); const assert = require('assert'); @@ -19,13 +18,12 @@ try { buf = Buffer.allocUnsafe(kStringMaxLength); } catch (e) { // If the exception is not due to memory confinement then rethrow it. - if (e.message !== 'Array buffer allocation failed') throw (e); + if (e.message !== 'Array buffer allocation failed') throw e; common.skip(skipMessage); } // Ensure we have enough memory available for future allocations to succeed. -if (!binding.ensureAllocation(2 * kStringMaxLength)) - common.skip(skipMessage); +if (!binding.ensureAllocation(2 * kStringMaxLength)) common.skip(skipMessage); const maxString = buf.toString('latin1'); assert.strictEqual(maxString.length, kStringMaxLength); diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-ascii.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-ascii.js index 7f5a8347956e43..8f748b4d07a87e 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-ascii.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-ascii.js @@ -4,8 +4,7 @@ const common = require('../../common'); const { internalBinding } = require('internal/test/binding'); const skipMessage = 'intensive toString tests due to memory confinements'; -if (!common.enoughTestMem) - common.skip(skipMessage); +if (!common.enoughTestMem) common.skip(skipMessage); const binding = require(`./build/${common.buildType}/binding`); @@ -18,20 +17,22 @@ try { buf = Buffer.allocUnsafe(kStringMaxLength + 1); } catch (e) { // If the exception is not due to memory confinement then rethrow it. - if (e.message !== 'Array buffer allocation failed') throw (e); + if (e.message !== 'Array buffer allocation failed') throw e; common.skip(skipMessage); } // Ensure we have enough memory available for future allocations to succeed. -if (!binding.ensureAllocation(2 * kStringMaxLength)) - common.skip(skipMessage); +if (!binding.ensureAllocation(2 * kStringMaxLength)) common.skip(skipMessage); const stringLengthHex = kStringMaxLength.toString(16); -common.expectsError(function() { - buf.toString('ascii'); -}, { - message: `Cannot create a string longer than 0x${stringLengthHex} ` + - 'characters', - code: 'ERR_STRING_TOO_LONG', - type: Error -}); +common.expectsError( + function() { + buf.toString('ascii'); + }, + { + message: + `Cannot create a string longer than 0x${stringLengthHex} ` + 'characters', + code: 'ERR_STRING_TOO_LONG', + type: Error + } +); diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-base64.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-base64.js index d7fe26814f7b24..4e7f93de6a41be 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-base64.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-base64.js @@ -4,8 +4,7 @@ const common = require('../../common'); const { internalBinding } = require('internal/test/binding'); const skipMessage = 'intensive toString tests due to memory confinements'; -if (!common.enoughTestMem) - common.skip(skipMessage); +if (!common.enoughTestMem) common.skip(skipMessage); const binding = require(`./build/${common.buildType}/binding`); @@ -18,20 +17,22 @@ try { buf = Buffer.allocUnsafe(kStringMaxLength + 1); } catch (e) { // If the exception is not due to memory confinement then rethrow it. - if (e.message !== 'Array buffer allocation failed') throw (e); + if (e.message !== 'Array buffer allocation failed') throw e; common.skip(skipMessage); } // Ensure we have enough memory available for future allocations to succeed. -if (!binding.ensureAllocation(2 * kStringMaxLength)) - common.skip(skipMessage); +if (!binding.ensureAllocation(2 * kStringMaxLength)) common.skip(skipMessage); const stringLengthHex = kStringMaxLength.toString(16); -common.expectsError(function() { - buf.toString('base64'); -}, { - message: `Cannot create a string longer than 0x${stringLengthHex} ` + - 'characters', - code: 'ERR_STRING_TOO_LONG', - type: Error -}); +common.expectsError( + function() { + buf.toString('base64'); + }, + { + message: + `Cannot create a string longer than 0x${stringLengthHex} ` + 'characters', + code: 'ERR_STRING_TOO_LONG', + type: Error + } +); diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-binary.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-binary.js index 7e75ba1246662c..b8a22e47e4ca72 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-binary.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-binary.js @@ -4,8 +4,7 @@ const common = require('../../common'); const { internalBinding } = require('internal/test/binding'); const skipMessage = 'intensive toString tests due to memory confinements'; -if (!common.enoughTestMem) - common.skip(skipMessage); +if (!common.enoughTestMem) common.skip(skipMessage); const binding = require(`./build/${common.buildType}/binding`); const assert = require('assert'); @@ -19,23 +18,25 @@ try { buf = Buffer.allocUnsafe(kStringMaxLength + 1); } catch (e) { // If the exception is not due to memory confinement then rethrow it. - if (e.message !== 'Array buffer allocation failed') throw (e); + if (e.message !== 'Array buffer allocation failed') throw e; common.skip(skipMessage); } // Ensure we have enough memory available for future allocations to succeed. -if (!binding.ensureAllocation(2 * kStringMaxLength)) - common.skip(skipMessage); +if (!binding.ensureAllocation(2 * kStringMaxLength)) common.skip(skipMessage); const stringLengthHex = kStringMaxLength.toString(16); -common.expectsError(function() { - buf.toString('latin1'); -}, { - message: `Cannot create a string longer than 0x${stringLengthHex} ` + - 'characters', - code: 'ERR_STRING_TOO_LONG', - type: Error -}); +common.expectsError( + function() { + buf.toString('latin1'); + }, + { + message: + `Cannot create a string longer than 0x${stringLengthHex} ` + 'characters', + code: 'ERR_STRING_TOO_LONG', + type: Error + } +); // FIXME: Free the memory early to avoid OOM. // REF: https://github.com/nodejs/reliability/issues/12#issuecomment-412619655 diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-hex.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-hex.js index 57242399bb02b9..5705a7b65391f7 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-hex.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-hex.js @@ -4,8 +4,7 @@ const common = require('../../common'); const { internalBinding } = require('internal/test/binding'); const skipMessage = 'intensive toString tests due to memory confinements'; -if (!common.enoughTestMem) - common.skip(skipMessage); +if (!common.enoughTestMem) common.skip(skipMessage); const binding = require(`./build/${common.buildType}/binding`); @@ -18,20 +17,22 @@ try { buf = Buffer.allocUnsafe(kStringMaxLength + 1); } catch (e) { // If the exception is not due to memory confinement then rethrow it. - if (e.message !== 'Array buffer allocation failed') throw (e); + if (e.message !== 'Array buffer allocation failed') throw e; common.skip(skipMessage); } // Ensure we have enough memory available for future allocations to succeed. -if (!binding.ensureAllocation(2 * kStringMaxLength)) - common.skip(skipMessage); +if (!binding.ensureAllocation(2 * kStringMaxLength)) common.skip(skipMessage); const stringLengthHex = kStringMaxLength.toString(16); -common.expectsError(function() { - buf.toString('hex'); -}, { - message: `Cannot create a string longer than 0x${stringLengthHex} ` + - 'characters', - code: 'ERR_STRING_TOO_LONG', - type: Error -}); +common.expectsError( + function() { + buf.toString('hex'); + }, + { + message: + `Cannot create a string longer than 0x${stringLengthHex} ` + 'characters', + code: 'ERR_STRING_TOO_LONG', + type: Error + } +); diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-utf8.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-utf8.js index 4a0908290c1926..1ee636b8a0aac4 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-utf8.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-utf8.js @@ -4,8 +4,7 @@ const common = require('../../common'); const { internalBinding } = require('internal/test/binding'); const skipMessage = 'intensive toString tests due to memory confinements'; -if (!common.enoughTestMem) - common.skip(skipMessage); +if (!common.enoughTestMem) common.skip(skipMessage); const binding = require(`./build/${common.buildType}/binding`); const assert = require('assert'); @@ -19,37 +18,43 @@ try { buf = Buffer.allocUnsafe(kStringMaxLength + 1); } catch (e) { // If the exception is not due to memory confinement then rethrow it. - if (e.message !== 'Array buffer allocation failed') throw (e); + if (e.message !== 'Array buffer allocation failed') throw e; common.skip(skipMessage); } // Ensure we have enough memory available for future allocations to succeed. -if (!binding.ensureAllocation(2 * kStringMaxLength)) - common.skip(skipMessage); +if (!binding.ensureAllocation(2 * kStringMaxLength)) common.skip(skipMessage); const stringLengthHex = kStringMaxLength.toString(16); -assert.throws(function() { - buf.toString(); -}, function(e) { - if (e.message !== 'Array buffer allocation failed') { - common.expectsError({ - message: `Cannot create a string longer than 0x${stringLengthHex} ` + - 'characters', - code: 'ERR_STRING_TOO_LONG', - type: Error - })(e); - return true; - } else { - return true; +assert.throws( + function() { + buf.toString(); + }, + function(e) { + if (e.message !== 'Array buffer allocation failed') { + common.expectsError({ + message: + `Cannot create a string longer than 0x${stringLengthHex} ` + + 'characters', + code: 'ERR_STRING_TOO_LONG', + type: Error + })(e); + return true; + } else { + return true; + } + } +); + +common.expectsError( + function() { + buf.toString('utf8'); + }, + { + message: + `Cannot create a string longer than 0x${stringLengthHex} ` + 'characters', + code: 'ERR_STRING_TOO_LONG', + type: Error } -}); - -common.expectsError(function() { - buf.toString('utf8'); -}, { - message: `Cannot create a string longer than 0x${stringLengthHex} ` + - 'characters', - code: 'ERR_STRING_TOO_LONG', - type: Error -}); +); diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-2.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-2.js index 3c613a69fd3fcd..af18df46999359 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-2.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-2.js @@ -4,8 +4,7 @@ const common = require('../../common'); const { internalBinding } = require('internal/test/binding'); const skipMessage = 'intensive toString tests due to memory confinements'; -if (!common.enoughTestMem) - common.skip(skipMessage); +if (!common.enoughTestMem) common.skip(skipMessage); const binding = require(`./build/${common.buildType}/binding`); const assert = require('assert'); @@ -19,13 +18,12 @@ try { buf = Buffer.allocUnsafe(kStringMaxLength + 2); } catch (e) { // If the exception is not due to memory confinement then rethrow it. - if (e.message !== 'Array buffer allocation failed') throw (e); + if (e.message !== 'Array buffer allocation failed') throw e; common.skip(skipMessage); } // Ensure we have enough memory available for future allocations to succeed. -if (!binding.ensureAllocation(2 * kStringMaxLength)) - common.skip(skipMessage); +if (!binding.ensureAllocation(2 * kStringMaxLength)) common.skip(skipMessage); const maxString = buf.toString('utf16le'); assert.strictEqual(maxString.length, Math.floor((kStringMaxLength + 2) / 2)); diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max.js index be571c5059ef8f..c77e5fd41d7137 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max.js @@ -4,8 +4,7 @@ const common = require('../../common'); const { internalBinding } = require('internal/test/binding'); const skipMessage = 'intensive toString tests due to memory confinements'; -if (!common.enoughTestMem) - common.skip(skipMessage); +if (!common.enoughTestMem) common.skip(skipMessage); const binding = require(`./build/${common.buildType}/binding`); @@ -18,21 +17,23 @@ try { buf = Buffer.allocUnsafe(kStringMaxLength * 2 + 2); } catch (e) { // If the exception is not due to memory confinement then rethrow it. - if (e.message !== 'Array buffer allocation failed') throw (e); + if (e.message !== 'Array buffer allocation failed') throw e; common.skip(skipMessage); } // Ensure we have enough memory available for future allocations to succeed. -if (!binding.ensureAllocation(2 * kStringMaxLength)) - common.skip(skipMessage); +if (!binding.ensureAllocation(2 * kStringMaxLength)) common.skip(skipMessage); const stringLengthHex = kStringMaxLength.toString(16); -common.expectsError(function() { - buf.toString('utf16le'); -}, { - message: `Cannot create a string longer than 0x${stringLengthHex} ` + - 'characters', - code: 'ERR_STRING_TOO_LONG', - type: Error -}); +common.expectsError( + function() { + buf.toString('utf16le'); + }, + { + message: + `Cannot create a string longer than 0x${stringLengthHex} ` + 'characters', + code: 'ERR_STRING_TOO_LONG', + type: Error + } +); diff --git a/test/async-hooks/hook-checks.js b/test/async-hooks/hook-checks.js index 44970378131c4a..378ba0527dc623 100644 --- a/test/async-hooks/hook-checks.js +++ b/test/async-hooks/hook-checks.js @@ -19,13 +19,14 @@ require('../common'); exports.checkInvocations = function checkInvocations(activity, hooks, stage) { const stageInfo = `Checking invocations at stage "${stage}":\n `; - assert.ok(activity != null, - `${stageInfo} Trying to check invocation for an activity, ` + - 'but it was empty/undefined.' + assert.ok( + activity != null, + `${stageInfo} Trying to check invocation for an activity, ` + + 'but it was empty/undefined.' ); // Check that actual invocations for all hooks match the expected invocations - [ 'init', 'before', 'after', 'destroy', 'promiseResolve' ].forEach(checkHook); + ['init', 'before', 'after', 'destroy', 'promiseResolve'].forEach(checkHook); function checkHook(k) { const val = hooks[k]; @@ -35,19 +36,22 @@ exports.checkInvocations = function checkInvocations(activity, hooks, stage) { if (val === 0) { // Didn't expect any invocations, but it was actually invoked const invocations = activity[k].length; - const msg = `${stageInfo} Called "${k}" ${invocations} time(s), ` + - 'but expected no invocations.'; + const msg = + `${stageInfo} Called "${k}" ${invocations} time(s), ` + + 'but expected no invocations.'; assert(activity[k] === null && activity[k] === undefined, msg); } else { // Expected some invocations, make sure that it was invoked at all - const msg1 = `${stageInfo} Never called "${k}", ` + - `but expected ${val} invocation(s).`; + const msg1 = + `${stageInfo} Never called "${k}", ` + + `but expected ${val} invocation(s).`; assert(activity[k] !== null && activity[k] !== undefined, msg1); // Now make sure that the expected count and // the actual invocation count match - const msg2 = `${stageInfo} Called "${k}" ${activity[k].length} ` + - `time(s), but expected ${val} invocation(s).`; + const msg2 = + `${stageInfo} Called "${k}" ${activity[k].length} ` + + `time(s), but expected ${val} invocation(s).`; assert.strictEqual(activity[k].length, val, msg2); } } diff --git a/test/async-hooks/init-hooks.js b/test/async-hooks/init-hooks.js index 817b2db0c781b4..78bdcf132cea92 100644 --- a/test/async-hooks/init-hooks.js +++ b/test/async-hooks/init-hooks.js @@ -19,16 +19,19 @@ if (typeof global.gc === 'function') { function noop() {} class ActivityCollector { - constructor(start, { - allowNoInit = false, - oninit, - onbefore, - onafter, - ondestroy, - onpromiseResolve, - logid = null, - logtype = null - } = {}) { + constructor( + start, + { + allowNoInit = false, + oninit, + onbefore, + onafter, + ondestroy, + onpromiseResolve, + logid = null, + logtype = null + } = {} + ) { this._start = start; this._allowNoInit = allowNoInit; this._activities = new Map(); @@ -40,8 +43,8 @@ class ActivityCollector { this.onbefore = typeof onbefore === 'function' ? onbefore : noop; this.onafter = typeof onafter === 'function' ? onafter : noop; this.ondestroy = typeof ondestroy === 'function' ? ondestroy : noop; - this.onpromiseResolve = typeof onpromiseResolve === 'function' ? - onpromiseResolve : noop; + this.onpromiseResolve = + typeof onpromiseResolve === 'function' ? onpromiseResolve : noop; // Create the hook with which we'll collect activity data this._asyncHook = async_hooks.createHook({ @@ -62,7 +65,7 @@ class ActivityCollector { } sanityCheck(types) { - if (types != null && !Array.isArray(types)) types = [ types ]; + if (types != null && !Array.isArray(types)) types = [types]; function activityString(a) { return util.inspect(a, false, 5, true); @@ -71,51 +74,67 @@ class ActivityCollector { const violations = []; let tempActivityString; - function v(msg) { violations.push(msg); } + function v(msg) { + violations.push(msg); + } for (const a of this._activities.values()) { tempActivityString = activityString(a); if (types != null && !types.includes(a.type)) continue; if (a.init && a.init.length > 1) { - v(`Activity inited twice\n${tempActivityString}` + - '\nExpected "init" to be called at most once'); + v( + `Activity inited twice\n${tempActivityString}` + + '\nExpected "init" to be called at most once' + ); } if (a.destroy && a.destroy.length > 1) { - v(`Activity destroyed twice\n${tempActivityString}` + - '\nExpected "destroy" to be called at most once'); + v( + `Activity destroyed twice\n${tempActivityString}` + + '\nExpected "destroy" to be called at most once' + ); } if (a.before && a.after) { if (a.before.length < a.after.length) { - v('Activity called "after" without calling "before"\n' + - `${tempActivityString}` + - '\nExpected no "after" call without a "before"'); + v( + 'Activity called "after" without calling "before"\n' + + `${tempActivityString}` + + '\nExpected no "after" call without a "before"' + ); } if (a.before.some((x, idx) => x > a.after[idx])) { - v('Activity had an instance where "after" ' + - 'was invoked before "before"\n' + - `${tempActivityString}` + - '\nExpected "after" to be called after "before"'); + v( + 'Activity had an instance where "after" ' + + 'was invoked before "before"\n' + + `${tempActivityString}` + + '\nExpected "after" to be called after "before"' + ); } } if (a.before && a.destroy) { if (a.before.some((x, idx) => x > a.destroy[idx])) { - v('Activity had an instance where "destroy" ' + - 'was invoked before "before"\n' + - `${tempActivityString}` + - '\nExpected "destroy" to be called after "before"'); + v( + 'Activity had an instance where "destroy" ' + + 'was invoked before "before"\n' + + `${tempActivityString}` + + '\nExpected "destroy" to be called after "before"' + ); } } if (a.after && a.destroy) { if (a.after.some((x, idx) => x > a.destroy[idx])) { - v('Activity had an instance where "destroy" ' + - 'was invoked before "after"\n' + - `${tempActivityString}` + - '\nExpected "destroy" to be called after "after"'); + v( + 'Activity had an instance where "destroy" ' + + 'was invoked before "after"\n' + + `${tempActivityString}` + + '\nExpected "destroy" to be called after "after"' + ); } } if (!a.handleIsObject) { - v(`No resource object\n${tempActivityString}` + - '\nExpected "init" to be called with a resource object'); + v( + `No resource object\n${tempActivityString}` + + '\nExpected "init" to be called with a resource object' + ); } } if (violations.length) { @@ -127,16 +146,17 @@ class ActivityCollector { inspect(opts = {}) { if (typeof opts === 'string') opts = { types: opts }; const { types = null, depth = 5, stage = null } = opts; - const activities = types == null ? - Array.from(this._activities.values()) : - this.activitiesOfTypes(types); + const activities = + types == null + ? Array.from(this._activities.values()) + : this.activitiesOfTypes(types); if (stage != null) console.log(`\n${stage}`); console.log(util.inspect(activities, false, depth, true)); } activitiesOfTypes(types) { - if (!Array.isArray(types)) types = [ types ]; + if (!Array.isArray(types)) types = [types]; return this.activities.filter((x) => types.includes(x.type)); } @@ -148,7 +168,7 @@ class ActivityCollector { if (h == null) return; if (h[hook] == null) h[hook] = []; const time = process.hrtime(this._start); - h[hook].push((time[0] * 1e9) + time[1]); + h[hook].push(time[0] * 1e9 + time[1]); } _getActivity(uid, hook) { @@ -166,8 +186,10 @@ class ActivityCollector { // callback, so we don't yield errors for these. return null; } else { - const err = new Error(`Found a handle whose ${hook}` + - ' hook was invoked but not its init hook'); + const err = new Error( + `Found a handle whose ${hook}` + + ' hook was invoked but not its init hook' + ); // Don't throw if we see invocations due to an assertion in a test // failing since we want to list the assertion failure instead if (/process\._fatalException/.test(err.stack)) return null; @@ -221,8 +243,10 @@ class ActivityCollector { } _maybeLog(uid, type, name) { - if (this._logid && - (type == null || this._logtype == null || this._logtype === type)) { + if ( + this._logid && + (type == null || this._logtype == null || this._logtype === type) + ) { print(`${this._logid}.${name}.uid-${uid}`); } } diff --git a/test/async-hooks/test-async-await.js b/test/async-hooks/test-async-await.js index 0103f63621e3ba..57c45906651e40 100644 --- a/test/async-hooks/test-async-await.js +++ b/test/async-hooks/test-async-await.js @@ -21,7 +21,7 @@ const hooks = initHooks({ oninit, onbefore, onafter, - ondestroy: null, // Intentionally not tested, since it will be removed soon + ondestroy: null, // Intentionally not tested, since it will be removed soon onpromiseResolve }); hooks.enable(); @@ -44,18 +44,24 @@ function onafter(asyncId) { return; } - assert.strictEqual(promisesExecutionState.get(asyncId), 'before', - 'after hook called for promise without prior call' + - 'to before hook'); - assert.strictEqual(promisesInitState.get(asyncId), 'resolved', - 'after hook called for promise without prior call' + - 'to resolve hook'); + assert.strictEqual( + promisesExecutionState.get(asyncId), + 'before', + 'after hook called for promise without prior call' + 'to before hook' + ); + assert.strictEqual( + promisesInitState.get(asyncId), + 'resolved', + 'after hook called for promise without prior call' + 'to resolve hook' + ); promisesExecutionState.set(asyncId, 'after'); } function onpromiseResolve(asyncId) { - assert(promisesInitState.has(asyncId), - 'resolve hook called for promise without prior call to init hook'); + assert( + promisesInitState.has(asyncId), + 'resolve hook called for promise without prior call to init hook' + ); promisesInitState.set(asyncId, 'resolved'); } @@ -76,13 +82,16 @@ function checkPromisesExecutionState() { } } -process.on('beforeExit', common.mustCall(() => { - hooks.disable(); - hooks.sanityCheck('PROMISE'); +process.on( + 'beforeExit', + common.mustCall(() => { + hooks.disable(); + hooks.sanityCheck('PROMISE'); - checkPromisesInitState(); - checkPromisesExecutionState(); -})); + checkPromisesInitState(); + checkPromisesExecutionState(); + }) +); async function asyncFunc() { await sleep(timeout); diff --git a/test/async-hooks/test-callback-error.js b/test/async-hooks/test-callback-error.js index 07ed274342fd06..ef3602c226d8a1 100644 --- a/test/async-hooks/test-callback-error.js +++ b/test/async-hooks/test-callback-error.js @@ -9,14 +9,18 @@ const arg = process.argv[2]; switch (arg) { case 'test_init_callback': initHooks({ - oninit: common.mustCall(() => { throw new Error(arg); }) + oninit: common.mustCall(() => { + throw new Error(arg); + }) }).enable(); new async_hooks.AsyncResource(`${arg}_type`); return; case 'test_callback': initHooks({ - onbefore: common.mustCall(() => { throw new Error(arg); }) + onbefore: common.mustCall(() => { + throw new Error(arg); + }) }).enable(); const resource = new async_hooks.AsyncResource(`${arg}_type`); resource.emitBefore(); @@ -24,7 +28,9 @@ switch (arg) { case 'test_callback_abort': initHooks({ - oninit: common.mustCall(() => { throw new Error(arg); }) + oninit: common.mustCall(() => { + throw new Error(arg); + }) }).enable(); new async_hooks.AsyncResource(`${arg}_type`); return; diff --git a/test/async-hooks/test-crypto-pbkdf2.js b/test/async-hooks/test-crypto-pbkdf2.js index 4788ce4a580656..e2cc6284a64d80 100644 --- a/test/async-hooks/test-crypto-pbkdf2.js +++ b/test/async-hooks/test-crypto-pbkdf2.js @@ -1,8 +1,7 @@ 'use strict'; const common = require('../common'); -if (!common.hasCrypto) - common.skip('missing crypto'); +if (!common.hasCrypto) common.skip('missing crypto'); if (!common.isMainThread) common.skip('Worker bootstrapping works differently -> different async IDs'); @@ -12,7 +11,6 @@ const initHooks = require('./init-hooks'); const { checkInvocations } = require('./hook-checks'); const crypto = require('crypto'); - const hooks = initHooks(); hooks.enable(); @@ -38,6 +36,9 @@ function onexit() { assert.strictEqual(a.type, 'PBKDF2REQUEST'); assert.strictEqual(typeof a.uid, 'number'); assert.strictEqual(a.triggerAsyncId, 1); - checkInvocations(a, { init: 1, before: 1, after: 1, destroy: 1 }, - 'when process exits'); + checkInvocations( + a, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'when process exits' + ); } diff --git a/test/async-hooks/test-crypto-randomBytes.js b/test/async-hooks/test-crypto-randomBytes.js index 88cd4643ab6638..fb293d4c0d7934 100644 --- a/test/async-hooks/test-crypto-randomBytes.js +++ b/test/async-hooks/test-crypto-randomBytes.js @@ -1,8 +1,7 @@ 'use strict'; const common = require('../common'); -if (!common.hasCrypto) - common.skip('missing crypto'); +if (!common.hasCrypto) common.skip('missing crypto'); if (!common.isMainThread) common.skip('Worker bootstrapping works differently -> different async IDs'); @@ -12,7 +11,6 @@ const initHooks = require('./init-hooks'); const { checkInvocations } = require('./hook-checks'); const crypto = require('crypto'); - const hooks = initHooks(); hooks.enable(); @@ -21,8 +19,11 @@ crypto.randomBytes(1, common.mustCall(onrandomBytes)); function onrandomBytes() { const as = hooks.activitiesOfTypes('RANDOMBYTESREQUEST'); const a = as[0]; - checkInvocations(a, { init: 1, before: 1 }, - 'while in onrandomBytes callback'); + checkInvocations( + a, + { init: 1, before: 1 }, + 'while in onrandomBytes callback' + ); tick(2); } @@ -39,6 +40,9 @@ function onexit() { assert.strictEqual(a.type, 'RANDOMBYTESREQUEST'); assert.strictEqual(typeof a.uid, 'number'); assert.strictEqual(a.triggerAsyncId, 1); - checkInvocations(a, { init: 1, before: 1, after: 1, destroy: 1 }, - 'when process exits'); + checkInvocations( + a, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'when process exits' + ); } diff --git a/test/async-hooks/test-disable-in-init.js b/test/async-hooks/test-disable-in-init.js index b7ab31e6d97dc2..fa17799a093aac 100644 --- a/test/async-hooks/test-disable-in-init.js +++ b/test/async-hooks/test-disable-in-init.js @@ -6,18 +6,22 @@ const fs = require('fs'); let nestedCall = false; -async_hooks.createHook({ - init: common.mustCall(function() { - nestedHook.disable(); - if (!nestedCall) { - nestedCall = true; - fs.access(__filename, common.mustCall()); - } - }, 2) -}).enable(); +async_hooks + .createHook({ + init: common.mustCall(function() { + nestedHook.disable(); + if (!nestedCall) { + nestedCall = true; + fs.access(__filename, common.mustCall()); + } + }, 2) + }) + .enable(); -const nestedHook = async_hooks.createHook({ - init: common.mustCall(2) -}).enable(); +const nestedHook = async_hooks + .createHook({ + init: common.mustCall(2) + }) + .enable(); fs.access(__filename, common.mustCall()); diff --git a/test/async-hooks/test-embedder.api.async-resource-no-type.js b/test/async-hooks/test-embedder.api.async-resource-no-type.js index 69b6667edb674c..7c6c4328199d37 100644 --- a/test/async-hooks/test-embedder.api.async-resource-no-type.js +++ b/test/async-hooks/test-embedder.api.async-resource-no-type.js @@ -23,12 +23,13 @@ if (process.argv[2] === 'child') { type: TypeError }); }); - } else { const args = process.argv.slice(1).concat('child'); - spawn(process.execPath, args) - .on('close', common.mustCall((code) => { + spawn(process.execPath, args).on( + 'close', + common.mustCall((code) => { // No error because the type was defaulted assert.strictEqual(code, 0); - })); + }) + ); } diff --git a/test/async-hooks/test-embedder.api.async-resource.after-on-destroyed.js b/test/async-hooks/test-embedder.api.async-resource.after-on-destroyed.js index 3cf0cc430f0fe0..d49897bacdf5f6 100644 --- a/test/async-hooks/test-embedder.api.async-resource.after-on-destroyed.js +++ b/test/async-hooks/test-embedder.api.async-resource.after-on-destroyed.js @@ -28,23 +28,32 @@ if (process.argv[2] === 'child') { console.log('heartbeat: still alive'); event2.emitAfter(); - } else { const args = process.argv.slice(1).concat('child'); let errData = Buffer.from(''); let outData = Buffer.from(''); const child = spawn(process.execPath, args); - child.stderr.on('data', (d) => { errData = Buffer.concat([ errData, d ]); }); - child.stdout.on('data', (d) => { outData = Buffer.concat([ outData, d ]); }); - - child.on('close', common.mustCall((code) => { - assert.strictEqual(code, 1); - assert.ok(heartbeatMsg.test(outData.toString()), - 'did not crash until we reached offending line of code ' + - `(found ${outData})`); - assert.ok(corruptedMsg.test(errData.toString()), - 'printed error contains corrupted message ' + - `(found ${errData})`); - })); + child.stderr.on('data', (d) => { + errData = Buffer.concat([errData, d]); + }); + child.stdout.on('data', (d) => { + outData = Buffer.concat([outData, d]); + }); + + child.on( + 'close', + common.mustCall((code) => { + assert.strictEqual(code, 1); + assert.ok( + heartbeatMsg.test(outData.toString()), + 'did not crash until we reached offending line of code ' + + `(found ${outData})` + ); + assert.ok( + corruptedMsg.test(errData.toString()), + 'printed error contains corrupted message ' + `(found ${errData})` + ); + }) + ); } diff --git a/test/async-hooks/test-embedder.api.async-resource.before-on-destroyed.js b/test/async-hooks/test-embedder.api.async-resource.before-on-destroyed.js index 6463c438ed9102..5d8bbcd766bb05 100644 --- a/test/async-hooks/test-embedder.api.async-resource.before-on-destroyed.js +++ b/test/async-hooks/test-embedder.api.async-resource.before-on-destroyed.js @@ -28,23 +28,32 @@ if (process.argv[2] === 'child') { console.log('heartbeat: still alive'); event2.emitBefore(); - } else { const args = process.argv.slice(1).concat('child'); let errData = Buffer.from(''); let outData = Buffer.from(''); const child = spawn(process.execPath, args); - child.stderr.on('data', (d) => { errData = Buffer.concat([ errData, d ]); }); - child.stdout.on('data', (d) => { outData = Buffer.concat([ outData, d ]); }); - - child.on('close', common.mustCall((code) => { - assert.strictEqual(code, 1); - assert.ok(heartbeatMsg.test(outData.toString()), - 'did not crash until we reached offending line of code ' + - `(found ${outData})`); - assert.ok(corruptedMsg.test(errData.toString()), - 'printed error contains corrupted message ' + - `(found ${errData})`); - })); + child.stderr.on('data', (d) => { + errData = Buffer.concat([errData, d]); + }); + child.stdout.on('data', (d) => { + outData = Buffer.concat([outData, d]); + }); + + child.on( + 'close', + common.mustCall((code) => { + assert.strictEqual(code, 1); + assert.ok( + heartbeatMsg.test(outData.toString()), + 'did not crash until we reached offending line of code ' + + `(found ${outData})` + ); + assert.ok( + corruptedMsg.test(errData.toString()), + 'printed error contains corrupted message ' + `(found ${errData})` + ); + }) + ); } diff --git a/test/async-hooks/test-embedder.api.async-resource.improper-order.js b/test/async-hooks/test-embedder.api.async-resource.improper-order.js index 048ae0841357ec..dbd1a879f12fd3 100644 --- a/test/async-hooks/test-embedder.api.async-resource.improper-order.js +++ b/test/async-hooks/test-embedder.api.async-resource.improper-order.js @@ -33,16 +33,26 @@ if (process.argv[2] === 'child') { let outData = Buffer.from(''); const child = spawn(process.execPath, args); - child.stderr.on('data', (d) => { errData = Buffer.concat([ errData, d ]); }); - child.stdout.on('data', (d) => { outData = Buffer.concat([ outData, d ]); }); - - child.on('close', common.mustCall((code) => { - assert.strictEqual(code, 1); - assert.ok(heartbeatMsg.test(outData.toString()), - 'did not crash until we reached offending line of code ' + - `(found ${outData})`); - assert.ok(corruptedMsg.test(errData.toString()), - 'printed error contains corrupted message ' + - `(found ${errData})`); - })); + child.stderr.on('data', (d) => { + errData = Buffer.concat([errData, d]); + }); + child.stdout.on('data', (d) => { + outData = Buffer.concat([outData, d]); + }); + + child.on( + 'close', + common.mustCall((code) => { + assert.strictEqual(code, 1); + assert.ok( + heartbeatMsg.test(outData.toString()), + 'did not crash until we reached offending line of code ' + + `(found ${outData})` + ); + assert.ok( + corruptedMsg.test(errData.toString()), + 'printed error contains corrupted message ' + `(found ${errData})` + ); + }) + ); } diff --git a/test/async-hooks/test-embedder.api.async-resource.improper-unwind.js b/test/async-hooks/test-embedder.api.async-resource.improper-unwind.js index cb9e338905c386..c67260c7ba1694 100644 --- a/test/async-hooks/test-embedder.api.async-resource.improper-unwind.js +++ b/test/async-hooks/test-embedder.api.async-resource.improper-unwind.js @@ -42,16 +42,26 @@ if (process.argv[2] === 'child') { let outData = Buffer.from(''); const child = spawn(process.execPath, args); - child.stderr.on('data', (d) => { errData = Buffer.concat([ errData, d ]); }); - child.stdout.on('data', (d) => { outData = Buffer.concat([ outData, d ]); }); - - child.on('close', common.mustCall((code) => { - assert.strictEqual(code, 1); - assert.ok(heartbeatMsg.test(outData.toString()), - 'did not crash until we reached offending line of code ' + - `(found ${outData})`); - assert.ok(corruptedMsg.test(errData.toString()), - 'printed error contains corrupted message ' + - `(found ${errData})`); - })); + child.stderr.on('data', (d) => { + errData = Buffer.concat([errData, d]); + }); + child.stdout.on('data', (d) => { + outData = Buffer.concat([outData, d]); + }); + + child.on( + 'close', + common.mustCall((code) => { + assert.strictEqual(code, 1); + assert.ok( + heartbeatMsg.test(outData.toString()), + 'did not crash until we reached offending line of code ' + + `(found ${outData})` + ); + assert.ok( + corruptedMsg.test(errData.toString()), + 'printed error contains corrupted message ' + `(found ${errData})` + ); + }) + ); } diff --git a/test/async-hooks/test-embedder.api.async-resource.js b/test/async-hooks/test-embedder.api.async-resource.js index 6f71a3e98cbf0f..6bdc6f2ddb7558 100644 --- a/test/async-hooks/test-embedder.api.async-resource.js +++ b/test/async-hooks/test-embedder.api.async-resource.js @@ -12,17 +12,19 @@ const { checkInvocations } = require('./hook-checks'); const hooks = initHooks(); hooks.enable(); -common.expectsError( - () => new AsyncResource(), { - code: 'ERR_INVALID_ARG_TYPE', - type: TypeError, - }); -common.expectsError(() => { - new AsyncResource('invalid_trigger_id', { triggerAsyncId: null }); -}, { - code: 'ERR_INVALID_ASYNC_ID', - type: RangeError, +common.expectsError(() => new AsyncResource(), { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError }); +common.expectsError( + () => { + new AsyncResource('invalid_trigger_id', { triggerAsyncId: null }); + }, + { + code: 'ERR_INVALID_ASYNC_ID', + type: RangeError + } +); assert.strictEqual( new AsyncResource('default_trigger_id').triggerAsyncId(), @@ -33,7 +35,7 @@ assert.strictEqual( // from async_hooks executionAsyncId const alcaTriggerId = async_hooks.executionAsyncId(); const alcaEvent = new AsyncResource('alcazares', alcaTriggerId); -const alcazaresActivities = hooks.activitiesOfTypes([ 'alcazares' ]); +const alcazaresActivities = hooks.activitiesOfTypes(['alcazares']); // alcazares event was constructed and thus only has an `init` call assert.strictEqual(alcazaresActivities.length, 1); @@ -48,40 +50,53 @@ assert.notStrictEqual(alcaEvent.asyncId(), alcaTriggerId); assert.strictEqual(alcaEvent.triggerAsyncId(), alcaTriggerId); alcaEvent.emitBefore(); -checkInvocations(alcazares, { init: 1, before: 1 }, - 'alcazares emitted before'); +checkInvocations(alcazares, { init: 1, before: 1 }, 'alcazares emitted before'); alcaEvent.emitAfter(); -checkInvocations(alcazares, { init: 1, before: 1, after: 1 }, - 'alcazares emitted after'); +checkInvocations( + alcazares, + { init: 1, before: 1, after: 1 }, + 'alcazares emitted after' +); alcaEvent.emitBefore(); -checkInvocations(alcazares, { init: 1, before: 2, after: 1 }, - 'alcazares emitted before again'); +checkInvocations( + alcazares, + { init: 1, before: 2, after: 1 }, + 'alcazares emitted before again' +); alcaEvent.emitAfter(); -checkInvocations(alcazares, { init: 1, before: 2, after: 2 }, - 'alcazares emitted after again'); +checkInvocations( + alcazares, + { init: 1, before: 2, after: 2 }, + 'alcazares emitted after again' +); alcaEvent.emitDestroy(); tick(1, common.mustCall(tick1)); function tick1() { - checkInvocations(alcazares, { init: 1, before: 2, after: 2, destroy: 1 }, - 'alcazares emitted destroy'); + checkInvocations( + alcazares, + { init: 1, before: 2, after: 2, destroy: 1 }, + 'alcazares emitted destroy' + ); // The below shows that we can pass any number as a trigger id const pobTriggerId = 111; const pobEvent = new AsyncResource('poblado', pobTriggerId); - const pobladoActivities = hooks.activitiesOfTypes([ 'poblado' ]); + const pobladoActivities = hooks.activitiesOfTypes(['poblado']); const poblado = pobladoActivities[0]; assert.strictEqual(poblado.type, 'poblado'); assert.strictEqual(typeof poblado.uid, 'number'); assert.strictEqual(poblado.triggerAsyncId, pobTriggerId); checkInvocations(poblado, { init: 1 }, 'poblado constructed'); pobEvent.emitBefore(); - checkInvocations(poblado, { init: 1, before: 1 }, - 'poblado emitted before'); + checkInvocations(poblado, { init: 1, before: 1 }, 'poblado emitted before'); pobEvent.emitAfter(); - checkInvocations(poblado, { init: 1, before: 1, after: 1 }, - 'poblado emitted after'); + checkInvocations( + poblado, + { init: 1, before: 1, after: 1 }, + 'poblado emitted after' + ); // after we disable the hooks we shouldn't receive any events anymore hooks.disable(); @@ -90,14 +105,19 @@ function tick1() { function tick2() { checkInvocations( - alcazares, { init: 1, before: 2, after: 2, destroy: 1 }, - 'alcazares emitted destroy a second time after hooks disabled'); + alcazares, + { init: 1, before: 2, after: 2, destroy: 1 }, + 'alcazares emitted destroy a second time after hooks disabled' + ); pobEvent.emitDestroy(); tick(1, common.mustCall(tick3)); } function tick3() { - checkInvocations(poblado, { init: 1, before: 1, after: 1 }, - 'poblado emitted destroy after hooks disabled'); + checkInvocations( + poblado, + { init: 1, before: 1, after: 1 }, + 'poblado emitted destroy after hooks disabled' + ); } } diff --git a/test/async-hooks/test-emit-before-after.js b/test/async-hooks/test-emit-before-after.js index 6a9ceaeefb8c0a..28afd1a9857203 100644 --- a/test/async-hooks/test-emit-before-after.js +++ b/test/async-hooks/test-emit-before-after.js @@ -20,21 +20,26 @@ switch (process.argv[2]) { } assert.ok(!process.argv[2]); - const c1 = spawnSync(process.execPath, [ - '--expose-internals', __filename, 'test_invalid_async_id' + '--expose-internals', + __filename, + 'test_invalid_async_id' ]); assert.strictEqual( c1.stderr.toString().split(/[\r\n]+/g)[0], - 'RangeError [ERR_INVALID_ASYNC_ID]: Invalid asyncId value: -2'); + 'RangeError [ERR_INVALID_ASYNC_ID]: Invalid asyncId value: -2' +); assert.strictEqual(c1.status, 1); const c2 = spawnSync(process.execPath, [ - '--expose-internals', __filename, 'test_invalid_trigger_id' + '--expose-internals', + __filename, + 'test_invalid_trigger_id' ]); assert.strictEqual( c2.stderr.toString().split(/[\r\n]+/g)[0], - 'RangeError [ERR_INVALID_ASYNC_ID]: Invalid triggerAsyncId value: -2'); + 'RangeError [ERR_INVALID_ASYNC_ID]: Invalid triggerAsyncId value: -2' +); assert.strictEqual(c2.status, 1); const expectedId = async_hooks.newAsyncId(); diff --git a/test/async-hooks/test-emit-init.js b/test/async-hooks/test-emit-init.js index f5d5687cb4d11d..b4901fdc9975f4 100644 --- a/test/async-hooks/test-emit-init.js +++ b/test/async-hooks/test-emit-init.js @@ -36,34 +36,45 @@ switch (process.argv[2]) { } assert.ok(!process.argv[2]); - const c1 = spawnSync(process.execPath, [ - '--expose-internals', __filename, 'test_invalid_async_id' + '--expose-internals', + __filename, + 'test_invalid_async_id' ]); assert.strictEqual( c1.stderr.toString().split(/[\r\n]+/g)[0], - 'RangeError [ERR_INVALID_ASYNC_ID]: Invalid asyncId value: undefined'); + 'RangeError [ERR_INVALID_ASYNC_ID]: Invalid asyncId value: undefined' +); assert.strictEqual(c1.status, 1); const c2 = spawnSync(process.execPath, [ - '--expose-internals', __filename, 'test_invalid_trigger_id' + '--expose-internals', + __filename, + 'test_invalid_trigger_id' ]); assert.strictEqual( c2.stderr.toString().split(/[\r\n]+/g)[0], - 'RangeError [ERR_INVALID_ASYNC_ID]: Invalid triggerAsyncId value: undefined'); + 'RangeError [ERR_INVALID_ASYNC_ID]: Invalid triggerAsyncId value: undefined' +); assert.strictEqual(c2.status, 1); const c3 = spawnSync(process.execPath, [ - '--expose-internals', __filename, 'test_invalid_trigger_id_negative' + '--expose-internals', + __filename, + 'test_invalid_trigger_id_negative' ]); assert.strictEqual( c3.stderr.toString().split(/[\r\n]+/g)[0], - 'RangeError [ERR_INVALID_ASYNC_ID]: Invalid triggerAsyncId value: -2'); + 'RangeError [ERR_INVALID_ASYNC_ID]: Invalid triggerAsyncId value: -2' +); assert.strictEqual(c3.status, 1); - -async_hooks.emitInit(expectedId, expectedType, expectedTriggerId, - expectedResource); +async_hooks.emitInit( + expectedId, + expectedType, + expectedTriggerId, + expectedResource +); hooks1.disable(); diff --git a/test/async-hooks/test-enable-disable.js b/test/async-hooks/test-enable-disable.js index c14a125688d0f4..b6f9d07884215c 100644 --- a/test/async-hooks/test-enable-disable.js +++ b/test/async-hooks/test-enable-disable.js @@ -94,7 +94,7 @@ if (!common.isMainThread) // Include "Unknown"s because hook2 will not be able to identify // the type of the first Immediate since it will miss its `init` invocation. -const types = [ 'Immediate', 'Unknown' ]; +const types = ['Immediate', 'Unknown']; // // Initializing hooks @@ -164,10 +164,16 @@ function onfirstImmediate() { assert.strictEqual(firstImmediate.type, 'Immediate'); assert.strictEqual(typeof firstImmediate.uid, 'number'); assert.strictEqual(typeof firstImmediate.triggerAsyncId, 'number'); - checkInvocations(as1[0], { init: 1, before: 1 }, - 'hook1[0]: on first immediate'); - checkInvocations(as3[0], { init: 1, before: 1 }, - 'hook3[0]: on first immediate'); + checkInvocations( + as1[0], + { init: 1, before: 1 }, + 'hook1[0]: on first immediate' + ); + checkInvocations( + as3[0], + { init: 1, before: 1 }, + 'hook3[0]: on first immediate' + ); // Setup the second Immediate, note that now hook2 is enabled and thus // will capture all lifetime events of this Immediate @@ -213,20 +219,38 @@ function onsecondImmediate() { assert.strictEqual(typeof secondImmediate.uid, 'number'); assert.strictEqual(typeof secondImmediate.triggerAsyncId, 'number'); - checkInvocations(hook1First, { init: 1, before: 1, after: 1, destroy: 1 }, - 'hook1First: on second immediate'); - checkInvocations(hook1Second, { init: 1, before: 1 }, - 'hook1Second: on second immediate'); + checkInvocations( + hook1First, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'hook1First: on second immediate' + ); + checkInvocations( + hook1Second, + { init: 1, before: 1 }, + 'hook1Second: on second immediate' + ); // hook2 missed the "init" and "before" since it was enabled after they // occurred - checkInvocations(hook2First, { after: 1, destroy: 1 }, - 'hook2First: on second immediate'); - checkInvocations(hook2Second, { init: 1, before: 1 }, - 'hook2Second: on second immediate'); - checkInvocations(hook3First, { init: 1, before: 1, after: 1, destroy: 1 }, - 'hook3First: on second immediate'); - checkInvocations(hook3Second, { init: 1, before: 1 }, - 'hook3Second: on second immediate'); + checkInvocations( + hook2First, + { after: 1, destroy: 1 }, + 'hook2First: on second immediate' + ); + checkInvocations( + hook2Second, + { init: 1, before: 1 }, + 'hook2Second: on second immediate' + ); + checkInvocations( + hook3First, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'hook3First: on second immediate' + ); + checkInvocations( + hook3Second, + { init: 1, before: 1 }, + 'hook3Second: on second immediate' + ); tick(1); } @@ -247,22 +271,40 @@ function onexit() { hook2.sanityCheck(); hook3.sanityCheck(); - checkInvocations(hook1First, { init: 1, before: 1, after: 1, destroy: 1 }, - 'hook1First: when process exits'); + checkInvocations( + hook1First, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'hook1First: when process exits' + ); // hook1 was disabled during hook2's "before" of the second immediate // and thus did not see "after" and "destroy" - checkInvocations(hook1Second, { init: 1, before: 1 }, - 'hook1Second: when process exits'); + checkInvocations( + hook1Second, + { init: 1, before: 1 }, + 'hook1Second: when process exits' + ); // hook2 missed the "init" and "before" since it was enabled after they // occurred - checkInvocations(hook2First, { after: 1, destroy: 1 }, - 'hook2First: when process exits'); - checkInvocations(hook2Second, { init: 1, before: 1, after: 1, destroy: 1 }, - 'hook2Second: when process exits'); - checkInvocations(hook3First, { init: 1, before: 1, after: 1, destroy: 1 }, - 'hook3First: when process exits'); + checkInvocations( + hook2First, + { after: 1, destroy: 1 }, + 'hook2First: when process exits' + ); + checkInvocations( + hook2Second, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'hook2Second: when process exits' + ); + checkInvocations( + hook3First, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'hook3First: when process exits' + ); // we don't see a "destroy" invocation here since hook3 disabled itself // during its "after" invocation - checkInvocations(hook3Second, { init: 1, before: 1, after: 1 }, - 'hook3Second: when process exits'); + checkInvocations( + hook3Second, + { init: 1, before: 1, after: 1 }, + 'hook3Second: when process exits' + ); } diff --git a/test/async-hooks/test-enable-in-init.js b/test/async-hooks/test-enable-in-init.js index e4be9f9f87e3eb..debab94ae97a53 100644 --- a/test/async-hooks/test-enable-in-init.js +++ b/test/async-hooks/test-enable-in-init.js @@ -9,14 +9,16 @@ const nestedHook = async_hooks.createHook({ }); let nestedCall = false; -async_hooks.createHook({ - init: common.mustCall(function(id, type) { - nestedHook.enable(); - if (!nestedCall) { - nestedCall = true; - fs.access(__filename, common.mustCall()); - } - }, 2) -}).enable(); +async_hooks + .createHook({ + init: common.mustCall(function(id, type) { + nestedHook.enable(); + if (!nestedCall) { + nestedCall = true; + fs.access(__filename, common.mustCall()); + } + }, 2) + }) + .enable(); fs.access(__filename, common.mustCall()); diff --git a/test/async-hooks/test-fseventwrap.js b/test/async-hooks/test-fseventwrap.js index 8608075c822ded..dcc5eb3e91599a 100644 --- a/test/async-hooks/test-fseventwrap.js +++ b/test/async-hooks/test-fseventwrap.js @@ -14,7 +14,7 @@ const hooks = initHooks(); hooks.enable(); const watcher = fs.watch(__filename, onwatcherChanged); -function onwatcherChanged() { } +function onwatcherChanged() {} watcher.close(); tick(2); diff --git a/test/async-hooks/test-fsreqcallback-access.js b/test/async-hooks/test-fsreqcallback-access.js index b1b75f5693050d..e7c53649785740 100644 --- a/test/async-hooks/test-fsreqcallback-access.js +++ b/test/async-hooks/test-fsreqcallback-access.js @@ -15,8 +15,7 @@ fs.access(__filename, common.mustCall(onaccess)); function onaccess() { const as = hooks.activitiesOfTypes('FSREQCALLBACK'); const a = as[0]; - checkInvocations(a, { init: 1, before: 1 }, - 'while in onaccess callback'); + checkInvocations(a, { init: 1, before: 1 }, 'while in onaccess callback'); tick(2); } @@ -32,6 +31,9 @@ function onexit() { const a = as[0]; assert.strictEqual(a.type, 'FSREQCALLBACK'); assert.strictEqual(typeof a.uid, 'number'); - checkInvocations(a, { init: 1, before: 1, after: 1, destroy: 1 }, - 'when process exits'); + checkInvocations( + a, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'when process exits' + ); } diff --git a/test/async-hooks/test-fsreqcallback-readFile.js b/test/async-hooks/test-fsreqcallback-readFile.js index 3ae31378cd3199..6203f319db5286 100644 --- a/test/async-hooks/test-fsreqcallback-readFile.js +++ b/test/async-hooks/test-fsreqcallback-readFile.js @@ -25,17 +25,29 @@ function onread() { assert.strictEqual(a.triggerAsyncId, lastParent); lastParent = a.uid; } - checkInvocations(as[0], { init: 1, before: 1, after: 1, destroy: 1 }, - 'reqwrap[0]: while in onread callback'); - checkInvocations(as[1], { init: 1, before: 1, after: 1, destroy: 1 }, - 'reqwrap[1]: while in onread callback'); - checkInvocations(as[2], { init: 1, before: 1, after: 1, destroy: 1 }, - 'reqwrap[2]: while in onread callback'); + checkInvocations( + as[0], + { init: 1, before: 1, after: 1, destroy: 1 }, + 'reqwrap[0]: while in onread callback' + ); + checkInvocations( + as[1], + { init: 1, before: 1, after: 1, destroy: 1 }, + 'reqwrap[1]: while in onread callback' + ); + checkInvocations( + as[2], + { init: 1, before: 1, after: 1, destroy: 1 }, + 'reqwrap[2]: while in onread callback' + ); // this callback is called from within the last fs req callback therefore // the last req is still going and after/destroy haven't been called yet - checkInvocations(as[3], { init: 1, before: 1 }, - 'reqwrap[3]: while in onread callback'); + checkInvocations( + as[3], + { init: 1, before: 1 }, + 'reqwrap[3]: while in onread callback' + ); tick(2); } @@ -46,6 +58,9 @@ function onexit() { hooks.sanityCheck('FSREQCALLBACK'); const as = hooks.activitiesOfTypes('FSREQCALLBACK'); const a = as.pop(); - checkInvocations(a, { init: 1, before: 1, after: 1, destroy: 1 }, - 'when process exits'); + checkInvocations( + a, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'when process exits' + ); } diff --git a/test/async-hooks/test-getaddrinforeqwrap.js b/test/async-hooks/test-getaddrinforeqwrap.js index f2a978d7640677..b88e242b4f0da5 100644 --- a/test/async-hooks/test-getaddrinforeqwrap.js +++ b/test/async-hooks/test-getaddrinforeqwrap.js @@ -37,6 +37,9 @@ function onexit() { const as = hooks.activitiesOfTypes('GETADDRINFOREQWRAP'); const a = as[0]; - checkInvocations(a, { init: 1, before: 1, after: 1, destroy: 1 }, - 'when process exits'); + checkInvocations( + a, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'when process exits' + ); } diff --git a/test/async-hooks/test-getnameinforeqwrap.js b/test/async-hooks/test-getnameinforeqwrap.js index 9e06cbf9cbf174..e0885d58b143dc 100644 --- a/test/async-hooks/test-getnameinforeqwrap.js +++ b/test/async-hooks/test-getnameinforeqwrap.js @@ -25,8 +25,11 @@ function onlookupService() { assert.strictEqual(a.type, 'GETNAMEINFOREQWRAP'); assert.strictEqual(typeof a.uid, 'number'); assert.strictEqual(a.triggerAsyncId, 1); - checkInvocations(a, { init: 1, before: 1 }, - 'while in onlookupService callback'); + checkInvocations( + a, + { init: 1, before: 1 }, + 'while in onlookupService callback' + ); tick(2); } @@ -38,6 +41,9 @@ function onexit() { const as = hooks.activitiesOfTypes('GETNAMEINFOREQWRAP'); const a = as[0]; - checkInvocations(a, { init: 1, before: 1, after: 1, destroy: 1 }, - 'when process exits'); + checkInvocations( + a, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'when process exits' + ); } diff --git a/test/async-hooks/test-graph.fsreq-readFile.js b/test/async-hooks/test-graph.fsreq-readFile.js index 0a310ed5774a67..ded03c2f01fc6a 100644 --- a/test/async-hooks/test-graph.fsreq-readFile.js +++ b/test/async-hooks/test-graph.fsreq-readFile.js @@ -16,11 +16,10 @@ process.on('exit', onexit); function onexit() { hooks.disable(); - verifyGraph( - hooks, - [ { type: 'FSREQCALLBACK', id: 'fsreq:1', triggerAsyncId: null }, - { type: 'FSREQCALLBACK', id: 'fsreq:2', triggerAsyncId: 'fsreq:1' }, - { type: 'FSREQCALLBACK', id: 'fsreq:3', triggerAsyncId: 'fsreq:2' }, - { type: 'FSREQCALLBACK', id: 'fsreq:4', triggerAsyncId: 'fsreq:3' } ] - ); + verifyGraph(hooks, [ + { type: 'FSREQCALLBACK', id: 'fsreq:1', triggerAsyncId: null }, + { type: 'FSREQCALLBACK', id: 'fsreq:2', triggerAsyncId: 'fsreq:1' }, + { type: 'FSREQCALLBACK', id: 'fsreq:3', triggerAsyncId: 'fsreq:2' }, + { type: 'FSREQCALLBACK', id: 'fsreq:4', triggerAsyncId: 'fsreq:3' } + ]); } diff --git a/test/async-hooks/test-graph.http.js b/test/async-hooks/test-graph.http.js index 414ebabeeeaea4..357505a02a4323 100644 --- a/test/async-hooks/test-graph.http.js +++ b/test/async-hooks/test-graph.http.js @@ -1,8 +1,7 @@ 'use strict'; const common = require('../common'); -if (!common.hasIPv6) - common.skip('IPv6 support required'); +if (!common.hasIPv6) common.skip('IPv6 support required'); const initHooks = require('./init-hooks'); const verifyGraph = require('./verify-graph'); @@ -11,43 +10,38 @@ const http = require('http'); const hooks = initHooks(); hooks.enable(); -const server = http.createServer(common.mustCall(function(req, res) { - res.end(); - this.close(common.mustCall()); -})); -server.listen(0, common.mustCall(function() { - http.get({ - host: '::1', - family: 6, - port: server.address().port - }, common.mustCall()); -})); +const server = http.createServer( + common.mustCall(function(req, res) { + res.end(); + this.close(common.mustCall()); + }) +); +server.listen( + 0, + common.mustCall(function() { + http.get( + { + host: '::1', + family: 6, + port: server.address().port + }, + common.mustCall() + ); + }) +); process.on('exit', function() { hooks.disable(); - verifyGraph( - hooks, - [ { type: 'TCPSERVERWRAP', - id: 'tcpserver:1', - triggerAsyncId: null }, - { type: 'TCPWRAP', id: 'tcp:1', triggerAsyncId: 'tcpserver:1' }, - { type: 'TCPCONNECTWRAP', - id: 'tcpconnect:1', - triggerAsyncId: 'tcp:1' }, - { type: 'HTTPPARSER', - id: 'httpparser:1', - triggerAsyncId: 'tcpserver:1' }, - { type: 'TCPWRAP', id: 'tcp:2', triggerAsyncId: 'tcpserver:1' }, - { type: 'Timeout', id: 'timeout:1', triggerAsyncId: 'tcp:2' }, - { type: 'HTTPPARSER', - id: 'httpparser:2', - triggerAsyncId: 'tcp:2' }, - { type: 'Timeout', - id: 'timeout:2', - triggerAsyncId: 'httpparser:2' }, - { type: 'SHUTDOWNWRAP', - id: 'shutdown:1', - triggerAsyncId: 'tcp:2' } ] - ); + verifyGraph(hooks, [ + { type: 'TCPSERVERWRAP', id: 'tcpserver:1', triggerAsyncId: null }, + { type: 'TCPWRAP', id: 'tcp:1', triggerAsyncId: 'tcpserver:1' }, + { type: 'TCPCONNECTWRAP', id: 'tcpconnect:1', triggerAsyncId: 'tcp:1' }, + { type: 'HTTPPARSER', id: 'httpparser:1', triggerAsyncId: 'tcpserver:1' }, + { type: 'TCPWRAP', id: 'tcp:2', triggerAsyncId: 'tcpserver:1' }, + { type: 'Timeout', id: 'timeout:1', triggerAsyncId: 'tcp:2' }, + { type: 'HTTPPARSER', id: 'httpparser:2', triggerAsyncId: 'tcp:2' }, + { type: 'Timeout', id: 'timeout:2', triggerAsyncId: 'httpparser:2' }, + { type: 'SHUTDOWNWRAP', id: 'shutdown:1', triggerAsyncId: 'tcp:2' } + ]); }); diff --git a/test/async-hooks/test-graph.intervals.js b/test/async-hooks/test-graph.intervals.js index 8aa46ab07b5471..9d6452dba18eb3 100644 --- a/test/async-hooks/test-graph.intervals.js +++ b/test/async-hooks/test-graph.intervals.js @@ -27,9 +27,8 @@ process.on('exit', onexit); function onexit() { hooks.disable(); - verifyGraph( - hooks, - [ { type: 'Timeout', id: 'timeout:1', triggerAsyncId: null }, - { type: 'Timeout', id: 'timeout:2', triggerAsyncId: 'timeout:1' }] - ); + verifyGraph(hooks, [ + { type: 'Timeout', id: 'timeout:1', triggerAsyncId: null }, + { type: 'Timeout', id: 'timeout:2', triggerAsyncId: 'timeout:1' } + ]); } diff --git a/test/async-hooks/test-graph.pipe.js b/test/async-hooks/test-graph.pipe.js index 162fb3639bfbfc..4dcc5098dee8d3 100644 --- a/test/async-hooks/test-graph.pipe.js +++ b/test/async-hooks/test-graph.pipe.js @@ -8,7 +8,7 @@ const spawn = require('child_process').spawn; const hooks = initHooks(); hooks.enable(); -const sleep = spawn('sleep', [ '0.1' ]); +const sleep = spawn('sleep', ['0.1']); sleep .on('exit', common.mustCall(onsleepExit)) @@ -22,11 +22,10 @@ process.on('exit', onexit); function onexit() { hooks.disable(); - verifyGraph( - hooks, - [ { type: 'PROCESSWRAP', id: 'process:1', triggerAsyncId: null }, - { type: 'PIPEWRAP', id: 'pipe:1', triggerAsyncId: null }, - { type: 'PIPEWRAP', id: 'pipe:2', triggerAsyncId: null }, - { type: 'PIPEWRAP', id: 'pipe:3', triggerAsyncId: null } ] - ); + verifyGraph(hooks, [ + { type: 'PROCESSWRAP', id: 'process:1', triggerAsyncId: null }, + { type: 'PIPEWRAP', id: 'pipe:1', triggerAsyncId: null }, + { type: 'PIPEWRAP', id: 'pipe:2', triggerAsyncId: null }, + { type: 'PIPEWRAP', id: 'pipe:3', triggerAsyncId: null } + ]); } diff --git a/test/async-hooks/test-graph.pipeconnect.js b/test/async-hooks/test-graph.pipeconnect.js index 03d2902c835d48..d0a018fcd10dcf 100644 --- a/test/async-hooks/test-graph.pipeconnect.js +++ b/test/async-hooks/test-graph.pipeconnect.js @@ -12,13 +12,18 @@ tmpdir.refresh(); const hooks = initHooks(); hooks.enable(); -net.createServer(function(c) { - c.end(); - this.close(); -}).listen(common.PIPE, common.mustCall(onlisten)); +net + .createServer(function(c) { + c.end(); + this.close(); + }) + .listen(common.PIPE, common.mustCall(onlisten)); function onlisten() { - net.connect(common.PIPE, common.mustCall(onconnect)); + net.connect( + common.PIPE, + common.mustCall(onconnect) + ); } function onconnect() {} @@ -27,13 +32,11 @@ process.on('exit', onexit); function onexit() { hooks.disable(); - verifyGraph( - hooks, - [ { type: 'PIPESERVERWRAP', id: 'pipeserver:1', triggerAsyncId: null }, - { type: 'PIPEWRAP', id: 'pipe:1', triggerAsyncId: 'pipeserver:1' }, - { type: 'PIPECONNECTWRAP', id: 'pipeconnect:1', - triggerAsyncId: 'pipe:1' }, - { type: 'PIPEWRAP', id: 'pipe:2', triggerAsyncId: 'pipeserver:1' }, - { type: 'SHUTDOWNWRAP', id: 'shutdown:1', triggerAsyncId: 'pipe:2' } ] - ); + verifyGraph(hooks, [ + { type: 'PIPESERVERWRAP', id: 'pipeserver:1', triggerAsyncId: null }, + { type: 'PIPEWRAP', id: 'pipe:1', triggerAsyncId: 'pipeserver:1' }, + { type: 'PIPECONNECTWRAP', id: 'pipeconnect:1', triggerAsyncId: 'pipe:1' }, + { type: 'PIPEWRAP', id: 'pipe:2', triggerAsyncId: 'pipeserver:1' }, + { type: 'SHUTDOWNWRAP', id: 'shutdown:1', triggerAsyncId: 'pipe:2' } + ]); } diff --git a/test/async-hooks/test-graph.shutdown.js b/test/async-hooks/test-graph.shutdown.js index f4f077c0dd1c83..b7b6f50fcaf67a 100644 --- a/test/async-hooks/test-graph.shutdown.js +++ b/test/async-hooks/test-graph.shutdown.js @@ -1,8 +1,7 @@ 'use strict'; const common = require('../common'); -if (!common.hasIPv6) - common.skip('IPv6 support required'); +if (!common.hasIPv6) common.skip('IPv6 support required'); const initHooks = require('./init-hooks'); const verifyGraph = require('./verify-graph'); @@ -16,7 +15,10 @@ const server = net .on('listening', common.mustCall(onlistening)); server.listen(); function onlistening() { - net.connect(server.address().port, common.mustCall(onconnected)); + net.connect( + server.address().port, + common.mustCall(onconnected) + ); } function onconnection(c) { @@ -32,15 +34,16 @@ process.on('exit', onexit); function onexit() { hooks.disable(); - verifyGraph( - hooks, - [ { type: 'TCPSERVERWRAP', id: 'tcpserver:1', triggerAsyncId: null }, - { type: 'TCPWRAP', id: 'tcp:1', triggerAsyncId: 'tcpserver:1' }, - { type: 'GETADDRINFOREQWRAP', - id: 'getaddrinforeq:1', triggerAsyncId: 'tcp:1' }, - { type: 'TCPCONNECTWRAP', - id: 'tcpconnect:1', triggerAsyncId: 'tcp:1' }, - { type: 'TCPWRAP', id: 'tcp:2', triggerAsyncId: 'tcpserver:1' }, - { type: 'SHUTDOWNWRAP', id: 'shutdown:1', triggerAsyncId: 'tcp:2' } ] - ); + verifyGraph(hooks, [ + { type: 'TCPSERVERWRAP', id: 'tcpserver:1', triggerAsyncId: null }, + { type: 'TCPWRAP', id: 'tcp:1', triggerAsyncId: 'tcpserver:1' }, + { + type: 'GETADDRINFOREQWRAP', + id: 'getaddrinforeq:1', + triggerAsyncId: 'tcp:1' + }, + { type: 'TCPCONNECTWRAP', id: 'tcpconnect:1', triggerAsyncId: 'tcp:1' }, + { type: 'TCPWRAP', id: 'tcp:2', triggerAsyncId: 'tcpserver:1' }, + { type: 'SHUTDOWNWRAP', id: 'shutdown:1', triggerAsyncId: 'tcp:2' } + ]); } diff --git a/test/async-hooks/test-graph.signal.js b/test/async-hooks/test-graph.signal.js index 4c5b857fc2e08f..f5f318bc4d5e81 100644 --- a/test/async-hooks/test-graph.signal.js +++ b/test/async-hooks/test-graph.signal.js @@ -1,8 +1,7 @@ 'use strict'; const common = require('../common'); -if (common.isWindows) - common.skip('no signals on Windows'); +if (common.isWindows) common.skip('no signals on Windows'); if (!common.isMainThread) common.skip('No signal handling available in Workers'); @@ -42,21 +41,20 @@ process.on('exit', onexit); function onexit() { hooks.disable(); - verifyGraph( - hooks, - [ { type: 'SIGNALWRAP', id: 'signal:1', triggerAsyncId: null }, - { type: 'PROCESSWRAP', id: 'process:1', triggerAsyncId: null }, - { type: 'PIPEWRAP', id: 'pipe:1', triggerAsyncId: null }, - { type: 'PIPEWRAP', id: 'pipe:2', triggerAsyncId: null }, - { type: 'PIPEWRAP', id: 'pipe:3', triggerAsyncId: null }, - { type: 'PROCESSWRAP', id: 'process:2', triggerAsyncId: 'signal:1' }, - { type: 'PIPEWRAP', id: 'pipe:4', triggerAsyncId: 'signal:1' }, - { type: 'PIPEWRAP', id: 'pipe:5', triggerAsyncId: 'signal:1' }, - { type: 'PIPEWRAP', id: 'pipe:6', triggerAsyncId: 'signal:1' }, - { type: 'SIGNALWRAP', id: 'signal:2', triggerAsyncId: 'signal:1' }, - { type: 'PROCESSWRAP', id: 'process:3', triggerAsyncId: 'signal:1' }, - { type: 'PIPEWRAP', id: 'pipe:7', triggerAsyncId: 'signal:1' }, - { type: 'PIPEWRAP', id: 'pipe:8', triggerAsyncId: 'signal:1' }, - { type: 'PIPEWRAP', id: 'pipe:9', triggerAsyncId: 'signal:1' } ] - ); + verifyGraph(hooks, [ + { type: 'SIGNALWRAP', id: 'signal:1', triggerAsyncId: null }, + { type: 'PROCESSWRAP', id: 'process:1', triggerAsyncId: null }, + { type: 'PIPEWRAP', id: 'pipe:1', triggerAsyncId: null }, + { type: 'PIPEWRAP', id: 'pipe:2', triggerAsyncId: null }, + { type: 'PIPEWRAP', id: 'pipe:3', triggerAsyncId: null }, + { type: 'PROCESSWRAP', id: 'process:2', triggerAsyncId: 'signal:1' }, + { type: 'PIPEWRAP', id: 'pipe:4', triggerAsyncId: 'signal:1' }, + { type: 'PIPEWRAP', id: 'pipe:5', triggerAsyncId: 'signal:1' }, + { type: 'PIPEWRAP', id: 'pipe:6', triggerAsyncId: 'signal:1' }, + { type: 'SIGNALWRAP', id: 'signal:2', triggerAsyncId: 'signal:1' }, + { type: 'PROCESSWRAP', id: 'process:3', triggerAsyncId: 'signal:1' }, + { type: 'PIPEWRAP', id: 'pipe:7', triggerAsyncId: 'signal:1' }, + { type: 'PIPEWRAP', id: 'pipe:8', triggerAsyncId: 'signal:1' }, + { type: 'PIPEWRAP', id: 'pipe:9', triggerAsyncId: 'signal:1' } + ]); } diff --git a/test/async-hooks/test-graph.statwatcher.js b/test/async-hooks/test-graph.statwatcher.js index 3067045d2bf8ac..1b0af1b8f0d88c 100644 --- a/test/async-hooks/test-graph.statwatcher.js +++ b/test/async-hooks/test-graph.statwatcher.js @@ -9,7 +9,7 @@ const fs = require('fs'); const hooks = initHooks(); hooks.enable(); -function onchange() { } +function onchange() {} // install first file watcher fs.watchFile(__filename, onchange); @@ -26,9 +26,8 @@ process.on('exit', onexit); function onexit() { hooks.disable(); - verifyGraph( - hooks, - [ { type: 'STATWATCHER', id: 'statwatcher:1', triggerAsyncId: null }, - { type: 'STATWATCHER', id: 'statwatcher:2', triggerAsyncId: null } ] - ); + verifyGraph(hooks, [ + { type: 'STATWATCHER', id: 'statwatcher:1', triggerAsyncId: null }, + { type: 'STATWATCHER', id: 'statwatcher:2', triggerAsyncId: null } + ]); } diff --git a/test/async-hooks/test-graph.tcp.js b/test/async-hooks/test-graph.tcp.js index c2253486ee651e..c75908e5317ddb 100644 --- a/test/async-hooks/test-graph.tcp.js +++ b/test/async-hooks/test-graph.tcp.js @@ -1,8 +1,7 @@ 'use strict'; const common = require('../common'); -if (!common.hasIPv6) - common.skip('IPv6 support required'); +if (!common.hasIPv6) common.skip('IPv6 support required'); const initHooks = require('./init-hooks'); const verifyGraph = require('./verify-graph'); @@ -17,8 +16,10 @@ const server = net server.listen(0); -net.connect({ port: server.address().port, host: '::1' }, - common.mustCall(onconnected)); +net.connect( + { port: server.address().port, host: '::1' }, + common.mustCall(onconnected) +); function onlistening() {} @@ -36,13 +37,11 @@ process.on('exit', onexit); function onexit() { hooks.disable(); - verifyGraph( - hooks, - [ { type: 'TCPSERVERWRAP', id: 'tcpserver:1', triggerAsyncId: null }, - { type: 'TCPWRAP', id: 'tcp:1', triggerAsyncId: null }, - { type: 'TCPCONNECTWRAP', - id: 'tcpconnect:1', triggerAsyncId: 'tcp:1' }, - { type: 'TCPWRAP', id: 'tcp:2', triggerAsyncId: 'tcpserver:1' }, - { type: 'SHUTDOWNWRAP', id: 'shutdown:1', triggerAsyncId: 'tcp:2' } ] - ); + verifyGraph(hooks, [ + { type: 'TCPSERVERWRAP', id: 'tcpserver:1', triggerAsyncId: null }, + { type: 'TCPWRAP', id: 'tcp:1', triggerAsyncId: null }, + { type: 'TCPCONNECTWRAP', id: 'tcpconnect:1', triggerAsyncId: 'tcp:1' }, + { type: 'TCPWRAP', id: 'tcp:2', triggerAsyncId: 'tcpserver:1' }, + { type: 'SHUTDOWNWRAP', id: 'shutdown:1', triggerAsyncId: 'tcp:2' } + ]); } diff --git a/test/async-hooks/test-graph.timeouts.js b/test/async-hooks/test-graph.timeouts.js index 2ec1420f0c03b1..e8fb26cf677a1a 100644 --- a/test/async-hooks/test-graph.timeouts.js +++ b/test/async-hooks/test-graph.timeouts.js @@ -23,10 +23,9 @@ process.on('exit', onexit); function onexit() { hooks.disable(); - verifyGraph( - hooks, - [ { type: 'Timeout', id: 'timeout:1', triggerAsyncId: null }, - { type: 'Timeout', id: 'timeout:2', triggerAsyncId: 'timeout:1' }, - { type: 'Timeout', id: 'timeout:3', triggerAsyncId: 'timeout:2' }] - ); + verifyGraph(hooks, [ + { type: 'Timeout', id: 'timeout:1', triggerAsyncId: null }, + { type: 'Timeout', id: 'timeout:2', triggerAsyncId: 'timeout:1' }, + { type: 'Timeout', id: 'timeout:3', triggerAsyncId: 'timeout:2' } + ]); } diff --git a/test/async-hooks/test-graph.tls-write.js b/test/async-hooks/test-graph.tls-write.js index 2ea03283e4c861..a0c504be1cd779 100644 --- a/test/async-hooks/test-graph.tls-write.js +++ b/test/async-hooks/test-graph.tls-write.js @@ -1,11 +1,9 @@ 'use strict'; const common = require('../common'); -if (!common.hasCrypto) - common.skip('missing crypto'); +if (!common.hasCrypto) common.skip('missing crypto'); -if (!common.hasIPv6) - common.skip('IPv6 support required'); +if (!common.hasIPv6) common.skip('IPv6 support required'); const initHooks = require('./init-hooks'); const verifyGraph = require('./verify-graph'); @@ -32,7 +30,10 @@ function onlistening() { // Creating client and connecting it to server // tls - .connect(server.address().port, { rejectUnauthorized: false }) + .connect( + server.address().port, + { rejectUnauthorized: false } + ) .on('secureConnect', common.mustCall(onsecureConnect)); } @@ -53,22 +54,23 @@ process.on('exit', onexit); function onexit() { hooks.disable(); - verifyGraph( - hooks, - [ { type: 'TCPSERVERWRAP', id: 'tcpserver:1', triggerAsyncId: null }, - { type: 'TCPWRAP', id: 'tcp:1', triggerAsyncId: 'tcpserver:1' }, - { type: 'TLSWRAP', id: 'tls:1', triggerAsyncId: 'tcpserver:1' }, - { type: 'GETADDRINFOREQWRAP', - id: 'getaddrinforeq:1', triggerAsyncId: 'tls:1' }, - { type: 'TCPCONNECTWRAP', - id: 'tcpconnect:1', triggerAsyncId: 'tcp:1' }, - { type: 'WRITEWRAP', id: 'write:1', triggerAsyncId: 'tcpconnect:1' }, - { type: 'TCPWRAP', id: 'tcp:2', triggerAsyncId: 'tcpserver:1' }, - { type: 'TLSWRAP', id: 'tls:2', triggerAsyncId: 'tcpserver:1' }, - { type: 'WRITEWRAP', id: 'write:2', triggerAsyncId: null }, - { type: 'WRITEWRAP', id: 'write:3', triggerAsyncId: null }, - { type: 'WRITEWRAP', id: 'write:4', triggerAsyncId: null }, - { type: 'Immediate', id: 'immediate:1', triggerAsyncId: 'tcp:1' }, - { type: 'Immediate', id: 'immediate:2', triggerAsyncId: 'tcp:2' } ] - ); + verifyGraph(hooks, [ + { type: 'TCPSERVERWRAP', id: 'tcpserver:1', triggerAsyncId: null }, + { type: 'TCPWRAP', id: 'tcp:1', triggerAsyncId: 'tcpserver:1' }, + { type: 'TLSWRAP', id: 'tls:1', triggerAsyncId: 'tcpserver:1' }, + { + type: 'GETADDRINFOREQWRAP', + id: 'getaddrinforeq:1', + triggerAsyncId: 'tls:1' + }, + { type: 'TCPCONNECTWRAP', id: 'tcpconnect:1', triggerAsyncId: 'tcp:1' }, + { type: 'WRITEWRAP', id: 'write:1', triggerAsyncId: 'tcpconnect:1' }, + { type: 'TCPWRAP', id: 'tcp:2', triggerAsyncId: 'tcpserver:1' }, + { type: 'TLSWRAP', id: 'tls:2', triggerAsyncId: 'tcpserver:1' }, + { type: 'WRITEWRAP', id: 'write:2', triggerAsyncId: null }, + { type: 'WRITEWRAP', id: 'write:3', triggerAsyncId: null }, + { type: 'WRITEWRAP', id: 'write:4', triggerAsyncId: null }, + { type: 'Immediate', id: 'immediate:1', triggerAsyncId: 'tcp:1' }, + { type: 'Immediate', id: 'immediate:2', triggerAsyncId: 'tcp:2' } + ]); } diff --git a/test/async-hooks/test-httpparser.request.js b/test/async-hooks/test-httpparser.request.js index cb56419137163a..abb852a183b52c 100644 --- a/test/async-hooks/test-httpparser.request.js +++ b/test/async-hooks/test-httpparser.request.js @@ -22,9 +22,7 @@ const REQUEST = HTTPParser.REQUEST; const kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; -const request = Buffer.from( - 'GET /hello HTTP/1.1\r\n\r\n' -); +const request = Buffer.from('GET /hello HTTP/1.1\r\n\r\n'); const parser = new HTTPParser(REQUEST); const as = hooks.activitiesOfTypes('HTTPPARSER'); @@ -39,8 +37,11 @@ parser[kOnHeadersComplete] = common.mustCall(onheadersComplete); parser.execute(request, 0, request.length); function onheadersComplete() { - checkInvocations(httpparser, { init: 1, before: 1 }, - 'when onheadersComplete called'); + checkInvocations( + httpparser, + { init: 1, before: 1 }, + 'when onheadersComplete called' + ); tick(1, common.mustCall(tick1)); } @@ -54,6 +55,9 @@ process.on('exit', onexit); function onexit() { hooks.disable(); hooks.sanityCheck('HTTPPARSER'); - checkInvocations(httpparser, { init: 1, before: 1, after: 1, destroy: 1 }, - 'when process exits'); + checkInvocations( + httpparser, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'when process exits' + ); } diff --git a/test/async-hooks/test-httpparser.response.js b/test/async-hooks/test-httpparser.response.js index b1f804ef7d42a9..df14eae50313c7 100644 --- a/test/async-hooks/test-httpparser.response.js +++ b/test/async-hooks/test-httpparser.response.js @@ -25,10 +25,10 @@ const kOnBody = HTTPParser.kOnBody | 0; const request = Buffer.from( 'HTTP/1.1 200 OK\r\n' + - 'Content-Type: text/plain\r\n' + - 'Content-Length: 4\r\n' + - '\r\n' + - 'pong' + 'Content-Type: text/plain\r\n' + + 'Content-Length: 4\r\n' + + '\r\n' + + 'pong' ); const parser = new HTTPParser(RESPONSE); @@ -45,13 +45,19 @@ parser[kOnBody] = common.mustCall(onbody); parser.execute(request, 0, request.length); function onheadersComplete() { - checkInvocations(httpparser, { init: 1, before: 1 }, - 'when onheadersComplete called'); + checkInvocations( + httpparser, + { init: 1, before: 1 }, + 'when onheadersComplete called' + ); } function onbody() { - checkInvocations(httpparser, { init: 1, before: 2, after: 1 }, - 'when onbody called'); + checkInvocations( + httpparser, + { init: 1, before: 2, after: 1 }, + 'when onbody called' + ); tick(1, common.mustCall(tick1)); } @@ -65,6 +71,9 @@ process.on('exit', onexit); function onexit() { hooks.disable(); hooks.sanityCheck('HTTPPARSER'); - checkInvocations(httpparser, { init: 1, before: 2, after: 2, destroy: 1 }, - 'when process exits'); + checkInvocations( + httpparser, + { init: 1, before: 2, after: 2, destroy: 1 }, + 'when process exits' + ); } diff --git a/test/async-hooks/test-immediate.js b/test/async-hooks/test-immediate.js index 7b51902f77cbeb..08cfd7df74bb0a 100644 --- a/test/async-hooks/test-immediate.js +++ b/test/async-hooks/test-immediate.js @@ -18,16 +18,18 @@ const imd1 = as[0]; assert.strictEqual(imd1.type, 'Immediate'); assert.strictEqual(typeof imd1.uid, 'number'); assert.strictEqual(typeof imd1.triggerAsyncId, 'number'); -checkInvocations(imd1, { init: 1 }, - 'imd1: when first set immediate installed'); +checkInvocations(imd1, { init: 1 }, 'imd1: when first set immediate installed'); let imd2; function onimmediate() { let as = hooks.activitiesOfTypes('Immediate'); assert.strictEqual(as.length, 1); - checkInvocations(imd1, { init: 1, before: 1 }, - 'imd1: when first set immediate triggered'); + checkInvocations( + imd1, + { init: 1, before: 1 }, + 'imd1: when first set immediate triggered' + ); // install second immediate setImmediate(common.mustCall(onimmediateTwo)); @@ -37,17 +39,29 @@ function onimmediate() { assert.strictEqual(imd2.type, 'Immediate'); assert.strictEqual(typeof imd2.uid, 'number'); assert.strictEqual(typeof imd2.triggerAsyncId, 'number'); - checkInvocations(imd1, { init: 1, before: 1 }, - 'imd1: when second set immediate installed'); - checkInvocations(imd2, { init: 1 }, - 'imd2: when second set immediate installed'); + checkInvocations( + imd1, + { init: 1, before: 1 }, + 'imd1: when second set immediate installed' + ); + checkInvocations( + imd2, + { init: 1 }, + 'imd2: when second set immediate installed' + ); } function onimmediateTwo() { - checkInvocations(imd1, { init: 1, before: 1, after: 1, destroy: 1 }, - 'imd1: when second set immediate triggered'); - checkInvocations(imd2, { init: 1, before: 1 }, - 'imd2: when second set immediate triggered'); + checkInvocations( + imd1, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'imd1: when second set immediate triggered' + ); + checkInvocations( + imd2, + { init: 1, before: 1 }, + 'imd2: when second set immediate triggered' + ); tick(1); } @@ -56,8 +70,14 @@ process.on('exit', onexit); function onexit() { hooks.disable(); hooks.sanityCheck('Immediate'); - checkInvocations(imd1, { init: 1, before: 1, after: 1, destroy: 1 }, - 'imd1: when process exits'); - checkInvocations(imd2, { init: 1, before: 1, after: 1, destroy: 1 }, - 'imd2: when process exits'); + checkInvocations( + imd1, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'imd1: when process exits' + ); + checkInvocations( + imd2, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'imd2: when process exits' + ); } diff --git a/test/async-hooks/test-nexttick-default-trigger.js b/test/async-hooks/test-nexttick-default-trigger.js index 1bc93f29737389..1559a7b3881ffc 100644 --- a/test/async-hooks/test-nexttick-default-trigger.js +++ b/test/async-hooks/test-nexttick-default-trigger.js @@ -14,15 +14,24 @@ hooks.enable(); const rootAsyncId = async_hooks.executionAsyncId(); -process.nextTick(common.mustCall(function() { - assert.strictEqual(async_hooks.triggerAsyncId(), rootAsyncId); -})); +process.nextTick( + common.mustCall(function() { + assert.strictEqual(async_hooks.triggerAsyncId(), rootAsyncId); + }) +); process.on('exit', function() { hooks.sanityCheck(); const as = hooks.activitiesOfTypes('TickObject'); - checkInvocations(as[0], { - init: 1, before: 1, after: 1, destroy: 1 - }, 'when process exits'); + checkInvocations( + as[0], + { + init: 1, + before: 1, + after: 1, + destroy: 1 + }, + 'when process exits' + ); }); diff --git a/test/async-hooks/test-no-assert-when-disabled.js b/test/async-hooks/test-no-assert-when-disabled.js index 70114d1e1140f8..c7ab6ca3efe45e 100644 --- a/test/async-hooks/test-no-assert-when-disabled.js +++ b/test/async-hooks/test-no-assert-when-disabled.js @@ -3,7 +3,7 @@ const common = require('../common'); if (!common.isMainThread) - common.skip('Workers don\'t inherit per-env state like the check flag'); + common.skip("Workers don't inherit per-env state like the check flag"); const async_hooks = require('internal/async_hooks'); diff --git a/test/async-hooks/test-pipeconnectwrap.js b/test/async-hooks/test-pipeconnectwrap.js index 6c68186e2f239f..d55039b08ebab7 100644 --- a/test/async-hooks/test-pipeconnectwrap.js +++ b/test/async-hooks/test-pipeconnectwrap.js @@ -17,11 +17,15 @@ let pipe1, pipe2; let pipeserver; let pipeconnect; -net.createServer(common.mustCall(function(c) { - c.end(); - this.close(); - process.nextTick(maybeOnconnect.bind(null, 'server')); -})).listen(common.PIPE, common.mustCall(onlisten)); +net + .createServer( + common.mustCall(function(c) { + c.end(); + this.close(); + process.nextTick(maybeOnconnect.bind(null, 'server')); + }) + ) + .listen(common.PIPE, common.mustCall(onlisten)); function onlisten() { const pipeservers = hooks.activitiesOfTypes('PIPESERVERWRAP'); @@ -29,8 +33,10 @@ function onlisten() { assert.strictEqual(pipeservers.length, 1); assert.strictEqual(pipeconnects.length, 0); - net.connect(common.PIPE, - common.mustCall(maybeOnconnect.bind(null, 'client'))); + net.connect( + common.PIPE, + common.mustCall(maybeOnconnect.bind(null, 'client')) + ); const pipes = hooks.activitiesOfTypes('PIPEWRAP'); pipeconnects = hooks.activitiesOfTypes('PIPECONNECTWRAP'); @@ -44,7 +50,7 @@ function onlisten() { assert.strictEqual(pipeserver.type, 'PIPESERVERWRAP'); assert.strictEqual(pipe1.type, 'PIPEWRAP'); assert.strictEqual(pipeconnect.type, 'PIPECONNECTWRAP'); - for (const a of [ pipeserver, pipe1, pipeconnect ]) { + for (const a of [pipeserver, pipe1, pipeconnect]) { assert.strictEqual(typeof a.uid, 'number'); assert.strictEqual(typeof a.triggerAsyncId, 'number'); checkInvocations(a, { init: 1 }, 'after net.connect'); @@ -68,11 +74,17 @@ function maybeOnconnect(source) { assert.strictEqual(typeof pipe2.uid, 'number'); assert.strictEqual(typeof pipe2.triggerAsyncId, 'number'); - checkInvocations(pipeserver, { init: 1, before: 1, after: 1 }, - 'pipeserver, client connected'); + checkInvocations( + pipeserver, + { init: 1, before: 1, after: 1 }, + 'pipeserver, client connected' + ); checkInvocations(pipe1, { init: 1 }, 'pipe1, client connected'); - checkInvocations(pipeconnect, { init: 1, before: 1 }, - 'pipeconnect, client connected'); + checkInvocations( + pipeconnect, + { init: 1, before: 1 }, + 'pipeconnect, client connected' + ); checkInvocations(pipe2, { init: 1 }, 'pipe2, client connected'); tick(5); } @@ -85,12 +97,24 @@ function onexit() { hooks.sanityCheck('PIPESERVERWRAP'); hooks.sanityCheck('PIPECONNECTWRAP'); // TODO(thlorenz) why have some of those 'before' and 'after' called twice - checkInvocations(pipeserver, { init: 1, before: 1, after: 1, destroy: 1 }, - 'pipeserver, process exiting'); - checkInvocations(pipe1, { init: 1, before: 2, after: 2, destroy: 1 }, - 'pipe1, process exiting'); - checkInvocations(pipeconnect, { init: 1, before: 1, after: 1, destroy: 1 }, - 'pipeconnect, process exiting'); - checkInvocations(pipe2, { init: 1, before: 2, after: 2, destroy: 1 }, - 'pipe2, process exiting'); + checkInvocations( + pipeserver, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'pipeserver, process exiting' + ); + checkInvocations( + pipe1, + { init: 1, before: 2, after: 2, destroy: 1 }, + 'pipe1, process exiting' + ); + checkInvocations( + pipeconnect, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'pipeconnect, process exiting' + ); + checkInvocations( + pipe2, + { init: 1, before: 2, after: 2, destroy: 1 }, + 'pipe2, process exiting' + ); } diff --git a/test/async-hooks/test-pipewrap.js b/test/async-hooks/test-pipewrap.js index a632115d228d64..51f66546a96c43 100644 --- a/test/async-hooks/test-pipewrap.js +++ b/test/async-hooks/test-pipewrap.js @@ -16,7 +16,7 @@ if (!common.isMainThread) const hooks = initHooks(); hooks.enable(); -const nodeVersionSpawn = spawn(process.execPath, [ '--version' ]); +const nodeVersionSpawn = spawn(process.execPath, ['--version']); nodeVersionSpawn .on('exit', common.mustCall(onsleepExit)) @@ -36,18 +36,24 @@ const pipe3 = pipes[2]; assert.strictEqual(processwrap.type, 'PROCESSWRAP'); assert.strictEqual(processwrap.triggerAsyncId, 1); -checkInvocations(processwrap, { init: 1 }, - 'processwrap when sleep.spawn was called'); +checkInvocations( + processwrap, + { init: 1 }, + 'processwrap when sleep.spawn was called' +); -[ pipe1, pipe2, pipe3 ].forEach((x) => { +[pipe1, pipe2, pipe3].forEach((x) => { assert.strictEqual(x.type, 'PIPEWRAP'); assert.strictEqual(x.triggerAsyncId, 1); checkInvocations(x, { init: 1 }, 'pipe wrap when sleep.spawn was called'); }); function onsleepExit() { - checkInvocations(processwrap, { init: 1, before: 1 }, - 'processwrap while in onsleepExit callback'); + checkInvocations( + processwrap, + { init: 1, before: 1 }, + 'processwrap while in onsleepExit callback' + ); } function onsleepClose() { @@ -55,7 +61,8 @@ function onsleepClose() { checkInvocations( processwrap, { init: 1, before: 1, after: 1 }, - 'processwrap while in onsleepClose callback') + 'processwrap while in onsleepClose callback' + ) ); } @@ -69,9 +76,10 @@ function onexit() { checkInvocations( processwrap, { init: 1, before: 1, after: 1 }, - 'processwrap while in onsleepClose callback'); + 'processwrap while in onsleepClose callback' + ); - [ pipe1, pipe2, pipe3 ].forEach((x) => { + [pipe1, pipe2, pipe3].forEach((x) => { assert.strictEqual(x.type, 'PIPEWRAP'); assert.strictEqual(x.triggerAsyncId, 1); }); @@ -81,10 +89,19 @@ function onexit() { // Usually it is just one event, but it can be more. assert.ok(ioEvents >= 3, `at least 3 stdout io events, got ${ioEvents}`); - checkInvocations(pipe1, { init: 1, before: 1, after: 1 }, - 'pipe wrap when sleep.spawn was called'); - checkInvocations(pipe2, { init: 1, before: ioEvents, after: ioEvents }, - 'pipe wrap when sleep.spawn was called'); - checkInvocations(pipe3, { init: 1, before: 2, after: 2 }, - 'pipe wrap when sleep.spawn was called'); + checkInvocations( + pipe1, + { init: 1, before: 1, after: 1 }, + 'pipe wrap when sleep.spawn was called' + ); + checkInvocations( + pipe2, + { init: 1, before: ioEvents, after: ioEvents }, + 'pipe wrap when sleep.spawn was called' + ); + checkInvocations( + pipe3, + { init: 1, before: 2, after: 2 }, + 'pipe wrap when sleep.spawn was called' + ); } diff --git a/test/async-hooks/test-promise.chain-promise-before-init-hooks.js b/test/async-hooks/test-promise.chain-promise-before-init-hooks.js index 9046bc3514abfc..83f5b0adafc9c5 100644 --- a/test/async-hooks/test-promise.chain-promise-before-init-hooks.js +++ b/test/async-hooks/test-promise.chain-promise-before-init-hooks.js @@ -8,9 +8,11 @@ const { checkInvocations } = require('./hook-checks'); if (!common.isMainThread) common.skip('Worker bootstrapping works differently -> different async IDs'); -const p = new Promise(common.mustCall(function executor(resolve, reject) { - resolve(5); -})); +const p = new Promise( + common.mustCall(function executor(resolve, reject) { + resolve(5); + }) +); p.then(function afterresolution(val) { assert.strictEqual(val, 5); @@ -22,7 +24,6 @@ const hooks = initHooks(); hooks._allowNoInit = true; hooks.enable(); - process.on('exit', function onexit() { hooks.disable(); hooks.sanityCheck('PROMISE'); diff --git a/test/async-hooks/test-promise.js b/test/async-hooks/test-promise.js index 729704b7928f7d..3b6e36e39bd868 100644 --- a/test/async-hooks/test-promise.js +++ b/test/async-hooks/test-promise.js @@ -13,7 +13,7 @@ const hooks = initHooks(); hooks.enable(); -const p = (new Promise(common.mustCall(executor))); +const p = new Promise(common.mustCall(executor)); p.then(afterresolution); function executor(resolve, reject) { @@ -29,8 +29,11 @@ function afterresolution(val) { const as = hooks.activitiesOfTypes('PROMISE'); assert.strictEqual(as.length, 2); checkInvocations(as[0], { init: 1 }, 'after resolution parent promise'); - checkInvocations(as[1], { init: 1, before: 1 }, - 'after resolution child promise'); + checkInvocations( + as[1], + { init: 1, before: 1 }, + 'after resolution child promise' + ); } process.on('exit', onexit); diff --git a/test/async-hooks/test-promise.promise-before-init-hooks.js b/test/async-hooks/test-promise.promise-before-init-hooks.js index 957d1a75e49f70..1950f27235d835 100644 --- a/test/async-hooks/test-promise.promise-before-init-hooks.js +++ b/test/async-hooks/test-promise.promise-before-init-hooks.js @@ -5,9 +5,11 @@ const assert = require('assert'); const initHooks = require('./init-hooks'); const { checkInvocations } = require('./hook-checks'); -const p = new Promise(common.mustCall(function executor(resolve, reject) { - resolve(5); -})); +const p = new Promise( + common.mustCall(function executor(resolve, reject) { + resolve(5); + }) +); // init hooks after promise was created const hooks = initHooks({ allowNoInit: true }); @@ -17,8 +19,11 @@ p.then(function afterresolution(val) { assert.strictEqual(val, 5); const as = hooks.activitiesOfTypes('PROMISE'); assert.strictEqual(as.length, 1); - checkInvocations(as[0], { init: 1, before: 1 }, - 'after resolution child promise'); + checkInvocations( + as[0], + { init: 1, before: 1 }, + 'after resolution child promise' + ); return val; }); diff --git a/test/async-hooks/test-querywrap.js b/test/async-hooks/test-querywrap.js index f6e7e12e81e9c0..9c73bfb3ddcc90 100644 --- a/test/async-hooks/test-querywrap.js +++ b/test/async-hooks/test-querywrap.js @@ -19,7 +19,7 @@ function onresolved() { const a = as[0]; assert.strictEqual(as.length, 1); checkInvocations(a, { init: 1, before: 1 }, 'while in onresolved callback'); - tick(1E4); + tick(1e4); } process.on('exit', onexit); @@ -35,6 +35,9 @@ function onexit() { assert.strictEqual(a.type, 'QUERYWRAP'); assert.strictEqual(typeof a.uid, 'number'); assert.strictEqual(typeof a.triggerAsyncId, 'number'); - checkInvocations(a, { init: 1, before: 1, after: 1, destroy: 1 }, - 'when process exits'); + checkInvocations( + a, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'when process exits' + ); } diff --git a/test/async-hooks/test-queue-microtask.js b/test/async-hooks/test-queue-microtask.js index dfa537752e37fc..a881026c63b4dd 100644 --- a/test/async-hooks/test-queue-microtask.js +++ b/test/async-hooks/test-queue-microtask.js @@ -11,15 +11,24 @@ hooks.enable(); const rootAsyncId = async_hooks.executionAsyncId(); -queueMicrotask(common.mustCall(function() { - assert.strictEqual(async_hooks.triggerAsyncId(), rootAsyncId); -})); +queueMicrotask( + common.mustCall(function() { + assert.strictEqual(async_hooks.triggerAsyncId(), rootAsyncId); + }) +); process.on('exit', function() { hooks.sanityCheck(); const as = hooks.activitiesOfTypes('Microtask'); - checkInvocations(as[0], { - init: 1, before: 1, after: 1, destroy: 1 - }, 'when process exits'); + checkInvocations( + as[0], + { + init: 1, + before: 1, + after: 1, + destroy: 1 + }, + 'when process exits' + ); }); diff --git a/test/async-hooks/test-shutdownwrap.js b/test/async-hooks/test-shutdownwrap.js index fea4a3a166a270..cf18b489541c8a 100644 --- a/test/async-hooks/test-shutdownwrap.js +++ b/test/async-hooks/test-shutdownwrap.js @@ -15,7 +15,10 @@ const server = net .on('listening', common.mustCall(onlistening)); server.listen(); function onlistening() { - net.connect(server.address().port, common.mustCall(onconnected)); + net.connect( + server.address().port, + common.mustCall(onconnected) + ); } // It is non-deterministic in which order onconnection and onconnected fire. @@ -36,7 +39,6 @@ function onconnection(c) { function onconnected() { if (endedConnection) { assert.strictEqual(hooks.activitiesOfTypes('SHUTDOWNWRAP').length, 1); - } else { assert.strictEqual(hooks.activitiesOfTypes('SHUTDOWNWRAP').length, 0); } @@ -44,8 +46,11 @@ function onconnected() { function onserverClosed() { const as = hooks.activitiesOfTypes('SHUTDOWNWRAP'); - checkInvocations(as[0], { init: 1, before: 1, after: 1, destroy: 1 }, - 'when server closed'); + checkInvocations( + as[0], + { init: 1, before: 1, after: 1, destroy: 1 }, + 'when server closed' + ); } process.on('exit', onexit); @@ -58,6 +63,9 @@ function onexit() { assert.strictEqual(a.type, 'SHUTDOWNWRAP'); assert.strictEqual(typeof a.uid, 'number'); assert.strictEqual(typeof a.triggerAsyncId, 'number'); - checkInvocations(as[0], { init: 1, before: 1, after: 1, destroy: 1 }, - 'when process exits'); + checkInvocations( + as[0], + { init: 1, before: 1, after: 1, destroy: 1 }, + 'when process exits' + ); } diff --git a/test/async-hooks/test-signalwrap.js b/test/async-hooks/test-signalwrap.js index c94d763450ab24..43a96c2ad57c74 100644 --- a/test/async-hooks/test-signalwrap.js +++ b/test/async-hooks/test-signalwrap.js @@ -1,8 +1,7 @@ 'use strict'; const common = require('../common'); -if (common.isWindows) - common.skip('no signals in Windows'); +if (common.isWindows) common.skip('no signals in Windows'); if (!common.isMainThread) common.skip('No signal handling available in Workers'); @@ -39,16 +38,20 @@ function onsigusr2() { if (count === 1) { // first invocation checkInvocations( - signal1, { init: 1, before: 1 }, - ' signal1: when first SIGUSR2 handler is called for the first time'); + signal1, + { init: 1, before: 1 }, + ' signal1: when first SIGUSR2 handler is called for the first time' + ); // trigger same signal handler again exec(`kill -USR2 ${process.pid}`); } else { // second invocation checkInvocations( - signal1, { init: 1, before: 2, after: 1 }, - 'signal1: when first SIGUSR2 handler is called for the second time'); + signal1, + { init: 1, before: 2, after: 1 }, + 'signal1: when first SIGUSR2 handler is called for the second time' + ); // install another signal handler process.removeAllListeners('SIGUSR2'); @@ -62,11 +65,15 @@ function onsigusr2() { assert.strictEqual(typeof signal2.triggerAsyncId, 'number'); checkInvocations( - signal1, { init: 1, before: 2, after: 1 }, - 'signal1: when second SIGUSR2 handler is set up'); + signal1, + { init: 1, before: 2, after: 1 }, + 'signal1: when second SIGUSR2 handler is set up' + ); checkInvocations( - signal2, { init: 1 }, - 'signal2: when second SIGUSR2 handler is setup'); + signal2, + { init: 1 }, + 'signal2: when second SIGUSR2 handler is setup' + ); exec(`kill -USR2 ${process.pid}`); } @@ -76,11 +83,15 @@ function onsigusr2Again() { clearInterval(interval); setImmediate(() => { checkInvocations( - signal1, { init: 1, before: 2, after: 2, destroy: 1 }, - 'signal1: when second SIGUSR2 handler is called'); + signal1, + { init: 1, before: 2, after: 2, destroy: 1 }, + 'signal1: when second SIGUSR2 handler is called' + ); checkInvocations( - signal2, { init: 1, before: 1 }, - 'signal2: when second SIGUSR2 handler is called'); + signal2, + { init: 1, before: 1 }, + 'signal2: when second SIGUSR2 handler is called' + ); }); } @@ -90,10 +101,14 @@ function onexit() { hooks.disable(); hooks.sanityCheck('SIGNALWRAP'); checkInvocations( - signal1, { init: 1, before: 2, after: 2, destroy: 1 }, - 'signal1: when second SIGUSR2 process exits'); + signal1, + { init: 1, before: 2, after: 2, destroy: 1 }, + 'signal1: when second SIGUSR2 process exits' + ); // second signal not destroyed yet since its event listener is still active checkInvocations( - signal2, { init: 1, before: 1, after: 1 }, - 'signal2: when second SIGUSR2 process exits'); + signal2, + { init: 1, before: 1, after: 1 }, + 'signal2: when second SIGUSR2 process exits' + ); } diff --git a/test/async-hooks/test-statwatcher.js b/test/async-hooks/test-statwatcher.js index 92832a46803bd4..e0bbd793895555 100644 --- a/test/async-hooks/test-statwatcher.js +++ b/test/async-hooks/test-statwatcher.js @@ -32,8 +32,11 @@ const statwatcher1 = as[0]; assert.strictEqual(statwatcher1.type, 'STATWATCHER'); assert.strictEqual(typeof statwatcher1.uid, 'number'); assert.strictEqual(statwatcher1.triggerAsyncId, 1); -checkInvocations(statwatcher1, { init: 1 }, - 'watcher1: when started to watch file'); +checkInvocations( + statwatcher1, + { init: 1 }, + 'watcher1: when started to watch file' +); // install second file watcher const w2 = fs.watchFile(file2, { interval: 10 }, onchange); @@ -44,42 +47,73 @@ const statwatcher2 = as[1]; assert.strictEqual(statwatcher2.type, 'STATWATCHER'); assert.strictEqual(typeof statwatcher2.uid, 'number'); assert.strictEqual(statwatcher2.triggerAsyncId, 1); -checkInvocations(statwatcher1, { init: 1 }, - 'watcher1: when started to watch second file'); -checkInvocations(statwatcher2, { init: 1 }, - 'watcher2: when started to watch second file'); +checkInvocations( + statwatcher1, + { init: 1 }, + 'watcher1: when started to watch second file' +); +checkInvocations( + statwatcher2, + { init: 1 }, + 'watcher2: when started to watch second file' +); -setTimeout(() => fs.writeFileSync(file1, 'foo++'), - common.platformTimeout(100)); -w1.once('change', common.mustCall(() => { - setImmediate(() => { - checkInvocations(statwatcher1, { init: 1, before: 1, after: 1 }, - 'watcher1: when unwatched first file'); - checkInvocations(statwatcher2, { init: 1 }, - 'watcher2: when unwatched first file'); +setTimeout(() => fs.writeFileSync(file1, 'foo++'), common.platformTimeout(100)); +w1.once( + 'change', + common.mustCall(() => { + setImmediate(() => { + checkInvocations( + statwatcher1, + { init: 1, before: 1, after: 1 }, + 'watcher1: when unwatched first file' + ); + checkInvocations( + statwatcher2, + { init: 1 }, + 'watcher2: when unwatched first file' + ); - setTimeout(() => fs.writeFileSync(file2, 'bar++'), - common.platformTimeout(100)); - w2.once('change', common.mustCall(() => { - setImmediate(() => { - checkInvocations(statwatcher1, { init: 1, before: 1, after: 1 }, - 'watcher1: when unwatched second file'); - checkInvocations(statwatcher2, { init: 1, before: 1, after: 1 }, - 'watcher2: when unwatched second file'); - fs.unwatchFile(file1); - fs.unwatchFile(file2); - }); - })); - }); -})); + setTimeout( + () => fs.writeFileSync(file2, 'bar++'), + common.platformTimeout(100) + ); + w2.once( + 'change', + common.mustCall(() => { + setImmediate(() => { + checkInvocations( + statwatcher1, + { init: 1, before: 1, after: 1 }, + 'watcher1: when unwatched second file' + ); + checkInvocations( + statwatcher2, + { init: 1, before: 1, after: 1 }, + 'watcher2: when unwatched second file' + ); + fs.unwatchFile(file1); + fs.unwatchFile(file2); + }); + }) + ); + }); + }) +); process.on('exit', onexit); function onexit() { hooks.disable(); hooks.sanityCheck('STATWATCHER'); - checkInvocations(statwatcher1, { init: 1, before: 1, after: 1 }, - 'watcher1: when process exits'); - checkInvocations(statwatcher2, { init: 1, before: 1, after: 1 }, - 'watcher2: when process exits'); + checkInvocations( + statwatcher1, + { init: 1, before: 1, after: 1 }, + 'watcher1: when process exits' + ); + checkInvocations( + statwatcher2, + { init: 1, before: 1, after: 1 }, + 'watcher2: when process exits' + ); } diff --git a/test/async-hooks/test-tcpwrap.js b/test/async-hooks/test-tcpwrap.js index a01a1fc4fe21d4..721aa89295ccf6 100644 --- a/test/async-hooks/test-tcpwrap.js +++ b/test/async-hooks/test-tcpwrap.js @@ -2,8 +2,7 @@ 'use strict'; const common = require('../common'); -if (!common.hasIPv6) - common.skip('IPv6 support required'); +if (!common.hasIPv6) common.skip('IPv6 support required'); const assert = require('assert'); const tick = require('../common/tick'); @@ -40,7 +39,8 @@ const server = net { net.connect( { port: server.address().port, host: '::1' }, - common.mustCall(onconnected)); + common.mustCall(onconnected) + ); const tcps = hooks.activitiesOfTypes('TCPWRAP'); assert.strictEqual(tcps.length, 1); process.nextTick(() => { @@ -54,8 +54,11 @@ const server = net assert.strictEqual(typeof tcp1.uid, 'number'); assert.strictEqual(typeof tcp1.triggerAsyncId, 'number'); - checkInvocations(tcpserver, { init: 1 }, - 'tcpserver when client is connecting'); + checkInvocations( + tcpserver, + { init: 1 }, + 'tcpserver when client is connecting' + ); checkInvocations(tcp1, { init: 1 }, 'tcp1 when client is connecting'); } @@ -70,12 +73,14 @@ function ontcpConnection(serverConnection) { if (tcpconnect != null) { // When client receives connection first ('onconnected') and the server // second then we see an 'after' here, otherwise not - const expected = serverConnection ? - { init: 1, before: 1, after: 1 } : - { init: 1, before: 1 }; + const expected = serverConnection + ? { init: 1, before: 1, after: 1 } + : { init: 1, before: 1 }; checkInvocations( - tcpconnect, expected, - 'tcpconnect: when both client and server received connection'); + tcpconnect, + expected, + 'tcpconnect: when both client and server received connection' + ); return; } @@ -89,8 +94,11 @@ function ontcpConnection(serverConnection) { // When client receives connection first ('onconnected'), we 'before' has // been invoked at this point already, otherwise it only was 'init'ed const expected = serverConnection ? { init: 1 } : { init: 1, before: 1 }; - checkInvocations(tcpconnect, expected, - 'tcpconnect: when tcp connection is established'); + checkInvocations( + tcpconnect, + expected, + 'tcpconnect: when tcp connection is established' + ); } let serverConnected = false; @@ -98,9 +106,9 @@ function onconnected() { ontcpConnection(false); // In the case that the client connects before the server TCPWRAP 'before' // and 'after' weren't invoked yet. Also @see ontcpConnection. - const expected = serverConnected ? - { init: 1, before: 1, after: 1 } : - { init: 1 }; + const expected = serverConnected + ? { init: 1, before: 1, after: 1 } + : { init: 1 }; checkInvocations(tcpserver, expected, 'tcpserver when client connects'); checkInvocations(tcp1, { init: 1 }, 'tcp1 when client connects'); } @@ -109,7 +117,7 @@ function onconnection(c) { serverConnected = true; ontcpConnection(true); - const tcps = hooks.activitiesOfTypes([ 'TCPWRAP' ]); + const tcps = hooks.activitiesOfTypes(['TCPWRAP']); const tcpconnects = hooks.activitiesOfTypes('TCPCONNECTWRAP'); assert.strictEqual(tcps.length, 2); assert.strictEqual(tcpconnects.length, 1); @@ -118,8 +126,11 @@ function onconnection(c) { assert.strictEqual(typeof tcp2.uid, 'number'); assert.strictEqual(typeof tcp2.triggerAsyncId, 'number'); - checkInvocations(tcpserver, { init: 1, before: 1 }, - 'tcpserver when server receives connection'); + checkInvocations( + tcpserver, + { init: 1, before: 1 }, + 'tcpserver when server receives connection' + ); checkInvocations(tcp1, { init: 1 }, 'tcp1 when server receives connection'); checkInvocations(tcp2, { init: 1 }, 'tcp2 when server receives connection'); @@ -128,20 +139,35 @@ function onconnection(c) { } function onserverClosed() { - checkInvocations(tcpserver, { init: 1, before: 1, after: 1, destroy: 1 }, - 'tcpserver when server is closed'); + checkInvocations( + tcpserver, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'tcpserver when server is closed' + ); setImmediate(() => { - checkInvocations(tcp1, { init: 1, before: 2, after: 2, destroy: 1 }, - 'tcp1 after server is closed'); + checkInvocations( + tcp1, + { init: 1, before: 2, after: 2, destroy: 1 }, + 'tcp1 after server is closed' + ); }); - checkInvocations(tcp2, { init: 1, before: 1, after: 1 }, - 'tcp2 synchronously when server is closed'); + checkInvocations( + tcp2, + { init: 1, before: 1, after: 1 }, + 'tcp2 synchronously when server is closed' + ); tick(2, () => { - checkInvocations(tcp2, { init: 1, before: 2, after: 2, destroy: 1 }, - 'tcp2 when server is closed'); - checkInvocations(tcpconnect, { init: 1, before: 1, after: 1, destroy: 1 }, - 'tcpconnect when server is closed'); + checkInvocations( + tcp2, + { init: 1, before: 2, after: 2, destroy: 1 }, + 'tcp2 when server is closed' + ); + checkInvocations( + tcpconnect, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'tcpconnect when server is closed' + ); }); } @@ -149,17 +175,26 @@ process.on('exit', onexit); function onexit() { hooks.disable(); - hooks.sanityCheck([ 'TCPWRAP', 'TCPSERVERWRAP', 'TCPCONNECTWRAP' ]); + hooks.sanityCheck(['TCPWRAP', 'TCPSERVERWRAP', 'TCPCONNECTWRAP']); - checkInvocations(tcpserver, { init: 1, before: 1, after: 1, destroy: 1 }, - 'tcpserver when process exits'); checkInvocations( - tcp1, { init: 1, before: 2, after: 2, destroy: 1 }, - 'tcp1 when process exits'); + tcpserver, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'tcpserver when process exits' + ); + checkInvocations( + tcp1, + { init: 1, before: 2, after: 2, destroy: 1 }, + 'tcp1 when process exits' + ); checkInvocations( - tcp2, { init: 1, before: 2, after: 2, destroy: 1 }, - 'tcp2 when process exits'); + tcp2, + { init: 1, before: 2, after: 2, destroy: 1 }, + 'tcp2 when process exits' + ); checkInvocations( - tcpconnect, { init: 1, before: 1, after: 1, destroy: 1 }, - 'tcpconnect when process exits'); + tcpconnect, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'tcpconnect when process exits' + ); } diff --git a/test/async-hooks/test-timers.setInterval.js b/test/async-hooks/test-timers.setInterval.js index 10b2bafb2a2598..3b05dbf9347459 100644 --- a/test/async-hooks/test-timers.setInterval.js +++ b/test/async-hooks/test-timers.setInterval.js @@ -23,8 +23,11 @@ function ontimeout() { if (iter === 0) { checkInvocations(t1, { init: 1, before: 1 }, 't1: when first timer fired'); } else { - checkInvocations(t1, { init: 1, before: 2, after: 1 }, - 't1: when first interval fired again'); + checkInvocations( + t1, + { init: 1, before: 2, after: 1 }, + 't1: when first interval fired again' + ); clearInterval(interval); return; } @@ -33,14 +36,20 @@ function ontimeout() { throw new Error('setInterval Error'); } -process.once('uncaughtException', common.mustCall((err) => { - assert.strictEqual(err.message, 'setInterval Error'); -})); +process.once( + 'uncaughtException', + common.mustCall((err) => { + assert.strictEqual(err.message, 'setInterval Error'); + }) +); process.on('exit', () => { hooks.disable(); hooks.sanityCheck('Timeout'); - checkInvocations(t1, { init: 1, before: 2, after: 2, destroy: 1 }, - 't1: when process exits'); + checkInvocations( + t1, + { init: 1, before: 2, after: 2, destroy: 1 }, + 't1: when process exits' + ); }); diff --git a/test/async-hooks/test-timers.setTimeout.js b/test/async-hooks/test-timers.setTimeout.js index 748fa5565eee64..69056f3307a10c 100644 --- a/test/async-hooks/test-timers.setTimeout.js +++ b/test/async-hooks/test-timers.setTimeout.js @@ -29,10 +29,12 @@ function ontimeout() { const as = hooks.activitiesOfTypes('Timeout'); t2 = as[1]; assert.strictEqual(as.length, 2); - checkInvocations(t1, { init: 1, before: 1 }, - 't1: when second timer installed'); - checkInvocations(t2, { init: 1 }, - 't2: when second timer installed'); + checkInvocations( + t1, + { init: 1, before: 1 }, + 't1: when second timer installed' + ); + checkInvocations(t2, { init: 1 }, 't2: when second timer installed'); timer = setTimeout(common.mustNotCall(), 2 ** 31 - 1); } @@ -40,10 +42,12 @@ function ontimeout() { function onSecondTimeout() { const as = hooks.activitiesOfTypes('Timeout'); assert.strictEqual(as.length, 3); - checkInvocations(t1, { init: 1, before: 1, after: 1 }, - 't1: when second timer fired'); - checkInvocations(t2, { init: 1, before: 1 }, - 't2: when second timer fired'); + checkInvocations( + t1, + { init: 1, before: 1, after: 1 }, + 't1: when second timer fired' + ); + checkInvocations(t2, { init: 1, before: 1 }, 't2: when second timer fired'); clearTimeout(timer); tick(2); } @@ -54,8 +58,14 @@ function onexit() { hooks.disable(); hooks.sanityCheck('Timeout'); - checkInvocations(t1, { init: 1, before: 1, after: 1, destroy: 1 }, - 't1: when process exits'); - checkInvocations(t2, { init: 1, before: 1, after: 1, destroy: 1 }, - 't2: when process exits'); + checkInvocations( + t1, + { init: 1, before: 1, after: 1, destroy: 1 }, + 't1: when process exits' + ); + checkInvocations( + t2, + { init: 1, before: 1, after: 1, destroy: 1 }, + 't2: when process exits' + ); } diff --git a/test/async-hooks/test-tlswrap.js b/test/async-hooks/test-tlswrap.js index 354cd7ad0cd91d..6ca5f47a929393 100644 --- a/test/async-hooks/test-tlswrap.js +++ b/test/async-hooks/test-tlswrap.js @@ -1,8 +1,7 @@ 'use strict'; const common = require('../common'); -if (!common.hasCrypto) - common.skip('missing crypto'); +if (!common.hasCrypto) common.skip('missing crypto'); const assert = require('assert'); const fixtures = require('../common/fixtures'); @@ -33,7 +32,10 @@ function onlistening() { // Creating client and connecting it to server // tls - .connect(server.address().port, { rejectUnauthorized: false }) + .connect( + server.address().port, + { rejectUnauthorized: false } + ) .on('secureConnect', common.mustCall(onsecureConnect)); const as = hooks.activitiesOfTypes('TLSWRAP'); @@ -59,35 +61,56 @@ function onsecureConnection() { // TODO(thlorenz) which callback did the server wrap execute that already // finished as well? - checkInvocations(svr, { init: 1, before: 1, after: 1 }, - 'server: when server has secure connection'); - - checkInvocations(client, { init: 1, before: 2, after: 1 }, - 'client: when server has secure connection'); + checkInvocations( + svr, + { init: 1, before: 1, after: 1 }, + 'server: when server has secure connection' + ); + + checkInvocations( + client, + { init: 1, before: 2, after: 1 }, + 'client: when server has secure connection' + ); } function onsecureConnect() { // // Client connected to server // - checkInvocations(svr, { init: 1, before: 2, after: 1 }, - 'server: when client connected'); - checkInvocations(client, { init: 1, before: 2, after: 2 }, - 'client: when client connected'); + checkInvocations( + svr, + { init: 1, before: 2, after: 1 }, + 'server: when client connected' + ); + checkInvocations( + client, + { init: 1, before: 2, after: 2 }, + 'client: when client connected' + ); // // Destroying client socket // this.destroy(); - checkInvocations(svr, { init: 1, before: 2, after: 1 }, - 'server: when destroying client'); - checkInvocations(client, { init: 1, before: 2, after: 2 }, - 'client: when destroying client'); + checkInvocations( + svr, + { init: 1, before: 2, after: 1 }, + 'server: when destroying client' + ); + checkInvocations( + client, + { init: 1, before: 2, after: 2 }, + 'client: when destroying client' + ); tick(5, tick1); function tick1() { - checkInvocations(svr, { init: 1, before: 2, after: 2 }, - 'server: when client destroyed'); + checkInvocations( + svr, + { init: 1, before: 2, after: 2 }, + 'server: when client destroyed' + ); // TODO: why is client not destroyed here even after 5 ticks? // or could it be that it isn't actually destroyed until // the server is closed? @@ -95,17 +118,26 @@ function onsecureConnect() { tick(5, tick1); return; } - checkInvocations(client, { init: 1, before: 3, after: 3 }, - 'client: when client destroyed'); + checkInvocations( + client, + { init: 1, before: 3, after: 3 }, + 'client: when client destroyed' + ); // // Closing server // server.close(common.mustCall(onserverClosed)); // No changes to invocations until server actually closed below - checkInvocations(svr, { init: 1, before: 2, after: 2 }, - 'server: when closing server'); - checkInvocations(client, { init: 1, before: 3, after: 3 }, - 'client: when closing server'); + checkInvocations( + svr, + { init: 1, before: 2, after: 2 }, + 'server: when closing server' + ); + checkInvocations( + client, + { init: 1, before: 3, after: 3 }, + 'client: when closing server' + ); } } @@ -113,12 +145,21 @@ function onserverClosed() { // // Server closed // - tick(1E4, common.mustCall(() => { - checkInvocations(svr, { init: 1, before: 2, after: 2 }, - 'server: when server closed'); - checkInvocations(client, { init: 1, before: 3, after: 3 }, - 'client: when server closed'); - })); + tick( + 1e4, + common.mustCall(() => { + checkInvocations( + svr, + { init: 1, before: 2, after: 2 }, + 'server: when server closed' + ); + checkInvocations( + client, + { init: 1, before: 3, after: 3 }, + 'client: when server closed' + ); + }) + ); } process.on('exit', onexit); @@ -127,8 +168,14 @@ function onexit() { hooks.disable(); hooks.sanityCheck('TLSWRAP'); - checkInvocations(svr, { init: 1, before: 2, after: 2 }, - 'server: when process exits'); - checkInvocations(client, { init: 1, before: 3, after: 3 }, - 'client: when process exits'); + checkInvocations( + svr, + { init: 1, before: 2, after: 2 }, + 'server: when process exits' + ); + checkInvocations( + client, + { init: 1, before: 3, after: 3 }, + 'client: when process exits' + ); } diff --git a/test/async-hooks/test-ttywrap.readstream.js b/test/async-hooks/test-ttywrap.readstream.js index bf81a3266c1fb6..d11ccac713ea65 100644 --- a/test/async-hooks/test-ttywrap.readstream.js +++ b/test/async-hooks/test-ttywrap.readstream.js @@ -11,8 +11,7 @@ const { checkInvocations } = require('./hook-checks'); const hooks = initHooks(); hooks.enable(); -if (!process.stdin.isTTY) - return common.skip('no valid readable TTY available'); +if (!process.stdin.isTTY) return common.skip('no valid readable TTY available'); // test specific setup const checkInitOpts = { init: 1 }; @@ -34,9 +33,10 @@ const delayedOnCloseHandler = common.mustCall(() => { checkInvocations(tty, checkEndedOpts, 'when tty ended'); }); process.stdin.on('error', (err) => assert.fail(err)); -process.stdin.on('close', common.mustCall(() => - tick(2, delayedOnCloseHandler) -)); +process.stdin.on( + 'close', + common.mustCall(() => tick(2, delayedOnCloseHandler)) +); process.stdin.destroy(); checkInvocations(tty, checkInitOpts, 'when tty.end() was invoked'); diff --git a/test/async-hooks/test-ttywrap.writestream.js b/test/async-hooks/test-ttywrap.writestream.js index 44f32e80f015c2..06215c7b649a06 100644 --- a/test/async-hooks/test-ttywrap.writestream.js +++ b/test/async-hooks/test-ttywrap.writestream.js @@ -34,9 +34,10 @@ const delayedOnCloseHandler = common.mustCall(() => { checkInvocations(tty, checkEndedOpts, 'when tty ended'); }); process.stdout.on('error', (err) => assert.fail(err)); -process.stdout.on('close', common.mustCall(() => - tick(2, delayedOnCloseHandler) -)); +process.stdout.on( + 'close', + common.mustCall(() => tick(2, delayedOnCloseHandler)) +); process.stdout.destroy(); checkInvocations(tty, checkInitOpts, 'when tty.end() was invoked'); diff --git a/test/async-hooks/test-udpsendwrap.js b/test/async-hooks/test-udpsendwrap.js index d8ab77730f4921..6a46ed5f2e44a4 100644 --- a/test/async-hooks/test-udpsendwrap.js +++ b/test/async-hooks/test-udpsendwrap.js @@ -18,8 +18,13 @@ const sock = dgram function onlistening() { sock.send( - Buffer.alloc(2), 0, 2, sock.address().port, - undefined, common.mustCall(onsent)); + Buffer.alloc(2), + 0, + 2, + sock.address().port, + undefined, + common.mustCall(onsent) + ); // init not called synchronously because dns lookup always wraps // callback in a next tick even if no lookup is needed @@ -50,6 +55,9 @@ process.on('exit', onexit); function onexit() { hooks.disable(); hooks.sanityCheck('UDPSENDWRAP'); - checkInvocations(send, { init: 1, before: 1, after: 1, destroy: 1 }, - 'when process exits'); + checkInvocations( + send, + { init: 1, before: 1, after: 1, destroy: 1 }, + 'when process exits' + ); } diff --git a/test/async-hooks/test-udpwrap.js b/test/async-hooks/test-udpwrap.js index 0a0e03c5d5148d..0a0d87ebd490b4 100644 --- a/test/async-hooks/test-udpwrap.js +++ b/test/async-hooks/test-udpwrap.js @@ -32,6 +32,5 @@ process.on('exit', onexit); function onexit() { hooks.disable(); hooks.sanityCheck('UDPWRAP'); - checkInvocations(udpwrap, { init: 1, destroy: 1 }, - 'when process exits'); + checkInvocations(udpwrap, { init: 1, destroy: 1 }, 'when process exits'); } diff --git a/test/async-hooks/test-writewrap.js b/test/async-hooks/test-writewrap.js index 4f3455480ba849..69137c26dcc736 100644 --- a/test/async-hooks/test-writewrap.js +++ b/test/async-hooks/test-writewrap.js @@ -12,7 +12,8 @@ hooks.enable(); // // Creating server and listening on port // -const server = net.createServer() +const server = net + .createServer() .on('listening', common.mustCall(onlistening)) .on('connection', common.mustCall(onconnection)) .listen(0); @@ -24,17 +25,18 @@ function onlistening() { // // Creating client and connecting it to server // - net - .connect(server.address().port) - .on('connect', common.mustCall(onconnect)); + net.connect(server.address().port).on('connect', common.mustCall(onconnect)); assert.strictEqual(hooks.activitiesOfTypes('WRITEWRAP').length, 0); } function checkDestroyedWriteWraps(n, stage) { const as = hooks.activitiesOfTypes('WRITEWRAP'); - assert.strictEqual(as.length, n, - `${as.length} out of ${n} WRITEWRAPs when ${stage}`); + assert.strictEqual( + as.length, + n, + `${as.length} out of ${n} WRITEWRAPs when ${stage}` + ); function checkValidWriteWrap(w) { assert.strictEqual(w.type, 'WRITEWRAP'); @@ -47,7 +49,7 @@ function checkDestroyedWriteWraps(n, stage) { } function onconnection(conn) { - conn.write('hi'); // Let the client know we're ready. + conn.write('hi'); // Let the client know we're ready. conn.resume(); // // Server received client connection diff --git a/test/async-hooks/test-zlib.zlib-binding.deflate.js b/test/async-hooks/test-zlib.zlib-binding.deflate.js index 972052b2d570a5..48d39726186429 100644 --- a/test/async-hooks/test-zlib.zlib-binding.deflate.js +++ b/test/async-hooks/test-zlib.zlib-binding.deflate.js @@ -38,7 +38,9 @@ handle.init( constants.Z_DEFAULT_MEMLEVEL, constants.Z_DEFAULT_STRATEGY, buffers.writeResult, - function processCallback() { this.cb(); }, + function processCallback() { + this.cb(); + }, buffers.dictionary ); checkInvocations(hdl, { init: 1 }, 'when initialized handle'); @@ -51,13 +53,19 @@ checkInvocations(hdl, { init: 1 }, 'when invoked write() on handle'); function onwritten() { if (--count) { // first write - checkInvocations(hdl, { init: 1, before: 1 }, - 'when wrote to handle the first time'); + checkInvocations( + hdl, + { init: 1, before: 1 }, + 'when wrote to handle the first time' + ); handle.write(true, buffers.inBuf, 0, 1, buffers.outBuf, 0, 1); } else { // second write - checkInvocations(hdl, { init: 1, before: 2, after: 1 }, - 'when wrote to handle the second time'); + checkInvocations( + hdl, + { init: 1, before: 2, after: 1 }, + 'when wrote to handle the second time' + ); } } diff --git a/test/async-hooks/verify-graph.js b/test/async-hooks/verify-graph.js index 95c55c15958b2c..ae148e6f21734d 100644 --- a/test/async-hooks/verify-graph.js +++ b/test/async-hooks/verify-graph.js @@ -82,7 +82,7 @@ module.exports = function verifyGraph(hooks, graph) { errors.forEach((x) => console.error( `'${x.id}' expected to be triggered by '${x.expectedTid}', ` + - `but was triggered by '${x.actualTid}' instead.` + `but was triggered by '${x.actualTid}' instead.` ) ); } diff --git a/test/benchmark/test-benchmark-assert.js b/test/benchmark/test-benchmark-assert.js index 8a8ba0244489e5..dc2f9083957091 100644 --- a/test/benchmark/test-benchmark-assert.js +++ b/test/benchmark/test-benchmark-assert.js @@ -7,15 +7,12 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark( - 'assert', - [ - 'strict=1', - 'len=1', - 'method=', - 'n=1', - 'primitive=null', - 'size=1', - 'type=Int8Array' - ] -); +runBenchmark('assert', [ + 'strict=1', + 'len=1', + 'method=', + 'n=1', + 'primitive=null', + 'size=1', + 'type=Int8Array' +]); diff --git a/test/benchmark/test-benchmark-async-hooks.js b/test/benchmark/test-benchmark-async-hooks.js index 4cb6f89a8c70e3..4df5ace627a555 100644 --- a/test/benchmark/test-benchmark-async-hooks.js +++ b/test/benchmark/test-benchmark-async-hooks.js @@ -2,17 +2,11 @@ const common = require('../common'); -if (!common.hasCrypto) - common.skip('missing crypto'); +if (!common.hasCrypto) common.skip('missing crypto'); if (!common.enoughTestMem) common.skip('Insufficient memory for async_hooks benchmark test'); const runBenchmark = require('../common/benchmark'); -runBenchmark('async_hooks', - [ - 'method=trackingDisabled', - 'n=10' - ], - {}); +runBenchmark('async_hooks', ['method=trackingDisabled', 'n=10'], {}); diff --git a/test/benchmark/test-benchmark-buffer.js b/test/benchmark/test-benchmark-buffer.js index 171f755647d21f..3171220aa9ec21 100644 --- a/test/benchmark/test-benchmark-buffer.js +++ b/test/benchmark/test-benchmark-buffer.js @@ -4,26 +4,28 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('buffers', - [ - 'aligned=true', - 'args=1', - 'buffer=fast', - 'byteLength=1', - 'charsPerLine=6', - 'encoding=utf8', - 'endian=BE', - 'len=2', - 'linesCount=1', - 'method=', - 'n=1', - 'pieces=1', - 'pieceSize=1', - 'search=@', - 'size=1', - 'source=array', - 'type=', - 'value=0', - 'withTotalLength=0' - ], - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark( + 'buffers', + [ + 'aligned=true', + 'args=1', + 'buffer=fast', + 'byteLength=1', + 'charsPerLine=6', + 'encoding=utf8', + 'endian=BE', + 'len=2', + 'linesCount=1', + 'method=', + 'n=1', + 'pieces=1', + 'pieceSize=1', + 'search=@', + 'size=1', + 'source=array', + 'type=', + 'value=0', + 'withTotalLength=0' + ], + { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 } +); diff --git a/test/benchmark/test-benchmark-child-process.js b/test/benchmark/test-benchmark-child-process.js index 365777069bc4cf..15ad023e38f1a9 100644 --- a/test/benchmark/test-benchmark-child-process.js +++ b/test/benchmark/test-benchmark-child-process.js @@ -4,12 +4,8 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('child_process', - [ - 'dur=0', - 'n=1', - 'len=1', - 'params=1', - 'methodName=execSync', - ], - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark( + 'child_process', + ['dur=0', 'n=1', 'len=1', 'params=1', 'methodName=execSync'], + { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 } +); diff --git a/test/benchmark/test-benchmark-crypto.js b/test/benchmark/test-benchmark-crypto.js index f24edf675f92f0..91248d7bb87dbc 100644 --- a/test/benchmark/test-benchmark-crypto.js +++ b/test/benchmark/test-benchmark-crypto.js @@ -2,25 +2,25 @@ const common = require('../common'); -if (!common.hasCrypto) - common.skip('missing crypto'); +if (!common.hasCrypto) common.skip('missing crypto'); -if (common.hasFipsCrypto) - common.skip('some benchmarks are FIPS-incompatible'); +if (common.hasFipsCrypto) common.skip('some benchmarks are FIPS-incompatible'); const runBenchmark = require('../common/benchmark'); -runBenchmark('crypto', - [ - 'algo=sha256', - 'api=stream', - 'cipher=', - 'keylen=1024', - 'len=1', - 'n=1', - 'out=buffer', - 'type=buf', - 'v=crypto', - 'writes=1', - ], - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark( + 'crypto', + [ + 'algo=sha256', + 'api=stream', + 'cipher=', + 'keylen=1024', + 'len=1', + 'n=1', + 'out=buffer', + 'type=buf', + 'v=crypto', + 'writes=1' + ], + { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 } +); diff --git a/test/benchmark/test-benchmark-dgram.js b/test/benchmark/test-benchmark-dgram.js index 8c93cd5a0c9239..b1731a0781b542 100644 --- a/test/benchmark/test-benchmark-dgram.js +++ b/test/benchmark/test-benchmark-dgram.js @@ -8,10 +8,12 @@ const runBenchmark = require('../common/benchmark'); // sequential rather than parallel to make sure it does not conflict with // tests that choose random available ports. -runBenchmark('dgram', ['address=true', - 'chunks=2', - 'dur=0.1', - 'len=1', - 'n=1', - 'num=1', - 'type=send']); +runBenchmark('dgram', [ + 'address=true', + 'chunks=2', + 'dur=0.1', + 'len=1', + 'n=1', + 'num=1', + 'type=send' +]); diff --git a/test/benchmark/test-benchmark-dns.js b/test/benchmark/test-benchmark-dns.js index 27c3271c74d86d..929cf7bcf104e4 100644 --- a/test/benchmark/test-benchmark-dns.js +++ b/test/benchmark/test-benchmark-dns.js @@ -4,7 +4,8 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -const env = Object.assign({}, process.env, - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +const env = Object.assign({}, process.env, { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1 +}); runBenchmark('dns', ['n=1', 'all=false', 'name=127.0.0.1'], env); diff --git a/test/benchmark/test-benchmark-es.js b/test/benchmark/test-benchmark-es.js index 47fe4ab3f91a63..96e521659f32bf 100644 --- a/test/benchmark/test-benchmark-es.js +++ b/test/benchmark/test-benchmark-es.js @@ -4,15 +4,17 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('es', - [ - 'method=', - 'count=1', - 'context=null', - 'rest=0', - 'mode=', - 'n=1', - 'encoding=ascii', - 'size=1e1' - ], - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark( + 'es', + [ + 'method=', + 'count=1', + 'context=null', + 'rest=0', + 'mode=', + 'n=1', + 'encoding=ascii', + 'size=1e1' + ], + { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 } +); diff --git a/test/benchmark/test-benchmark-events.js b/test/benchmark/test-benchmark-events.js index 06be60a84abb5b..8d72419960b9f6 100644 --- a/test/benchmark/test-benchmark-events.js +++ b/test/benchmark/test-benchmark-events.js @@ -4,6 +4,6 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('events', - ['argc=0', 'listeners=1', 'n=1'], - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark('events', ['argc=0', 'listeners=1', 'n=1'], { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1 +}); diff --git a/test/benchmark/test-benchmark-fs.js b/test/benchmark/test-benchmark-fs.js index 7ae32fe617d58f..c28ddb2ec32005 100644 --- a/test/benchmark/test-benchmark-fs.js +++ b/test/benchmark/test-benchmark-fs.js @@ -6,17 +6,21 @@ const runBenchmark = require('../common/benchmark'); const tmpdir = require('../common/tmpdir'); tmpdir.refresh(); -runBenchmark('fs', [ - 'n=1', - 'size=1', - 'dur=0.1', - 'len=1024', - 'concurrent=1', - 'pathType=relative', - 'statType=fstat', - 'statSyncType=fstatSync', - 'encodingType=buf', - 'filesize=1024', - 'dir=.github', - 'withFileTypes=false' -], { NODE_TMPDIR: tmpdir.path, NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark( + 'fs', + [ + 'n=1', + 'size=1', + 'dur=0.1', + 'len=1024', + 'concurrent=1', + 'pathType=relative', + 'statType=fstat', + 'statSyncType=fstatSync', + 'encodingType=buf', + 'filesize=1024', + 'dir=.github', + 'withFileTypes=false' + ], + { NODE_TMPDIR: tmpdir.path, NODEJS_BENCHMARK_ZERO_ALLOWED: 1 } +); diff --git a/test/benchmark/test-benchmark-http.js b/test/benchmark/test-benchmark-http.js index 7255e655c094e6..e0558e600604f8 100644 --- a/test/benchmark/test-benchmark-http.js +++ b/test/benchmark/test-benchmark-http.js @@ -11,24 +11,26 @@ if (!common.enoughTestMem) const runBenchmark = require('../common/benchmark'); -runBenchmark('http', - [ - 'benchmarker=test-double-http', - 'c=1', - 'chunkedEnc=true', - 'chunks=0', - 'dur=0.1', - 'duplicates=1', - 'input=keep-alive', - 'key=""', - 'len=1', - 'method=write', - 'n=1', - 'res=normal', - 'type=asc', - 'value=X-Powered-By' - ], - { - NODEJS_BENCHMARK_ZERO_ALLOWED: 1, - duration: 0 - }); +runBenchmark( + 'http', + [ + 'benchmarker=test-double-http', + 'c=1', + 'chunkedEnc=true', + 'chunks=0', + 'dur=0.1', + 'duplicates=1', + 'input=keep-alive', + 'key=""', + 'len=1', + 'method=write', + 'n=1', + 'res=normal', + 'type=asc', + 'value=X-Powered-By' + ], + { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1, + duration: 0 + } +); diff --git a/test/benchmark/test-benchmark-http2.js b/test/benchmark/test-benchmark-http2.js index 1668a7b87fe643..f7e26e6a6508db 100644 --- a/test/benchmark/test-benchmark-http2.js +++ b/test/benchmark/test-benchmark-http2.js @@ -1,8 +1,7 @@ 'use strict'; const common = require('../common'); -if (!common.hasCrypto) - common.skip('missing crypto'); +if (!common.hasCrypto) common.skip('missing crypto'); if (!common.enoughTestMem) common.skip('Insufficient memory for HTTP/2 benchmark test'); @@ -13,17 +12,19 @@ if (!common.enoughTestMem) const runBenchmark = require('../common/benchmark'); -runBenchmark('http2', - [ - 'benchmarker=test-double-http2', - 'clients=1', - 'length=65536', - 'n=1', - 'nheaders=0', - 'requests=1', - 'streams=1' - ], - { - NODEJS_BENCHMARK_ZERO_ALLOWED: 1, - duration: 0 - }); +runBenchmark( + 'http2', + [ + 'benchmarker=test-double-http2', + 'clients=1', + 'length=65536', + 'n=1', + 'nheaders=0', + 'requests=1', + 'streams=1' + ], + { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1, + duration: 0 + } +); diff --git a/test/benchmark/test-benchmark-misc.js b/test/benchmark/test-benchmark-misc.js index b88415280833bc..329c1ef65ac4be 100644 --- a/test/benchmark/test-benchmark-misc.js +++ b/test/benchmark/test-benchmark-misc.js @@ -4,13 +4,17 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('misc', [ - 'concat=0', - 'dur=0.1', - 'method=', - 'n=1', - 'type=', - 'val=magyarország.icom.museum', - 'script=test/fixtures/semicolon', - 'mode=worker' -], { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark( + 'misc', + [ + 'concat=0', + 'dur=0.1', + 'method=', + 'n=1', + 'type=', + 'val=magyarország.icom.museum', + 'script=test/fixtures/semicolon', + 'mode=worker' + ], + { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 } +); diff --git a/test/benchmark/test-benchmark-module.js b/test/benchmark/test-benchmark-module.js index d81936210c00fe..6b35c5208931d0 100644 --- a/test/benchmark/test-benchmark-module.js +++ b/test/benchmark/test-benchmark-module.js @@ -4,8 +4,4 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('module', [ - 'n=1', - 'useCache=true', - 'fullPath=true' -]); +runBenchmark('module', ['n=1', 'useCache=true', 'fullPath=true']); diff --git a/test/benchmark/test-benchmark-napi.js b/test/benchmark/test-benchmark-napi.js index 1a1ff23d60c5c0..97a09535bb90c3 100644 --- a/test/benchmark/test-benchmark-napi.js +++ b/test/benchmark/test-benchmark-napi.js @@ -3,7 +3,7 @@ const common = require('../common'); if (common.isWindows) { - common.skip('vcbuild.bat doesn\'t build the n-api benchmarks yet'); + common.skip("vcbuild.bat doesn't build the n-api benchmarks yet"); } if (!common.isMainThread) { @@ -15,10 +15,6 @@ if (process.features.debug) { } const runBenchmark = require('../common/benchmark'); -runBenchmark('napi', - [ - 'n=1', - 'engine=v8', - 'type=String' - ], - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark('napi', ['n=1', 'engine=v8', 'type=String'], { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1 +}); diff --git a/test/benchmark/test-benchmark-net.js b/test/benchmark/test-benchmark-net.js index 5d3d283fc7903e..16a82b1596c08c 100644 --- a/test/benchmark/test-benchmark-net.js +++ b/test/benchmark/test-benchmark-net.js @@ -8,10 +8,6 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('net', - [ - 'dur=0', - 'len=1024', - 'type=buf' - ], - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark('net', ['dur=0', 'len=1024', 'type=buf'], { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1 +}); diff --git a/test/benchmark/test-benchmark-path.js b/test/benchmark/test-benchmark-path.js index 890fd7ae41f548..762d4fc10f41a5 100644 --- a/test/benchmark/test-benchmark-path.js +++ b/test/benchmark/test-benchmark-path.js @@ -4,11 +4,6 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('path', - [ - 'n=1', - 'path=', - 'pathext=', - 'paths=', - 'props=' - ], { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark('path', ['n=1', 'path=', 'pathext=', 'paths=', 'props='], { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1 +}); diff --git a/test/benchmark/test-benchmark-process.js b/test/benchmark/test-benchmark-process.js index 15cb678017e7bb..eab32fa5e7b972 100644 --- a/test/benchmark/test-benchmark-process.js +++ b/test/benchmark/test-benchmark-process.js @@ -4,8 +4,6 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('process', - [ - 'n=1', - 'type=raw' - ], { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark('process', ['n=1', 'type=raw'], { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1 +}); diff --git a/test/benchmark/test-benchmark-querystring.js b/test/benchmark/test-benchmark-querystring.js index 77d0ac99ff97d8..3b6d4a116c8497 100644 --- a/test/benchmark/test-benchmark-querystring.js +++ b/test/benchmark/test-benchmark-querystring.js @@ -4,9 +4,8 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('querystring', - [ 'n=1', - 'input="there is nothing to unescape here"', - 'type=noencode' - ], - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark( + 'querystring', + ['n=1', 'input="there is nothing to unescape here"', 'type=noencode'], + { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 } +); diff --git a/test/benchmark/test-benchmark-streams.js b/test/benchmark/test-benchmark-streams.js index f90838794cdf2a..c1489d863374a1 100644 --- a/test/benchmark/test-benchmark-streams.js +++ b/test/benchmark/test-benchmark-streams.js @@ -4,10 +4,6 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('streams', - [ - 'kind=duplex', - 'type=buffer', - 'n=1' - ], - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark('streams', ['kind=duplex', 'type=buffer', 'n=1'], { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1 +}); diff --git a/test/benchmark/test-benchmark-string_decoder.js b/test/benchmark/test-benchmark-string_decoder.js index f2fd6abe4b8f5f..4274746402fe87 100644 --- a/test/benchmark/test-benchmark-string_decoder.js +++ b/test/benchmark/test-benchmark-string_decoder.js @@ -4,7 +4,9 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('string_decoder', ['chunkLen=16', - 'encoding=utf8', - 'inLen=32', - 'n=1']); +runBenchmark('string_decoder', [ + 'chunkLen=16', + 'encoding=utf8', + 'inLen=32', + 'n=1' +]); diff --git a/test/benchmark/test-benchmark-timers.js b/test/benchmark/test-benchmark-timers.js index af3c49bd714742..972d4f28c14f6a 100644 --- a/test/benchmark/test-benchmark-timers.js +++ b/test/benchmark/test-benchmark-timers.js @@ -4,10 +4,6 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('timers', - [ - 'direction=start', - 'n=1', - 'type=depth', - ], - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark('timers', ['direction=start', 'n=1', 'type=depth'], { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1 +}); diff --git a/test/benchmark/test-benchmark-tls.js b/test/benchmark/test-benchmark-tls.js index 40c14af8302bdb..0aa33332234374 100644 --- a/test/benchmark/test-benchmark-tls.js +++ b/test/benchmark/test-benchmark-tls.js @@ -2,8 +2,7 @@ const common = require('../common'); -if (!common.hasCrypto) - common.skip('missing crypto'); +if (!common.hasCrypto) common.skip('missing crypto'); if (!common.enoughTestMem) common.skip('Insufficient memory for TLS benchmark test'); @@ -14,16 +13,18 @@ if (!common.enoughTestMem) const runBenchmark = require('../common/benchmark'); -runBenchmark('tls', - [ - 'concurrency=1', - 'dur=0.1', - 'n=1', - 'size=2', - 'securing=SecurePair', - 'type=asc' - ], - { - NODEJS_BENCHMARK_ZERO_ALLOWED: 1, - duration: 0 - }); +runBenchmark( + 'tls', + [ + 'concurrency=1', + 'dur=0.1', + 'n=1', + 'size=2', + 'securing=SecurePair', + 'type=asc' + ], + { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1, + duration: 0 + } +); diff --git a/test/benchmark/test-benchmark-url.js b/test/benchmark/test-benchmark-url.js index 92bb34de278f80..9b3515264003c1 100644 --- a/test/benchmark/test-benchmark-url.js +++ b/test/benchmark/test-benchmark-url.js @@ -4,20 +4,22 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('url', - [ - 'method=legacy', - 'loopMethod=forEach', - 'accessMethod=get', - 'type=short', - 'searchParam=noencode', - 'href=short', - 'input=short', - 'domain=empty', - 'path=up', - 'to=ascii', - 'prop=href', - 'n=1', - 'param=one' - ], - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark( + 'url', + [ + 'method=legacy', + 'loopMethod=forEach', + 'accessMethod=get', + 'type=short', + 'searchParam=noencode', + 'href=short', + 'input=short', + 'domain=empty', + 'path=up', + 'to=ascii', + 'prop=href', + 'n=1', + 'param=one' + ], + { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 } +); diff --git a/test/benchmark/test-benchmark-util.js b/test/benchmark/test-benchmark-util.js index 97b02bbdeed5cd..e9583fdf1dfc29 100644 --- a/test/benchmark/test-benchmark-util.js +++ b/test/benchmark/test-benchmark-util.js @@ -4,15 +4,19 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('util', - ['argument=false', - 'input=', - 'method=Array', - 'n=1', - 'option=none', - 'pos=start', - 'size=1', - 'type=', - 'len=1', - 'version=native'], - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark( + 'util', + [ + 'argument=false', + 'input=', + 'method=Array', + 'n=1', + 'option=none', + 'pos=start', + 'size=1', + 'type=', + 'len=1', + 'version=native' + ], + { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 } +); diff --git a/test/benchmark/test-benchmark-v8.js b/test/benchmark/test-benchmark-v8.js index 22861785db9c05..ddf230b1407761 100644 --- a/test/benchmark/test-benchmark-v8.js +++ b/test/benchmark/test-benchmark-v8.js @@ -4,9 +4,6 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('v8', - [ - 'method=getHeapStatistics', - 'n=1' - ], - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark('v8', ['method=getHeapStatistics', 'n=1'], { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1 +}); diff --git a/test/benchmark/test-benchmark-vm.js b/test/benchmark/test-benchmark-vm.js index 79ab6a03402522..6787f7afabeff4 100644 --- a/test/benchmark/test-benchmark-vm.js +++ b/test/benchmark/test-benchmark-vm.js @@ -4,10 +4,6 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('vm', - [ - 'breakOnSigint=0', - 'withSigintListener=0', - 'n=1' - ], - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); +runBenchmark('vm', ['breakOnSigint=0', 'withSigintListener=0', 'n=1'], { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1 +}); diff --git a/test/benchmark/test-benchmark-worker.js b/test/benchmark/test-benchmark-worker.js index ae9a8a6701ae4a..86f2653ad0a143 100644 --- a/test/benchmark/test-benchmark-worker.js +++ b/test/benchmark/test-benchmark-worker.js @@ -11,13 +11,10 @@ if (!common.enoughTestMem) const runBenchmark = require('../common/benchmark'); -runBenchmark('worker', - [ - 'n=1', - 'sendsPerBroadcast=1', - 'workers=1', - 'payload=string' - ], - { - NODEJS_BENCHMARK_ZERO_ALLOWED: 1 - }); +runBenchmark( + 'worker', + ['n=1', 'sendsPerBroadcast=1', 'workers=1', 'payload=string'], + { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1 + } +); diff --git a/test/benchmark/test-benchmark-zlib.js b/test/benchmark/test-benchmark-zlib.js index 25b7d1a4d5f905..de4517541ef2bd 100644 --- a/test/benchmark/test-benchmark-zlib.js +++ b/test/benchmark/test-benchmark-zlib.js @@ -4,15 +4,17 @@ require('../common'); const runBenchmark = require('../common/benchmark'); -runBenchmark('zlib', - [ - 'method=deflate', - 'n=1', - 'options=true', - 'type=Deflate', - 'inputLen=1024', - 'duration=0.001' - ], - { - 'NODEJS_BENCHMARK_ZERO_ALLOWED': 1 - }); +runBenchmark( + 'zlib', + [ + 'method=deflate', + 'n=1', + 'options=true', + 'type=Deflate', + 'inputLen=1024', + 'duration=0.001' + ], + { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1 + } +); diff --git a/test/code-cache/test-code-cache-generator.js b/test/code-cache/test-code-cache-generator.js index 972d89629c0a23..f60cef1f95cb2e 100644 --- a/test/code-cache/test-code-cache-generator.js +++ b/test/code-cache/test-code-cache-generator.js @@ -13,16 +13,21 @@ const fs = require('fs'); const readline = require('readline'); const generator = path.join( - __dirname, '..', '..', 'tools', 'generate_code_cache.js' + __dirname, + '..', + '..', + 'tools', + 'generate_code_cache.js' ); tmpdir.refresh(); const dest = path.join(tmpdir.path, 'cache.cc'); // Run tools/generate_code_cache.js -const child = spawnSync( - process.execPath, - ['--expose-internals', generator, dest] -); +const child = spawnSync(process.execPath, [ + '--expose-internals', + generator, + dest +]); assert.ifError(child.error); if (child.status !== 0) { console.log(child.stderr.toString()); @@ -43,16 +48,22 @@ const rl = readline.createInterface({ let hasCacheDef = false; let hasHashDef = false; -rl.on('line', common.mustCallAtLeast((line) => { - if (line.includes('DefineCodeCache(')) { - hasCacheDef = true; - } - if (line.includes('DefineCodeCacheHash(')) { - hasHashDef = true; - } -}, 2)); - -rl.on('close', common.mustCall(() => { - assert.ok(hasCacheDef); - assert.ok(hasHashDef); -})); +rl.on( + 'line', + common.mustCallAtLeast((line) => { + if (line.includes('DefineCodeCache(')) { + hasCacheDef = true; + } + if (line.includes('DefineCodeCacheHash(')) { + hasHashDef = true; + } + }, 2) +); + +rl.on( + 'close', + common.mustCall(() => { + assert.ok(hasCacheDef); + assert.ok(hasHashDef); + }) +); diff --git a/test/code-cache/test-code-cache.js b/test/code-cache/test-code-cache.js index 994facff1996c2..81b69cd7abbb29 100644 --- a/test/code-cache/test-code-cache.js +++ b/test/code-cache/test-code-cache.js @@ -11,21 +11,16 @@ const { cachableBuiltins, cannotUseCache } = require('internal/bootstrap/cache'); -const { - isMainThread -} = require('worker_threads'); +const { isMainThread } = require('worker_threads'); -const { - internalBinding -} = require('internal/test/binding'); -const { - compiledWithoutCache, - compiledWithCache -} = internalBinding('native_module'); +const { internalBinding } = require('internal/test/binding'); +const { compiledWithoutCache, compiledWithCache } = internalBinding( + 'native_module' +); for (const key of cachableBuiltins) { if (!isMainThread && key === 'trace_events') { - continue; // Cannot load trace_events in workers + continue; // Cannot load trace_events in workers } require(key); } @@ -49,11 +44,15 @@ if (process.config.variables.node_code_cache_path === undefined) { for (const key of loadedModules) { if (cannotUseCache.includes(key)) { - assert(compiledWithoutCache.has(key), - `"${key}" should've been compiled without code cache`); + assert( + compiledWithoutCache.has(key), + `"${key}" should've been compiled without code cache` + ); } else { - assert(compiledWithCache.has(key), - `"${key}" should've been compiled with code cache`); + assert( + compiledWithCache.has(key), + `"${key}" should've been compiled with code cache` + ); } } } diff --git a/test/common/countdown.js b/test/common/countdown.js index 67252657ec28b7..c5f6b47631dc6a 100644 --- a/test/common/countdown.js +++ b/test/common/countdown.js @@ -17,8 +17,7 @@ class Countdown { dec() { assert(this[kLimit] > 0, 'Countdown expired'); - if (--this[kLimit] === 0) - this[kCallback](); + if (--this[kLimit] === 0) this[kCallback](); return this[kLimit]; } diff --git a/test/common/dns.js b/test/common/dns.js index 01245c33d6997c..efb30ec7ae1618 100644 --- a/test/common/dns.js +++ b/test/common/dns.js @@ -27,7 +27,7 @@ function readDomainFromPacket(buffer, offset) { const length = buffer[offset]; if (length === 0) { return { nread: 1, domain: '' }; - } else if ((length & 0xC0) === 0) { + } else if ((length & 0xc0) === 0) { offset += 1; const chunk = buffer.toString('ascii', offset, offset + length); // Read the rest of the domain. @@ -38,9 +38,9 @@ function readDomainFromPacket(buffer, offset) { }; } else { // Pointer to another part of the packet. - assert.strictEqual(length & 0xC0, 0xC0); + assert.strictEqual(length & 0xc0, 0xc0); // eslint-disable-next-line space-infix-ops, space-unary-ops - const pointeeOffset = buffer.readUInt16BE(offset) &~ 0xC000; + const pointeeOffset = buffer.readUInt16BE(offset) & ~0xc000; return { nread: 2, domain: readDomainFromPacket(buffer, pointeeOffset) @@ -53,7 +53,7 @@ function parseDNSPacket(buffer) { const parsed = { id: buffer.readUInt16BE(0), - flags: buffer.readUInt16BE(2), + flags: buffer.readUInt16BE(2) }; const counts = [ @@ -64,7 +64,7 @@ function parseDNSPacket(buffer) { ]; let offset = 12; - for (const [ sectionName, count ] of counts) { + for (const [sectionName, count] of counts) { parsed[sectionName] = []; for (let i = 0; i < count; ++i) { const { nread, domain } = readDomainFromPacket(buffer, offset); @@ -74,13 +74,12 @@ function parseDNSPacket(buffer) { const rr = { domain, - cls: buffer.readUInt16BE(offset + 2), + cls: buffer.readUInt16BE(offset + 2) }; offset += 4; for (const name in types) { - if (types[name] === type) - rr.type = name; + if (types[name] === type) rr.type = name; } if (sectionName !== 'questions') { @@ -91,30 +90,30 @@ function parseDNSPacket(buffer) { switch (type) { case types.A: assert.strictEqual(dataLength, 4); - rr.address = `${buffer[offset + 0]}.${buffer[offset + 1]}.` + - `${buffer[offset + 2]}.${buffer[offset + 3]}`; + rr.address = + `${buffer[offset + 0]}.${buffer[offset + 1]}.` + + `${buffer[offset + 2]}.${buffer[offset + 3]}`; break; case types.AAAA: assert.strictEqual(dataLength, 16); - rr.address = buffer.toString('hex', offset, offset + 16) - .replace(/(.{4}(?!$))/g, '$1:'); + rr.address = buffer + .toString('hex', offset, offset + 16) + .replace(/(.{4}(?!$))/g, '$1:'); break; - case types.TXT: - { + case types.TXT: { let position = offset; rr.entries = []; while (position < offset + dataLength) { const txtLength = buffer[offset]; - rr.entries.push(buffer.toString('utf8', - position + 1, - position + 1 + txtLength)); + rr.entries.push( + buffer.toString('utf8', position + 1, position + 1 + txtLength) + ); position += 1 + txtLength; } assert.strictEqual(position, offset + dataLength); break; } - case types.MX: - { + case types.MX: { rr.priority = buffer.readInt16BE(buffer, offset); offset += 2; const { nread, domain } = readDomainFromPacket(buffer, offset); @@ -124,15 +123,13 @@ function parseDNSPacket(buffer) { } case types.NS: case types.CNAME: - case types.PTR: - { + case types.PTR: { const { nread, domain } = readDomainFromPacket(buffer, offset); rr.value = domain; assert.strictEqual(nread, dataLength); break; } - case types.SOA: - { + case types.SOA: { const mname = readDomainFromPacket(buffer, offset); const rname = readDomainFromPacket(buffer, offset + mname.nread); rr.nsname = mname.domain; @@ -181,48 +178,58 @@ function writeIPv6(ip) { } function writeDomainName(domain) { - return Buffer.concat(domain.split('.').map((label) => { - assert(label.length < 64); - return Buffer.concat([ - Buffer.from([label.length]), - Buffer.from(label, 'ascii') - ]); - }).concat([Buffer.alloc(1)])); + return Buffer.concat( + domain + .split('.') + .map((label) => { + assert(label.length < 64); + return Buffer.concat([ + Buffer.from([label.length]), + Buffer.from(label, 'ascii') + ]); + }) + .concat([Buffer.alloc(1)]) + ); } function writeDNSPacket(parsed) { const buffers = []; const kStandardResponseFlags = 0x8180; - buffers.push(new Uint16Array([ - parsed.id, - parsed.flags === undefined ? kStandardResponseFlags : parsed.flags, - parsed.questions && parsed.questions.length, - parsed.answers && parsed.answers.length, - parsed.authorityAnswers && parsed.authorityAnswers.length, - parsed.additionalRecords && parsed.additionalRecords.length, - ])); + buffers.push( + new Uint16Array([ + parsed.id, + parsed.flags === undefined ? kStandardResponseFlags : parsed.flags, + parsed.questions && parsed.questions.length, + parsed.answers && parsed.answers.length, + parsed.authorityAnswers && parsed.authorityAnswers.length, + parsed.additionalRecords && parsed.additionalRecords.length + ]) + ); for (const q of parsed.questions) { assert(types[q.type]); buffers.push(writeDomainName(q.domain)); - buffers.push(new Uint16Array([ - types[q.type], - q.cls === undefined ? classes.IN : q.cls - ])); + buffers.push( + new Uint16Array([types[q.type], q.cls === undefined ? classes.IN : q.cls]) + ); } - for (const rr of [].concat(parsed.answers, - parsed.authorityAnswers, - parsed.additionalRecords)) { + for (const rr of [].concat( + parsed.answers, + parsed.authorityAnswers, + parsed.additionalRecords + )) { if (!rr) continue; assert(types[rr.type]); buffers.push(writeDomainName(rr.domain)); - buffers.push(new Uint16Array([ - types[rr.type], - rr.cls === undefined ? classes.IN : rr.cls - ])); + buffers.push( + new Uint16Array([ + types[rr.type], + rr.cls === undefined ? classes.IN : rr.cls + ]) + ); buffers.push(new Int32Array([rr.ttl])); const rdLengthBuf = new Uint16Array(1); @@ -249,25 +256,29 @@ function writeDNSPacket(parsed) { case 'MX': rdLengthBuf[0] = 2; buffers.push(new Uint16Array([rr.priority])); - // fall through + // fall through case 'NS': case 'CNAME': - case 'PTR': - { + case 'PTR': { const domain = writeDomainName(rr.exchange || rr.value); rdLengthBuf[0] += domain.length; buffers.push(domain); break; } - case 'SOA': - { + case 'SOA': { const mname = writeDomainName(rr.nsname); const rname = writeDomainName(rr.hostmaster); rdLengthBuf[0] = mname.length + rname.length + 20; buffers.push(mname, rname); - buffers.push(new Uint32Array([ - rr.serial, rr.refresh, rr.retry, rr.expire, rr.minttl - ])); + buffers.push( + new Uint32Array([ + rr.serial, + rr.refresh, + rr.retry, + rr.expire, + rr.minttl + ]) + ); break; } default: @@ -275,16 +286,20 @@ function writeDNSPacket(parsed) { } } - return Buffer.concat(buffers.map((typedArray) => { - const buf = Buffer.from(typedArray.buffer, - typedArray.byteOffset, - typedArray.byteLength); - if (os.endianness() === 'LE') { - if (typedArray.BYTES_PER_ELEMENT === 2) buf.swap16(); - if (typedArray.BYTES_PER_ELEMENT === 4) buf.swap32(); - } - return buf; - })); + return Buffer.concat( + buffers.map((typedArray) => { + const buf = Buffer.from( + typedArray.buffer, + typedArray.byteOffset, + typedArray.byteLength + ); + if (os.endianness() === 'LE') { + if (typedArray.BYTES_PER_ELEMENT === 2) buf.swap16(); + if (typedArray.BYTES_PER_ELEMENT === 4) buf.swap32(); + } + return buf; + }) + ); } const mockedErrorCode = 'ENOTFOUND'; diff --git a/test/common/fixtures.js b/test/common/fixtures.js index b45e5bc8091865..9505de9e0e882f 100644 --- a/test/common/fixtures.js +++ b/test/common/fixtures.js @@ -11,8 +11,7 @@ function fixturesPath(...args) { } function readFixtureSync(args, enc) { - if (Array.isArray(args)) - return fs.readFileSync(fixturesPath(...args), enc); + if (Array.isArray(args)) return fs.readFileSync(fixturesPath(...args), enc); return fs.readFileSync(fixturesPath(args), enc); } diff --git a/test/common/heap.js b/test/common/heap.js index e23670b64c8a2d..51bd9f4f6659c2 100644 --- a/test/common/heap.js +++ b/test/common/heap.js @@ -40,25 +40,32 @@ class State { // Validate the v8 heap snapshot validateSnapshot(rootName, expected, { loose = false } = {}) { const rootNodes = this.snapshot.filter( - (node) => node.name === rootName && node.type !== 'string'); + (node) => node.name === rootName && node.type !== 'string' + ); if (loose) { - assert(rootNodes.length >= expected.length, - `Expect to find at least ${expected.length} '${rootName}', ` + - `found ${rootNodes.length}`); + assert( + rootNodes.length >= expected.length, + `Expect to find at least ${expected.length} '${rootName}', ` + + `found ${rootNodes.length}` + ); } else { assert.strictEqual( - rootNodes.length, expected.length, + rootNodes.length, + expected.length, `Expect to find ${expected.length} '${rootName}', ` + - `found ${rootNodes.length}`); + `found ${rootNodes.length}` + ); } for (const expectation of expected) { if (expectation.children) { for (const expectedEdge of expectation.children) { - const check = typeof expectedEdge === 'function' ? expectedEdge : - (edge) => (isEdge(edge, expectedEdge)); - const hasChild = rootNodes.some( - (node) => node.outgoingEdges.some(check) + const check = + typeof expectedEdge === 'function' + ? expectedEdge + : (edge) => isEdge(edge, expectedEdge); + const hasChild = rootNodes.some((node) => + node.outgoingEdges.some(check) ); // Don't use assert with a custom message here. Otherwise the // inspection in the message is done eagerly and wastes a lot of CPU @@ -66,7 +73,8 @@ class State { if (!hasChild) { throw new Error( 'expected to find child ' + - `${util.inspect(expectedEdge)} in ${inspectNode(rootNodes)}`); + `${util.inspect(expectedEdge)} in ${inspectNode(rootNodes)}` + ); } } } @@ -79,30 +87,35 @@ class State { (node) => node.name === rootName ); if (loose) { - assert(rootNodes.length >= expected.length, - `Expect to find at least ${expected.length} '${rootName}', ` + - `found ${rootNodes.length}`); + assert( + rootNodes.length >= expected.length, + `Expect to find at least ${expected.length} '${rootName}', ` + + `found ${rootNodes.length}` + ); } else { assert.strictEqual( - rootNodes.length, expected.length, + rootNodes.length, + expected.length, `Expect to find ${expected.length} '${rootName}', ` + - `found ${rootNodes.length}`); + `found ${rootNodes.length}` + ); } for (const expectation of expected) { if (expectation.children) { for (const expectedEdge of expectation.children) { - const check = typeof expectedEdge === 'function' ? expectedEdge : - (edge) => (isEdge(edge, expectedEdge)); + const check = + typeof expectedEdge === 'function' + ? expectedEdge + : (edge) => isEdge(edge, expectedEdge); // Don't use assert with a custom message here. Otherwise the // inspection in the message is done eagerly and wastes a lot of CPU // time. - const hasChild = rootNodes.some( - (node) => node.edges.some(check) - ); + const hasChild = rootNodes.some((node) => node.edges.some(check)); if (!hasChild) { throw new Error( 'expected to find child ' + - `${util.inspect(expectedEdge)} in ${inspectNode(rootNodes)}`); + `${util.inspect(expectedEdge)} in ${inspectNode(rootNodes)}` + ); } } } diff --git a/test/common/hijackstdio.js b/test/common/hijackstdio.js index fcc98208f0ec8c..e2377e5da68735 100644 --- a/test/common/hijackstdio.js +++ b/test/common/hijackstdio.js @@ -5,14 +5,16 @@ const stdWrite = {}; function hijackStdWritable(name, listener) { const stream = process[name]; - const _write = stdWrite[name] = stream.write; + const _write = (stdWrite[name] = stream.write); stream.writeTimes = 0; stream.write = function(data, callback) { try { listener(data); } catch (e) { - process.nextTick(() => { throw e; }); + process.nextTick(() => { + throw e; + }); } _write.call(stream, data, callback); diff --git a/test/common/http2.js b/test/common/http2.js index f84a66861755b9..d3f28a5ac51005 100644 --- a/test/common/http2.js +++ b/test/common/http2.js @@ -11,34 +11,39 @@ const FLAG_EOH = 0x4; const FLAG_PADDED = 0x8; const PADDING = Buffer.alloc(255); -const kClientMagic = Buffer.from('505249202a20485454502f322' + - 'e300d0a0d0a534d0d0a0d0a', 'hex'); - -const kFakeRequestHeaders = Buffer.from('828684410f7777772e65' + - '78616d706c652e636f6d', 'hex'); - - -const kFakeResponseHeaders = Buffer.from('4803333032580770726976617465611d' + - '4d6f6e2c203231204f63742032303133' + - '2032303a31333a323120474d546e1768' + - '747470733a2f2f7777772e6578616d70' + - '6c652e636f6d', 'hex'); +const kClientMagic = Buffer.from( + '505249202a20485454502f322' + 'e300d0a0d0a534d0d0a0d0a', + 'hex' +); + +const kFakeRequestHeaders = Buffer.from( + '828684410f7777772e65' + '78616d706c652e636f6d', + 'hex' +); + +const kFakeResponseHeaders = Buffer.from( + '4803333032580770726976617465611d' + + '4d6f6e2c203231204f63742032303133' + + '2032303a31333a323120474d546e1768' + + '747470733a2f2f7777772e6578616d70' + + '6c652e636f6d', + 'hex' +); function isUint32(val) { return val >>> 0 === val; } function isUint24(val) { - return val >>> 0 === val && val <= 0xFFFFFF; + return val >>> 0 === val && val <= 0xffffff; } function isUint8(val) { - return val >>> 0 === val && val <= 0xFF; + return val >>> 0 === val && val <= 0xff; } function write32BE(array, pos, val) { - if (!isUint32(val)) - throw new RangeError('val is not a 32-bit number'); + if (!isUint32(val)) throw new RangeError('val is not a 32-bit number'); array[pos++] = (val >> 24) & 0xff; array[pos++] = (val >> 16) & 0xff; array[pos++] = (val >> 8) & 0xff; @@ -46,16 +51,14 @@ function write32BE(array, pos, val) { } function write24BE(array, pos, val) { - if (!isUint24(val)) - throw new RangeError('val is not a 24-bit number'); + if (!isUint24(val)) throw new RangeError('val is not a 24-bit number'); array[pos++] = (val >> 16) & 0xff; array[pos++] = (val >> 8) & 0xff; array[pos++] = val & 0xff; } function write8(array, pos, val) { - if (!isUint8(val)) - throw new RangeError('val is not an 8-bit number'); + if (!isUint8(val)) throw new RangeError('val is not an 8-bit number'); array[pos] = val; } @@ -76,8 +79,7 @@ class Frame { class SettingsFrame extends Frame { constructor(ack = false) { let flags = 0; - if (ack) - flags |= FLAG_ACK; + if (ack) flags |= FLAG_ACK; super(0, 4, flags, 0); } } diff --git a/test/common/index.js b/test/common/index.js index 7b668e58c48ead..dbf2ee63d3e4ac 100644 --- a/test/common/index.js +++ b/test/common/index.js @@ -21,7 +21,7 @@ /* eslint-disable node-core/required-modules, node-core/crypto-check */ 'use strict'; -const process = global.process; // Some tests tamper with the process global. +const process = global.process; // Some tests tamper with the process global. const path = require('path'); const fs = require('fs'); const assert = require('assert'); @@ -29,10 +29,7 @@ const os = require('os'); const { exec, execSync, spawnSync } = require('child_process'); const util = require('util'); const tmpdir = require('./tmpdir'); -const { - bits, - hasIntl -} = process.binding('config'); +const { bits, hasIntl } = process.binding('config'); const noop = () => {}; @@ -47,21 +44,22 @@ const isMainThread = (() => { const isWindows = process.platform === 'win32'; const isAIX = process.platform === 'aix'; -const isLinuxPPCBE = (process.platform === 'linux') && - (process.arch === 'ppc64') && - (os.endianness() === 'BE'); +const isLinuxPPCBE = + process.platform === 'linux' && + process.arch === 'ppc64' && + os.endianness() === 'BE'; const isSunOS = process.platform === 'sunos'; const isFreeBSD = process.platform === 'freebsd'; const isOpenBSD = process.platform === 'openbsd'; const isLinux = process.platform === 'linux'; const isOSX = process.platform === 'darwin'; -const isOSXMojave = isOSX && (os.release().startsWith('18')); +const isOSXMojave = isOSX && os.release().startsWith('18'); const enoughTestMem = os.totalmem() > 0x70000000; /* 1.75 Gb */ const cpus = os.cpus(); -const enoughTestCpu = Array.isArray(cpus) && - (cpus.length > 1 || cpus[0].speed > 999); +const enoughTestCpu = + Array.isArray(cpus) && (cpus.length > 1 || cpus[0].speed > 999); const rootDir = isWindows ? 'c:\\' : '/'; @@ -79,8 +77,7 @@ if (process.env.NODE_TEST_WITH_ASYNC_HOOKS) { process.on('exit', () => { // iterate through handles to make sure nothing crashes - for (const k in initHandles) - util.inspect(initHandles[k]); + for (const k in initHandles) util.inspect(initHandles[k]); }); const _queueDestroyAsyncId = async_wrap.queueDestroyAsyncId; @@ -94,46 +91,50 @@ if (process.env.NODE_TEST_WITH_ASYNC_HOOKS) { _queueDestroyAsyncId(id); }; - require('async_hooks').createHook({ - init(id, ty, tr, r) { - if (initHandles[id]) { - process._rawDebug( - `Is same resource: ${r === initHandles[id].resource}`); - process._rawDebug(`Previous stack:\n${initHandles[id].stack}\n`); - throw new Error(`init called twice for same id (${id})`); + require('async_hooks') + .createHook({ + init(id, ty, tr, r) { + if (initHandles[id]) { + process._rawDebug( + `Is same resource: ${r === initHandles[id].resource}` + ); + process._rawDebug(`Previous stack:\n${initHandles[id].stack}\n`); + throw new Error(`init called twice for same id (${id})`); + } + initHandles[id] = { resource: r, stack: new Error().stack.substr(6) }; + }, + before() {}, + after() {}, + destroy(id) { + if (destroydIdsList[id] !== undefined) { + process._rawDebug(destroydIdsList[id]); + process._rawDebug(); + throw new Error(`destroy called for same id (${id})`); + } + destroydIdsList[id] = new Error().stack; } - initHandles[id] = { resource: r, stack: new Error().stack.substr(6) }; - }, - before() { }, - after() { }, - destroy(id) { - if (destroydIdsList[id] !== undefined) { - process._rawDebug(destroydIdsList[id]); - process._rawDebug(); - throw new Error(`destroy called for same id (${id})`); - } - destroydIdsList[id] = new Error().stack; - }, - }).enable(); + }) + .enable(); } let opensslCli = null; let inFreeBSDJail = null; let localhostIPv4 = null; -const localIPv6Hosts = - isLinux ? [ - // Debian/Ubuntu - 'ip6-localhost', - 'ip6-loopback', +const localIPv6Hosts = isLinux + ? [ + // Debian/Ubuntu + 'ip6-localhost', + 'ip6-loopback', - // SUSE - 'ipv6-localhost', - 'ipv6-loopback', + // SUSE + 'ipv6-localhost', + 'ipv6-loopback', - // Typically universal - 'localhost', - ] : [ 'localhost' ]; + // Typically universal + 'localhost' + ] + : ['localhost']; const PIPE = (() => { const localRelative = path.relative(process.cwd(), `${tmpdir.path}/`); @@ -146,8 +147,9 @@ const hasIPv6 = (() => { const iFaces = os.networkInterfaces(); const re = isWindows ? /Loopback Pseudo-Interface/ : /lo/; return Object.keys(iFaces).some((name) => { - return re.test(name) && - iFaces[name].some(({ family }) => family === 'IPv6'); + return ( + re.test(name) && iFaces[name].some(({ family }) => family === 'IPv6') + ); }); })(); @@ -167,9 +169,10 @@ function childShouldThrowAndAbort() { testCmd += `"${process.argv[1]}" child`; const child = exec(testCmd); child.on('exit', function onExit(exitCode, signal) { - const errMsg = 'Test should have aborted ' + - `but instead exited with exit code ${exitCode}` + - ` and signal ${signal}`; + const errMsg = + 'Test should have aborted ' + + `but instead exited with exit code ${exitCode}` + + ` and signal ${signal}`; assert(nodeProcessAborted(exitCode, signal), errMsg); }); } @@ -180,38 +183,30 @@ function createZeroFilledFile(filename) { fs.closeSync(fd); } - -const pwdCommand = isWindows ? - ['cmd.exe', ['/d', '/c', 'cd']] : - ['pwd', []]; - +const pwdCommand = isWindows ? ['cmd.exe', ['/d', '/c', 'cd']] : ['pwd', []]; function platformTimeout(ms) { // ESLint will not support 'bigint' in valid-typeof until it reaches stage 4. // See https://github.com/eslint/eslint/pull/9636. // eslint-disable-next-line valid-typeof - const multipliers = typeof ms === 'bigint' ? - { two: 2n, four: 4n, seven: 7n } : { two: 2, four: 4, seven: 7 }; + const multipliers = + typeof ms === 'bigint' + ? { two: 2n, four: 4n, seven: 7n } + : { two: 2, four: 4, seven: 7 }; - if (process.features.debug) - ms = multipliers.two * ms; + if (process.features.debug) ms = multipliers.two * ms; - if (global.__coverage__) - ms = multipliers.four * ms; + if (global.__coverage__) ms = multipliers.four * ms; - if (isAIX) - return multipliers.two * ms; // default localhost speed is slower on AIX + if (isAIX) return multipliers.two * ms; // default localhost speed is slower on AIX - if (process.arch !== 'arm') - return ms; + if (process.arch !== 'arm') return ms; const armv = process.config.variables.arm_version; - if (armv === '6') - return multipliers.seven * ms; // ARMv6 + if (armv === '6') return multipliers.seven * ms; // ARMv6 - if (armv === '7') - return multipliers.two * ms; // ARMv7 + if (armv === '7') return multipliers.two * ms; // ARMv7 return ms; // ARMv8+ } @@ -298,11 +293,18 @@ function runCallChecks(exitCode) { }); failed.forEach(function(context) { - console.log('Mismatched %s function calls. Expected %s, actual %d.', - context.name, - context.messageSegment, - context.actual); - console.log(context.stack.split('\n').slice(2).join('\n')); + console.log( + 'Mismatched %s function calls. Expected %s, actual %d.', + context.name, + context.messageSegment, + context.actual + ); + console.log( + context.stack + .split('\n') + .slice(2) + .join('\n') + ); }); if (failed.length) process.exit(1); @@ -332,7 +334,7 @@ function _mustCallInner(fn, criteria = 1, field) { const context = { [field]: criteria, actual: 0, - stack: (new Error()).stack, + stack: new Error().stack, name: fn.name || '' }; @@ -357,9 +359,11 @@ function hasMultiLocalhost() { } function skipIfEslintMissing() { - if (!fs.existsSync( - path.join(__dirname, '..', '..', 'tools', 'node_modules', 'eslint') - )) { + if ( + !fs.existsSync( + path.join(__dirname, '..', '..', 'tools', 'node_modules', 'eslint') + ) + ) { skip('missing ESLint'); } } @@ -372,8 +376,11 @@ function canCreateSymLink() { // whoami.exe needs to be the one from System32 // If unix tools are in the path, they can shadow the one we want, // so use the full path while executing whoami - const whoamiPath = path.join(process.env.SystemRoot, - 'System32', 'whoami.exe'); + const whoamiPath = path.join( + process.env.SystemRoot, + 'System32', + 'whoami.exe' + ); try { const output = execSync(`${whoamiPath} /priv`, { timout: 1000 }); @@ -402,7 +409,8 @@ function mustNotCall(msg) { const callSite = getCallSite(mustNotCall); return function mustNotCall() { assert.fail( - `${msg || 'function should not have been called'} at ${callSite}`); + `${msg || 'function should not have been called'} at ${callSite}` + ); }; } @@ -435,8 +443,7 @@ function nodeProcessAborted(exitCode, signal) { // which corresponds to exit code 3221225477 (0xC0000005) // (ii) Otherwise, _exit(134) which is called in place of abort() due to // raising SIGABRT exiting with ambiguous exit code '3' by default - if (isWindows) - expectedExitCodes = [0xC0000005, 134]; + if (isWindows) expectedExitCodes = [0xc0000005, 134]; // When using --abort-on-uncaught-exception, V8 will use // base::OS::Abort to terminate the process. @@ -471,8 +478,10 @@ function _expectWarning(name, expected) { const map = new Map(expected); return mustCall((warning) => { assert.strictEqual(warning.name, name); - assert.ok(map.has(warning.message), - `unexpected error message: "${warning.message}"`); + assert.ok( + map.has(warning.message), + `unexpected error message: "${warning.message}"` + ); const code = map.get(warning.message); assert.strictEqual(warning.code, code); // Remove a warning message after it is seen so that we guarantee that we @@ -493,10 +502,12 @@ function expectWarningByMap(warningMap) { Object.keys(warningMap).forEach((name) => { let expected = warningMap[name]; if (!Array.isArray(expected)) { - throw new Error('warningMap entries must be arrays consisting of two ' + - 'entries: [message, warningCode]'); + throw new Error( + 'warningMap entries must be arrays consisting of two ' + + 'entries: [message, warningCode]' + ); } - if (!(Array.isArray(expected[0]))) { + if (!Array.isArray(expected[0])) { if (expected.length === 0) { return; } @@ -521,8 +532,7 @@ function expectWarning(nameOrMap, expected, code) { class Comparison { constructor(obj, keys) { for (const key of keys) { - if (key in obj) - this[key] = obj[key]; + if (key in obj) this[key] = obj[key]; } } } @@ -556,16 +566,19 @@ function expectsError(fn, settings, exact) { constructor = Object.getPrototypeOf(error.constructor); } // Add the `type` to the error to properly compare and visualize it. - if (!('type' in error)) - error.type = constructor; + if (!('type' in error)) error.type = constructor; } - if ('message' in settings && - typeof settings.message === 'object' && - settings.message.test(error.message)) { + if ( + 'message' in settings && + typeof settings.message === 'object' && + settings.message.test(error.message) + ) { // Make a copy so we are able to modify the settings. innerSettings = Object.create( - settings, Object.getOwnPropertyDescriptors(settings)); + settings, + Object.getOwnPropertyDescriptors(settings) + ); // Visualize the message as identical in case of other errors. innerSettings.message = error.message; } @@ -595,7 +608,6 @@ function expectsError(fn, settings, exact) { message: err.message }); } - } return true; } @@ -656,7 +668,9 @@ function getBufferSources(buf) { } // Crash the process on unhandled rejections. -const crashOnUnhandledRejection = (err) => { throw err; }; +const crashOnUnhandledRejection = (err) => { + throw err; +}; process.on('unhandledRejection', crashOnUnhandledRejection); function disableCrashOnUnhandledRejection() { process.removeListener('unhandledRejection', crashOnUnhandledRejection); @@ -741,7 +755,9 @@ module.exports = { skipIfInspectorDisabled, skipIfWorker, - get localhostIPv6() { return '::1'; }, + get localhostIPv6() { + return '::1'; + }, get hasFipsCrypto() { return hasCrypto && require('crypto').fips; @@ -750,8 +766,10 @@ module.exports = { get inFreeBSDJail() { if (inFreeBSDJail !== null) return inFreeBSDJail; - if (exports.isFreeBSD && - execSync('sysctl -n security.jail.jailed').toString() === '1\n') { + if ( + exports.isFreeBSD && + execSync('sysctl -n security.jail.jailed').toString() === '1\n' + ) { inFreeBSDJail = true; } else { inFreeBSDJail = false; @@ -769,9 +787,11 @@ module.exports = { if (process.env.LOCALHOST) { localhostIPv4 = process.env.LOCALHOST; } else { - console.error('Looks like we\'re in a FreeBSD Jail. ' + - 'Please provide your default interface address ' + - 'as LOCALHOST or expect some tests to fail.'); + console.error( + "Looks like we're in a FreeBSD Jail. " + + 'Please provide your default interface address ' + + 'as LOCALHOST or expect some tests to fail.' + ); } } @@ -808,5 +828,4 @@ module.exports = { } return +process.env.NODE_COMMON_PORT || 12346; } - }; diff --git a/test/common/inspector-helper.js b/test/common/inspector-helper.js index 7cac2b29f9c90c..97382dc49137cf 100644 --- a/test/common/inspector-helper.js +++ b/test/common/inspector-helper.js @@ -38,12 +38,9 @@ function makeBufferingDataCallback(dataCallback) { const newData = Buffer.concat([buffer, data]); const str = newData.toString('utf8'); const lines = str.replace(/\r/g, '').split('\n'); - if (str.endsWith('\n')) - buffer = Buffer.alloc(0); - else - buffer = Buffer.from(lines.pop(), 'utf8'); - for (const line of lines) - dataCallback(line); + if (str.endsWith('\n')) buffer = Buffer.alloc(0); + else buffer = Buffer.from(lines.pop(), 'utf8'); + for (const line of lines) dataCallback(line); }; } @@ -58,16 +55,14 @@ function tearDown(child, err) { function parseWSFrame(buffer) { // Protocol described in https://tools.ietf.org/html/rfc6455#section-5 let message = null; - if (buffer.length < 2) - return { length: 0, message }; + if (buffer.length < 2) return { length: 0, message }; if (buffer[0] === 0x88 && buffer[1] === 0x00) { return { length: 2, message, closed: true }; } assert.strictEqual(buffer[0], 0x81); - let dataLen = 0x7F & buffer[1]; + let dataLen = 0x7f & buffer[1]; let bodyOffset = 2; - if (buffer.length < bodyOffset + dataLen) - return 0; + if (buffer.length < bodyOffset + dataLen) return 0; if (dataLen === 126) { dataLen = buffer.readUInt16BE(2); bodyOffset = 4; @@ -76,18 +71,17 @@ function parseWSFrame(buffer) { dataLen = buffer.readUIntBE(4, 6); bodyOffset = 10; } - if (buffer.length < bodyOffset + dataLen) - return { length: 0, message }; - const jsonPayload = - buffer.slice(bodyOffset, bodyOffset + dataLen).toString('utf8'); + if (buffer.length < bodyOffset + dataLen) return { length: 0, message }; + const jsonPayload = buffer + .slice(bodyOffset, bodyOffset + dataLen) + .toString('utf8'); try { message = JSON.parse(jsonPayload); } catch (e) { console.error(`JSON.parse() failed for: ${jsonPayload}`); throw e; } - if (DEBUG) - console.log('[received]', JSON.stringify(message)); + if (DEBUG) console.log('[received]', JSON.stringify(message)); return { length: bodyOffset + dataLen, message }; } @@ -103,11 +97,11 @@ function formatWSFrame(message) { if (bodyLen < 126) { byte2 = 0x80 + bodyLen; } else if (bodyLen < 65536) { - byte2 = 0xFE; + byte2 = 0xfe; wsHeaderBuf.writeUInt16BE(bodyLen, 2); maskOffset = 4; } else { - byte2 = 0xFF; + byte2 = 0xff; wsHeaderBuf.writeUInt32BE(bodyLen, 2); wsHeaderBuf.writeUInt32BE(0, 6); maskOffset = 10; @@ -116,7 +110,7 @@ function formatWSFrame(message) { wsHeaderBuf.writeUInt32BE(0x01020408, maskOffset); for (let i = 0; i < messageBuf.length; i++) - messageBuf[i] = messageBuf[i] ^ (1 << (i % 4)); + messageBuf[i] = messageBuf[i] ^ (1 << i % 4); return Buffer.concat([wsHeaderBuf.slice(0, maskOffset + 4), messageBuf]); } @@ -136,15 +130,13 @@ class InspectorSession { buffer = Buffer.concat([buffer, data]); do { const { length, message, closed } = parseWSFrame(buffer); - if (!length) - break; + if (!length) break; if (closed) { - socket.write(Buffer.from([0x88, 0x00])); // WS close frame + socket.write(Buffer.from([0x88, 0x00])); // WS close frame } buffer = buffer.slice(length); - if (message) - this._onMessage(message); + if (message) this._onMessage(message); } while (true); }); this._terminationPromise = new Promise((resolve) => { @@ -165,16 +157,15 @@ class InspectorSession { if (message.id) { const { resolve, reject } = this._commandResponsePromises.get(message.id); this._commandResponsePromises.delete(message.id); - if (message.result) - resolve(message.result); - else - reject(message.error); + if (message.result) resolve(message.result); + else reject(message.error); } else { if (message.method === 'Debugger.scriptParsed') { const { scriptId, url } = message.params; this._scriptsIdsByUrl.set(scriptId, url); - const fileUrl = url.startsWith('file:') ? - url : pathToFileURL(url).toString(); + const fileUrl = url.startsWith('file:') + ? url + : pathToFileURL(url).toString(); if (fileUrl === this.scriptURL().toString()) { this.mainScriptId = scriptId; } @@ -194,25 +185,24 @@ class InspectorSession { _sendMessage(message) { const msg = JSON.parse(JSON.stringify(message)); // Clone! msg.id = this._nextId++; - if (DEBUG) - console.log('[sent]', JSON.stringify(msg)); + if (DEBUG) console.log('[sent]', JSON.stringify(msg)); const responsePromise = new Promise((resolve, reject) => { this._commandResponsePromises.set(msg.id, { resolve, reject }); }); - return new Promise( - (resolve) => this._socket.write(formatWSFrame(msg), resolve)) - .then(() => responsePromise); + return new Promise((resolve) => + this._socket.write(formatWSFrame(msg), resolve) + ).then(() => responsePromise); } send(commands) { if (Array.isArray(commands)) { // Multiple commands means the response does not matter. There might even // never be a response. - return Promise - .all(commands.map((command) => this._sendMessage(command))) - .then(() => {}); + return Promise.all( + commands.map((command) => this._sendMessage(command)) + ).then(() => {}); } else { return this._sendMessage(commands); } @@ -222,7 +212,10 @@ class InspectorSession { const desc = description || methodOrPredicate; const message = `Timed out waiting for matching notification (${desc}))`; return fires( - this._asyncWaitForNotification(methodOrPredicate), message, TIMEOUT); + this._asyncWaitForNotification(methodOrPredicate), + message, + TIMEOUT + ); } async _asyncWaitForNotification(methodOrPredicate) { @@ -230,14 +223,15 @@ class InspectorSession { return notification.method === methodOrPredicate; } const predicate = - typeof methodOrPredicate === 'string' ? matchMethod : methodOrPredicate; + typeof methodOrPredicate === 'string' ? matchMethod : methodOrPredicate; let notification = null; do { if (this._unprocessedNotifications.length) { notification = this._unprocessedNotifications.shift(); } else { notification = await new Promise( - (resolve) => this._notificationCallback = resolve); + (resolve) => (this._notificationCallback = resolve) + ); } } while (!predicate(notification)); return notification; @@ -248,32 +242,32 @@ class InspectorSession { const callFrame = message.params.callFrames[0]; const location = callFrame.location; const scriptPath = this._scriptsIdsByUrl.get(location.scriptId); - assert.strictEqual(scriptPath.toString(), - expectedScriptPath.toString(), - `${scriptPath} !== ${expectedScriptPath}`); + assert.strictEqual( + scriptPath.toString(), + expectedScriptPath.toString(), + `${scriptPath} !== ${expectedScriptPath}` + ); assert.strictEqual(location.lineNumber, line); return true; } } waitForBreakOnLine(line, url) { - return this - .waitForNotification( - (notification) => - this._isBreakOnLineNotification(notification, line, url), - `break on ${url}:${line}`); + return this.waitForNotification( + (notification) => + this._isBreakOnLineNotification(notification, line, url), + `break on ${url}:${line}` + ); } _matchesConsoleOutputNotification(notification, type, values) { - if (!Array.isArray(values)) - values = [ values ]; + if (!Array.isArray(values)) values = [values]; if (notification.method === 'Runtime.consoleAPICalled') { const params = notification.params; if (params.type === type) { let i = 0; for (const value of params.args) { - if (value.value !== values[i++]) - return false; + if (value.value !== values[i++]) return false; } return i === values.length; } @@ -283,20 +277,25 @@ class InspectorSession { waitForConsoleOutput(type, values) { const desc = `Console output matching ${JSON.stringify(values)}`; return this.waitForNotification( - (notification) => this._matchesConsoleOutputNotification(notification, - type, values), - desc); + (notification) => + this._matchesConsoleOutputNotification(notification, type, values), + desc + ); } async runToCompletion() { console.log('[test]', 'Verify node waits for the frontend to disconnect'); - await this.send({ 'method': 'Debugger.resume' }); + await this.send({ method: 'Debugger.resume' }); await this.waitForNotification((notification) => { - return notification.method === 'Runtime.executionContextDestroyed' && - notification.params.executionContextId === 1; + return ( + notification.method === 'Runtime.executionContextDestroyed' && + notification.params.executionContextId === 1 + ); }); - while ((await this._instance.nextStderrString()) !== - 'Waiting for the debugger to disconnect...'); + while ( + (await this._instance.nextStderrString()) !== + 'Waiting for the debugger to disconnect...' + ); await this.disconnect(); } @@ -314,29 +313,38 @@ class InspectorSession { } class NodeInstance extends EventEmitter { - constructor(inspectorFlags = ['--inspect-brk=0'], - scriptContents = '', - scriptFile = _MAINSCRIPT) { + constructor( + inspectorFlags = ['--inspect-brk=0'], + scriptContents = '', + scriptFile = _MAINSCRIPT + ) { super(); this._scriptPath = scriptFile; this._script = scriptFile ? null : scriptContents; this._portCallback = null; - this.portPromise = new Promise((resolve) => this._portCallback = resolve); - this._process = spawnChildProcess(inspectorFlags, scriptContents, - scriptFile); + this.portPromise = new Promise((resolve) => (this._portCallback = resolve)); + this._process = spawnChildProcess( + inspectorFlags, + scriptContents, + scriptFile + ); this._running = true; this._stderrLineCallback = null; this._unprocessedStderrLines = []; - this._process.stdout.on('data', makeBufferingDataCallback( - (line) => { + this._process.stdout.on( + 'data', + makeBufferingDataCallback((line) => { this.emit('stdout', line); console.log('[out]', line); - })); + }) + ); - this._process.stderr.on('data', makeBufferingDataCallback( - (message) => this.onStderrLine(message))); + this._process.stderr.on( + 'data', + makeBufferingDataCallback((message) => this.onStderrLine(message)) + ); this._shutdownPromise = new Promise((resolve) => { this._process.once('exit', (exitCode, signal) => { @@ -348,10 +356,14 @@ class NodeInstance extends EventEmitter { static async startViaSignal(scriptContents) { const instance = new NodeInstance( - [], `${scriptContents}\nprocess._rawDebug('started');`, undefined); + [], + `${scriptContents}\nprocess._rawDebug('started');`, + undefined + ); const msg = 'Timed out waiting for process to start'; - while (await fires(instance.nextStderrString(), msg, TIMEOUT) !== - 'started') {} + while ( + (await fires(instance.nextStderrString(), msg, TIMEOUT)) !== 'started' + ) {} process._debugProcess(instance._process.pid); return instance; } @@ -375,26 +387,31 @@ class NodeInstance extends EventEmitter { httpGet(host, path, hostHeaderValue) { console.log('[test]', `Testing ${path}`); - const headers = hostHeaderValue ? { 'Host': hostHeaderValue } : null; - return this.portPromise.then((port) => new Promise((resolve, reject) => { - const req = http.get({ host, port, path, headers }, (res) => { - let response = ''; - res.setEncoding('utf8'); - res - .on('data', (data) => response += data.toString()) - .on('end', () => { - resolve(response); - }); + const headers = hostHeaderValue ? { Host: hostHeaderValue } : null; + return this.portPromise + .then( + (port) => + new Promise((resolve, reject) => { + const req = http.get({ host, port, path, headers }, (res) => { + let response = ''; + res.setEncoding('utf8'); + res + .on('data', (data) => (response += data.toString())) + .on('end', () => { + resolve(response); + }); + }); + req.on('error', reject); + }) + ) + .then((response) => { + try { + return JSON.parse(response); + } catch (e) { + e.body = response; + throw e; + } }); - req.on('error', reject); - })).then((response) => { - try { - return JSON.parse(response); - } catch (e) { - e.body = response; - throw e; - } - }); } async sendUpgradeRequest() { @@ -405,8 +422,8 @@ class NodeInstance extends EventEmitter { port, path: parseURL(devtoolsUrl).path, headers: { - 'Connection': 'Upgrade', - 'Upgrade': 'websocket', + Connection: 'Upgrade', + Upgrade: 'websocket', 'Sec-WebSocket-Version': 13, 'Sec-WebSocket-Key': 'key==' } @@ -418,8 +435,9 @@ class NodeInstance extends EventEmitter { const upgradeRequest = await this.sendUpgradeRequest(); return new Promise((resolve, reject) => { upgradeRequest - .on('upgrade', - (message, socket) => resolve(new InspectorSession(socket, this))) + .on('upgrade', (message, socket) => + resolve(new InspectorSession(socket, this)) + ) .on('response', common.mustNotCall('Upgrade was not received')); }); } @@ -429,10 +447,12 @@ class NodeInstance extends EventEmitter { const upgradeRequest = await this.sendUpgradeRequest(); return new Promise((resolve, reject) => { upgradeRequest - .on('upgrade', common.mustNotCall('Upgrade was received')) - .on('response', (response) => - response.on('data', () => {}) - .on('end', () => resolve(response.statusCode))); + .on('upgrade', common.mustNotCall('Upgrade was received')) + .on('response', (response) => + response + .on('data', () => {}) + .on('end', () => resolve(response.statusCode)) + ); }); } @@ -443,7 +463,7 @@ class NodeInstance extends EventEmitter { nextStderrString() { if (this._unprocessedStderrLines.length) return Promise.resolve(this._unprocessedStderrLines.shift()); - return new Promise((resolve) => this._stderrLineCallback = resolve); + return new Promise((resolve) => (this._stderrLineCallback = resolve)); } write(message) { @@ -467,27 +487,32 @@ class NodeInstance extends EventEmitter { } function onResolvedOrRejected(promise, callback) { - return promise.then((result) => { - callback(); - return result; - }, (error) => { - callback(); - throw error; - }); + return promise.then( + (result) => { + callback(); + return result; + }, + (error) => { + callback(); + throw error; + } + ); } function timeoutPromise(error, timeoutMs) { let clearCallback = null; let done = false; - const promise = onResolvedOrRejected(new Promise((resolve, reject) => { - const timeout = setTimeout(() => reject(error), timeoutMs); - clearCallback = () => { - if (done) - return; - clearTimeout(timeout); - resolve(); - }; - }), () => done = true); + const promise = onResolvedOrRejected( + new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject(error), timeoutMs); + clearCallback = () => { + if (done) return; + clearTimeout(timeout); + resolve(); + }; + }), + () => (done = true) + ); promise.clear = clearCallback; return promise; } diff --git a/test/common/ongc.js b/test/common/ongc.js index d8e27beb8f0a13..461634f8b64bcd 100644 --- a/test/common/ongc.js +++ b/test/common/ongc.js @@ -8,21 +8,23 @@ const gcTrackerTag = 'NODE_TEST_COMMON_GC_TRACKER'; function onGC(obj, gcListener) { const async_hooks = require('async_hooks'); - const onGcAsyncHook = async_hooks.createHook({ - init: common.mustCallAtLeast(function(id, type) { - if (this.trackedId === undefined) { - assert.strictEqual(type, gcTrackerTag); - this.trackedId = id; + const onGcAsyncHook = async_hooks + .createHook({ + init: common.mustCallAtLeast(function(id, type) { + if (this.trackedId === undefined) { + assert.strictEqual(type, gcTrackerTag); + this.trackedId = id; + } + }), + destroy(id) { + assert.notStrictEqual(this.trackedId, -1); + if (id === this.trackedId) { + this.gcListener.ongc(); + onGcAsyncHook.disable(); + } } - }), - destroy(id) { - assert.notStrictEqual(this.trackedId, -1); - if (id === this.trackedId) { - this.gcListener.ongc(); - onGcAsyncHook.disable(); - } - } - }).enable(); + }) + .enable(); onGcAsyncHook.gcListener = gcListener; gcTrackerMap.set(obj, new async_hooks.AsyncResource(gcTrackerTag)); diff --git a/test/common/tls.js b/test/common/tls.js index 3560af671bce25..a95c2a2c06dd07 100644 --- a/test/common/tls.js +++ b/test/common/tls.js @@ -14,8 +14,10 @@ class TestTLSSocket extends net.Socket { this.handshake_list = []; // AES128-GCM-SHA256 this.ciphers = Buffer.from('000002009c0', 'hex'); - this.pre_master_secret = - Buffer.concat([this.version, crypto.randomBytes(46)]); + this.pre_master_secret = Buffer.concat([ + this.version, + crypto.randomBytes(46) + ]); this.master_secret = null; this.write_seq = 0; this.client_random = crypto.randomBytes(32); @@ -25,16 +27,20 @@ class TestTLSSocket extends net.Socket { }); this.on('server_random', (server_random) => { - this.master_secret = PRF12('sha256', this.pre_master_secret, - 'master secret', - Buffer.concat([this.client_random, - server_random]), - 48); - const key_block = PRF12('sha256', this.master_secret, - 'key expansion', - Buffer.concat([server_random, - this.client_random]), - 40); + this.master_secret = PRF12( + 'sha256', + this.pre_master_secret, + 'master secret', + Buffer.concat([this.client_random, server_random]), + 48 + ); + const key_block = PRF12( + 'sha256', + this.master_secret, + 'key expansion', + Buffer.concat([server_random, this.client_random]), + 40 + ); this.client_writeKey = key_block.slice(0, 16); this.client_writeIV = key_block.slice(32, 36); }); @@ -42,22 +48,33 @@ class TestTLSSocket extends net.Socket { createClientHello() { const compressions = Buffer.from('0100', 'hex'); // null - const msg = addHandshakeHeader(0x01, Buffer.concat([ - this.version, this.client_random, this.ciphers, compressions - ])); + const msg = addHandshakeHeader( + 0x01, + Buffer.concat([ + this.version, + this.client_random, + this.ciphers, + compressions + ]) + ); this.emit('handshake', msg); return addRecordHeader(0x16, msg); } createClientKeyExchange() { - const encrypted_pre_master_secret = crypto.publicEncrypt({ - key: this.server_cert, - padding: crypto.constants.RSA_PKCS1_PADDING - }, this.pre_master_secret); + const encrypted_pre_master_secret = crypto.publicEncrypt( + { + key: this.server_cert, + padding: crypto.constants.RSA_PKCS1_PADDING + }, + this.pre_master_secret + ); const length = Buffer.alloc(2); length.writeUIntBE(encrypted_pre_master_secret.length, 0, 2); - const msg = addHandshakeHeader(0x10, Buffer.concat([ - length, encrypted_pre_master_secret])); + const msg = addHandshakeHeader( + 0x10, + Buffer.concat([length, encrypted_pre_master_secret]) + ); this.emit('handshake', msg); return addRecordHeader(0x16, msg); } @@ -66,8 +83,13 @@ class TestTLSSocket extends net.Socket { const shasum = crypto.createHash('sha256'); shasum.update(Buffer.concat(this.handshake_list)); const message_hash = shasum.digest(); - const r = PRF12('sha256', this.master_secret, - 'client finished', message_hash, 12); + const r = PRF12( + 'sha256', + this.master_secret, + 'client finished', + message_hash, + 12 + ); const msg = addHandshakeHeader(0x14, r); this.emit('handshake', msg); return addRecordHeader(0x16, msg); diff --git a/test/common/tmpdir.js b/test/common/tmpdir.js index ca761b7f94a642..76090d3025f1ff 100644 --- a/test/common/tmpdir.js +++ b/test/common/tmpdir.js @@ -9,22 +9,16 @@ function rimrafSync(p) { try { st = fs.lstatSync(p); } catch (e) { - if (e.code === 'ENOENT') - return; + if (e.code === 'ENOENT') return; } try { - if (st && st.isDirectory()) - rmdirSync(p, null); - else - fs.unlinkSync(p); + if (st && st.isDirectory()) rmdirSync(p, null); + else fs.unlinkSync(p); } catch (e) { - if (e.code === 'ENOENT') - return; - if (e.code === 'EPERM') - return rmdirSync(p, e); - if (e.code !== 'EISDIR') - throw e; + if (e.code === 'ENOENT') return; + if (e.code === 'EPERM') return rmdirSync(p, e); + if (e.code !== 'EISDIR') throw e; rmdirSync(p, e); } } @@ -33,8 +27,7 @@ function rmdirSync(p, originalEr) { try { fs.rmdirSync(p); } catch (e) { - if (e.code === 'ENOTDIR') - throw originalEr; + if (e.code === 'ENOTDIR') throw originalEr; if (e.code === 'ENOTEMPTY' || e.code === 'EEXIST' || e.code === 'EPERM') { const enc = process.platform === 'linux' ? 'buffer' : 'utf8'; fs.readdirSync(p, enc).forEach((f) => { @@ -50,8 +43,9 @@ function rmdirSync(p, originalEr) { } } -const testRoot = process.env.NODE_TEST_DIR ? - fs.realpathSync(process.env.NODE_TEST_DIR) : path.resolve(__dirname, '..'); +const testRoot = process.env.NODE_TEST_DIR + ? fs.realpathSync(process.env.NODE_TEST_DIR) + : path.resolve(__dirname, '..'); // Using a `.` prefixed name, which is the convention for "hidden" on POSIX, // gets tools to ignore it by default or by simple rules, especially eslint. diff --git a/test/common/wpt.js b/test/common/wpt.js index 59dbe26d2abdcb..ec90cf6268c05d 100644 --- a/test/common/wpt.js +++ b/test/common/wpt.js @@ -25,11 +25,17 @@ const harnessMock = { assert_true: (value, message) => assert.strictEqual(value, true, message), assert_false: (value, message) => assert.strictEqual(value, false, message), assert_throws: (code, func, desc) => { - assert.throws(func, function(err) { - return typeof err === 'object' && - 'name' in err && - err.name.startsWith(code.name); - }, desc); + assert.throws( + func, + function(err) { + return ( + typeof err === 'object' && + 'name' in err && + err.name.startsWith(code.name) + ); + }, + desc + ); }, assert_array_equals: assert.deepStrictEqual, assert_unreached(desc) { @@ -48,18 +54,21 @@ class ResourceLoader { '/resources/WebIDLParser.js', '/resources/webidl2/lib/webidl2.js' ); - const file = url.startsWith('/') ? - fixtures.path('wpt', url) : - fixtures.path('wpt', this.path, url); + const file = url.startsWith('/') + ? fixtures.path('wpt', url) + : fixtures.path('wpt', this.path, url); if (asPromise) { - return fsPromises.readFile(file) - .then((data) => { - return { - ok: true, - json() { return JSON.parse(data.toString()); }, - text() { return data.toString(); } - }; - }); + return fsPromises.readFile(file).then((data) => { + return { + ok: true, + json() { + return JSON.parse(data.toString()); + }, + text() { + return data.toString(); + } + }; + }); } else { return fs.readFileSync(file, 'utf8'); } @@ -76,7 +85,7 @@ class WPTTest { */ constructor(mod, filename, requires, failReason, skipReason) { this.module = mod; // name of the WPT module, e.g. 'url' - this.filename = filename; // name of the test file + this.filename = filename; // name of the test file this.requires = requires; this.failReason = failReason; this.skipReason = skipReason; @@ -117,8 +126,7 @@ class StatusLoader { failReason = this.status[file].fail; skipReason = this.status[file].skip; } - return new WPTTest(this.path, file, requires, - failReason, skipReason); + return new WPTTest(this.path, file, requires, failReason, skipReason); } load() { @@ -212,7 +220,7 @@ class WPTRunner { for (const test of queue) { const filename = test.filename; const content = test.getContent(); - const meta = test.title = this.getMeta(content); + const meta = (test.title = this.getMeta(content)); const absolutePath = test.getAbsolutePath(); const context = this.generateContext(test.filename); @@ -222,11 +230,15 @@ class WPTRunner { filename: absolutePath }); } catch (err) { - this.fail(filename, { - name: '', - message: err.message, - stack: err.stack - }, 'UNCAUGHT'); + this.fail( + filename, + { + name: '', + message: err.message, + stack: err.stack + }, + 'UNCAUGHT' + ); this.inProgress.delete(filename); } } @@ -244,7 +256,9 @@ class WPTRunner { }, location: {}, GLOBAL: { - isWindow() { return false; } + isWindow() { + return false; + } }, Object }; @@ -262,8 +276,8 @@ class WPTRunner { } generateContext(filename) { - const sandbox = this.sandbox = this.getSandbox(); - const context = this.context = vm.createContext(sandbox); + const sandbox = (this.sandbox = this.getSandbox()); + const context = (this.context = vm.createContext(sandbox)); const harnessPath = fixtures.path('wpt', 'resources', 'testharness.js'); const harness = fs.readFileSync(harnessPath, 'utf8'); @@ -271,16 +285,14 @@ class WPTRunner { filename: harnessPath }); - sandbox.add_result_callback( - this.resultCallback.bind(this, filename) - ); + sandbox.add_result_callback(this.resultCallback.bind(this, filename)); sandbox.add_completion_callback( this.completionCallback.bind(this, filename) ); sandbox.self = sandbox; // TODO(joyeecheung): we are not a window - work with the upstream to // add a new scope for us. - sandbox.document = {}; // Pretend we are Window + sandbox.document = {}; // Pretend we are Window return context; } @@ -352,8 +364,9 @@ class WPTRunner { console.log(`[${item.reason}] ${item.test.name}`); console.log(item.test.message); console.log(item.test.stack); - const command = `${process.execPath} ${process.execArgv}` + - ` ${require.main.filename} ${filename}`; + const command = + `${process.execPath} ${process.execArgv}` + + ` ${require.main.filename} ${filename}`; console.log(`Command: ${command}\n`); } assert.fail(`${unexpectedFailures.length} unexpected failures found`); diff --git a/test/doctool/test-apilinks.js b/test/doctool/test-apilinks.js index e53c81a08a7203..a5980e3bff5b15 100644 --- a/test/doctool/test-apilinks.js +++ b/test/doctool/test-apilinks.js @@ -16,24 +16,25 @@ fs.readdirSync(apilinks).forEach((fixture) => { const expectedContent = fs.readFileSync(file + 'on', 'utf8'); - const output = execFileSync( - process.execPath, - [script, file], - { encoding: 'utf-8' } - ); + const output = execFileSync(process.execPath, [script, file], { + encoding: 'utf-8' + }); const expectedLinks = JSON.parse(expectedContent); const actualLinks = JSON.parse(output); for (const [k, v] of Object.entries(expectedLinks)) { assert.ok(k in actualLinks, `link not found: ${k}`); - assert.ok(actualLinks[k].endsWith('/' + v), - `link ${actualLinks[k]} expected to end with ${v}`); + assert.ok( + actualLinks[k].endsWith('/' + v), + `link ${actualLinks[k]} expected to end with ${v}` + ); delete actualLinks[k]; } assert.strictEqual( - Object.keys(actualLinks).length, 0, + Object.keys(actualLinks).length, + 0, `unexpected links returned ${JSON.stringify(actualLinks)}` ); }); diff --git a/test/doctool/test-doctool-html.js b/test/doctool/test-doctool-html.js index 499034cd8a3684..a50ae87e409fb3 100644 --- a/test/doctool/test-doctool-html.js +++ b/test/doctool/test-doctool-html.js @@ -15,7 +15,8 @@ const html = require('../../tools/doc/html.js'); const path = require('path'); module.paths.unshift( - path.join(__dirname, '..', '..', 'tools', 'doc', 'node_modules')); + path.join(__dirname, '..', '..', 'tools', 'doc', 'node_modules') +); const unified = require('unified'); const markdown = require('remark-parse'); const remark2rehype = require('remark-rehype'); @@ -34,10 +35,7 @@ function toHTML({ input, filename, nodeVersion }, cb) { .use(htmlStringify) .processSync(input); - html.toHTML( - { input, content, filename, nodeVersion }, - cb - ); + html.toHTML({ input, content, filename, nodeVersion }, cb); } // Test data is a list of objects with two properties. @@ -48,12 +46,14 @@ function toHTML({ input, filename, nodeVersion }, cb) { const testData = [ { file: fixtures.path('sample_document.md'), - html: '
  1. fish
  2. fish
' + + html: + '
  1. fish
  2. fish
' + '
  • Redfish
  • Bluefish
' }, { file: fixtures.path('order_of_end_tags_5873.md'), - html: '

ClassMethod: Buffer.from(array) ' + + html: + '

ClassMethod: Buffer.from(array) ' + '#

' + '