From 3edd27248d95e9461f2241ce26b1b0362d7ee8c7 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Fri, 24 Mar 2017 09:46:44 -0700 Subject: [PATCH 01/82] test: add common.noop, default for common.mustCall() Export a new common.noop no-operation function for general use. Allow using common.mustCall() without a fn argument to simplify test cases. Replace various non-op functions throughout tests with common.noop PR-URL: https://github.com/nodejs/node/pull/12027 Reviewed-By: Jeremiah Senkpiel Reviewed-By: Richard Lau Reviewed-By: Gibson Fahnestock Reviewed-By: Teddy Katz Reviewed-By: Colin Ihrig Reviewed-By: Franziska Hinkelmann --- test/addons/async-hello-world/test.js | 2 +- test/common/index.js | 16 +++++-- test/debugger/test-debugger-client.js | 4 +- test/fixtures/child-process-persistent.js | 2 +- test/parallel/test-assert.js | 3 +- .../parallel/test-child-process-disconnect.js | 2 +- test/parallel/test-child-process-kill.js | 4 +- test/parallel/test-child-process-stdin.js | 4 +- test/parallel/test-cluster-eaccess.js | 4 +- .../test-cluster-setup-master-emit.js | 2 +- test/parallel/test-cluster-worker-destroy.js | 4 +- .../test-cluster-worker-wait-server-close.js | 2 +- test/parallel/test-common.js | 4 +- test/parallel/test-crypto-random.js | 2 +- .../test-dgram-close-is-not-callback.js | 2 +- test/parallel/test-dgram-close.js | 4 +- test/parallel/test-dgram-send-empty-buffer.js | 2 +- test/parallel/test-domain-crypto.js | 6 +-- test/parallel/test-domain-exit-dispose.js | 2 +- test/parallel/test-domain-timers.js | 2 +- test/parallel/test-domain.js | 4 +- test/parallel/test-env-var-no-warnings.js | 2 +- ...test-event-emitter-check-listener-leaks.js | 32 +++++++------- .../test-event-emitter-get-max-listeners.js | 6 +-- .../test-event-emitter-listener-count.js | 10 ++--- ...-emitter-max-listeners-warning-for-null.js | 4 +- ...mitter-max-listeners-warning-for-symbol.js | 4 +- ...est-event-emitter-max-listeners-warning.js | 6 +-- .../test-event-emitter-max-listeners.js | 2 +- test/parallel/test-event-emitter-once.js | 2 +- ...test-event-emitter-remove-all-listeners.js | 6 +-- test/parallel/test-event-emitter-subclass.js | 4 +- test/parallel/test-event-emitter-symbols.js | 2 +- test/parallel/test-fs-mkdir.js | 2 +- test/parallel/test-fs-read-stream-inherit.js | 12 ++--- test/parallel/test-fs-read-stream.js | 10 ++--- test/parallel/test-fs-watchfile.js | 2 +- test/parallel/test-handle-wrap-close-abort.js | 2 +- test/parallel/test-http-abort-client.js | 2 +- .../test-http-client-aborted-event.js | 2 +- test/parallel/test-http-invalidheaderfield.js | 4 +- .../test-http-pause-resume-one-end.js | 2 +- test/parallel/test-http-set-timeout-server.js | 8 ++-- test/parallel/test-http-upgrade-server.js | 4 +- test/parallel/test-https-close.js | 2 +- .../parallel/test-net-connect-options-ipv6.js | 2 +- test/parallel/test-net-connect-options.js | 2 +- ...n-close-server-callback-is-not-function.js | 2 +- .../parallel/test-net-socket-destroy-twice.js | 2 +- test/parallel/test-next-tick.js | 6 +-- test/parallel/test-process-next-tick.js | 2 +- .../test-promises-unhandled-rejections.js | 34 +++++++------- test/parallel/test-querystring.js | 4 +- test/parallel/test-readline-interface.js | 8 ++-- test/parallel/test-regress-GH-5051.js | 4 +- test/parallel/test-repl-.save.load.js | 6 +-- test/parallel/test-repl-history-perm.js | 2 +- test/parallel/test-repl-mode.js | 2 +- test/parallel/test-repl.js | 2 +- test/parallel/test-signal-handler.js | 4 +- test/parallel/test-stream-big-push.js | 2 +- test/parallel/test-stream-end-paused.js | 2 +- test/parallel/test-stream-events-prepend.js | 2 +- test/parallel/test-stream-pipe-after-end.js | 4 +- .../test-stream-pipe-error-handling.js | 6 +-- test/parallel/test-stream-readable-event.js | 6 +-- test/parallel/test-stream-wrap.js | 2 +- test/parallel/test-stream2-read-sync-stack.js | 2 +- .../test-stream2-readable-legacy-drain.js | 4 +- .../test-stream2-readable-non-empty-end.js | 2 +- .../test-stream2-readable-wrap-empty.js | 8 ++-- test/parallel/test-stream2-readable-wrap.js | 2 +- test/parallel/test-stream2-writable.js | 10 ++--- .../test-timers-uncaught-exception.js | 2 +- test/parallel/test-timers-unref-call.js | 4 +- ...-timers-unref-remove-other-unref-timers.js | 2 +- test/parallel/test-timers-unref.js | 8 ++-- test/parallel/test-timers-zero-timeout.js | 2 +- test/parallel/test-timers.js | 2 +- test/parallel/test-tls-cert-regression.js | 2 +- test/parallel/test-tls-connect-simple.js | 4 +- test/parallel/test-tls-connect.js | 4 +- .../parallel/test-tls-delayed-attach-error.js | 2 +- test/parallel/test-tls-env-extra-ca.js | 2 +- test/parallel/test-tls-invoke-queued.js | 2 +- test/parallel/test-tls-legacy-onselect.js | 2 +- test/parallel/test-tls-passphrase.js | 44 +++++++++---------- test/parallel/test-url.js | 4 +- test/parallel/test-util.js | 6 +-- test/parallel/test-vm-function-declaration.js | 2 +- test/parallel/test-zlib-close-after-write.js | 2 +- test/parallel/test-zlib-write-after-close.js | 2 +- test/parallel/test-zlib-zero-byte.js | 2 +- test/pummel/test-http-client-reconnect-bug.js | 2 +- test/pummel/test-net-connect-memleak.js | 2 +- test/pummel/test-stream2-basic.js | 4 +- test/sequential/test-child-process-pass-fd.js | 2 +- test/sequential/test-fs-watch.js | 2 +- .../test-https-set-timeout-server.js | 8 ++-- 99 files changed, 237 insertions(+), 226 deletions(-) diff --git a/test/addons/async-hello-world/test.js b/test/addons/async-hello-world/test.js index a6aa8aa20fffbc..fbd0d7eeb7ef13 100644 --- a/test/addons/async-hello-world/test.js +++ b/test/addons/async-hello-world/test.js @@ -6,5 +6,5 @@ const binding = require(`./build/${common.buildType}/binding`); binding(5, common.mustCall(function(err, val) { assert.strictEqual(err, null); assert.strictEqual(val, 10); - process.nextTick(common.mustCall(function() {})); + process.nextTick(common.mustCall()); })); diff --git a/test/common/index.js b/test/common/index.js index 455d50fe6c344a..21897a39cac456 100644 --- a/test/common/index.js +++ b/test/common/index.js @@ -12,6 +12,9 @@ const Timer = process.binding('timer_wrap').Timer; const testRoot = process.env.NODE_TEST_DIR ? fs.realpathSync(process.env.NODE_TEST_DIR) : path.resolve(__dirname, '..'); +const noop = () => {}; + +exports.noop = noop; exports.fixturesDir = path.join(__dirname, '..', 'fixtures'); exports.tmpDirName = 'tmp'; // PORT should match the definition in test/testpy/__init__.py. @@ -419,6 +422,13 @@ function runCallChecks(exitCode) { exports.mustCall = function(fn, expected) { + if (typeof fn === 'number') { + expected = fn; + fn = noop; + } else if (fn === undefined) { + fn = noop; + } + if (expected === undefined) expected = 1; else if (typeof expected !== 'number') @@ -487,9 +497,9 @@ util.inherits(ArrayStream, stream.Stream); exports.ArrayStream = ArrayStream; ArrayStream.prototype.readable = true; ArrayStream.prototype.writable = true; -ArrayStream.prototype.pause = function() {}; -ArrayStream.prototype.resume = function() {}; -ArrayStream.prototype.write = function() {}; +ArrayStream.prototype.pause = noop; +ArrayStream.prototype.resume = noop; +ArrayStream.prototype.write = noop; // Returns true if the exit code "exitCode" and/or signal name "signal" // represent the exit code and/or signal name of a node process that aborted, diff --git a/test/debugger/test-debugger-client.js b/test/debugger/test-debugger-client.js index 660d8e286ee250..89b22bc2a054fc 100644 --- a/test/debugger/test-debugger-client.js +++ b/test/debugger/test-debugger-client.js @@ -129,7 +129,7 @@ addTest(function(client, done) { let connectCount = 0; const script = 'setTimeout(function() { console.log("blah"); });' + - 'setInterval(function() {}, 1000000);'; + 'setInterval(common.noop, 1000000);'; let nodeProcess; @@ -172,7 +172,7 @@ function doTest(cb, done) { console.error('>>> connecting...'); c.connect(debug.port); c.on('break', function() { - c.reqContinue(function() {}); + c.reqContinue(common.noop); }); c.on('ready', function() { connectCount++; diff --git a/test/fixtures/child-process-persistent.js b/test/fixtures/child-process-persistent.js index 45a50f5a263ad6..c5b1f26d84f8b9 100644 --- a/test/fixtures/child-process-persistent.js +++ b/test/fixtures/child-process-persistent.js @@ -1 +1 @@ -setInterval(function() {}, 500); +setInterval(common.noop, 500); diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 3a81c6f810425a..ac55f6f5113857 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const a = require('assert'); @@ -515,6 +515,7 @@ testAssertionMessage(/a/, '/a/'); testAssertionMessage(/abc/gim, '/abc/gim'); testAssertionMessage(function f() {}, '[Function: f]'); testAssertionMessage(function() {}, '[Function]'); +testAssertionMessage(common.noop, '[Function: noop]'); testAssertionMessage({}, '{}'); testAssertionMessage(circular, '{ y: 1, x: [Circular] }'); testAssertionMessage({a: undefined, b: null}, '{ a: undefined, b: null }'); diff --git a/test/parallel/test-child-process-disconnect.js b/test/parallel/test-child-process-disconnect.js index ee9488d1cd0b05..d4fa99557cec11 100644 --- a/test/parallel/test-child-process-disconnect.js +++ b/test/parallel/test-child-process-disconnect.js @@ -57,7 +57,7 @@ if (process.argv[2] === 'child') { })); // the process should also self terminate without using signals - child.on('exit', common.mustCall(function() {})); + child.on('exit', common.mustCall()); // when child is listening child.on('message', function(obj) { diff --git a/test/parallel/test-child-process-kill.js b/test/parallel/test-child-process-kill.js index e0e951610dc146..02bd739f0beb27 100644 --- a/test/parallel/test-child-process-kill.js +++ b/test/parallel/test-child-process-kill.js @@ -4,9 +4,9 @@ const assert = require('assert'); const spawn = require('child_process').spawn; const cat = spawn(common.isWindows ? 'cmd' : 'cat'); -cat.stdout.on('end', common.mustCall(function() {})); +cat.stdout.on('end', common.mustCall()); cat.stderr.on('data', common.mustNotCall()); -cat.stderr.on('end', common.mustCall(function() {})); +cat.stderr.on('end', common.mustCall()); cat.on('exit', common.mustCall(function(code, signal) { assert.strictEqual(code, null); diff --git a/test/parallel/test-child-process-stdin.js b/test/parallel/test-child-process-stdin.js index 3da722ec71de2d..d811bc46b540e7 100644 --- a/test/parallel/test-child-process-stdin.js +++ b/test/parallel/test-child-process-stdin.js @@ -22,11 +22,11 @@ cat.stdout.on('data', function(chunk) { response += chunk; }); -cat.stdout.on('end', common.mustCall(function() {})); +cat.stdout.on('end', common.mustCall()); cat.stderr.on('data', common.mustNotCall()); -cat.stderr.on('end', common.mustCall(function() {})); +cat.stderr.on('end', common.mustCall()); cat.on('exit', common.mustCall(function(status) { assert.strictEqual(0, status); diff --git a/test/parallel/test-cluster-eaccess.js b/test/parallel/test-cluster-eaccess.js index 3682bac69064df..66ea101556db18 100644 --- a/test/parallel/test-cluster-eaccess.js +++ b/test/parallel/test-cluster-eaccess.js @@ -14,10 +14,10 @@ if (cluster.isMaster) { const worker = cluster.fork(); // makes sure master is able to fork the worker - cluster.on('fork', common.mustCall(function() {})); + cluster.on('fork', common.mustCall()); // makes sure the worker is ready - worker.on('online', common.mustCall(function() {})); + worker.on('online', common.mustCall()); worker.on('message', common.mustCall(function(err) { // disconnect first, so that we will not leave zombies diff --git a/test/parallel/test-cluster-setup-master-emit.js b/test/parallel/test-cluster-setup-master-emit.js index 5b828e7b8e360f..a93441c116dff4 100644 --- a/test/parallel/test-cluster-setup-master-emit.js +++ b/test/parallel/test-cluster-setup-master-emit.js @@ -22,5 +22,5 @@ function emitAndCatch2(next) { } emitAndCatch(common.mustCall(function() { - emitAndCatch2(common.mustCall(function() {})); + emitAndCatch2(common.mustCall()); })); diff --git a/test/parallel/test-cluster-worker-destroy.js b/test/parallel/test-cluster-worker-destroy.js index 62000254247a1f..4c03d4d440322d 100644 --- a/test/parallel/test-cluster-worker-destroy.js +++ b/test/parallel/test-cluster-worker-destroy.js @@ -17,8 +17,8 @@ if (cluster.isMaster) { worker2 = cluster.fork(); [worker1, worker2].forEach(function(worker) { - worker.on('disconnect', common.mustCall(function() {})); - worker.on('exit', common.mustCall(function() {})); + worker.on('disconnect', common.mustCall()); + worker.on('exit', common.mustCall()); }); } else { if (cluster.worker.id === 1) { diff --git a/test/parallel/test-cluster-worker-wait-server-close.js b/test/parallel/test-cluster-worker-wait-server-close.js index 1d19398a3d8799..f91003e9a5c33e 100644 --- a/test/parallel/test-cluster-worker-wait-server-close.js +++ b/test/parallel/test-cluster-worker-wait-server-close.js @@ -20,7 +20,7 @@ if (cluster.isWorker) { // Although not typical, the worker process can exit before the disconnect // event fires. Use this to keep the process open until the event has fired. - const keepOpen = setInterval(function() {}, 9999); + const keepOpen = setInterval(common.noop, 9999); // Check worker events and properties process.once('disconnect', function() { diff --git a/test/parallel/test-common.js b/test/parallel/test-common.js index 17f41840e4ffa5..86c6f8a0dd5b29 100644 --- a/test/parallel/test-common.js +++ b/test/parallel/test-common.js @@ -7,9 +7,9 @@ global.gc = 42; // Not a valid global unless --expose_gc is set. assert.deepStrictEqual(common.leakedGlobals(), ['gc']); assert.throws(function() { - common.mustCall(function() {}, 'foo'); + common.mustCall(common.noop, 'foo'); }, /^TypeError: Invalid expected value: foo$/); assert.throws(function() { - common.mustCall(function() {}, /foo/); + common.mustCall(common.noop, /foo/); }, /^TypeError: Invalid expected value: \/foo\/$/); diff --git a/test/parallel/test-crypto-random.js b/test/parallel/test-crypto-random.js index 28b8847e56478c..29928ad6e18a82 100644 --- a/test/parallel/test-crypto-random.js +++ b/test/parallel/test-crypto-random.js @@ -17,7 +17,7 @@ const expectedErrorRegexp = /^TypeError: size must be a number >= 0$/; [crypto.randomBytes, crypto.pseudoRandomBytes].forEach(function(f) { [-1, undefined, null, false, true, {}, []].forEach(function(value) { assert.throws(function() { f(value); }, expectedErrorRegexp); - assert.throws(function() { f(value, function() {}); }, expectedErrorRegexp); + assert.throws(function() { f(value, common.noop); }, expectedErrorRegexp); }); [0, 1, 2, 4, 16, 256, 1024].forEach(function(len) { diff --git a/test/parallel/test-dgram-close-is-not-callback.js b/test/parallel/test-dgram-close-is-not-callback.js index 416c5b305e1c49..70700a16c6a798 100644 --- a/test/parallel/test-dgram-close-is-not-callback.js +++ b/test/parallel/test-dgram-close-is-not-callback.js @@ -17,5 +17,5 @@ const portGetter = dgram.createSocket('udp4') socket.close('bad argument'); portGetter.close(); - socket.on('close', common.mustCall(function() {})); + socket.on('close', common.mustCall()); })); diff --git a/test/parallel/test-dgram-close.js b/test/parallel/test-dgram-close.js index 482cf529e6720f..f4845da479286a 100644 --- a/test/parallel/test-dgram-close.js +++ b/test/parallel/test-dgram-close.js @@ -18,8 +18,8 @@ const portGetter = dgram.createSocket('udp4') portGetter.address().port, portGetter.address().address); - assert.strictEqual(socket.close(common.mustCall(function() {})), socket); - socket.on('close', common.mustCall(function() {})); + assert.strictEqual(socket.close(common.mustCall()), socket); + socket.on('close', common.mustCall()); socket = null; // Verify that accessing handle after closure doesn't throw diff --git a/test/parallel/test-dgram-send-empty-buffer.js b/test/parallel/test-dgram-send-empty-buffer.js index 56a0383eb14c9e..0486b2bdbe3959 100644 --- a/test/parallel/test-dgram-send-empty-buffer.js +++ b/test/parallel/test-dgram-send-empty-buffer.js @@ -22,6 +22,6 @@ client.bind(0, common.mustCall(function() { const buf = Buffer.alloc(0); let interval = setInterval(function() { - client.send(buf, 0, 0, port, '127.0.0.1', common.mustCall(function() {})); + client.send(buf, 0, 0, port, '127.0.0.1', common.mustCall()); }, 10); })); diff --git a/test/parallel/test-domain-crypto.js b/test/parallel/test-domain-crypto.js index dfa2636816aff4..bc9c4b6d467ec4 100644 --- a/test/parallel/test-domain-crypto.js +++ b/test/parallel/test-domain-crypto.js @@ -17,7 +17,7 @@ global.domain = require('domain'); // should not throw a 'TypeError: undefined is not a function' exception crypto.randomBytes(8); -crypto.randomBytes(8, function() {}); +crypto.randomBytes(8, common.noop); crypto.pseudoRandomBytes(8); -crypto.pseudoRandomBytes(8, function() {}); -crypto.pbkdf2('password', 'salt', 8, 8, function() {}); +crypto.pseudoRandomBytes(8, common.noop); +crypto.pbkdf2('password', 'salt', 8, 8, common.noop); diff --git a/test/parallel/test-domain-exit-dispose.js b/test/parallel/test-domain-exit-dispose.js index e1797cb660a0c0..a9c69ac3396712 100644 --- a/test/parallel/test-domain-exit-dispose.js +++ b/test/parallel/test-domain-exit-dispose.js @@ -22,7 +22,7 @@ function err() { function err2() { // this timeout should never be called, since the domain gets // disposed when the error happens. - setTimeout(common.mustCall(() => {}, 0), 1); + setTimeout(common.mustNotCall(), 1); // this function doesn't exist, and throws an error as a result. err3(); // eslint-disable-line no-undef diff --git a/test/parallel/test-domain-timers.js b/test/parallel/test-domain-timers.js index 7d51b61fd04be6..7fff5468564449 100644 --- a/test/parallel/test-domain-timers.js +++ b/test/parallel/test-domain-timers.js @@ -32,4 +32,4 @@ immediated.run(function() { }); }); -timeout = setTimeout(function() {}, 10 * 1000); +timeout = setTimeout(common.noop, 10 * 1000); diff --git a/test/parallel/test-domain.js b/test/parallel/test-domain.js index ab286429f5c5d5..f5dc699f2595b9 100644 --- a/test/parallel/test-domain.js +++ b/test/parallel/test-domain.js @@ -1,7 +1,7 @@ 'use strict'; // Simple tests of most basic domain functionality. -require('../common'); +const common = require('../common'); const assert = require('assert'); const domain = require('domain'); const events = require('events'); @@ -238,7 +238,7 @@ let fst = fs.createReadStream('stream for nonexistent file'); d.add(fst); expectCaught++; -[42, null, , false, function() {}, 'string'].forEach(function(something) { +[42, null, , false, common.noop, 'string'].forEach(function(something) { const d = new domain.Domain(); d.run(function() { process.nextTick(function() { diff --git a/test/parallel/test-env-var-no-warnings.js b/test/parallel/test-env-var-no-warnings.js index 1df31d8920753d..37774f2a161a52 100644 --- a/test/parallel/test-env-var-no-warnings.js +++ b/test/parallel/test-env-var-no-warnings.js @@ -29,7 +29,7 @@ if (process.argv[2] === 'child') { test({ NODE_NO_WARNINGS: false }); test({ NODE_NO_WARNINGS: {} }); test({ NODE_NO_WARNINGS: [] }); - test({ NODE_NO_WARNINGS: function() {} }); + test({ NODE_NO_WARNINGS: common.noop }); test({ NODE_NO_WARNINGS: 0 }); test({ NODE_NO_WARNINGS: -1 }); test({ NODE_NO_WARNINGS: '0' }); diff --git a/test/parallel/test-event-emitter-check-listener-leaks.js b/test/parallel/test-event-emitter-check-listener-leaks.js index 5b9787f1b83bba..0f5f3757c64932 100644 --- a/test/parallel/test-event-emitter-check-listener-leaks.js +++ b/test/parallel/test-event-emitter-check-listener-leaks.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const events = require('events'); @@ -7,40 +7,40 @@ let e = new events.EventEmitter(); // default for (let i = 0; i < 10; i++) { - e.on('default', function() {}); + e.on('default', common.noop); } assert.ok(!e._events['default'].hasOwnProperty('warned')); -e.on('default', function() {}); +e.on('default', common.noop); assert.ok(e._events['default'].warned); // symbol const symbol = Symbol('symbol'); e.setMaxListeners(1); -e.on(symbol, function() {}); +e.on(symbol, common.noop); assert.ok(!e._events[symbol].hasOwnProperty('warned')); -e.on(symbol, function() {}); +e.on(symbol, common.noop); assert.ok(e._events[symbol].hasOwnProperty('warned')); // specific e.setMaxListeners(5); for (let i = 0; i < 5; i++) { - e.on('specific', function() {}); + e.on('specific', common.noop); } assert.ok(!e._events['specific'].hasOwnProperty('warned')); -e.on('specific', function() {}); +e.on('specific', common.noop); assert.ok(e._events['specific'].warned); // only one e.setMaxListeners(1); -e.on('only one', function() {}); +e.on('only one', common.noop); assert.ok(!e._events['only one'].hasOwnProperty('warned')); -e.on('only one', function() {}); +e.on('only one', common.noop); assert.ok(e._events['only one'].hasOwnProperty('warned')); // unlimited e.setMaxListeners(0); for (let i = 0; i < 1000; i++) { - e.on('unlimited', function() {}); + e.on('unlimited', common.noop); } assert.ok(!e._events['unlimited'].hasOwnProperty('warned')); @@ -49,26 +49,26 @@ events.EventEmitter.defaultMaxListeners = 42; e = new events.EventEmitter(); for (let i = 0; i < 42; ++i) { - e.on('fortytwo', function() {}); + e.on('fortytwo', common.noop); } assert.ok(!e._events['fortytwo'].hasOwnProperty('warned')); -e.on('fortytwo', function() {}); +e.on('fortytwo', common.noop); assert.ok(e._events['fortytwo'].hasOwnProperty('warned')); delete e._events['fortytwo'].warned; events.EventEmitter.defaultMaxListeners = 44; -e.on('fortytwo', function() {}); +e.on('fortytwo', common.noop); assert.ok(!e._events['fortytwo'].hasOwnProperty('warned')); -e.on('fortytwo', function() {}); +e.on('fortytwo', common.noop); assert.ok(e._events['fortytwo'].hasOwnProperty('warned')); // but _maxListeners still has precedence over defaultMaxListeners events.EventEmitter.defaultMaxListeners = 42; e = new events.EventEmitter(); e.setMaxListeners(1); -e.on('uno', function() {}); +e.on('uno', common.noop); assert.ok(!e._events['uno'].hasOwnProperty('warned')); -e.on('uno', function() {}); +e.on('uno', common.noop); assert.ok(e._events['uno'].hasOwnProperty('warned')); // chainable diff --git a/test/parallel/test-event-emitter-get-max-listeners.js b/test/parallel/test-event-emitter-get-max-listeners.js index 9acc71fd7920e3..98ac02e87130b5 100644 --- a/test/parallel/test-event-emitter-get-max-listeners.js +++ b/test/parallel/test-event-emitter-get-max-listeners.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const EventEmitter = require('events'); @@ -15,5 +15,5 @@ assert.strictEqual(emitter.getMaxListeners(), 3); // https://github.com/nodejs/node/issues/523 - second call should not throw. const recv = {}; -EventEmitter.prototype.on.call(recv, 'event', function() {}); -EventEmitter.prototype.on.call(recv, 'event', function() {}); +EventEmitter.prototype.on.call(recv, 'event', common.noop); +EventEmitter.prototype.on.call(recv, 'event', common.noop); diff --git a/test/parallel/test-event-emitter-listener-count.js b/test/parallel/test-event-emitter-listener-count.js index ebfed8b2ee33b1..50247f42770ba8 100644 --- a/test/parallel/test-event-emitter-listener-count.js +++ b/test/parallel/test-event-emitter-listener-count.js @@ -1,15 +1,15 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const EventEmitter = require('events'); const emitter = new EventEmitter(); -emitter.on('foo', function() {}); -emitter.on('foo', function() {}); -emitter.on('baz', function() {}); +emitter.on('foo', common.noop); +emitter.on('foo', common.noop); +emitter.on('baz', common.noop); // Allow any type -emitter.on(123, function() {}); +emitter.on(123, common.noop); assert.strictEqual(EventEmitter.listenerCount(emitter, 'foo'), 2); assert.strictEqual(emitter.listenerCount('foo'), 2); diff --git a/test/parallel/test-event-emitter-max-listeners-warning-for-null.js b/test/parallel/test-event-emitter-max-listeners-warning-for-null.js index 62b06f67d92f28..16d9e28bb1eb44 100644 --- a/test/parallel/test-event-emitter-max-listeners-warning-for-null.js +++ b/test/parallel/test-event-emitter-max-listeners-warning-for-null.js @@ -18,5 +18,5 @@ process.on('warning', common.mustCall((warning) => { assert.ok(warning.message.includes('2 null listeners added.')); })); -e.on(null, function() {}); -e.on(null, function() {}); +e.on(null, common.noop); +e.on(null, common.noop); diff --git a/test/parallel/test-event-emitter-max-listeners-warning-for-symbol.js b/test/parallel/test-event-emitter-max-listeners-warning-for-symbol.js index 97bf189270395b..bd1a8bec7758b0 100644 --- a/test/parallel/test-event-emitter-max-listeners-warning-for-symbol.js +++ b/test/parallel/test-event-emitter-max-listeners-warning-for-symbol.js @@ -20,5 +20,5 @@ process.on('warning', common.mustCall((warning) => { assert.ok(warning.message.includes('2 Symbol(symbol) listeners added.')); })); -e.on(symbol, function() {}); -e.on(symbol, function() {}); +e.on(symbol, common.noop); +e.on(symbol, common.noop); diff --git a/test/parallel/test-event-emitter-max-listeners-warning.js b/test/parallel/test-event-emitter-max-listeners-warning.js index 21f4ee0cc6bcde..f0cdac1919d209 100644 --- a/test/parallel/test-event-emitter-max-listeners-warning.js +++ b/test/parallel/test-event-emitter-max-listeners-warning.js @@ -18,6 +18,6 @@ process.on('warning', common.mustCall((warning) => { assert.ok(warning.message.includes('2 event-type listeners added.')); })); -e.on('event-type', function() {}); -e.on('event-type', function() {}); // Trigger warning. -e.on('event-type', function() {}); // Verify that warning is emitted only once. +e.on('event-type', common.noop); +e.on('event-type', common.noop); // Trigger warning. +e.on('event-type', common.noop); // Verify that warning is emitted only once. diff --git a/test/parallel/test-event-emitter-max-listeners.js b/test/parallel/test-event-emitter-max-listeners.js index 2946c48f8fb30e..88156e90a0b347 100644 --- a/test/parallel/test-event-emitter-max-listeners.js +++ b/test/parallel/test-event-emitter-max-listeners.js @@ -4,7 +4,7 @@ const assert = require('assert'); const events = require('events'); const e = new events.EventEmitter(); -e.on('maxListeners', common.mustCall(function() {})); +e.on('maxListeners', common.mustCall()); // Should not corrupt the 'maxListeners' queue. e.setMaxListeners(42); diff --git a/test/parallel/test-event-emitter-once.js b/test/parallel/test-event-emitter-once.js index e304bccb6e2d42..c23a6c6769c0e6 100644 --- a/test/parallel/test-event-emitter-once.js +++ b/test/parallel/test-event-emitter-once.js @@ -24,7 +24,7 @@ e.once('e', common.mustCall(function() { e.emit('e'); })); -e.once('e', common.mustCall(function() {})); +e.once('e', common.mustCall()); e.emit('e'); diff --git a/test/parallel/test-event-emitter-remove-all-listeners.js b/test/parallel/test-event-emitter-remove-all-listeners.js index e793cedb0dd4cf..8c4d2caa74fb58 100644 --- a/test/parallel/test-event-emitter-remove-all-listeners.js +++ b/test/parallel/test-event-emitter-remove-all-listeners.js @@ -70,9 +70,9 @@ function listener() {} ee.on('removeListener', function(name, listener) { assert.strictEqual(expectLength--, this.listeners('baz').length); }); - ee.on('baz', function() {}); - ee.on('baz', function() {}); - ee.on('baz', function() {}); + ee.on('baz', common.noop); + ee.on('baz', common.noop); + ee.on('baz', common.noop); assert.strictEqual(ee.listeners('baz').length, expectLength + 1); ee.removeAllListeners('baz'); assert.strictEqual(ee.listeners('baz').length, 0); diff --git a/test/parallel/test-event-emitter-subclass.js b/test/parallel/test-event-emitter-subclass.js index eb2018e78e4b85..c0ce3392f7298f 100644 --- a/test/parallel/test-event-emitter-subclass.js +++ b/test/parallel/test-event-emitter-subclass.js @@ -13,7 +13,7 @@ function MyEE(cb) { EventEmitter.call(this); } -const myee = new MyEE(common.mustCall(function() {})); +const myee = new MyEE(common.mustCall()); util.inherits(ErrorEE, EventEmitter); @@ -41,6 +41,6 @@ MyEE2.prototype = new EventEmitter(); const ee1 = new MyEE2(); const ee2 = new MyEE2(); -ee1.on('x', function() {}); +ee1.on('x', common.noop); assert.strictEqual(ee2.listenerCount('x'), 0); diff --git a/test/parallel/test-event-emitter-symbols.js b/test/parallel/test-event-emitter-symbols.js index 9a2ae72f64464c..98d44ff3fa2afb 100644 --- a/test/parallel/test-event-emitter-symbols.js +++ b/test/parallel/test-event-emitter-symbols.js @@ -6,7 +6,7 @@ const assert = require('assert'); const ee = new EventEmitter(); const foo = Symbol('foo'); -const listener = common.mustCall(function() {}); +const listener = common.mustCall(); ee.on(foo, listener); assert.deepStrictEqual(ee.listeners(foo), [listener]); diff --git a/test/parallel/test-fs-mkdir.js b/test/parallel/test-fs-mkdir.js index e70880ef981d7e..cf744215a04ea4 100644 --- a/test/parallel/test-fs-mkdir.js +++ b/test/parallel/test-fs-mkdir.js @@ -56,4 +56,4 @@ common.refreshTmpDir(); // Keep the event loop alive so the async mkdir() requests // have a chance to run (since they don't ref the event loop). -process.nextTick(function() {}); +process.nextTick(common.noop); diff --git a/test/parallel/test-fs-read-stream-inherit.js b/test/parallel/test-fs-read-stream-inherit.js index d71dc3d4381272..b0bbde153539cc 100644 --- a/test/parallel/test-fs-read-stream-inherit.js +++ b/test/parallel/test-fs-read-stream-inherit.js @@ -39,7 +39,7 @@ let paused = false; }); - file.on('end', common.mustCall(function() {})); + file.on('end', common.mustCall()); file.on('close', common.mustCall(function() { @@ -139,7 +139,7 @@ let paused = false; let file7 = fs.createReadStream(rangeFile, Object.create({autoClose: false })); assert.strictEqual(file7.autoClose, false); - file7.on('data', function() {}); + file7.on('data', common.noop); file7.on('end', common.mustCall(function() { process.nextTick(common.mustCall(function() { assert(!file7.closed); @@ -169,8 +169,8 @@ let paused = false; { const options = Object.create({fd: 13337, autoClose: false}); const file8 = fs.createReadStream(null, options); - file8.on('data', function() {}); - file8.on('error', common.mustCall(function() {})); + file8.on('data', common.noop); + file8.on('error', common.mustCall()); process.on('exit', function() { assert(!file8.closed); assert(!file8.destroyed); @@ -181,8 +181,8 @@ let paused = false; // Make sure stream is destroyed when file does not exist. { const file9 = fs.createReadStream('/path/to/file/that/does/not/exist'); - file9.on('data', function() {}); - file9.on('error', common.mustCall(function() {})); + file9.on('data', common.noop); + file9.on('error', common.mustCall()); process.on('exit', function() { assert(!file9.closed); diff --git a/test/parallel/test-fs-read-stream.js b/test/parallel/test-fs-read-stream.js index d17703fabe6a27..5948845fcd8cbc 100644 --- a/test/parallel/test-fs-read-stream.js +++ b/test/parallel/test-fs-read-stream.js @@ -138,7 +138,7 @@ pauseRes.pause(); pauseRes.resume(); let file7 = fs.createReadStream(rangeFile, {autoClose: false }); -file7.on('data', function() {}); +file7.on('data', common.noop); file7.on('end', function() { process.nextTick(function() { assert(!file7.closed); @@ -161,13 +161,13 @@ function file7Next() { // Just to make sure autoClose won't close the stream because of error. const file8 = fs.createReadStream(null, {fd: 13337, autoClose: false }); -file8.on('data', function() {}); -file8.on('error', common.mustCall(function() {})); +file8.on('data', common.noop); +file8.on('error', common.mustCall()); // Make sure stream is destroyed when file does not exist. const file9 = fs.createReadStream('/path/to/file/that/does/not/exist'); -file9.on('data', function() {}); -file9.on('error', common.mustCall(function() {})); +file9.on('data', common.noop); +file9.on('error', common.mustCall()); process.on('exit', function() { assert(file7.closed); diff --git a/test/parallel/test-fs-watchfile.js b/test/parallel/test-fs-watchfile.js index fcd28be0c1f126..f583eb8989c06f 100644 --- a/test/parallel/test-fs-watchfile.js +++ b/test/parallel/test-fs-watchfile.js @@ -15,7 +15,7 @@ assert.throws(function() { }, /"watchFile\(\)" requires a listener function/); assert.throws(function() { - fs.watchFile(new Object(), function() {}); + fs.watchFile(new Object(), common.noop); }, /Path must be a string/); const enoentFile = path.join(common.tmpDir, 'non-existent-file'); diff --git a/test/parallel/test-handle-wrap-close-abort.js b/test/parallel/test-handle-wrap-close-abort.js index e9f69195ad29cd..492907ee05540f 100644 --- a/test/parallel/test-handle-wrap-close-abort.js +++ b/test/parallel/test-handle-wrap-close-abort.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -process.on('uncaughtException', common.mustCall(function() {}, 2)); +process.on('uncaughtException', common.mustCall(common.noop, 2)); setTimeout(function() { process.nextTick(function() { diff --git a/test/parallel/test-http-abort-client.js b/test/parallel/test-http-abort-client.js index 8d3960376761e5..c44681cf9a9884 100644 --- a/test/parallel/test-http-abort-client.js +++ b/test/parallel/test-http-abort-client.js @@ -38,6 +38,6 @@ server.listen(0, common.mustCall(function() { }); // it would be nice if this worked: - res.on('close', common.mustCall(function() {})); + res.on('close', common.mustCall()); })); })); diff --git a/test/parallel/test-http-client-aborted-event.js b/test/parallel/test-http-client-aborted-event.js index 951a128f51b261..a9036a927df1e6 100644 --- a/test/parallel/test-http-client-aborted-event.js +++ b/test/parallel/test-http-client-aborted-event.js @@ -13,6 +13,6 @@ server.listen(0, common.mustCall(function() { headers: { connection: 'keep-alive' } }, common.mustCall(function(res) { server.close(); - res.on('aborted', common.mustCall(function() {})); + res.on('aborted', common.mustCall()); })); })); diff --git a/test/parallel/test-http-invalidheaderfield.js b/test/parallel/test-http-invalidheaderfield.js index aaed46c69cd592..6bae65c86e726f 100644 --- a/test/parallel/test-http-invalidheaderfield.js +++ b/test/parallel/test-http-invalidheaderfield.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const EventEmitter = require('events'); const http = require('http'); @@ -28,7 +28,7 @@ server.listen(0, function() { port: server.address().port, headers: {'testing 123': 123} }; - http.get(options, function() {}); + http.get(options, common.noop); }, function(err) { ee.emit('done'); diff --git a/test/parallel/test-http-pause-resume-one-end.js b/test/parallel/test-http-pause-resume-one-end.js index 6b98246cc271ac..5f5ab4b309e078 100644 --- a/test/parallel/test-http-pause-resume-one-end.js +++ b/test/parallel/test-http-pause-resume-one-end.js @@ -22,6 +22,6 @@ server.listen(0, common.mustCall(function() { }); })); - res.on('end', common.mustCall(function() {})); + res.on('end', common.mustCall()); })); })); diff --git a/test/parallel/test-http-set-timeout-server.js b/test/parallel/test-http-set-timeout-server.js index 8f301af5a9dcc4..314b5f56b2601c 100644 --- a/test/parallel/test-http-set-timeout-server.js +++ b/test/parallel/test-http-set-timeout-server.js @@ -31,7 +31,7 @@ test(function serverTimeout(cb) { // just do nothing, we should get a timeout event. }); server.listen(common.mustCall(function() { - http.get({ port: server.address().port }).on('error', function() {}); + http.get({ port: server.address().port }).on('error', common.noop); })); const s = server.setTimeout(50, function(socket) { caughtTimeout = true; @@ -60,7 +60,7 @@ test(function serverRequestTimeout(cb) { server.listen(common.mustCall(function() { const port = server.address().port; const req = http.request({ port: port, method: 'POST' }); - req.on('error', function() {}); + req.on('error', common.noop); req.write('Hello'); // req is in progress })); @@ -83,7 +83,7 @@ test(function serverResponseTimeout(cb) { }); server.listen(common.mustCall(function() { const port = server.address().port; - http.get({ port: port }).on('error', function() {}); + http.get({ port: port }).on('error', common.noop); })); }); @@ -111,7 +111,7 @@ test(function serverRequestNotTimeoutAfterEnd(cb) { }); server.listen(common.mustCall(function() { const port = server.address().port; - http.get({ port: port }).on('error', function() {}); + http.get({ port: port }).on('error', common.noop); })); }); diff --git a/test/parallel/test-http-upgrade-server.js b/test/parallel/test-http-upgrade-server.js index c641f1576e8703..72c9313b846184 100644 --- a/test/parallel/test-http-upgrade-server.js +++ b/test/parallel/test-http-upgrade-server.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const util = require('util'); @@ -16,7 +16,7 @@ function createTestServer() { } function testServer() { - http.Server.call(this, function() {}); + http.Server.call(this, common.noop); this.on('connection', function() { requests_recv++; diff --git a/test/parallel/test-https-close.js b/test/parallel/test-https-close.js index a9b2a579637408..20f03a591cd992 100644 --- a/test/parallel/test-https-close.js +++ b/test/parallel/test-https-close.js @@ -31,7 +31,7 @@ server.on('connection', function(connection) { }); function shutdown() { - server.close(common.mustCall(function() {})); + server.close(common.mustCall()); for (const key in connections) { connections[key].destroy(); diff --git a/test/parallel/test-net-connect-options-ipv6.js b/test/parallel/test-net-connect-options-ipv6.js index e9d8a78cbbefef..2164f550ce941f 100644 --- a/test/parallel/test-net-connect-options-ipv6.js +++ b/test/parallel/test-net-connect-options-ipv6.js @@ -15,7 +15,7 @@ let localhostTries = 10; const server = net.createServer({allowHalfOpen: true}, function(socket) { socket.resume(); - socket.on('end', common.mustCall(function() {})); + socket.on('end', common.mustCall()); socket.end(); }); diff --git a/test/parallel/test-net-connect-options.js b/test/parallel/test-net-connect-options.js index e794c40859856a..09db7ccea97bfb 100644 --- a/test/parallel/test-net-connect-options.js +++ b/test/parallel/test-net-connect-options.js @@ -7,7 +7,7 @@ const server = net.createServer({ allowHalfOpen: true }, common.mustCall(function(socket) { socket.resume(); - socket.on('end', common.mustCall(function() {})); + socket.on('end', common.mustCall()); socket.end(); })); diff --git a/test/parallel/test-net-listen-close-server-callback-is-not-function.js b/test/parallel/test-net-listen-close-server-callback-is-not-function.js index 243ec038f75aeb..459ca3e5384445 100644 --- a/test/parallel/test-net-listen-close-server-callback-is-not-function.js +++ b/test/parallel/test-net-listen-close-server-callback-is-not-function.js @@ -4,7 +4,7 @@ const net = require('net'); const server = net.createServer(common.mustNotCall()); -server.on('close', common.mustCall(function() {})); +server.on('close', common.mustCall()); server.listen(0, common.mustNotCall()); diff --git a/test/parallel/test-net-socket-destroy-twice.js b/test/parallel/test-net-socket-destroy-twice.js index 749964751b39ad..3763acdf7ce3ed 100644 --- a/test/parallel/test-net-socket-destroy-twice.js +++ b/test/parallel/test-net-socket-destroy-twice.js @@ -11,5 +11,5 @@ conn.on('error', common.mustCall(() => { conn.destroy(); })); -conn.on('close', common.mustCall(function() {})); +conn.on('close', common.mustCall()); server.close(); diff --git a/test/parallel/test-next-tick.js b/test/parallel/test-next-tick.js index 001e8a2e471e03..a57b6444fc9835 100644 --- a/test/parallel/test-next-tick.js +++ b/test/parallel/test-next-tick.js @@ -4,15 +4,15 @@ const assert = require('assert'); process.nextTick(common.mustCall(function() { process.nextTick(common.mustCall(function() { - process.nextTick(common.mustCall(function() {})); + process.nextTick(common.mustCall()); })); })); setTimeout(common.mustCall(function() { - process.nextTick(common.mustCall(function() {})); + process.nextTick(common.mustCall()); }), 50); -process.nextTick(common.mustCall(function() {})); +process.nextTick(common.mustCall()); const obj = {}; diff --git a/test/parallel/test-process-next-tick.js b/test/parallel/test-process-next-tick.js index e67ebae0a29559..383b87a030a0b5 100644 --- a/test/parallel/test-process-next-tick.js +++ b/test/parallel/test-process-next-tick.js @@ -10,7 +10,7 @@ for (let i = 0; i < N; ++i) { process.nextTick(common.mustCall(cb)); } -process.on('uncaughtException', common.mustCall(function() {}, N)); +process.on('uncaughtException', common.mustCall(common.noop, N)); process.on('exit', function() { process.removeAllListeners('uncaughtException'); diff --git a/test/parallel/test-promises-unhandled-rejections.js b/test/parallel/test-promises-unhandled-rejections.js index 87dc743625a0ab..8fe3d46864ee24 100644 --- a/test/parallel/test-promises-unhandled-rejections.js +++ b/test/parallel/test-promises-unhandled-rejections.js @@ -164,7 +164,7 @@ asyncTest('Catching a promise rejection after setImmediate is not' + }); _reject(e); setImmediate(function() { - promise.then(common.fail, function() {}); + promise.then(common.fail, common.noop); }); }); @@ -240,7 +240,7 @@ asyncTest( function(done) { const e = new Error(); onUnhandledFail(done); - Promise.reject(e).then(common.fail, function() {}); + Promise.reject(e).then(common.fail, common.noop); } ); @@ -252,7 +252,7 @@ asyncTest( onUnhandledFail(done); new Promise(function(_, reject) { reject(e); - }).then(common.fail, function() {}); + }).then(common.fail, common.noop); } ); @@ -262,7 +262,7 @@ asyncTest('Attaching a promise catch in a process.nextTick is soon enough to' + onUnhandledFail(done); const promise = Promise.reject(e); process.nextTick(function() { - promise.then(common.fail, function() {}); + promise.then(common.fail, common.noop); }); }); @@ -274,7 +274,7 @@ asyncTest('Attaching a promise catch in a process.nextTick is soon enough to' + reject(e); }); process.nextTick(function() { - promise.then(common.fail, function() {}); + promise.then(common.fail, common.noop); }); }); @@ -385,7 +385,7 @@ asyncTest('Catching the Promise.all() of a collection that includes a' + 'rejected promise prevents unhandledRejection', function(done) { const e = new Error(); onUnhandledFail(done); - Promise.all([Promise.reject(e)]).then(common.fail, function() {}); + Promise.all([Promise.reject(e)]).then(common.fail, common.noop); }); asyncTest( @@ -401,7 +401,7 @@ asyncTest( }); p = Promise.all([p]); process.nextTick(function() { - p.then(common.fail, function() {}); + p.then(common.fail, common.noop); }); } ); @@ -455,7 +455,7 @@ asyncTest('Waiting for some combination of process.nextTick + promise' + Promise.resolve().then(function() { process.nextTick(function() { Promise.resolve().then(function() { - a.catch(function() {}); + a.catch(common.noop); }); }); }); @@ -474,7 +474,7 @@ asyncTest('Waiting for some combination of process.nextTick + promise' + Promise.resolve().then(function() { process.nextTick(function() { Promise.resolve().then(function() { - a.catch(function() {}); + a.catch(common.noop); }); }); }); @@ -494,7 +494,7 @@ asyncTest('Waiting for some combination of process.nextTick + promise ' + Promise.resolve().then(function() { process.nextTick(function() { Promise.resolve().then(function() { - a.catch(function() {}); + a.catch(common.noop); }); }); }); @@ -514,7 +514,7 @@ asyncTest('Waiting for some combination of promise microtasks + ' + process.nextTick(function() { Promise.resolve().then(function() { process.nextTick(function() { - a.catch(function() {}); + a.catch(common.noop); }); }); }); @@ -535,7 +535,7 @@ asyncTest( process.nextTick(function() { Promise.resolve().then(function() { process.nextTick(function() { - a.catch(function() {}); + a.catch(common.noop); }); }); }); @@ -556,7 +556,7 @@ asyncTest('Waiting for some combination of promise microtasks +' + process.nextTick(function() { Promise.resolve().then(function() { process.nextTick(function() { - a.catch(function() {}); + a.catch(common.noop); }); }); }); @@ -575,7 +575,7 @@ asyncTest('setImmediate + promise microtasks is too late to attach a catch' + let p = Promise.reject(e); setImmediate(function() { Promise.resolve().then(function() { - p.catch(function() {}); + p.catch(common.noop); }); }); }); @@ -592,7 +592,7 @@ asyncTest('setImmediate + promise microtasks is too late to attach a catch' + Promise.resolve().then(function() { Promise.resolve().then(function() { Promise.resolve().then(function() { - p.catch(function() {}); + p.catch(common.noop); }); }); }); @@ -614,7 +614,7 @@ asyncTest('setImmediate + promise microtasks is too late to attach a catch' + Promise.resolve().then(function() { Promise.resolve().then(function() { Promise.resolve().then(function() { - p.catch(function() {}); + p.catch(common.noop); }); }); }); @@ -682,7 +682,7 @@ asyncTest('Throwing an error inside a rejectionHandled handler goes to' + const p = Promise.reject(e); setTimeout(function() { try { - p.catch(function() {}); + p.catch(common.noop); } catch (e) { done(new Error('fail')); } diff --git a/test/parallel/test-querystring.js b/test/parallel/test-querystring.js index bc28eddd2a8a3a..6b636c337927de 100644 --- a/test/parallel/test-querystring.js +++ b/test/parallel/test-querystring.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); // test using assert @@ -72,7 +72,7 @@ extendedFunction.prototype = {a: 'b'}; const qsWeirdObjects = [ [{regexp: /./g}, 'regexp=', {'regexp': ''}], [{regexp: new RegExp('.', 'g')}, 'regexp=', {'regexp': ''}], - [{fn: function() {}}, 'fn=', {'fn': ''}], + [{fn: common.noop}, 'fn=', {'fn': ''}], [{fn: new Function('')}, 'fn=', {'fn': ''}], [{math: Math}, 'math=', {'math': ''}], [{e: extendedFunction}, 'e=', {'e': ''}], diff --git a/test/parallel/test-readline-interface.js b/test/parallel/test-readline-interface.js index e89da72a6fb738..ddabc20b39026f 100644 --- a/test/parallel/test-readline-interface.js +++ b/test/parallel/test-readline-interface.js @@ -11,10 +11,10 @@ function FakeInput() { EventEmitter.call(this); } inherits(FakeInput, EventEmitter); -FakeInput.prototype.resume = function() {}; -FakeInput.prototype.pause = function() {}; -FakeInput.prototype.write = function() {}; -FakeInput.prototype.end = function() {}; +FakeInput.prototype.resume = common.noop; +FakeInput.prototype.pause = common.noop; +FakeInput.prototype.write = common.noop; +FakeInput.prototype.end = common.noop; function isWarned(emitter) { for (const name in emitter) { diff --git a/test/parallel/test-regress-GH-5051.js b/test/parallel/test-regress-GH-5051.js index ecaf55d625b815..f0a2d7aa7f1825 100644 --- a/test/parallel/test-regress-GH-5051.js +++ b/test/parallel/test-regress-GH-5051.js @@ -1,11 +1,11 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const agent = require('http').globalAgent; // small stub just so we can call addRequest directly const req = { - getHeader: function() {} + getHeader: common.noop }; agent.maxSockets = 0; diff --git a/test/parallel/test-repl-.save.load.js b/test/parallel/test-repl-.save.load.js index 449dd28e90d59e..283fc142f9650a 100644 --- a/test/parallel/test-repl-.save.load.js +++ b/test/parallel/test-repl-.save.load.js @@ -77,7 +77,7 @@ putIn.write = function(data) { // make sure I get a failed to load message and not some crazy error assert.strictEqual(data, 'Failed to load:' + loadFile + '\n'); // eat me to avoid work - putIn.write = function() {}; + putIn.write = common.noop; }; putIn.run(['.load ' + loadFile]); @@ -86,7 +86,7 @@ loadFile = common.tmpDir; putIn.write = function(data) { assert.strictEqual(data, 'Failed to load:' + loadFile + ' is not a valid file\n'); - putIn.write = function() {}; + putIn.write = common.noop; }; putIn.run(['.load ' + loadFile]); @@ -102,7 +102,7 @@ putIn.write = function(data) { // make sure I get a failed to save message and not some other error assert.strictEqual(data, 'Failed to save:' + invalidFileName + '\n'); // reset to no-op - putIn.write = function() {}; + putIn.write = common.noop; }; // save it to a file diff --git a/test/parallel/test-repl-history-perm.js b/test/parallel/test-repl-history-perm.js index 69b973db2b79bc..4ccb139f6da738 100644 --- a/test/parallel/test-repl-history-perm.js +++ b/test/parallel/test-repl-history-perm.js @@ -19,7 +19,7 @@ const Duplex = require('stream').Duplex; // and mode 600. const stream = new Duplex(); -stream.pause = stream.resume = function() {}; +stream.pause = stream.resume = common.noop; // ends immediately stream._read = function() { this.push(null); diff --git a/test/parallel/test-repl-mode.js b/test/parallel/test-repl-mode.js index 7c113e2fc620c5..cf492a7e4b3f93 100644 --- a/test/parallel/test-repl-mode.js +++ b/test/parallel/test-repl-mode.js @@ -52,7 +52,7 @@ function testAutoMode() { function initRepl(mode) { const input = new Stream(); - input.write = input.pause = input.resume = function() {}; + input.write = input.pause = input.resume = common.noop; input.readable = true; const output = new Stream(); diff --git a/test/parallel/test-repl.js b/test/parallel/test-repl.js index 2fc888de67b1f8..6fc9d020185c77 100644 --- a/test/parallel/test-repl.js +++ b/test/parallel/test-repl.js @@ -200,7 +200,7 @@ function error_test() { { client: client_unix, send: 'blah()', expect: `1\n${prompt_unix}` }, // Functions should not evaluate twice (#2773) - { client: client_unix, send: 'var I = [1,2,3,function() {}]; I.pop()', + { client: client_unix, send: 'var I = [1,2,3,common.noop]; I.pop()', expect: '[Function]' }, // Multiline object { client: client_unix, send: '{ a: ', diff --git a/test/parallel/test-signal-handler.js b/test/parallel/test-signal-handler.js index 004878ac741595..a040d7cc4c2145 100644 --- a/test/parallel/test-signal-handler.js +++ b/test/parallel/test-signal-handler.js @@ -9,7 +9,7 @@ if (common.isWindows) { console.log(`process.pid: ${process.pid}`); -process.on('SIGUSR1', common.mustCall(function() {})); +process.on('SIGUSR1', common.mustCall()); process.on('SIGUSR1', common.mustCall(function() { setTimeout(function() { @@ -31,5 +31,5 @@ setInterval(function() { // has been previously registered, and `process.listeners(SIGNAL).length === 1` process.on('SIGHUP', common.mustNotCall()); process.removeAllListeners('SIGHUP'); -process.on('SIGHUP', common.mustCall(function() {})); +process.on('SIGHUP', common.mustCall()); process.kill(process.pid, 'SIGHUP'); diff --git a/test/parallel/test-stream-big-push.js b/test/parallel/test-stream-big-push.js index 9083820d42b546..849014ad707823 100644 --- a/test/parallel/test-stream-big-push.js +++ b/test/parallel/test-stream-big-push.js @@ -28,7 +28,7 @@ function _read() { r._read = common.mustCall(_read, 3); -r.on('end', common.mustCall(function() {})); +r.on('end', common.mustCall()); // push some data in to start. // we've never gotten any read event at this point. diff --git a/test/parallel/test-stream-end-paused.js b/test/parallel/test-stream-end-paused.js index 4b585fdb999890..007066242b00d1 100644 --- a/test/parallel/test-stream-end-paused.js +++ b/test/parallel/test-stream-end-paused.js @@ -19,7 +19,7 @@ stream.on('data', function() { stream.pause(); setTimeout(common.mustCall(function() { - stream.on('end', common.mustCall(function() {})); + stream.on('end', common.mustCall()); stream.resume(); }), 1); diff --git a/test/parallel/test-stream-events-prepend.js b/test/parallel/test-stream-events-prepend.js index 63d9a32807c5d5..254d9a3690aee5 100644 --- a/test/parallel/test-stream-events-prepend.js +++ b/test/parallel/test-stream-events-prepend.js @@ -23,7 +23,7 @@ Readable.prototype._read = function() { }; const w = new Writable(); -w.on('pipe', common.mustCall(function() {})); +w.on('pipe', common.mustCall()); const r = new Readable(); r.pipe(w); diff --git a/test/parallel/test-stream-pipe-after-end.js b/test/parallel/test-stream-pipe-after-end.js index 79ebb2c0e0990d..fe41d54cabc5f0 100644 --- a/test/parallel/test-stream-pipe-after-end.js +++ b/test/parallel/test-stream-pipe-after-end.js @@ -42,11 +42,11 @@ const piper = new TestReadable(); piper.read(); setTimeout(common.mustCall(function() { - ender.on('end', common.mustCall(function() {})); + ender.on('end', common.mustCall()); const c = ender.read(); assert.strictEqual(c, null); const w = new TestWritable(); - w.on('finish', common.mustCall(function() {})); + w.on('finish', common.mustCall()); piper.pipe(w); }), 1); diff --git a/test/parallel/test-stream-pipe-error-handling.js b/test/parallel/test-stream-pipe-error-handling.js index db79f6e5f36c70..0f6f855a43ae80 100644 --- a/test/parallel/test-stream-pipe-error-handling.js +++ b/test/parallel/test-stream-pipe-error-handling.js @@ -79,11 +79,11 @@ const Stream = require('stream').Stream; }), 1); }); - w.on('error', common.mustCall(function() {})); - w._write = function() {}; + w.on('error', common.mustCall()); + w._write = common.noop; r.pipe(w); // Removing some OTHER random listener should not do anything - w.removeListener('error', function() {}); + w.removeListener('error', common.noop); removed = true; } diff --git a/test/parallel/test-stream-readable-event.js b/test/parallel/test-stream-readable-event.js index 626858ab914857..422c79d1c1b35d 100644 --- a/test/parallel/test-stream-readable-event.js +++ b/test/parallel/test-stream-readable-event.js @@ -19,7 +19,7 @@ const Readable = require('stream').Readable; setTimeout(function() { // we're testing what we think we are assert(!r._readableState.reading); - r.on('readable', common.mustCall(function() {})); + r.on('readable', common.mustCall()); }, 1); } @@ -39,7 +39,7 @@ const Readable = require('stream').Readable; setTimeout(function() { // assert we're testing what we think we are assert(r._readableState.reading); - r.on('readable', common.mustCall(function() {})); + r.on('readable', common.mustCall()); }, 1); } @@ -59,6 +59,6 @@ const Readable = require('stream').Readable; setTimeout(function() { // assert we're testing what we think we are assert(!r._readableState.reading); - r.on('readable', common.mustCall(function() {})); + r.on('readable', common.mustCall()); }, 1); } diff --git a/test/parallel/test-stream-wrap.js b/test/parallel/test-stream-wrap.js index dbcb58a98cd8b2..5312596afac40d 100644 --- a/test/parallel/test-stream-wrap.js +++ b/test/parallel/test-stream-wrap.js @@ -28,4 +28,4 @@ function testShutdown(callback) { req.handle.shutdown(req); } -testShutdown(common.mustCall(function() {})); +testShutdown(common.mustCall()); diff --git a/test/parallel/test-stream2-read-sync-stack.js b/test/parallel/test-stream2-read-sync-stack.js index d4e11af3b8f7c1..314dc375f20b3b 100644 --- a/test/parallel/test-stream2-read-sync-stack.js +++ b/test/parallel/test-stream2-read-sync-stack.js @@ -20,6 +20,6 @@ r.on('readable', function onReadable() { r.read(N * 2); }); -r.on('end', common.mustCall(function() {})); +r.on('end', common.mustCall()); r.read(0); diff --git a/test/parallel/test-stream2-readable-legacy-drain.js b/test/parallel/test-stream2-readable-legacy-drain.js index d6db6ba232c693..ebacbc3939c4f1 100644 --- a/test/parallel/test-stream2-readable-legacy-drain.js +++ b/test/parallel/test-stream2-readable-legacy-drain.js @@ -12,7 +12,7 @@ r._read = function(n) { return r.push(++reads === N ? null : Buffer.allocUnsafe(1)); }; -r.on('end', common.mustCall(function() {})); +r.on('end', common.mustCall()); const w = new Stream(); w.writable = true; @@ -29,7 +29,7 @@ function drain() { w.emit('drain'); } -w.end = common.mustCall(function() {}); +w.end = common.mustCall(); // Just for kicks, let's mess with the drain count. // This verifies that even if it gets negative in the diff --git a/test/parallel/test-stream2-readable-non-empty-end.js b/test/parallel/test-stream2-readable-non-empty-end.js index 46481fe1dcda4c..0df461eb5f2919 100644 --- a/test/parallel/test-stream2-readable-non-empty-end.js +++ b/test/parallel/test-stream2-readable-non-empty-end.js @@ -40,7 +40,7 @@ test.read(0); function next() { // now let's make 'end' happen test.removeListener('end', thrower); - test.on('end', common.mustCall(function() {})); + test.on('end', common.mustCall()); // one to get the last byte let r = test.read(); diff --git a/test/parallel/test-stream2-readable-wrap-empty.js b/test/parallel/test-stream2-readable-wrap-empty.js index 5b2dae3c5327fa..3282f5da6cfae1 100644 --- a/test/parallel/test-stream2-readable-wrap-empty.js +++ b/test/parallel/test-stream2-readable-wrap-empty.js @@ -5,13 +5,13 @@ const Readable = require('_stream_readable'); const EE = require('events').EventEmitter; const oldStream = new EE(); -oldStream.pause = function() {}; -oldStream.resume = function() {}; +oldStream.pause = common.noop; +oldStream.resume = common.noop; const newStream = new Readable().wrap(oldStream); newStream - .on('readable', function() {}) - .on('end', common.mustCall(function() {})); + .on('readable', common.noop) + .on('end', common.mustCall()); oldStream.emit('end'); diff --git a/test/parallel/test-stream2-readable-wrap.js b/test/parallel/test-stream2-readable-wrap.js index aa091dc3d806f0..f7ae81c4ba83b5 100644 --- a/test/parallel/test-stream2-readable-wrap.js +++ b/test/parallel/test-stream2-readable-wrap.js @@ -12,7 +12,7 @@ function runTest(highWaterMark, objectMode, produce) { objectMode: objectMode }); assert.strictEqual(r, r.wrap(old)); - r.on('end', common.mustCall(function() {})); + r.on('end', common.mustCall()); old.pause = function() { old.emit('pause'); diff --git a/test/parallel/test-stream2-writable.js b/test/parallel/test-stream2-writable.js index dd470db9624050..136d4dc3dcef7e 100644 --- a/test/parallel/test-stream2-writable.js +++ b/test/parallel/test-stream2-writable.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const W = require('_stream_writable'); const D = require('_stream_duplex'); const assert = require('assert'); @@ -283,7 +283,7 @@ test('encoding should be ignored for buffers', function(t) { test('writables are not pipable', function(t) { const w = new W(); - w._write = function() {}; + w._write = common.noop; let gotError = false; w.on('error', function() { gotError = true; @@ -295,8 +295,8 @@ test('writables are not pipable', function(t) { test('duplexes are pipable', function(t) { const d = new D(); - d._read = function() {}; - d._write = function() {}; + d._read = common.noop; + d._write = common.noop; let gotError = false; d.on('error', function() { gotError = true; @@ -308,7 +308,7 @@ test('duplexes are pipable', function(t) { test('end(chunk) two times is an error', function(t) { const w = new W(); - w._write = function() {}; + w._write = common.noop; let gotError = false; w.on('error', function(er) { gotError = true; diff --git a/test/parallel/test-timers-uncaught-exception.js b/test/parallel/test-timers-uncaught-exception.js index 4304a984189b81..75d264a1ec86fa 100644 --- a/test/parallel/test-timers-uncaught-exception.js +++ b/test/parallel/test-timers-uncaught-exception.js @@ -10,7 +10,7 @@ setTimeout(common.mustCall(function() { }), 1); // ...but the second one should still run -setTimeout(common.mustCall(function() {}), 1); +setTimeout(common.mustCall(), 1); function uncaughtException(err) { assert.strictEqual(err.message, errorMsg); diff --git a/test/parallel/test-timers-unref-call.js b/test/parallel/test-timers-unref-call.js index 5384441838763a..8dfda0c5a85e39 100644 --- a/test/parallel/test-timers-unref-call.js +++ b/test/parallel/test-timers-unref-call.js @@ -1,11 +1,11 @@ 'use strict'; -require('../common'); +const common = require('../common'); const Timer = process.binding('timer_wrap').Timer; Timer.now = function() { return ++Timer.now.ticks; }; Timer.now.ticks = 0; -const t = setInterval(function() {}, 1); +const t = setInterval(common.noop, 1); const o = { _idleStart: 0, _idleTimeout: 1 }; t.unref.call(o); diff --git a/test/parallel/test-timers-unref-remove-other-unref-timers.js b/test/parallel/test-timers-unref-remove-other-unref-timers.js index 7b4f55abe79a82..221f5bb6fd93ab 100644 --- a/test/parallel/test-timers-unref-remove-other-unref-timers.js +++ b/test/parallel/test-timers-unref-remove-other-unref-timers.js @@ -29,4 +29,4 @@ timers.enroll(foo, 50); timers._unrefActive(foo); // Keep the process open. -setTimeout(function() {}, 100); +setTimeout(common.noop, 100); diff --git a/test/parallel/test-timers-unref.js b/test/parallel/test-timers-unref.js index 2bde08f914d790..aeccacece885a4 100644 --- a/test/parallel/test-timers-unref.js +++ b/test/parallel/test-timers-unref.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); let interval_fired = false; @@ -13,11 +13,11 @@ const LONG_TIME = 10 * 1000; const SHORT_TIME = 100; assert.doesNotThrow(function() { - setTimeout(function() {}, 10).unref().ref().unref(); + setTimeout(common.noop, 10).unref().ref().unref(); }, 'ref and unref are chainable'); assert.doesNotThrow(function() { - setInterval(function() {}, 10).unref().ref().unref(); + setInterval(common.noop, 10).unref().ref().unref(); }, 'ref and unref are chainable'); setInterval(function() { @@ -56,7 +56,7 @@ setInterval(function() { // Should not assert on args.Holder()->InternalFieldCount() > 0. See #4261. { - const t = setInterval(function() {}, 1); + const t = setInterval(common.noop, 1); process.nextTick(t.unref.bind({})); process.nextTick(t.unref.bind(t)); } diff --git a/test/parallel/test-timers-zero-timeout.js b/test/parallel/test-timers-zero-timeout.js index 5d72cfe85fb870..c3edd92260e2db 100644 --- a/test/parallel/test-timers-zero-timeout.js +++ b/test/parallel/test-timers-zero-timeout.js @@ -5,7 +5,7 @@ const assert = require('assert'); // https://github.com/joyent/node/issues/2079 - zero timeout drops extra args { setTimeout(common.mustCall(f), 0, 'foo', 'bar', 'baz'); - setTimeout(function() {}, 0); + setTimeout(common.noop, 0); function f(a, b, c) { assert.strictEqual(a, 'foo'); diff --git a/test/parallel/test-timers.js b/test/parallel/test-timers.js index 7ace816c2ceaeb..daabfcf29ddf19 100644 --- a/test/parallel/test-timers.js +++ b/test/parallel/test-timers.js @@ -56,5 +56,5 @@ setTimeout(common.mustCall(function() { }), 2); // Test 10 ms timeout separately. -setTimeout(common.mustCall(function() {}), 10); +setTimeout(common.mustCall(), 10); setInterval(common.mustCall(function() { clearInterval(this); }), 10); diff --git a/test/parallel/test-tls-cert-regression.js b/test/parallel/test-tls-cert-regression.js index ff5827bcf844ee..3cf7423b7d9807 100644 --- a/test/parallel/test-tls-cert-regression.js +++ b/test/parallel/test-tls-cert-regression.js @@ -42,5 +42,5 @@ function test(cert, key, cb) { } test(cert, key, common.mustCall(function() { - test(Buffer.from(cert), Buffer.from(key), common.mustCall(function() {})); + test(Buffer.from(cert), Buffer.from(key), common.mustCall()); })); diff --git a/test/parallel/test-tls-connect-simple.js b/test/parallel/test-tls-connect-simple.js index f169773c77a26e..84cbe633eda7c8 100644 --- a/test/parallel/test-tls-connect-simple.js +++ b/test/parallel/test-tls-connect-simple.js @@ -18,8 +18,8 @@ const options = { const server = tls.Server(options, common.mustCall(function(socket) { if (++serverConnected === 2) { - server.close(common.mustCall(function() {})); - server.on('close', common.mustCall(function() {})); + server.close(common.mustCall()); + server.on('close', common.mustCall()); } }, 2)); diff --git a/test/parallel/test-tls-connect.js b/test/parallel/test-tls-connect.js index 082e2e48a9dcc0..0a6af35e7d1f5a 100644 --- a/test/parallel/test-tls-connect.js +++ b/test/parallel/test-tls-connect.js @@ -20,7 +20,7 @@ const path = require('path'); const options = {cert: cert, key: key, port: common.PORT}; const conn = tls.connect(options, common.fail); - conn.on('error', common.mustCall(function() {})); + conn.on('error', common.mustCall()); } // SSL_accept/SSL_connect error handling @@ -37,5 +37,5 @@ const path = require('path'); assert.ok(false); // callback should never be executed }); - conn.on('error', common.mustCall(function() {})); + conn.on('error', common.mustCall()); } diff --git a/test/parallel/test-tls-delayed-attach-error.js b/test/parallel/test-tls-delayed-attach-error.js index c7b6bf33127a5e..35da6d0e42efed 100644 --- a/test/parallel/test-tls-delayed-attach-error.js +++ b/test/parallel/test-tls-delayed-attach-error.js @@ -23,7 +23,7 @@ const server = net.createServer(common.mustCall(function(c) { secureContext: tls.createSecureContext(options) }); - s.on('_tlsError', common.mustCall(function() {})); + s.on('_tlsError', common.mustCall()); s.on('close', function() { server.close(); diff --git a/test/parallel/test-tls-env-extra-ca.js b/test/parallel/test-tls-env-extra-ca.js index 8c561d921cb802..4580f1579f6213 100644 --- a/test/parallel/test-tls-env-extra-ca.js +++ b/test/parallel/test-tls-env-extra-ca.js @@ -16,7 +16,7 @@ const fs = require('fs'); if (process.env.CHILD) { const copts = { port: process.env.PORT, - checkServerIdentity: function() {}, + checkServerIdentity: common.noop, }; const client = tls.connect(copts, function() { client.end('hi'); diff --git a/test/parallel/test-tls-invoke-queued.js b/test/parallel/test-tls-invoke-queued.js index 08053e026249e6..2a8037c8d74119 100644 --- a/test/parallel/test-tls-invoke-queued.js +++ b/test/parallel/test-tls-invoke-queued.js @@ -21,7 +21,7 @@ const server = tls.createServer({ c._write('world!', null, function() { c.destroy(); }); - c._write(' gosh', null, function() {}); + c._write(' gosh', null, common.noop); }); server.close(); diff --git a/test/parallel/test-tls-legacy-onselect.js b/test/parallel/test-tls-legacy-onselect.js index 9af65c43a0661c..6540639cc93e7c 100644 --- a/test/parallel/test-tls-legacy-onselect.js +++ b/test/parallel/test-tls-legacy-onselect.js @@ -10,7 +10,7 @@ const net = require('net'); const server = net.Server(common.mustCall(function(raw) { const pair = tls.createSecurePair(null, true, false, false); - pair.on('error', function() {}); + pair.on('error', common.noop); pair.ssl.setSNICallback(common.mustCall(function() { raw.destroy(); server.close(); diff --git a/test/parallel/test-tls-passphrase.js b/test/parallel/test-tls-passphrase.js index f2f6f5ccdacda8..f8fc4c9313d9da 100644 --- a/test/parallel/test-tls-passphrase.js +++ b/test/parallel/test-tls-passphrase.js @@ -39,14 +39,14 @@ server.listen(0, common.mustCall(function() { passphrase: 'passphrase', cert: cert, rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, key: rawKey, cert: cert, rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, @@ -54,7 +54,7 @@ server.listen(0, common.mustCall(function() { passphrase: 'ignored', cert: cert, rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); // Buffer[] tls.connect({ @@ -63,14 +63,14 @@ server.listen(0, common.mustCall(function() { passphrase: 'passphrase', cert: [cert], rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, key: [rawKey], cert: [cert], rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, @@ -78,7 +78,7 @@ server.listen(0, common.mustCall(function() { passphrase: 'ignored', cert: [cert], rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); // string tls.connect({ @@ -87,14 +87,14 @@ server.listen(0, common.mustCall(function() { passphrase: 'passphrase', cert: cert.toString(), rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, key: rawKey.toString(), cert: cert.toString(), rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, @@ -102,7 +102,7 @@ server.listen(0, common.mustCall(function() { passphrase: 'ignored', cert: cert.toString(), rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); // String[] tls.connect({ @@ -111,14 +111,14 @@ server.listen(0, common.mustCall(function() { passphrase: 'passphrase', cert: [cert.toString()], rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, key: [rawKey.toString()], cert: [cert.toString()], rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, @@ -126,7 +126,7 @@ server.listen(0, common.mustCall(function() { passphrase: 'ignored', cert: [cert.toString()], rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); // Object[] tls.connect({ @@ -134,7 +134,7 @@ server.listen(0, common.mustCall(function() { key: [{pem: passKey, passphrase: 'passphrase'}], cert: cert, rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, @@ -142,7 +142,7 @@ server.listen(0, common.mustCall(function() { passphrase: 'ignored', cert: cert, rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, @@ -150,28 +150,28 @@ server.listen(0, common.mustCall(function() { passphrase: 'passphrase', cert: cert, rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, key: [{pem: passKey.toString(), passphrase: 'passphrase'}], cert: cert, rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, key: [{pem: rawKey, passphrase: 'ignored'}], cert: cert, rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, key: [{pem: rawKey.toString(), passphrase: 'ignored'}], cert: cert, rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, @@ -179,7 +179,7 @@ server.listen(0, common.mustCall(function() { passphrase: 'ignored', cert: cert, rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, @@ -187,21 +187,21 @@ server.listen(0, common.mustCall(function() { passphrase: 'ignored', cert: cert, rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, key: [{pem: rawKey}], cert: cert, rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); tls.connect({ port: this.address().port, key: [{pem: rawKey.toString()}], cert: cert, rejectUnauthorized: false - }, common.mustCall(function() {})); + }, common.mustCall()); })).unref(); const errMessagePassword = /bad password read/; diff --git a/test/parallel/test-url.js b/test/parallel/test-url.js index 4e123305b5fddb..251557f8ac98af 100644 --- a/test/parallel/test-url.js +++ b/test/parallel/test-url.js @@ -1,6 +1,6 @@ /* eslint-disable max-len */ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const url = require('url'); @@ -1684,7 +1684,7 @@ const throws = [ true, false, 0, - function() {} + common.noop ]; for (let i = 0; i < throws.length; i++) { assert.throws(function() { url.format(throws[i]); }, TypeError); diff --git a/test/parallel/test-util.js b/test/parallel/test-util.js index 3b7e78ea1e464e..867cae95935caf 100644 --- a/test/parallel/test-util.js +++ b/test/parallel/test-util.js @@ -12,7 +12,7 @@ assert.strictEqual(true, util.isArray(new Array(5))); assert.strictEqual(true, util.isArray(new Array('with', 'some', 'entries'))); assert.strictEqual(true, util.isArray(context('Array')())); assert.strictEqual(false, util.isArray({})); -assert.strictEqual(false, util.isArray({ push: function() {} })); +assert.strictEqual(false, util.isArray({ push: common.noop })); assert.strictEqual(false, util.isArray(/regexp/)); assert.strictEqual(false, util.isArray(new Error())); assert.strictEqual(false, util.isArray(Object.create(Array.prototype))); @@ -61,7 +61,7 @@ assert.strictEqual(false, util.isPrimitive(new Error())); assert.strictEqual(false, util.isPrimitive(new Date())); assert.strictEqual(false, util.isPrimitive([])); assert.strictEqual(false, util.isPrimitive(/regexp/)); -assert.strictEqual(false, util.isPrimitive(function() {})); +assert.strictEqual(false, util.isPrimitive(common.noop)); assert.strictEqual(false, util.isPrimitive(new Number(1))); assert.strictEqual(false, util.isPrimitive(new String('bla'))); assert.strictEqual(false, util.isPrimitive(new Boolean(true))); @@ -117,7 +117,7 @@ assert.strictEqual(util.isSymbol(), false); assert.strictEqual(util.isSymbol('string'), false); assert.strictEqual(util.isFunction(() => {}), true); -assert.strictEqual(util.isFunction(function() {}), true); +assert.strictEqual(util.isFunction(common.noop), true); assert.strictEqual(util.isFunction(), false); assert.strictEqual(util.isFunction('string'), false); diff --git a/test/parallel/test-vm-function-declaration.js b/test/parallel/test-vm-function-declaration.js index c2aff80f02b524..ff594644c68de0 100644 --- a/test/parallel/test-vm-function-declaration.js +++ b/test/parallel/test-vm-function-declaration.js @@ -7,7 +7,7 @@ const o = vm.createContext({ console: console }); // Function declaration and expression should both be copied to the // sandboxed context. -let code = 'var a = function() {};\n'; +let code = 'var a = function () {};\n'; code += 'function b(){}\n'; // Grab the global b function as the completion value, to ensure that diff --git a/test/parallel/test-zlib-close-after-write.js b/test/parallel/test-zlib-close-after-write.js index d25ccfe381f113..8977fd36add703 100644 --- a/test/parallel/test-zlib-close-after-write.js +++ b/test/parallel/test-zlib-close-after-write.js @@ -5,5 +5,5 @@ const zlib = require('zlib'); zlib.gzip('hello', common.mustCall(function(err, out) { const unzip = zlib.createGunzip(); unzip.write(out); - unzip.close(common.mustCall(function() {})); + unzip.close(common.mustCall()); })); diff --git a/test/parallel/test-zlib-write-after-close.js b/test/parallel/test-zlib-write-after-close.js index fdad1708c81ff0..e169a06639917f 100644 --- a/test/parallel/test-zlib-write-after-close.js +++ b/test/parallel/test-zlib-write-after-close.js @@ -5,6 +5,6 @@ const zlib = require('zlib'); zlib.gzip('hello', common.mustCall(function(err, out) { const unzip = zlib.createGunzip(); - unzip.close(common.mustCall(function() {})); + unzip.close(common.mustCall()); assert.throws(() => unzip.write(out), /^Error: zlib binding closed$/); })); diff --git a/test/parallel/test-zlib-zero-byte.js b/test/parallel/test-zlib-zero-byte.js index cd4cf41f98ac07..95b75e739fd115 100644 --- a/test/parallel/test-zlib-zero-byte.js +++ b/test/parallel/test-zlib-zero-byte.js @@ -13,6 +13,6 @@ gz.on('data', function(c) { gz.on('end', common.mustCall(function() { assert.strictEqual(received, 20); })); -gz.on('finish', common.mustCall(function() {})); +gz.on('finish', common.mustCall()); gz.write(emptyBuffer); gz.end(); diff --git a/test/pummel/test-http-client-reconnect-bug.js b/test/pummel/test-http-client-reconnect-bug.js index ae29a11fa83d49..cb376fe3dac49c 100644 --- a/test/pummel/test-http-client-reconnect-bug.js +++ b/test/pummel/test-http-client-reconnect-bug.js @@ -11,7 +11,7 @@ server.on('listening', common.mustCall(function() { const client = http.createClient(common.PORT); client.on('error', common.mustCall(function(err) {})); - client.on('end', common.mustCall(function() {})); + client.on('end', common.mustCall()); const request = client.request('GET', '/', {'host': 'localhost'}); request.end(); diff --git a/test/pummel/test-net-connect-memleak.js b/test/pummel/test-net-connect-memleak.js index f16034e4773510..6799b412b693a0 100644 --- a/test/pummel/test-net-connect-memleak.js +++ b/test/pummel/test-net-connect-memleak.js @@ -10,7 +10,7 @@ assert.strictEqual( 'function', 'Run this test with --expose-gc' ); -net.createServer(function() {}).listen(common.PORT); +net.createServer(common.noop).listen(common.PORT); let before = 0; { diff --git a/test/pummel/test-stream2-basic.js b/test/pummel/test-stream2-basic.js index 46cc2f63086fbe..d15030cd9d94d9 100644 --- a/test/pummel/test-stream2-basic.js +++ b/test/pummel/test-stream2-basic.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const R = require('_stream_readable'); const assert = require('assert'); @@ -451,7 +451,7 @@ test('adding readable triggers data flow', function(t) { test('chainable', function(t) { const r = new R(); - r._read = function() {}; + r._read = common.noop; const r2 = r.setEncoding('utf8').pause().resume().pause(); t.equal(r, r2); t.end(); diff --git a/test/sequential/test-child-process-pass-fd.js b/test/sequential/test-child-process-pass-fd.js index 404ae854a15953..2d05407e67b99f 100644 --- a/test/sequential/test-child-process-pass-fd.js +++ b/test/sequential/test-child-process-pass-fd.js @@ -45,7 +45,7 @@ if (process.argv[2] !== 'child') { // the only thing keeping this worker alive will be IPC. This is important, // because it means a worker with no parent will have no referenced handles, // thus no work to do, and will exit immediately, preventing process leaks. - process.on('message', function() {}); + process.on('message', common.noop); const server = net.createServer((c) => { process.once('message', function(msg) { diff --git a/test/sequential/test-fs-watch.js b/test/sequential/test-fs-watch.js index 1780099eba4f9b..b99e86a7e65e4f 100644 --- a/test/sequential/test-fs-watch.js +++ b/test/sequential/test-fs-watch.js @@ -117,7 +117,7 @@ assert.throws(function() { oldhandle.close(); // clean up assert.throws(function() { - const w = fs.watchFile(__filename, {persistent: false}, function() {}); + const w = fs.watchFile(__filename, {persistent: false}, common.noop); oldhandle = w._handle; w._handle = { stop: w._handle.stop }; w.stop(); diff --git a/test/sequential/test-https-set-timeout-server.js b/test/sequential/test-https-set-timeout-server.js index 6c7afa5df9b304..b1a597e34de345 100644 --- a/test/sequential/test-https-set-timeout-server.js +++ b/test/sequential/test-https-set-timeout-server.js @@ -48,7 +48,7 @@ test(function serverTimeout(cb) { https.get({ port: this.address().port, rejectUnauthorized: false - }).on('error', function() {}); + }).on('error', common.noop); })); }); @@ -69,7 +69,7 @@ test(function serverRequestTimeout(cb) { method: 'POST', rejectUnauthorized: false }); - req.on('error', function() {}); + req.on('error', common.noop); req.write('Hello'); // req is in progress }); @@ -90,7 +90,7 @@ test(function serverResponseTimeout(cb) { https.get({ port: this.address().port, rejectUnauthorized: false - }).on('error', function() {}); + }).on('error', common.noop); }); }); @@ -110,7 +110,7 @@ test(function serverRequestNotTimeoutAfterEnd(cb) { https.get({ port: this.address().port, rejectUnauthorized: false - }).on('error', function() {}); + }).on('error', common.noop); }); }); From 2d96b0127d84579335f8e92d514e4e96e81ab545 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Fri, 24 Mar 2017 12:37:59 -0700 Subject: [PATCH 02/82] tools: add rule prefering common.mustNotCall() Prefer using `common.mustNotCall()` over `common.mustCall(fn, 0)` PR-URL: https://github.com/nodejs/node/pull/12027 Reviewed-By: Jeremiah Senkpiel Reviewed-By: Richard Lau Reviewed-By: Gibson Fahnestock Reviewed-By: Teddy Katz Reviewed-By: Colin Ihrig Reviewed-By: Franziska Hinkelmann --- test/.eslintrc.yaml | 3 ++ .../eslint-rules/prefer-common-mustnotcall.js | 39 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 tools/eslint-rules/prefer-common-mustnotcall.js diff --git a/test/.eslintrc.yaml b/test/.eslintrc.yaml index 8414b828137e5d..4fea04d632f2d4 100644 --- a/test/.eslintrc.yaml +++ b/test/.eslintrc.yaml @@ -6,6 +6,9 @@ rules: no-var: 2 prefer-const: 2 + # Custom rules in tools/eslint-rules + prefer-common-mustnotcall: 2 + ## common module is mandatory in tests required-modules: [2, common] prefer-assert-methods: 2 diff --git a/tools/eslint-rules/prefer-common-mustnotcall.js b/tools/eslint-rules/prefer-common-mustnotcall.js new file mode 100644 index 00000000000000..6bc428ed59a8b8 --- /dev/null +++ b/tools/eslint-rules/prefer-common-mustnotcall.js @@ -0,0 +1,39 @@ +/** + * @fileoverview Prefer common.mustNotCall(msg) over common.mustCall(fn, 0) + * @author James M Snell + */ +'use strict'; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const msg = 'Please use common.mustNotCall(msg) instead of ' + + 'common.mustCall(fn, 0) or common.mustCall(0).'; + +function isCommonMustCall(node) { + return node && + node.callee && + node.callee.object && + node.callee.object.name === 'common' && + node.callee.property && + node.callee.property.name === 'mustCall'; +} + +function isArgZero(argument) { + return argument && + typeof argument.value === 'number' && + argument.value === 0; +} + +module.exports = function(context) { + return { + CallExpression(node) { + if (isCommonMustCall(node) && + (isArgZero(node.arguments[0]) || // catch common.mustCall(0) + isArgZero(node.arguments[1]))) { // catch common.mustCall(fn, 0) + context.report(node, msg); + } + } + }; +}; From ce86b8e0fa70904c4536c6a3808f4d77054ae3ad Mon Sep 17 00:00:00 2001 From: Refael Ackermann Date: Tue, 9 May 2017 17:16:52 -0400 Subject: [PATCH 03/82] test: add mustCallAtLeast PR-URL: https://github.com/nodejs/node/pull/12935 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- test/common/README.md | 17 ++++++++++--- test/common/index.js | 35 ++++++++++++++++++--------- test/fixtures/failmustcall1.js | 3 +++ test/fixtures/failmustcall2.js | 3 +++ test/parallel/test-common.js | 44 ++++++++++++++++++++++++++++++++-- 5 files changed, 86 insertions(+), 16 deletions(-) create mode 100644 test/fixtures/failmustcall1.js create mode 100644 test/fixtures/failmustcall2.js diff --git a/test/common/README.md b/test/common/README.md index 267d28140c5003..492b5acdea586c 100644 --- a/test/common/README.md +++ b/test/common/README.md @@ -182,9 +182,9 @@ Gets IP of localhost Array of IPV6 hosts. -### mustCall([fn][, expected]) -* fn [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) -* expected [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) default = 1 +### mustCall([fn][, exact]) +* `fn` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) default = `common.noop` +* `exact` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) default = 1 * return [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Returns a function that calls `fn`. If the returned function has not been called @@ -193,6 +193,17 @@ fail. If `fn` is not provided, `common.noop` will be used. +### mustCallAtLeast([fn][, minimum]) +* `fn` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) default = `common.noop` +* `minimum` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) default = 1 +* return [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) + +Returns a function that calls `fn`. If the returned function has not been called +at least `minimum` number of times when the test is complete, then the test will +fail. + +If `fn` is not provided, `common.noop` will be used. + ### nodeProcessAborted(exitCode, signal) * `exitCode` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `signal` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) diff --git a/test/common/index.js b/test/common/index.js index 21897a39cac456..ec889b4aff2dc5 100644 --- a/test/common/index.js +++ b/test/common/index.js @@ -406,13 +406,19 @@ function runCallChecks(exitCode) { if (exitCode !== 0) return; const failed = mustCallChecks.filter(function(context) { - return context.actual !== context.expected; + if ('minimum' in context) { + context.messageSegment = `at least ${context.minimum}`; + return context.actual < context.minimum; + } else { + context.messageSegment = `exactly ${context.exact}`; + return context.actual !== context.exact; + } }); failed.forEach(function(context) { - console.log('Mismatched %s function calls. Expected %d, actual %d.', + console.log('Mismatched %s function calls. Expected %s, actual %d.', context.name, - context.expected, + context.messageSegment, context.actual); console.log(context.stack.split('\n').slice(2).join('\n')); }); @@ -420,22 +426,29 @@ function runCallChecks(exitCode) { if (failed.length) process.exit(1); } +exports.mustCall = function(fn, exact) { + return _mustCallInner(fn, exact, 'exact'); +}; -exports.mustCall = function(fn, expected) { +exports.mustCallAtLeast = function(fn, minimum) { + return _mustCallInner(fn, minimum, 'minimum'); +}; + +function _mustCallInner(fn, criteria, field) { if (typeof fn === 'number') { - expected = fn; + criteria = fn; fn = noop; } else if (fn === undefined) { fn = noop; } - if (expected === undefined) - expected = 1; - else if (typeof expected !== 'number') - throw new TypeError(`Invalid expected value: ${expected}`); + if (criteria === undefined) + criteria = 1; + else if (typeof criteria !== 'number') + throw new TypeError(`Invalid ${field} value: ${criteria}`); const context = { - expected: expected, + [field]: criteria, actual: 0, stack: (new Error()).stack, name: fn.name || '' @@ -450,7 +463,7 @@ exports.mustCall = function(fn, expected) { context.actual++; return fn.apply(this, arguments); }; -}; +} exports.hasMultiLocalhost = function hasMultiLocalhost() { const TCP = process.binding('tcp_wrap').TCP; diff --git a/test/fixtures/failmustcall1.js b/test/fixtures/failmustcall1.js new file mode 100644 index 00000000000000..a54740eb296267 --- /dev/null +++ b/test/fixtures/failmustcall1.js @@ -0,0 +1,3 @@ +const common = require('../common'); +const f = common.mustCall( () => {}, 2); +f(); diff --git a/test/fixtures/failmustcall2.js b/test/fixtures/failmustcall2.js new file mode 100644 index 00000000000000..89f8d23922e78a --- /dev/null +++ b/test/fixtures/failmustcall2.js @@ -0,0 +1,3 @@ +const common = require('../common'); +const f = common.mustCallAtLeast(() => {}, 2); +f(); diff --git a/test/parallel/test-common.js b/test/parallel/test-common.js index 86c6f8a0dd5b29..f955585143593c 100644 --- a/test/parallel/test-common.js +++ b/test/parallel/test-common.js @@ -2,14 +2,54 @@ const common = require('../common'); const assert = require('assert'); +const {join} = require('path'); +const {execFile} = require('child_process'); + common.globalCheck = false; global.gc = 42; // Not a valid global unless --expose_gc is set. assert.deepStrictEqual(common.leakedGlobals(), ['gc']); assert.throws(function() { common.mustCall(common.noop, 'foo'); -}, /^TypeError: Invalid expected value: foo$/); +}, /^TypeError: Invalid exact value: foo$/); assert.throws(function() { common.mustCall(common.noop, /foo/); -}, /^TypeError: Invalid expected value: \/foo\/$/); +}, /^TypeError: Invalid exact value: \/foo\/$/); + +const fnOnce = common.mustCall(() => {}); +fnOnce(); +const fnTwice = common.mustCall(() => {}, 2); +fnTwice(); +fnTwice(); +const fnAtLeast1Called1 = common.mustCallAtLeast(() => {}, 1); +fnAtLeast1Called1(); +const fnAtLeast1Called2 = common.mustCallAtLeast(() => {}, 1); +fnAtLeast1Called2(); +fnAtLeast1Called2(); +const fnAtLeast2Called2 = common.mustCallAtLeast(() => {}, 2); +fnAtLeast2Called2(); +fnAtLeast2Called2(); +const fnAtLeast2Called3 = common.mustCallAtLeast(() => {}, 2); +fnAtLeast2Called3(); +fnAtLeast2Called3(); +fnAtLeast2Called3(); + +const failFixtures = [ + [ + join(common.fixturesDir, 'failmustcall1.js'), + 'Mismatched function calls. Expected exactly 2, actual 1.' + ], [ + join(common.fixturesDir, 'failmustcall2.js'), + 'Mismatched function calls. Expected at least 2, actual 1.' + ] +]; +for (const p of failFixtures) { + const [file, expected] = p; + execFile(process.argv[0], [file], common.mustCall((ex, stdout, stderr) => { + assert.ok(ex); + assert.strictEqual(stderr, ''); + const firstLine = stdout.split('\n').shift(); + assert.strictEqual(firstLine, expected); + })); +} From 189dc42bb4336523a8a398f707ab005704ee7cba Mon Sep 17 00:00:00 2001 From: Refael Ackermann Date: Thu, 18 May 2017 18:58:00 -0400 Subject: [PATCH 04/82] test: harden test-dgram-bind-shared-ports * add `mustCall` and `mustNotCall` to all callbacks * added `known_issue` for port binding Backport-PR-URL: https://github.com/nodejs/node/pull/14327 PR-URL: https://github.com/nodejs/node/pull/13100 Refs: https://github.com/nodejs/node/issues/13055 Refs: https://github.com/nodejs/node/pull/12999 Refs: https://github.com/nodejs/node/issues/13526 Reviewed-By: James M Snell Reviewed-By: Matteo Collina --- ...st-dgram-bind-shared-ports-after-port-0.js | 56 +++++++++ .../test-dgram-bind-shared-ports.js | 108 ++++++++++++------ 2 files changed, 128 insertions(+), 36 deletions(-) create mode 100644 test/known_issues/test-dgram-bind-shared-ports-after-port-0.js diff --git a/test/known_issues/test-dgram-bind-shared-ports-after-port-0.js b/test/known_issues/test-dgram-bind-shared-ports-after-port-0.js new file mode 100644 index 00000000000000..7b750c765ba226 --- /dev/null +++ b/test/known_issues/test-dgram-bind-shared-ports-after-port-0.js @@ -0,0 +1,56 @@ +'use strict'; +const common = require('../common'); + +// This test should fail because at present `cluster` does not know how to share +// a socket when `worker1` binds with `port: 0`, and others try to bind to the +// assigned port number from `worker1` +// +// *Note*: since this is a `known_issue` we try to swallow all errors except +// the one we are interested in + +const assert = require('assert'); +const cluster = require('cluster'); +const dgram = require('dgram'); +const BYE = 'bye'; + +if (cluster.isMaster) { + const worker1 = cluster.fork(); + + // verify that Windows doesn't support this scenario + worker1.on('error', (err) => { + if (err.code === 'ENOTSUP') throw err; + }); + + worker1.on('message', (msg) => { + if (typeof msg !== 'object') process.exit(0); + if (msg.message !== 'success') process.exit(0); + if (typeof msg.port1 !== 'number') process.exit(0); + + const worker2 = cluster.fork({ PRT1: msg.port1 }); + worker2.on('message', () => process.exit(0)); + worker2.on('exit', (code, signal) => { + // this is the droid we are looking for + assert.strictEqual(code, 0); + assert.strictEqual(signal, null); + }); + + // cleanup anyway + process.on('exit', () => { + worker1.send(BYE); + worker2.send(BYE); + }); + }); + // end master code +} else { + // worker code + process.on('message', (msg) => msg === BYE && process.exit(0)); + + // first worker will bind to '0', second will try the assigned port and fail + const PRT1 = process.env.PRT1 || 0; + const socket1 = dgram.createSocket('udp4', () => {}); + socket1.on('error', PRT1 === 0 ? () => {} : assert.fail); + socket1.bind( + { address: common.localhostIPv4, port: PRT1, exclusive: false }, + () => process.send({ message: 'success', port1: socket1.address().port }) + ); +} diff --git a/test/sequential/test-dgram-bind-shared-ports.js b/test/sequential/test-dgram-bind-shared-ports.js index df294ef03e0e57..7e4f4e850aafbb 100644 --- a/test/sequential/test-dgram-bind-shared-ports.js +++ b/test/sequential/test-dgram-bind-shared-ports.js @@ -1,56 +1,92 @@ 'use strict'; const common = require('../common'); + +// This test asserts the semantics of dgram::socket.bind({ exclusive }) +// when called from a cluster.Worker + const assert = require('assert'); const cluster = require('cluster'); const dgram = require('dgram'); - -function noop() { } +const BYE = 'bye'; +const WORKER2_NAME = 'wrker2'; if (cluster.isMaster) { const worker1 = cluster.fork(); if (common.isWindows) { - const checkErrType = (er) => { - assert.strictEqual(er.code, 'ENOTSUP'); + worker1.on('error', common.mustCall((err) => { + console.log(err); + assert.strictEqual(err.code, 'ENOTSUP'); worker1.kill(); - }; - - worker1.on('error', common.mustCall(checkErrType, 1)); + })); return; } - worker1.on('message', (msg) => { + worker1.on('message', common.mustCall((msg) => { + console.log(msg); assert.strictEqual(msg, 'success'); - const worker2 = cluster.fork(); - worker2.on('message', (msg) => { - assert.strictEqual(msg, 'socket2:EADDRINUSE'); - worker1.kill(); - worker2.kill(); - }); - }); + const worker2 = cluster.fork({ WORKER2_NAME }); + worker2.on('message', common.mustCall((msg) => { + console.log(msg); + assert.strictEqual(msg, 'socket3:EADDRINUSE'); + + // finish test + worker1.send(BYE); + worker2.send(BYE); + })); + worker2.on('exit', common.mustCall((code, signal) => { + assert.strictEqual(signal, null); + assert.strictEqual(code, 0); + })); + })); + worker1.on('exit', common.mustCall((code, signal) => { + assert.strictEqual(signal, null); + assert.strictEqual(code, 0); + })); + // end master code } else { - const socket1 = dgram.createSocket('udp4', noop); - const socket2 = dgram.createSocket('udp4', noop); - - socket1.on('error', (err) => { - // no errors expected - process.send(`socket1:${err.code}`); - }); - - socket2.on('error', (err) => { - // an error is expected on the second worker - process.send(`socket2:${err.code}`); - }); - - socket1.bind({ - address: 'localhost', - port: common.PORT, - exclusive: false - }, () => { - socket2.bind({ port: common.PORT + 1, exclusive: true }, () => { - // the first worker should succeed + // worker code + process.on('message', common.mustCallAtLeast((msg) => { + if (msg === BYE) process.exit(0); + }), 1); + + const isSecondWorker = process.env.WORKER2_NAME === WORKER2_NAME; + const socket1 = dgram.createSocket('udp4', common.mustNotCall()); + const socket2 = dgram.createSocket('udp4', common.mustNotCall()); + const socket3 = dgram.createSocket('udp4', common.mustNotCall()); + + socket1.on('error', (err) => assert.fail(undefined, undefined, err)); + socket2.on('error', (err) => assert.fail(undefined, undefined, err)); + + // First worker should bind, second should err + const socket3OnBind = + isSecondWorker ? + common.mustNotCall() : + common.mustCall(() => { + const port3 = socket3.address().port; + assert.strictEqual(typeof port3, 'number'); process.send('success'); }); - }); + // an error is expected only in the second worker + const socket3OnError = + !isSecondWorker ? + common.mustNotCall() : + common.mustCall((err) => { + process.send(`socket3:${err.code}`); + }); + const address = common.localhostIPv4; + const opt1 = { address, port: 0, exclusive: false }; + const opt2 = { address, port: common.PORT, exclusive: false }; + const opt3 = { address, port: common.PORT + 1, exclusive: true }; + socket1.bind(opt1, common.mustCall(() => { + const port1 = socket1.address().port; + assert.strictEqual(typeof port1, 'number'); + socket2.bind(opt2, common.mustCall(() => { + const port2 = socket2.address().port; + assert.strictEqual(typeof port2, 'number'); + socket3.on('error', socket3OnError); + socket3.bind(opt3, socket3OnBind); + })); + })); } From a28f7a270893222b773d5d998294ceb56c24030f Mon Sep 17 00:00:00 2001 From: XadillaX Date: Thu, 10 Aug 2017 14:47:14 +0800 Subject: [PATCH 05/82] dns: fix `resolve` failed starts without network Fix the bug that you start process without network at first, but it connected lately, `dns.resolve` will stay failed with ECONNREFUSED because c-ares servers fallback to 127.0.0.1 at the very beginning. If c-ares servers "127.0.0.1" is detected and its not set by user self, and last query is not OK, recreating `ares_channel` operation will be triggered to reload servers. Fixes: https://github.com/nodejs/node/issues/1644 Backport-PR-URL: https://github.com/nodejs/node/pull/14434 PR-URL: https://github.com/nodejs/node/pull/13076 Reviewed-By: Anna Henningsen Reviewed-By: Ben Noordhuis --- src/cares_wrap.cc | 160 +++++++++++++++++++++++++--------------------- src/env-inl.h | 18 ++++++ src/env.h | 6 ++ 3 files changed, 110 insertions(+), 74 deletions(-) diff --git a/src/cares_wrap.cc b/src/cares_wrap.cc index 44d0926ba6b178..d40d4b3256f193 100644 --- a/src/cares_wrap.cc +++ b/src/cares_wrap.cc @@ -372,6 +372,69 @@ struct CaresAsyncData { uv_async_t async_handle; }; +void SetupCaresChannel(Environment* env) { + struct ares_options options; + memset(&options, 0, sizeof(options)); + options.flags = ARES_FLAG_NOCHECKRESP; + options.sock_state_cb = ares_sockstate_cb; + options.sock_state_cb_data = env; + + /* We do the call to ares_init_option for caller. */ + int r = ares_init_options(env->cares_channel_ptr(), + &options, + ARES_OPT_FLAGS | ARES_OPT_SOCK_STATE_CB); + + if (r != ARES_SUCCESS) { + ares_library_cleanup(); + return env->ThrowError(ToErrorCodeString(r)); + } +} + + +/** + * This function is to check whether current servers are fallback servers + * when cares initialized. + * + * The fallback servers of cares is [ "127.0.0.1" ] with no user additional + * setting. + */ +void AresEnsureServers(Environment* env) { + /* if last query is OK or servers are set by user self, do not check */ + if (env->cares_query_last_ok() || !env->cares_is_servers_default()) { + return; + } + + ares_channel channel = env->cares_channel(); + ares_addr_node* servers = nullptr; + + ares_get_servers(channel, &servers); + + /* if no server or multi-servers, ignore */ + if (servers == nullptr) return; + if (servers->next != nullptr) { + ares_free_data(servers); + env->set_cares_is_servers_default(false); + return; + } + + /* if the only server is not 127.0.0.1, ignore */ + if (servers[0].family != AF_INET || + servers[0].addr.addr4.s_addr != htonl(INADDR_LOOPBACK)) { + ares_free_data(servers); + env->set_cares_is_servers_default(false); + return; + } + + ares_free_data(servers); + servers = nullptr; + + /* destroy channel and reset channel */ + ares_destroy(channel); + + SetupCaresChannel(env); +} + + class QueryWrap : public AsyncWrap { public: QueryWrap(Environment* env, Local req_wrap_obj) @@ -402,6 +465,13 @@ class QueryWrap : public AsyncWrap { return static_cast(this); } + static void AresQuery(Environment* env, const char* name, + int dnsclass, int type, ares_callback callback, + void* arg) { + AresEnsureServers(env); + ares_query(env->cares_channel(), name, dnsclass, type, callback, arg); + } + static void CaresAsyncClose(uv_handle_t* handle) { uv_async_t* async = reinterpret_cast(handle); auto data = static_cast(async->data); @@ -453,6 +523,7 @@ class QueryWrap : public AsyncWrap { async_handle, CaresAsyncCb)); + wrap->env()->set_cares_query_last_ok(status != ARES_ECONNREFUSED); async_handle->data = data; uv_async_send(async_handle); } @@ -478,6 +549,7 @@ class QueryWrap : public AsyncWrap { async_handle, CaresAsyncCb)); + wrap->env()->set_cares_query_last_ok(status != ARES_ECONNREFUSED); async_handle->data = data; uv_async_send(async_handle); } @@ -522,12 +594,7 @@ class QueryAWrap: public QueryWrap { } int Send(const char* name) override { - ares_query(env()->cares_channel(), - name, - ns_c_in, - ns_t_a, - Callback, - GetQueryArg()); + AresQuery(env(), name, ns_c_in, ns_t_a, Callback, GetQueryArg()); return 0; } @@ -570,12 +637,7 @@ class QueryAaaaWrap: public QueryWrap { } int Send(const char* name) override { - ares_query(env()->cares_channel(), - name, - ns_c_in, - ns_t_aaaa, - Callback, - GetQueryArg()); + AresQuery(env(), name, ns_c_in, ns_t_aaaa, Callback, GetQueryArg()); return 0; } @@ -618,12 +680,7 @@ class QueryCnameWrap: public QueryWrap { } int Send(const char* name) override { - ares_query(env()->cares_channel(), - name, - ns_c_in, - ns_t_cname, - Callback, - GetQueryArg()); + AresQuery(env(), name, ns_c_in, ns_t_cname, Callback, GetQueryArg()); return 0; } @@ -659,12 +716,7 @@ class QueryMxWrap: public QueryWrap { } int Send(const char* name) override { - ares_query(env()->cares_channel(), - name, - ns_c_in, - ns_t_mx, - Callback, - GetQueryArg()); + AresQuery(env(), name, ns_c_in, ns_t_mx, Callback, GetQueryArg()); return 0; } @@ -710,12 +762,7 @@ class QueryNsWrap: public QueryWrap { } int Send(const char* name) override { - ares_query(env()->cares_channel(), - name, - ns_c_in, - ns_t_ns, - Callback, - GetQueryArg()); + AresQuery(env(), name, ns_c_in, ns_t_ns, Callback, GetQueryArg()); return 0; } @@ -748,12 +795,7 @@ class QueryTxtWrap: public QueryWrap { } int Send(const char* name) override { - ares_query(env()->cares_channel(), - name, - ns_c_in, - ns_t_txt, - Callback, - GetQueryArg()); + AresQuery(env(), name, ns_c_in, ns_t_txt, Callback, GetQueryArg()); return 0; } @@ -805,12 +847,7 @@ class QuerySrvWrap: public QueryWrap { } int Send(const char* name) override { - ares_query(env()->cares_channel(), - name, - ns_c_in, - ns_t_srv, - Callback, - GetQueryArg()); + AresQuery(env(), name, ns_c_in, ns_t_srv, Callback, GetQueryArg()); return 0; } @@ -861,12 +898,7 @@ class QueryPtrWrap: public QueryWrap { } int Send(const char* name) override { - ares_query(env()->cares_channel(), - name, - ns_c_in, - ns_t_ptr, - Callback, - GetQueryArg()); + AresQuery(env(), name, ns_c_in, ns_t_ptr, Callback, GetQueryArg()); return 0; } @@ -904,12 +936,7 @@ class QueryNaptrWrap: public QueryWrap { } int Send(const char* name) override { - ares_query(env()->cares_channel(), - name, - ns_c_in, - ns_t_naptr, - Callback, - GetQueryArg()); + AresQuery(env(), name, ns_c_in, ns_t_naptr, Callback, GetQueryArg()); return 0; } @@ -968,12 +995,7 @@ class QuerySoaWrap: public QueryWrap { } int Send(const char* name) override { - ares_query(env()->cares_channel(), - name, - ns_c_in, - ns_t_soa, - Callback, - GetQueryArg()); + AresQuery(env(), name, ns_c_in, ns_t_soa, Callback, GetQueryArg()); return 0; } @@ -1434,6 +1456,9 @@ static void SetServers(const FunctionCallbackInfo& args) { delete[] servers; + if (err == ARES_SUCCESS) + env->set_cares_is_servers_default(false); + args.GetReturnValue().Set(err); } @@ -1468,20 +1493,7 @@ static void Initialize(Local target, if (r != ARES_SUCCESS) return env->ThrowError(ToErrorCodeString(r)); - struct ares_options options; - memset(&options, 0, sizeof(options)); - options.flags = ARES_FLAG_NOCHECKRESP; - options.sock_state_cb = ares_sockstate_cb; - options.sock_state_cb_data = env; - - /* We do the call to ares_init_option for caller. */ - r = ares_init_options(env->cares_channel_ptr(), - &options, - ARES_OPT_FLAGS | ARES_OPT_SOCK_STATE_CB); - if (r != ARES_SUCCESS) { - ares_library_cleanup(); - return env->ThrowError(ToErrorCodeString(r)); - } + SetupCaresChannel(env); /* Initialize the timeout timer. The timer won't be started until the */ /* first socket is opened. */ diff --git a/src/env-inl.h b/src/env-inl.h index 735dbca6857fa1..e2876de44a9390 100644 --- a/src/env-inl.h +++ b/src/env-inl.h @@ -219,6 +219,8 @@ inline Environment::Environment(v8::Local context, : isolate_(context->GetIsolate()), isolate_data_(IsolateData::GetOrCreate(context->GetIsolate(), loop)), timer_base_(uv_now(loop)), + cares_query_last_ok_(true), + cares_is_servers_default_(true), using_domains_(false), printed_error_(false), trace_sync_io_(false), @@ -453,6 +455,22 @@ inline ares_channel* Environment::cares_channel_ptr() { return &cares_channel_; } +inline bool Environment::cares_query_last_ok() { + return cares_query_last_ok_; +} + +inline void Environment::set_cares_query_last_ok(bool ok) { + cares_query_last_ok_ = ok; +} + +inline bool Environment::cares_is_servers_default() { + return cares_is_servers_default_; +} + +inline void Environment::set_cares_is_servers_default(bool is_default) { + cares_is_servers_default_ = is_default; +} + inline node_ares_task_list* Environment::cares_task_list() { return &cares_task_list_; } diff --git a/src/env.h b/src/env.h index bb4dab070606a8..940c97fe4ddbf1 100644 --- a/src/env.h +++ b/src/env.h @@ -437,6 +437,10 @@ class Environment { inline uv_timer_t* cares_timer_handle(); inline ares_channel cares_channel(); inline ares_channel* cares_channel_ptr(); + inline bool cares_query_last_ok(); + inline void set_cares_query_last_ok(bool ok); + inline bool cares_is_servers_default(); + inline void set_cares_is_servers_default(bool is_default); inline node_ares_task_list* cares_task_list(); inline bool using_domains() const; @@ -555,6 +559,8 @@ class Environment { const uint64_t timer_base_; uv_timer_t cares_timer_handle_; ares_channel cares_channel_; + bool cares_query_last_ok_; + bool cares_is_servers_default_; node_ares_task_list cares_task_list_; bool using_domains_; bool printed_error_; From cb3b866378a006fef7c2a29fb77ae48309b2e6fa Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Wed, 5 Apr 2017 14:04:44 -0700 Subject: [PATCH 06/82] src: supply missing comments for CLI options A few of the CLI option values exposed as properties on the process object were missing a comment, fix this. Backport-PR-URL: https://github.com/nodejs/node/pull/14483 PR-URL: https://github.com/nodejs/node/pull/12245 Reviewed-By: Richard Lau Reviewed-By: James M Snell Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig --- src/node.cc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/node.cc b/src/node.cc index 73ed460f361b44..180afa25f78f3e 100644 --- a/src/node.cc +++ b/src/node.cc @@ -3317,6 +3317,7 @@ void SetupProcessObject(Environment* env, READONLY_PROPERTY(process, "_forceRepl", True(env->isolate())); } + // -r, --require if (preload_module_count) { CHECK(preload_modules); Local array = Array::New(env->isolate()); @@ -3339,10 +3340,12 @@ void SetupProcessObject(Environment* env, READONLY_PROPERTY(process, "noDeprecation", True(env->isolate())); } + // --no-warnings if (no_process_warnings) { READONLY_PROPERTY(process, "noProcessWarnings", True(env->isolate())); } + // --trace-warnings if (trace_warnings) { READONLY_PROPERTY(process, "traceProcessWarnings", True(env->isolate())); } From 1576c0988655cb666448be80933c0977965c8db1 Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Wed, 5 Apr 2017 14:06:52 -0700 Subject: [PATCH 07/82] src: use option parser for expose_internals bootstrap_node.js was directly parsing process.execArgv to see if internals should be exposed, even though the argv was already parsed by node. This is unusual and unnecessary, change it to set the option value from the parser onto the config binding. Backport-PR-URL: https://github.com/nodejs/node/pull/14483 PR-URL: https://github.com/nodejs/node/pull/12245 Reviewed-By: Richard Lau Reviewed-By: James M Snell Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig --- lib/internal/bootstrap_node.js | 6 ++---- src/node.cc | 8 +++++++- src/node_config.cc | 3 +++ src/node_internals.h | 6 ++++++ test/parallel/test-internal-modules-expose.js | 4 ++++ 5 files changed, 22 insertions(+), 5 deletions(-) diff --git a/lib/internal/bootstrap_node.js b/lib/internal/bootstrap_node.js index 55dd4057ac95ce..de215dc2dce62b 100644 --- a/lib/internal/bootstrap_node.js +++ b/lib/internal/bootstrap_node.js @@ -443,11 +443,9 @@ return NativeModule._source.hasOwnProperty(id); }; - const EXPOSE_INTERNALS = process.execArgv.some(function(arg) { - return arg.match(/^--expose[-_]internals$/); - }); + const config = process.binding('config'); - if (EXPOSE_INTERNALS) { + if (config.exposeInternals) { NativeModule.nonInternalExists = NativeModule.exists; NativeModule.isInternal = function(id) { diff --git a/src/node.cc b/src/node.cc index 180afa25f78f3e..dfe84c67c165f8 100644 --- a/src/node.cc +++ b/src/node.cc @@ -199,6 +199,12 @@ bool trace_warnings = false; // that is used by lib/module.js bool config_preserve_symlinks = false; +// Set in node.cc by ParseArgs when --expose-internals or --expose_internals is +// used. +// Used in node_config.cc to set a constant on process.binding('config') +// that is used by lib/internal/bootstrap_node.js +bool config_expose_internals = false; + // process-relative uptime base, initialized at start-up static double prog_start_time; static bool debugger_running; @@ -3896,7 +3902,7 @@ static void ParseArgs(int* argc, #endif } else if (strcmp(arg, "--expose-internals") == 0 || strcmp(arg, "--expose_internals") == 0) { - // consumed in js + config_expose_internals = true; } else if (strcmp(arg, "--") == 0) { index += 1; break; diff --git a/src/node_config.cc b/src/node_config.cc index 401345f6a608be..4408bc3cf33ffc 100644 --- a/src/node_config.cc +++ b/src/node_config.cc @@ -44,6 +44,9 @@ void InitConfig(Local target, if (config_preserve_symlinks) READONLY_BOOLEAN_PROPERTY("preserveSymlinks"); + + if (config_expose_internals) + READONLY_BOOLEAN_PROPERTY("exposeInternals"); } // InitConfig } // namespace node diff --git a/src/node_internals.h b/src/node_internals.h index cb71720e8205d9..e93244a94c6927 100644 --- a/src/node_internals.h +++ b/src/node_internals.h @@ -43,6 +43,12 @@ extern std::string openssl_config; // that is used by lib/module.js extern bool config_preserve_symlinks; +// Set in node.cc by ParseArgs when --expose-internals or --expose_internals is +// used. +// Used in node_config.cc to set a constant on process.binding('config') +// that is used by lib/internal/bootstrap_node.js +extern bool config_expose_internals; + // Forward declaration class Environment; diff --git a/test/parallel/test-internal-modules-expose.js b/test/parallel/test-internal-modules-expose.js index 02ddfd87c363fc..ab48e36881268c 100644 --- a/test/parallel/test-internal-modules-expose.js +++ b/test/parallel/test-internal-modules-expose.js @@ -3,5 +3,9 @@ require('../common'); const assert = require('assert'); +const config = process.binding('config'); + +console.log(config, process.argv); assert.strictEqual(typeof require('internal/freelist').FreeList, 'function'); +assert.strictEqual(config.exposeInternals, true); From ee98df8a468e71f317edfc3ea0d934271417b5d6 Mon Sep 17 00:00:00 2001 From: jeyanthinath Date: Wed, 26 Jul 2017 12:04:04 +0530 Subject: [PATCH 08/82] test: mark test-fs-read-buffer-to-string-fail as flaky PR-URL: https://github.com/nodejs/node/pull/14495 Fixes: https://github.com/nodejs/node/issues/14430 Reviewed-By: Refael Ackermann Reviewed-By: Colin Ihrig --- test/parallel/parallel.status | 1 + 1 file changed, 1 insertion(+) diff --git a/test/parallel/parallel.status b/test/parallel/parallel.status index 97e7803f4d40a5..b2eccf8eb69c75 100644 --- a/test/parallel/parallel.status +++ b/test/parallel/parallel.status @@ -5,6 +5,7 @@ prefix parallel # sample-test : PASS,FLAKY [true] # This section applies to all platforms +test-fs-read-buffer-tostring-fail : PASS,FLAKY [$system==win32] From 3f2b8a9630bd192d22390717578a0ccd8b5dfe84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Mon, 24 Jul 2017 16:20:30 +0200 Subject: [PATCH 09/82] test: increase coverage for path.parse Backport-PR-URL: https://github.com/nodejs/node/pull/14787 PR-URL: https://github.com/nodejs/node/pull/14438 Reviewed-By: Refael Ackermann Reviewed-By: James M Snell Reviewed-By: Anna Henningsen Reviewed-By: Luigi Pinca Reviewed-By: Timothy Gu Reviewed-By: Colin Ihrig Reviewed-By: Khaidi Chu --- test/parallel/test-path-parse-format.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/parallel/test-path-parse-format.js b/test/parallel/test-path-parse-format.js index af175ba340deeb..b05d382fb6fdd4 100644 --- a/test/parallel/test-path-parse-format.js +++ b/test/parallel/test-path-parse-format.js @@ -11,6 +11,8 @@ const winPaths = [ 'file', '.\\file', 'C:\\', + 'C:', + '\\', '', // unc @@ -21,7 +23,9 @@ const winPaths = [ ]; const winSpecialCaseParseTests = [ - ['/foo/bar', {root: '/'}] + ['/foo/bar', { root: '/' }], + ['C:', { root: 'C:', dir: 'C:', base: '' }], + ['C:\\', { root: 'C:\\', dir: 'C:\\', base: '' }] ]; const winSpecialCaseFormatTests = [ From ba411f1e9b321ee42588978d65243c5451bef400 Mon Sep 17 00:00:00 2001 From: Timothy Gu Date: Mon, 24 Jul 2017 08:39:02 +0800 Subject: [PATCH 10/82] path: fix win32 volume-relative paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `path.resolve()` and `path.join()` are left alone in this commit due to the lack of clear semantics. Backport-PR-URL: https://github.com/nodejs/node/pull/14787 PR-URL: https://github.com/nodejs/node/pull/14440 Fixes: https://github.com/nodejs/node/issues/14405 Reviewed-By: Refael Ackermann Reviewed-By: Tobias Nießen --- lib/path.js | 45 ++++++++------ test/parallel/test-path-parse-format.js | 82 ++++++++++++++----------- test/parallel/test-path.js | 28 ++++++++- 3 files changed, 97 insertions(+), 58 deletions(-) diff --git a/lib/path.js b/lib/path.js index 3ed587e0e0e167..0853197678abdc 100644 --- a/lib/path.js +++ b/lib/path.js @@ -885,6 +885,7 @@ const win32 = { extname: function extname(path) { assertPath(path); + var start = 0; var startDot = -1; var startPart = 0; var end = -1; @@ -892,7 +893,20 @@ const win32 = { // Track the state of characters (if any) we see before our first dot and // after any path separator we find var preDotState = 0; - for (var i = path.length - 1; i >= 0; --i) { + + // Check for a drive letter prefix so as not to mistake the following + // path separator as an extra separator at the end of the path that can be + // disregarded + if (path.length >= 2) { + const code = path.charCodeAt(0); + if (path.charCodeAt(1) === 58/*:*/ && + ((code >= 65/*A*/ && code <= 90/*Z*/) || + (code >= 97/*a*/ && code <= 122/*z*/))) { + start = startPart = 2; + } + } + + for (var i = path.length - 1; i >= start; --i) { const code = path.charCodeAt(i); if (code === 47/*/*/ || code === 92/*\*/) { // If we reached a path separator that was not part of a set of path @@ -956,15 +970,12 @@ const win32 = { var len = path.length; var rootEnd = 0; var code = path.charCodeAt(0); - var isAbsolute = false; // Try to match a root if (len > 1) { if (code === 47/*/*/ || code === 92/*\*/) { // Possible UNC root - isAbsolute = true; - code = path.charCodeAt(1); rootEnd = 1; if (code === 47/*/*/ || code === 92/*\*/) { @@ -1023,7 +1034,6 @@ const win32 = { ret.root = ret.dir = path.slice(0, 3); return ret; } - isAbsolute = true; rootEnd = 3; } } else { @@ -1045,7 +1055,7 @@ const win32 = { ret.root = path.slice(0, rootEnd); var startDot = -1; - var startPart = 0; + var startPart = rootEnd; var end = -1; var matchedSlash = true; var i = path.length - 1; @@ -1094,26 +1104,21 @@ const win32 = { startDot === end - 1 && startDot === startPart + 1)) { if (end !== -1) { - if (startPart === 0 && isAbsolute) - ret.base = ret.name = path.slice(rootEnd, end); - else - ret.base = ret.name = path.slice(startPart, end); + ret.base = ret.name = path.slice(startPart, end); } } else { - if (startPart === 0 && isAbsolute) { - ret.name = path.slice(rootEnd, startDot); - ret.base = path.slice(rootEnd, end); - } else { - ret.name = path.slice(startPart, startDot); - ret.base = path.slice(startPart, end); - } + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); ret.ext = path.slice(startDot, end); } - if (startPart > 0) + // If the directory is the root, use the entire root as the `dir` including + // the trailing slash if any (`C:\abc` -> `C:\`). Otherwise, strip out the + // trailing slash (`C:\abc\def` -> `C:\abc`). + if (startPart > 0 && startPart !== rootEnd) ret.dir = path.slice(0, startPart - 1); - else if (isAbsolute) - ret.dir = path.slice(0, rootEnd); + else + ret.dir = ret.root; return ret; }, diff --git a/test/parallel/test-path-parse-format.js b/test/parallel/test-path-parse-format.js index b05d382fb6fdd4..f5d9881727f40f 100644 --- a/test/parallel/test-path-parse-format.js +++ b/test/parallel/test-path-parse-format.js @@ -4,28 +4,33 @@ const assert = require('assert'); const path = require('path'); const winPaths = [ - 'C:\\path\\dir\\index.html', - 'C:\\another_path\\DIR\\1\\2\\33\\\\index', - 'another_path\\DIR with spaces\\1\\2\\33\\index', - '\\foo\\C:', - 'file', - '.\\file', - 'C:\\', - 'C:', - '\\', - '', + // [path, root] + ['C:\\path\\dir\\index.html', 'C:\\'], + ['C:\\another_path\\DIR\\1\\2\\33\\\\index', 'C:\\'], + ['another_path\\DIR with spaces\\1\\2\\33\\index', ''], + ['\\', '\\'], + ['\\foo\\C:', '\\'], + ['file', ''], + ['file:stream', ''], + ['.\\file', ''], + ['C:', 'C:'], + ['C:.', 'C:'], + ['C:..', 'C:'], + ['C:abc', 'C:'], + ['C:\\', 'C:\\'], + ['C:\\abc', 'C:\\' ], + ['', ''], // unc - '\\\\server\\share\\file_path', - '\\\\server two\\shared folder\\file path.zip', - '\\\\teela\\admin$\\system32', - '\\\\?\\UNC\\server\\share' + ['\\\\server\\share\\file_path', '\\\\server\\share\\'], + ['\\\\server two\\shared folder\\file path.zip', + '\\\\server two\\shared folder\\'], + ['\\\\teela\\admin$\\system32', '\\\\teela\\admin$\\'], + ['\\\\?\\UNC\\server\\share', '\\\\?\\UNC\\'] ]; const winSpecialCaseParseTests = [ ['/foo/bar', { root: '/' }], - ['C:', { root: 'C:', dir: 'C:', base: '' }], - ['C:\\', { root: 'C:\\', dir: 'C:\\', base: '' }] ]; const winSpecialCaseFormatTests = [ @@ -39,26 +44,27 @@ const winSpecialCaseFormatTests = [ ]; const unixPaths = [ - '/home/user/dir/file.txt', - '/home/user/a dir/another File.zip', - '/home/user/a dir//another&File.', - '/home/user/a$$$dir//another File.zip', - 'user/dir/another File.zip', - 'file', - '.\\file', - './file', - 'C:\\foo', - '/', - '', - '.', - '..', - '/foo', - '/foo.', - '/foo.bar', - '/.', - '/.foo', - '/.foo.bar', - '/foo/bar.baz', + // [path, root] + ['/home/user/dir/file.txt', '/'], + ['/home/user/a dir/another File.zip', '/'], + ['/home/user/a dir//another&File.', '/'], + ['/home/user/a$$$dir//another File.zip', '/'], + ['user/dir/another File.zip', ''], + ['file', ''], + ['.\\file', ''], + ['./file', ''], + ['C:\\foo', ''], + ['/', '/'], + ['', ''], + ['.', ''], + ['..', ''], + ['/foo', '/'], + ['/foo.', '/'], + ['/foo.bar', '/'], + ['/.', '/'], + ['/.foo', '/'], + ['/.foo.bar', '/'], + ['/foo/bar.baz', '/'] ]; const unixSpecialCaseFormatTests = [ @@ -169,7 +175,7 @@ function checkErrors(path) { } function checkParseFormat(path, paths) { - paths.forEach(function(element) { + paths.forEach(function([element, root]) { const output = path.parse(element); assert.strictEqual(typeof output.root, 'string'); assert.strictEqual(typeof output.dir, 'string'); @@ -177,6 +183,8 @@ function checkParseFormat(path, paths) { assert.strictEqual(typeof output.ext, 'string'); assert.strictEqual(typeof output.name, 'string'); assert.strictEqual(path.format(output), element); + assert.strictEqual(output.root, root); + assert(output.dir.startsWith(output.root)); assert.strictEqual(output.dir, output.dir ? path.dirname(element) : ''); assert.strictEqual(output.base, path.basename(element)); assert.strictEqual(output.ext, path.extname(element)); diff --git a/test/parallel/test-path.js b/test/parallel/test-path.js index 46f36e36e7ec12..825f10d49d4153 100644 --- a/test/parallel/test-path.js +++ b/test/parallel/test-path.js @@ -51,6 +51,16 @@ assert.strictEqual(path.win32.basename('aaa\\bbb', 'bbb'), 'bbb'); assert.strictEqual(path.win32.basename('aaa\\bbb\\\\\\\\', 'bbb'), 'bbb'); assert.strictEqual(path.win32.basename('aaa\\bbb', 'bb'), 'b'); assert.strictEqual(path.win32.basename('aaa\\bbb', 'b'), 'bb'); +assert.strictEqual(path.win32.basename('C:'), ''); +assert.strictEqual(path.win32.basename('C:.'), '.'); +assert.strictEqual(path.win32.basename('C:\\'), ''); +assert.strictEqual(path.win32.basename('C:\\dir\\base.ext'), 'base.ext'); +assert.strictEqual(path.win32.basename('C:\\basename.ext'), 'basename.ext'); +assert.strictEqual(path.win32.basename('C:basename.ext'), 'basename.ext'); +assert.strictEqual(path.win32.basename('C:basename.ext\\'), 'basename.ext'); +assert.strictEqual(path.win32.basename('C:basename.ext\\\\'), 'basename.ext'); +assert.strictEqual(path.win32.basename('C:foo'), 'foo'); +assert.strictEqual(path.win32.basename('file:stream'), 'file:stream'); // On unix a backslash is just treated as any other character. assert.strictEqual(path.posix.basename('\\dir\\basename.ext'), @@ -99,6 +109,8 @@ assert.strictEqual(path.win32.dirname('c:foo\\'), 'c:'); assert.strictEqual(path.win32.dirname('c:foo\\bar'), 'c:foo'); assert.strictEqual(path.win32.dirname('c:foo\\bar\\'), 'c:foo'); assert.strictEqual(path.win32.dirname('c:foo\\bar\\baz'), 'c:foo\\bar'); +assert.strictEqual(path.win32.dirname('file:stream'), '.'); +assert.strictEqual(path.win32.dirname('dir\\file:stream'), 'dir'); assert.strictEqual(path.win32.dirname('\\\\unc\\share'), '\\\\unc\\share'); assert.strictEqual(path.win32.dirname('\\\\unc\\share\\foo'), @@ -166,6 +178,7 @@ assert.strictEqual(path.win32.dirname('foo'), '.'); ['file./', '.'], ['file.//', '.'], ].forEach((test) => { + const expected = test[1]; [path.posix.extname, path.win32.extname].forEach((extname) => { let input = test[0]; let os; @@ -176,12 +189,19 @@ assert.strictEqual(path.win32.dirname('foo'), '.'); os = 'posix'; } const actual = extname(input); - const expected = test[1]; const message = `path.${os}.extname(${JSON.stringify(input)})\n expect=${ JSON.stringify(expected)}\n actual=${JSON.stringify(actual)}`; if (actual !== expected) failures.push(`\n${message}`); }); + { + const input = `C:${test[0].replace(slashRE, '\\')}`; + const actual = path.win32.extname(input); + const message = `path.win32.extname(${JSON.stringify(input)})\n expect=${ + JSON.stringify(expected)}\n actual=${JSON.stringify(actual)}`; + if (actual !== expected) + failures.push(`\n${message}`); + } }); assert.strictEqual(failures.length, 0, failures.join('')); @@ -385,6 +405,12 @@ assert.strictEqual(path.win32.normalize('a//b//.'), 'a\\b'); assert.strictEqual(path.win32.normalize('//server/share/dir/file.ext'), '\\\\server\\share\\dir\\file.ext'); assert.strictEqual(path.win32.normalize('/a/b/c/../../../x/y/z'), '\\x\\y\\z'); +assert.strictEqual(path.win32.normalize('C:'), 'C:.'); +assert.strictEqual(path.win32.normalize('C:..\\abc'), 'C:..\\abc'); +assert.strictEqual(path.win32.normalize('C:..\\..\\abc\\..\\def'), + 'C:..\\..\\def'); +assert.strictEqual(path.win32.normalize('C:\\.'), 'C:\\'); +assert.strictEqual(path.win32.normalize('file:stream'), 'file:stream'); assert.strictEqual(path.posix.normalize('./fixtures///b/../b/c.js'), 'fixtures/b/c.js'); From d75363be71f251ce36e9d46b77a29fcf43390f59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Sun, 23 Jul 2017 21:48:33 +0200 Subject: [PATCH 11/82] path: remove unnecessary string copies As the length of `path` is known at this point, there is no point in making an exact copy using `slice`. Backport-PR-URL: https://github.com/nodejs/node/pull/14787 PR-URL: https://github.com/nodejs/node/pull/14438 Reviewed-By: Refael Ackermann Reviewed-By: James M Snell Reviewed-By: Anna Henningsen Reviewed-By: Luigi Pinca Reviewed-By: Timothy Gu Reviewed-By: Colin Ihrig Reviewed-By: Khaidi Chu --- lib/path.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lib/path.js b/lib/path.js index 0853197678abdc..dc8a33f4996e5f 100644 --- a/lib/path.js +++ b/lib/path.js @@ -767,7 +767,9 @@ const win32 = { } } } else if (code === 47/*/*/ || code === 92/*\*/) { - return path[0]; + // `path` contains just a path separator, exit early to avoid + // unnecessary work + return path; } for (var i = len - 1; i >= offset; --i) { @@ -1031,7 +1033,7 @@ const win32 = { if (len === 3) { // `path` contains just a drive root, exit early to avoid // unnecessary work - ret.root = ret.dir = path.slice(0, 3); + ret.root = ret.dir = path; return ret; } rootEnd = 3; @@ -1039,7 +1041,7 @@ const win32 = { } else { // `path` contains just a drive root, exit early to avoid // unnecessary work - ret.root = ret.dir = path.slice(0, 2); + ret.root = ret.dir = path; return ret; } } @@ -1047,7 +1049,7 @@ const win32 = { } else if (code === 47/*/*/ || code === 92/*\*/) { // `path` contains just a path separator, exit early to avoid // unnecessary work - ret.root = ret.dir = path[0]; + ret.root = ret.dir = path; return ret; } From cbd2c77ad556a4bc1f28aa9b8542f1db6b7c7a11 Mon Sep 17 00:00:00 2001 From: "Steven R. Loomis" Date: Mon, 27 Mar 2017 13:39:47 -0700 Subject: [PATCH 12/82] tools: add missing #include "unicode/putil.h" * we use u_setDataDirectory() in "unicode/putil.h" * at present, this header is indirectly included, but this will change in ICU 59 * no impact on past ICUs. * this is an exact analog to https://github.com/nodejs/node/issues/11753 PR-URL: https://github.com/nodejs/node/pull/12078 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Richard Lau --- tools/icu/iculslocs.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/icu/iculslocs.cc b/tools/icu/iculslocs.cc index 2471e3f8583011..05c1747a31e163 100644 --- a/tools/icu/iculslocs.cc +++ b/tools/icu/iculslocs.cc @@ -55,6 +55,7 @@ Japanese, it doesn't *claim* to have Japanese. #include #include #include +#include const char* PROG = "iculslocs"; const char* NAME = U_ICUDATA_NAME; // assume ICU data From 0f36025d073a537e2e997d91de018111c660f13e Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Wed, 10 May 2017 20:59:04 -0700 Subject: [PATCH 13/82] timers: do not use user object call/apply Timers should work even if the user has monkey-patched `.call()` and `.apply()` to undesirable values. PR-URL: https://github.com/nodejs/node/pull/12960 Ref: https://github.com/nodejs/node/issues/12956 Reviewed-By: Refael Ackermann Reviewed-By: Jeremiah Senkpiel Reviewed-By: James M Snell Reviewed-By: Joyee Cheung Reviewed-By: Rich Trott --- lib/timers.js | 12 ++++---- test/parallel/test-timers-user-call.js | 40 ++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 6 deletions(-) create mode 100644 test/parallel/test-timers-user-call.js diff --git a/lib/timers.js b/lib/timers.js index 94567f7990b994..c220cf1226f64b 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -383,20 +383,20 @@ function ontimeout(timer) { var args = timer._timerArgs; var callback = timer._onTimeout; if (!args) - callback.call(timer); + timer._onTimeout(); else { switch (args.length) { case 1: - callback.call(timer, args[0]); + timer._onTimeout(args[0]); break; case 2: - callback.call(timer, args[0], args[1]); + timer._onTimeout(args[0], args[1]); break; case 3: - callback.call(timer, args[0], args[1], args[2]); + timer._onTimeout(args[0], args[1], args[2]); break; default: - callback.apply(timer, args); + Function.prototype.apply.call(callback, timer, args); } } if (timer._repeat) @@ -678,7 +678,7 @@ function runCallback(timer) { return timer._callback(argv[0], argv[1], argv[2]); // more than 3 arguments run slower with .apply default: - return timer._callback.apply(timer, argv); + return Function.prototype.apply.call(timer._callback, timer, argv); } } diff --git a/test/parallel/test-timers-user-call.js b/test/parallel/test-timers-user-call.js new file mode 100644 index 00000000000000..4ff24e688b5aa3 --- /dev/null +++ b/test/parallel/test-timers-user-call.js @@ -0,0 +1,40 @@ +// Make sure `setTimeout()` and friends don't throw if the user-supplied +// function has .call() and .apply() monkey-patched to undesirable values. + +// Refs: https://github.com/nodejs/node/issues/12956 + +'use strict'; + +const common = require('../common'); + +{ + const fn = common.mustCall(10); + fn.call = 'not a function'; + fn.apply = 'also not a function'; + setTimeout(fn, 1); + setTimeout(fn, 1, 'oneArg'); + setTimeout(fn, 1, 'two', 'args'); + setTimeout(fn, 1, 'three', '(3)', 'args'); + setTimeout(fn, 1, 'more', 'than', 'three', 'args'); + + setImmediate(fn, 1); + setImmediate(fn, 1, 'oneArg'); + setImmediate(fn, 1, 'two', 'args'); + setImmediate(fn, 1, 'three', '(3)', 'args'); + setImmediate(fn, 1, 'more', 'than', 'three', 'args'); +} + +{ + const testInterval = (...args) => { + const fn = common.mustCall(() => { clearInterval(interval); }); + fn.call = 'not a function'; + fn.apply = 'also not a function'; + const interval = setInterval(fn, 1, ...args); + }; + + testInterval(); + testInterval('oneArg'); + testInterval('two', 'args'); + testInterval('three', '(3)', 'args'); + testInterval('more', 'than', 'three', 'args'); +} From c7622e133f8df3fde5f1bc44eaecc5b8d3f988ec Mon Sep 17 00:00:00 2001 From: "daniel.bevenius" Date: Tue, 2 May 2017 03:28:17 -0700 Subject: [PATCH 14/82] deps: cherry-pick f5fad6d from upstream v8 Original commit message: This commit adds a getter for the private is_verbose_ member. The use case for this comes from Node.js where the ability to avoid calling FatalException if the TryCatch is verbose would be nice to have. BUG= Review-Url: https://codereview.chromium.org/2840803002 Cr-Commit-Position: refs/heads/master@{#45018} PR-URL: https://github.com/nodejs/node/pull/12826 Reviewed-By: Anna Henningsen Reviewed-By: Ben Noordhuis --- deps/v8/include/v8-version.h | 2 +- deps/v8/include/v8.h | 5 +++++ deps/v8/src/api.cc | 4 ++++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h index e2c861431c1091..aa916fc1259186 100644 --- a/deps/v8/include/v8-version.h +++ b/deps/v8/include/v8-version.h @@ -11,7 +11,7 @@ #define V8_MAJOR_VERSION 5 #define V8_MINOR_VERSION 1 #define V8_BUILD_NUMBER 281 -#define V8_PATCH_LEVEL 104 +#define V8_PATCH_LEVEL 105 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) diff --git a/deps/v8/include/v8.h b/deps/v8/include/v8.h index ec45c91d77e728..2184b4a4b9cb07 100644 --- a/deps/v8/include/v8.h +++ b/deps/v8/include/v8.h @@ -6869,6 +6869,11 @@ class V8_EXPORT TryCatch { */ void SetVerbose(bool value); + /** + * Returns true if verbosity is enabled. + */ + bool IsVerbose() const; + /** * Set whether or not this TryCatch should capture a Message object * which holds source information about where the exception diff --git a/deps/v8/src/api.cc b/deps/v8/src/api.cc index 50848c780dff0c..3fbf688b5fcf6b 100644 --- a/deps/v8/src/api.cc +++ b/deps/v8/src/api.cc @@ -2395,6 +2395,10 @@ void v8::TryCatch::SetVerbose(bool value) { is_verbose_ = value; } +bool v8::TryCatch::IsVerbose() const { + return is_verbose_; +} + void v8::TryCatch::SetCaptureMessage(bool value) { capture_message_ = value; From 2914926dfa031e631d7b1a1b8aaf259074d75e76 Mon Sep 17 00:00:00 2001 From: Daniel Bevenius Date: Wed, 3 May 2017 19:17:22 +0200 Subject: [PATCH 15/82] src: only call FatalException if not verbose This commit attempts to address the TODO regarding not calling FatalException if the try_catch is verbose. PR-URL: https://github.com/nodejs/node/pull/12826 Reviewed-By: Colin Ihrig Reviewed-By: Anna Henningsen Reviewed-By: Ben Noordhuis --- src/node.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/node.cc b/src/node.cc index dfe84c67c165f8..62648dbb3fdd69 100644 --- a/src/node.cc +++ b/src/node.cc @@ -2602,9 +2602,9 @@ void FatalException(Isolate* isolate, void FatalException(Isolate* isolate, const TryCatch& try_catch) { HandleScope scope(isolate); - // TODO(bajtos) do not call FatalException if try_catch is verbose - // (requires V8 API to expose getter for try_catch.is_verbose_) - FatalException(isolate, try_catch.Exception(), try_catch.Message()); + if (!try_catch.IsVerbose()) { + FatalException(isolate, try_catch.Exception(), try_catch.Message()); + } } From 9dde328d5ad16f67d7344d6355b20274f12e5d9f Mon Sep 17 00:00:00 2001 From: Refael Ackermann Date: Tue, 25 Apr 2017 17:36:50 -0400 Subject: [PATCH 16/82] build: reduce one level of spawning in node_gyp `configure` will now call `node_gyp` as a module instead of forking makes it easier to debug PR-URL: https://github.com/nodejs/node/pull/12653 Reviewed-By: Ben Noordhuis Reviewed-By: Gibson Fahnestock --- configure | 5 +++-- tools/gyp_node.py | 18 ++++++++---------- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/configure b/configure index 3948f18bcac7f4..1c2ee81cdafb4c 100755 --- a/configure +++ b/configure @@ -40,6 +40,7 @@ import nodedownload # imports in tools/ sys.path.insert(0, os.path.join(root_dir, 'tools')) import getmoduleversion +from gyp_node import run_gyp # parse our options parser = optparse.OptionParser() @@ -1370,7 +1371,7 @@ config = '\n'.join(map('='.join, config.iteritems())) + '\n' write('config.mk', do_not_edit + config) -gyp_args = [sys.executable, 'tools/gyp_node.py', '--no-parallel'] +gyp_args = ['--no-parallel'] if options.use_xcode: gyp_args += ['-f', 'xcode'] @@ -1389,4 +1390,4 @@ gyp_args += args if warn.warned: warn('warnings were emitted in the configure phase') -sys.exit(subprocess.call(gyp_args)) +run_gyp(gyp_args) diff --git a/tools/gyp_node.py b/tools/gyp_node.py index 1f0b2eaebe2c22..043053c3daa9d9 100755 --- a/tools/gyp_node.py +++ b/tools/gyp_node.py @@ -13,14 +13,6 @@ output_dir = os.path.join(os.path.abspath(node_root), 'out') def run_gyp(args): - rc = gyp.main(args) - if rc != 0: - print 'Error running GYP' - sys.exit(rc) - -if __name__ == '__main__': - args = sys.argv[1:] - # GYP bug. # On msvs it will crash if it gets an absolute path. # On Mac/make it will crash if it doesn't get an absolute path. @@ -58,5 +50,11 @@ def run_gyp(args): args.append('-Dlinux_use_bundled_gold=0') args.append('-Dlinux_use_gold_flags=0') - gyp_args = list(args) - run_gyp(gyp_args) + rc = gyp.main(args) + if rc != 0: + print 'Error running GYP' + sys.exit(rc) + + +if __name__ == '__main__': + run_gyp(sys.argv[1:]) From 4072073cd404f5b2656460f562041a657a6741a3 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 19 May 2017 22:14:21 -0700 Subject: [PATCH 17/82] test: check number of message events When a no-op message event handler is used in a test, make it clear what is expected by using `common.mustCall()` and `common.mustNotCall()`. PR-URL: https://github.com/nodejs/node/pull/13125 Reviewed-By: James M Snell Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Michael Dawson Reviewed-By: Gibson Fahnestock Reviewed-By: Refael Ackermann Reviewed-By: Luigi Pinca --- test/parallel/test-child-process-fork-ref2.js | 4 ++-- test/sequential/test-child-process-pass-fd.js | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/parallel/test-child-process-fork-ref2.js b/test/parallel/test-child-process-fork-ref2.js index 9f59aa344aa2c9..cf50a17ad00c64 100644 --- a/test/parallel/test-child-process-fork-ref2.js +++ b/test/parallel/test-child-process-fork-ref2.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const fork = require('child_process').fork; if (process.argv[2] === 'child') { @@ -8,7 +8,7 @@ if (process.argv[2] === 'child') { setTimeout(function() { console.log('child -> will this keep it alive?'); - process.on('message', function() { }); + process.on('message', common.mustNotCall()); }, 400); } else { diff --git a/test/sequential/test-child-process-pass-fd.js b/test/sequential/test-child-process-pass-fd.js index 2d05407e67b99f..b2481270faf065 100644 --- a/test/sequential/test-child-process-pass-fd.js +++ b/test/sequential/test-child-process-pass-fd.js @@ -45,7 +45,7 @@ if (process.argv[2] !== 'child') { // the only thing keeping this worker alive will be IPC. This is important, // because it means a worker with no parent will have no referenced handles, // thus no work to do, and will exit immediately, preventing process leaks. - process.on('message', common.noop); + process.on('message', common.mustCall()); const server = net.createServer((c) => { process.once('message', function(msg) { From 548aba44a3871cd7057fed2d012267226f167247 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sat, 20 May 2017 09:50:51 -0700 Subject: [PATCH 18/82] test: confirm callback is invoked in fs test Use common.mustCall() in test-fs-makeStatsCallback to confirm that the callback is invoked. PR-URL: https://github.com/nodejs/node/pull/13132 Reviewed-By: Colin Ihrig Reviewed-By: Anna Henningsen Reviewed-By: James M Snell Reviewed-By: Michael Dawson Reviewed-By: Alexey Orlenko Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Luigi Pinca --- test/parallel/test-fs-makeStatsCallback.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/parallel/test-fs-makeStatsCallback.js b/test/parallel/test-fs-makeStatsCallback.js index 67e6b18dd3d4f7..607fcdadee0b96 100644 --- a/test/parallel/test-fs-makeStatsCallback.js +++ b/test/parallel/test-fs-makeStatsCallback.js @@ -13,7 +13,7 @@ function testMakeStatsCallback(cb) { } // Verify the case where a callback function is provided -assert.doesNotThrow(testMakeStatsCallback(common.noop)); +assert.doesNotThrow(testMakeStatsCallback(common.mustCall())); // Passing undefined/nothing calls rethrow() internally assert.doesNotThrow(testMakeStatsCallback()); From 4442a1f36fd20a64b8e4214767cc6a876a172091 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 21 May 2017 14:36:12 -0700 Subject: [PATCH 19/82] test: check noop function invocations In test/pummel/test-stream2-basic.js, check that noop functions are called the expected number of times. PR-URL: https://github.com/nodejs/node/pull/13146 Reviewed-By: Refael Ackermann Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Matteo Collina Reviewed-By: Colin Ihrig --- test/pummel/test-stream2-basic.js | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/test/pummel/test-stream2-basic.js b/test/pummel/test-stream2-basic.js index d15030cd9d94d9..4ed4838ecfd1a7 100644 --- a/test/pummel/test-stream2-basic.js +++ b/test/pummel/test-stream2-basic.js @@ -125,7 +125,7 @@ test('a most basic test', function(t) { 'xxxxxxxxxxxxxxxxxxxxx' ]; r.on('end', function() { - t.same(reads, expect); + assert.deepStrictEqual(reads, expect); t.end(); }); @@ -158,7 +158,7 @@ test('pipe', function(t) { const w = new TestWriter(); w.on('end', function(received) { - t.same(received, expect); + assert.deepStrictEqual(received, expect); t.end(); }); @@ -204,7 +204,7 @@ test('pipe', function(t) { t.equal(ended0, false); ended0 = true; ended++; - t.same(results, expect[0]); + assert.deepStrictEqual(results, expect[0]); }); w[1].on('end', function(results) { @@ -212,7 +212,7 @@ test('pipe', function(t) { ended1 = true; ended++; t.equal(ended, 2); - t.same(results, expect[1]); + assert.deepStrictEqual(results, expect[1]); t.end(); }); @@ -239,11 +239,11 @@ test('multipipe', function(t) { let c = 2; w[0].on('end', function(received) { - t.same(received, expect, 'first'); + assert.deepStrictEqual(received, expect, 'first'); if (--c === 0) t.end(); }); w[1].on('end', function(received) { - t.same(received, expect, 'second'); + assert.deepStrictEqual(received, expect, 'second'); if (--c === 0) t.end(); }); @@ -284,13 +284,13 @@ test('multipipe', function(t) { w[0].on('end', function(results) { ended++; - t.same(results, expect[0]); + assert.deepStrictEqual(results, expect[0]); }); w[1].on('end', function(results) { ended++; t.equal(ended, 2); - t.same(results, expect[1]); + assert.deepStrictEqual(results, expect[1]); t.end(); }); @@ -300,10 +300,8 @@ test('multipipe', function(t) { }); test('back pressure respected', function(t) { - function noop() {} - const r = new R({ objectMode: true }); - r._read = noop; + r._read = common.mustNotCall(); let counter = 0; r.push(['one']); r.push(['two']); @@ -321,7 +319,7 @@ test('back pressure respected', function(t) { r.pipe(w3); }); }; - w1.end = noop; + w1.end = common.mustNotCall(); r.pipe(w1); @@ -347,7 +345,7 @@ test('back pressure respected', function(t) { return false; }; - w2.end = noop; + w2.end = common.mustCall(); let w3 = new R(); w3.write = function(chunk) { @@ -380,7 +378,7 @@ test('read(0) for ended streams', function(t) { const r = new R(); let written = false; let ended = false; - r._read = function(n) {}; + r._read = common.mustNotCall(); r.push(Buffer.from('foo')); r.push(null); @@ -451,7 +449,7 @@ test('adding readable triggers data flow', function(t) { test('chainable', function(t) { const r = new R(); - r._read = common.noop; + r._read = common.mustCall(); const r2 = r.setEncoding('utf8').pause().resume().pause(); t.equal(r, r2); t.end(); From 85a8d6e5381a3c48767dd6a181be7332c70493c5 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 21 May 2017 14:40:17 -0700 Subject: [PATCH 20/82] test: simplify assert usage in test-stream2-basic PR-URL: https://github.com/nodejs/node/pull/13146 Reviewed-By: Refael Ackermann Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Matteo Collina Reviewed-By: Colin Ihrig --- test/pummel/test-stream2-basic.js | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/test/pummel/test-stream2-basic.js b/test/pummel/test-stream2-basic.js index 4ed4838ecfd1a7..1bea98ff136799 100644 --- a/test/pummel/test-stream2-basic.js +++ b/test/pummel/test-stream2-basic.js @@ -85,9 +85,6 @@ function run() { const fn = next[1]; console.log('# %s', name); fn({ - same: assert.deepStrictEqual, - ok: assert, - equal: assert.strictEqual, end: function() { count--; run(); @@ -189,10 +186,10 @@ test('pipe', function(t) { w[0].on('write', function() { if (--writes === 0) { r.unpipe(); - t.equal(r._readableState.pipes, null); + assert.strictEqual(r._readableState.pipes, null); w[0].end(); r.pipe(w[1]); - t.equal(r._readableState.pipes, w[1]); + assert.strictEqual(r._readableState.pipes, w[1]); } }); @@ -201,17 +198,17 @@ test('pipe', function(t) { let ended0 = false; let ended1 = false; w[0].on('end', function(results) { - t.equal(ended0, false); + assert.strictEqual(ended0, false); ended0 = true; ended++; assert.deepStrictEqual(results, expect[0]); }); w[1].on('end', function(results) { - t.equal(ended1, false); + assert.strictEqual(ended1, false); ended1 = true; ended++; - t.equal(ended, 2); + assert.strictEqual(ended, 2); assert.deepStrictEqual(results, expect[1]); t.end(); }); @@ -289,7 +286,7 @@ test('multipipe', function(t) { w[1].on('end', function(results) { ended++; - t.equal(ended, 2); + assert.strictEqual(ended, 2); assert.deepStrictEqual(results, expect[1]); t.end(); }); @@ -441,8 +438,8 @@ test('adding readable triggers data flow', function(t) { }); r.on('end', function() { - t.equal(readCalled, 3); - t.ok(onReadable); + assert.strictEqual(readCalled, 3); + assert.ok(onReadable); t.end(); }); }); @@ -451,6 +448,6 @@ test('chainable', function(t) { const r = new R(); r._read = common.mustCall(); const r2 = r.setEncoding('utf8').pause().resume().pause(); - t.equal(r, r2); + assert.strictEqual(r, r2); t.end(); }); From 10ad1286f5084817e279fc697d3d451b38543b46 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 21 May 2017 14:43:09 -0700 Subject: [PATCH 21/82] test: move stream2 test from pummel to parallel test-stream2-basic runs in a few seconds. It can be moved to parallel. PR-URL: https://github.com/nodejs/node/pull/13146 Reviewed-By: Refael Ackermann Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Matteo Collina Reviewed-By: Colin Ihrig --- test/{pummel => parallel}/test-stream2-basic.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename test/{pummel => parallel}/test-stream2-basic.js (100%) diff --git a/test/pummel/test-stream2-basic.js b/test/parallel/test-stream2-basic.js similarity index 100% rename from test/pummel/test-stream2-basic.js rename to test/parallel/test-stream2-basic.js From 8fd7fcca2483d2dcf7e4a76c95bd9410406a2081 Mon Sep 17 00:00:00 2001 From: "Bradley T. Hughes" Date: Mon, 27 Mar 2017 09:48:21 +0000 Subject: [PATCH 22/82] build: support dtrace on ARM Use the same dtrace command on ARM as on i386. Patch obtained from FreeBSD PR 218081 [1]. 1. https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=218081 PR-URL: https://github.com/nodejs/node/pull/12193 Reviewed-By: Ben Noordhuis Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- node.gyp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/node.gyp b/node.gyp index 8bf26e276b2648..8be54752a28a41 100644 --- a/node.gyp +++ b/node.gyp @@ -488,7 +488,7 @@ '<(OBJ_DIR)/node/src/node_dtrace_ustack.o' ], 'conditions': [ - [ 'target_arch=="ia32"', { + [ 'target_arch=="ia32" or target_arch=="arm"', { 'action': [ 'dtrace', '-32', '-I<(SHARED_INTERMEDIATE_DIR)', '-Isrc', '-C', '-G', '-s', 'src/v8ustack.d', '-o', '<@(_outputs)', From 6ca963a0b177586c00f38d2503d2efb46de8ae9d Mon Sep 17 00:00:00 2001 From: Aditya Anand Date: Thu, 25 May 2017 17:32:47 +0530 Subject: [PATCH 23/82] test: replace `indexOf` with `includes` PR-URL: https://github.com/nodejs/node/pull/13215 Refs: https://github.com/nodejs/node/issues/12586 Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig Reviewed-By: Refael Ackermann Reviewed-By: James M Snell Reviewed-By: Gibson Fahnestock --- test/parallel/test-http-client-agent.js | 3 ++- test/parallel/test-http-client-default-headers-exist.js | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/test/parallel/test-http-client-agent.js b/test/parallel/test-http-client-agent.js index b90694523745d4..6d30a2236ef485 100644 --- a/test/parallel/test-http-client-agent.js +++ b/test/parallel/test-http-client-agent.js @@ -34,7 +34,8 @@ function request(i) { socket.on('close', function() { ++count; if (count < max) { - assert.strictEqual(http.globalAgent.sockets[name].indexOf(socket), -1); + assert.strictEqual(http.globalAgent.sockets[name].includes(socket), + false); } else { assert(!http.globalAgent.sockets.hasOwnProperty(name)); assert(!http.globalAgent.requests.hasOwnProperty(name)); diff --git a/test/parallel/test-http-client-default-headers-exist.js b/test/parallel/test-http-client-default-headers-exist.js index 06923b6c79c5c0..410f83449fc1b6 100644 --- a/test/parallel/test-http-client-default-headers-exist.js +++ b/test/parallel/test-http-client-default-headers-exist.js @@ -25,9 +25,9 @@ const server = http.createServer(function(req, res) { const requestHeaders = Object.keys(req.headers); requestHeaders.forEach(function(header) { - assert.notStrictEqual( - expectedHeaders[req.method].indexOf(header.toLowerCase()), - -1, + assert.strictEqual( + expectedHeaders[req.method].includes(header.toLowerCase()), + true, `${header} should not exist for method ${req.method}` ); }); From b997b8fb3cf67c4def4fcfd38bba4d755e2a05c0 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 26 May 2017 14:54:51 -0700 Subject: [PATCH 24/82] test: use mustNotCall() in test-stream2-objects Use `common.mustNotCall()` in test-stream2-objects.js to confirm that noop function is never invoked. PR-URL: https://github.com/nodejs/node/pull/13249 Reviewed-By: Refael Ackermann Reviewed-By: Luigi Pinca Reviewed-By: Benjamin Gruenbaum Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- test/parallel/test-stream2-objects.js | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/test/parallel/test-stream2-objects.js b/test/parallel/test-stream2-objects.js index cab838fbfc9acb..cea3a4845105df 100644 --- a/test/parallel/test-stream2-objects.js +++ b/test/parallel/test-stream2-objects.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const Readable = require('_stream_readable'); const Writable = require('_stream_writable'); const assert = require('assert'); @@ -54,7 +54,7 @@ function toArray(callback) { function fromArray(list) { const r = new Readable({ objectMode: true }); - r._read = noop; + r._read = common.mustNotCall(); list.forEach(function(chunk) { r.push(chunk); }); @@ -63,8 +63,6 @@ function fromArray(list) { return r; } -function noop() {} - test('can read objects from stream', function(t) { const r = fromArray([{ one: '1'}, { two: '2' }]); @@ -144,7 +142,7 @@ test('can read strings as objects', function(t) { const r = new Readable({ objectMode: true }); - r._read = noop; + r._read = common.mustNotCall(); const list = ['one', 'two', 'three']; list.forEach(function(str) { r.push(str); @@ -162,7 +160,7 @@ test('read(0) for object streams', function(t) { const r = new Readable({ objectMode: true }); - r._read = noop; + r._read = common.mustNotCall(); r.push('foobar'); r.push(null); @@ -178,7 +176,7 @@ test('falsey values', function(t) { const r = new Readable({ objectMode: true }); - r._read = noop; + r._read = common.mustNotCall(); r.push(false); r.push(0); @@ -229,7 +227,7 @@ test('high watermark push', function(t) { highWaterMark: 6, objectMode: true }); - r._read = function(n) {}; + r._read = common.mustNotCall(); for (let i = 0; i < 6; i++) { const bool = r.push(i); assert.strictEqual(bool, i !== 5); From 7919eee44b6a7d98a2df6d12101127a0768bb22d Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sat, 27 May 2017 14:28:26 -0700 Subject: [PATCH 25/82] test: use mustCall() in test-readline-interface Use `common.mustCall()` to make sure noop function is called as expected. PR-URL: https://github.com/nodejs/node/pull/13259 Reviewed-By: Refael Ackermann Reviewed-By: Richard Lau Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- test/parallel/test-readline-interface.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/parallel/test-readline-interface.js b/test/parallel/test-readline-interface.js index ddabc20b39026f..0e7e96a565a83d 100644 --- a/test/parallel/test-readline-interface.js +++ b/test/parallel/test-readline-interface.js @@ -541,7 +541,7 @@ function isWarned(emitter) { }); const rl = readline.createInterface({ - input: new Readable({ read: () => {} }), + input: new Readable({ read: common.mustCall() }), output: output, prompt: '$ ', terminal: terminal From 089bd3b24dbf35908e8aa312a772f64a88ce7066 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 28 May 2017 21:00:44 -0700 Subject: [PATCH 26/82] test: refactor test-net-server-bind * Use common.mustNotCall() and common.mustCall() as appropriate * Use block scoping * Move assertions out of `exit` handler and into callbacks * Order assert.strictEqual() args per docs * Remove console.log() calls * Move test from `parallel` to `sequential` so `common.PORT` can be used without conflicting with OS-provided ports in other `parallel` tests PR-URL: https://github.com/nodejs/node/pull/13273 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Luigi Pinca --- test/parallel/test-net-server-bind.js | 86 ------------------------- test/sequential/test-net-server-bind.js | 64 ++++++++++++++++++ 2 files changed, 64 insertions(+), 86 deletions(-) delete mode 100644 test/parallel/test-net-server-bind.js create mode 100644 test/sequential/test-net-server-bind.js diff --git a/test/parallel/test-net-server-bind.js b/test/parallel/test-net-server-bind.js deleted file mode 100644 index 2804271f6f19d4..00000000000000 --- a/test/parallel/test-net-server-bind.js +++ /dev/null @@ -1,86 +0,0 @@ -'use strict'; -const common = require('../common'); -const assert = require('assert'); -const net = require('net'); - - -// With only a callback, server should get a port assigned by the OS - -let address0; -const server0 = net.createServer(function(socket) { }); - -server0.listen(function() { - address0 = server0.address(); - console.log('address0 %j', address0); - server0.close(); -}); - - -// No callback to listen(), assume we can bind in 100 ms - -let address1; -let connectionKey1; -const server1 = net.createServer(function(socket) { }); - -server1.listen(common.PORT); - -setTimeout(function() { - address1 = server1.address(); - connectionKey1 = server1._connectionKey; - console.log('address1 %j', address1); - server1.close(); -}, 100); - - -// Callback to listen() - -let address2; -const server2 = net.createServer(function(socket) { }); - -server2.listen(common.PORT + 1, function() { - address2 = server2.address(); - console.log('address2 %j', address2); - server2.close(); -}); - - -// Backlog argument - -let address3; -const server3 = net.createServer(function(socket) { }); - -server3.listen(common.PORT + 2, '0.0.0.0', 127, function() { - address3 = server3.address(); - console.log('address3 %j', address3); - server3.close(); -}); - - -// Backlog argument without host argument - -let address4; -const server4 = net.createServer(function(socket) { }); - -server4.listen(common.PORT + 3, 127, function() { - address4 = server4.address(); - console.log('address4 %j', address4); - server4.close(); -}); - - -process.on('exit', function() { - assert.ok(address0.port > 100); - assert.strictEqual(common.PORT, address1.port); - - let expectedConnectionKey1; - - if (address1.family === 'IPv6') - expectedConnectionKey1 = `6::::${address1.port}`; - else - expectedConnectionKey1 = `4:0.0.0.0:${address1.port}`; - - assert.strictEqual(connectionKey1, expectedConnectionKey1); - assert.strictEqual(common.PORT + 1, address2.port); - assert.strictEqual(common.PORT + 2, address3.port); - assert.strictEqual(common.PORT + 3, address4.port); -}); diff --git a/test/sequential/test-net-server-bind.js b/test/sequential/test-net-server-bind.js new file mode 100644 index 00000000000000..56216d0ed60619 --- /dev/null +++ b/test/sequential/test-net-server-bind.js @@ -0,0 +1,64 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); + + +// With only a callback, server should get a port assigned by the OS +{ + const server = net.createServer(common.mustNotCall()); + + server.listen(common.mustCall(function() { + assert.ok(server.address().port > 100); + server.close(); + })); +} + +// No callback to listen(), assume we can bind in 100 ms +{ + const server = net.createServer(common.mustNotCall()); + + server.listen(common.PORT); + + setTimeout(function() { + const address = server.address(); + assert.strictEqual(address.port, common.PORT); + + if (address.family === 'IPv6') + assert.strictEqual(server._connectionKey, `6::::${address.port}`); + else + assert.strictEqual(server._connectionKey, `4:0.0.0.0:${address.port}`); + + server.close(); + }, 100); +} + +// Callback to listen() +{ + const server = net.createServer(common.mustNotCall()); + + server.listen(common.PORT + 1, common.mustCall(function() { + assert.strictEqual(server.address().port, common.PORT + 1); + server.close(); + })); +} + +// Backlog argument +{ + const server = net.createServer(common.mustNotCall()); + + server.listen(common.PORT + 2, '0.0.0.0', 127, common.mustCall(function() { + assert.strictEqual(server.address().port, common.PORT + 2); + server.close(); + })); +} + +// Backlog argument without host argument +{ + const server = net.createServer(common.mustNotCall()); + + server.listen(common.PORT + 3, 127, common.mustCall(function() { + assert.strictEqual(server.address().port, common.PORT + 3); + server.close(); + })); +} From 30201e572d5f0944b9743bfd3160973fc7206625 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Wed, 31 May 2017 22:26:55 -0700 Subject: [PATCH 27/82] test: add documentation for common.mustNotCall() PR-URL: https://github.com/nodejs/node/pull/13359 Reviewed-By: Daniel Bevenius Reviewed-By: Luigi Pinca Reviewed-By: Vse Mozhet Byt Reviewed-By: Gibson Fahnestock Reviewed-By: Colin Ihrig Reviewed-By: Michael Dawson Reviewed-By: Richard Lau Reviewed-By: James M Snell Reviewed-By: David Cai --- test/common/README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/common/README.md b/test/common/README.md index 492b5acdea586c..01d19116bdac29 100644 --- a/test/common/README.md +++ b/test/common/README.md @@ -204,6 +204,12 @@ fail. If `fn` is not provided, `common.noop` will be used. +### mustNotCall([msg]) +* `msg` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) default = 'function should not have been called' +* return [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) + +Returns a function that triggers an `AssertionError` if it is invoked. `msg` is used as the error message for the `AssertionError`. + ### nodeProcessAborted(exitCode, signal) * `exitCode` [<Number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) * `signal` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) From 7c2befce3b49c37d2054cfa9e4c8bc28bead2ff2 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sat, 3 Jun 2017 13:22:57 -0700 Subject: [PATCH 28/82] test: refactor test-dgram-oob-buffer * Change common.noop to common.mustNotCall() to verify callback is not invoked. * Add destructuring assignment for clarity. Yeah, clarity. That's why. PR-URL: https://github.com/nodejs/node/pull/13443 Reviewed-By: Anna Henningsen Reviewed-By: Gibson Fahnestock Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Michael Dawson --- test/parallel/test-dgram-oob-buffer.js | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/test/parallel/test-dgram-oob-buffer.js b/test/parallel/test-dgram-oob-buffer.js index b49baa2e0d8dad..f93533479b2d93 100644 --- a/test/parallel/test-dgram-oob-buffer.js +++ b/test/parallel/test-dgram-oob-buffer.js @@ -10,15 +10,14 @@ const socket = dgram.createSocket('udp4'); const buf = Buffer.from([1, 2, 3, 4]); const portGetter = dgram.createSocket('udp4') .bind(0, 'localhost', common.mustCall(() => { - const address = portGetter.address(); + const { address, port } = portGetter.address(); portGetter.close(common.mustCall(() => { - function ok() {} - socket.send(buf, 0, 0, address.port, address.address, ok); - socket.send(buf, 0, 4, address.port, address.address, ok); - socket.send(buf, 1, 3, address.port, address.address, ok); - socket.send(buf, 3, 1, address.port, address.address, ok); + socket.send(buf, 0, 0, port, address, common.mustNotCall()); + socket.send(buf, 0, 4, port, address, common.mustNotCall()); + socket.send(buf, 1, 3, port, address, common.mustNotCall()); + socket.send(buf, 3, 1, port, address, common.mustNotCall()); // Since length of zero means nothing, don't error despite OOB. - socket.send(buf, 4, 0, address.port, address.address, ok); + socket.send(buf, 4, 0, port, address, common.mustNotCall()); socket.close(); })); From c15393c196bc70e4d5fe69472283bedda0ce36ea Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 4 Jun 2017 11:19:05 -0700 Subject: [PATCH 29/82] test: check callback not invoked on lookup error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use `common.mustNotCall()` to confirm that callback is not invoked when `dns.lookup()` throws. PR-URL: https://github.com/nodejs/node/pull/13456 Reviewed-By: Tobias Nießen Reviewed-By: Anna Henningsen Reviewed-By: Refael Ackermann Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Gibson Fahnestock --- test/parallel/test-dns-lookup.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/parallel/test-dns-lookup.js b/test/parallel/test-dns-lookup.js index a720c46e02a630..a1fad873e33f37 100644 --- a/test/parallel/test-dns-lookup.js +++ b/test/parallel/test-dns-lookup.js @@ -24,7 +24,7 @@ assert.throws(() => { hints: 100, family: 0, all: false - }, () => {}); + }, common.mustNotCall()); }, /^TypeError: Invalid argument: hints must use valid flags$/); assert.throws(() => { @@ -32,7 +32,7 @@ assert.throws(() => { hints: 0, family: 20, all: false - }, () => {}); + }, common.mustNotCall()); }, /^TypeError: Invalid argument: family must be 4 or 6$/); assert.doesNotThrow(() => { From 1a95a51766e4c55679b2e3d029d566a85b19cdb4 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 5 Jun 2017 11:22:26 -0700 Subject: [PATCH 30/82] test: refactor domain tests * Check that noop callback is or isn't invoked as appropriate using common.mustCall() and common.mustNotCall() * Fix typo in array literal PR-URL: https://github.com/nodejs/node/pull/13480 Reviewed-By: James M Snell Reviewed-By: Refael Ackermann Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: Michael Dawson --- test/parallel/test-domain-crypto.js | 6 +++--- test/parallel/test-domain-timers.js | 4 +--- test/parallel/test-domain.js | 4 ++-- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/test/parallel/test-domain-crypto.js b/test/parallel/test-domain-crypto.js index bc9c4b6d467ec4..7f009b45df5639 100644 --- a/test/parallel/test-domain-crypto.js +++ b/test/parallel/test-domain-crypto.js @@ -17,7 +17,7 @@ global.domain = require('domain'); // should not throw a 'TypeError: undefined is not a function' exception crypto.randomBytes(8); -crypto.randomBytes(8, common.noop); +crypto.randomBytes(8, common.mustCall()); crypto.pseudoRandomBytes(8); -crypto.pseudoRandomBytes(8, common.noop); -crypto.pbkdf2('password', 'salt', 8, 8, common.noop); +crypto.pseudoRandomBytes(8, common.mustCall()); +crypto.pbkdf2('password', 'salt', 8, 8, 'sha1', common.mustCall()); diff --git a/test/parallel/test-domain-timers.js b/test/parallel/test-domain-timers.js index 7fff5468564449..bb130ae0808589 100644 --- a/test/parallel/test-domain-timers.js +++ b/test/parallel/test-domain-timers.js @@ -3,8 +3,6 @@ const common = require('../common'); const domain = require('domain'); const assert = require('assert'); -let timeout; - const timeoutd = domain.create(); timeoutd.on('error', common.mustCall(function(e) { @@ -32,4 +30,4 @@ immediated.run(function() { }); }); -timeout = setTimeout(common.noop, 10 * 1000); +const timeout = setTimeout(common.mustNotCall(), 10 * 1000); diff --git a/test/parallel/test-domain.js b/test/parallel/test-domain.js index f5dc699f2595b9..0233eb88eb268b 100644 --- a/test/parallel/test-domain.js +++ b/test/parallel/test-domain.js @@ -1,7 +1,7 @@ 'use strict'; // Simple tests of most basic domain functionality. -const common = require('../common'); +require('../common'); const assert = require('assert'); const domain = require('domain'); const events = require('events'); @@ -238,7 +238,7 @@ let fst = fs.createReadStream('stream for nonexistent file'); d.add(fst); expectCaught++; -[42, null, , false, common.noop, 'string'].forEach(function(something) { +[42, null, undefined, false, () => {}, 'string'].forEach(function(something) { const d = new domain.Domain(); d.run(function() { process.nextTick(function() { From 8033cf3ecb3fa1b288ff2fee5e0b5280c9010f62 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Tue, 6 Jun 2017 09:53:32 -0700 Subject: [PATCH 31/82] test: refactor test-fs-read-* * Use `common.mustNotCall()` in place of `common.noop` where appropriate * Increase specificity of regular expressions (that is, make them match the whole error string rather than part of the error string) in `assert.throws()` calls PR-URL: https://github.com/nodejs/node/pull/13501 Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: Michael Dawson --- test/parallel/test-fs-read-file-assert-encoding.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/parallel/test-fs-read-file-assert-encoding.js b/test/parallel/test-fs-read-file-assert-encoding.js index 897bcd3bc98795..ac0f45f98b30d4 100644 --- a/test/parallel/test-fs-read-file-assert-encoding.js +++ b/test/parallel/test-fs-read-file-assert-encoding.js @@ -1,6 +1,6 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const fs = require('fs'); @@ -8,6 +8,6 @@ const encoding = 'foo-8'; const filename = 'bar.txt'; assert.throws( - fs.readFile.bind(fs, filename, { encoding }, () => {}), - new RegExp(`Error: Unknown encoding: ${encoding}$`) + fs.readFile.bind(fs, filename, { encoding }, common.mustNotCall()), + new RegExp(`^Error: Unknown encoding: ${encoding}$`) ); From bfea6b26f0c6232e58722c25f7365ad47e241ef9 Mon Sep 17 00:00:00 2001 From: XadillaX Date: Thu, 8 Jun 2017 21:12:11 +0800 Subject: [PATCH 32/82] src: merge `fn_name` in NODE_SET_PROTOTYPE_METHOD Merge two duplicate `fn_name` into one in NODE_SET_PROTOTYPE_METHOD, it may improve a bit performance. PR-URL: https://github.com/nodejs/node/pull/13547 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Refael Ackermann Reviewed-By: James M Snell --- src/node.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/node.h b/src/node.h index 55ad8031104d3c..103ff98709a395 100644 --- a/src/node.h +++ b/src/node.h @@ -282,7 +282,7 @@ inline void NODE_SET_PROTOTYPE_METHOD(v8::Local recv, v8::FunctionTemplate::New(isolate, callback, v8::Local(), s); v8::Local fn_name = v8::String::NewFromUtf8(isolate, name); t->SetClassName(fn_name); - recv->PrototypeTemplate()->Set(v8::String::NewFromUtf8(isolate, name), t); + recv->PrototypeTemplate()->Set(fn_name, t); } #define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD From 245f6b09a4154224e38d5fb46a4818e19b2b160f Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 9 Jun 2017 13:12:39 -0700 Subject: [PATCH 33/82] test: use mustNotCall in test-http-eof-on-connect Confirm that callback is not being invoked in test-http-eof-on-connect.js. PR-URL: https://github.com/nodejs/node/pull/13587 Reviewed-By: Colin Ihrig Reviewed-By: Refael Ackermann Reviewed-By: Anna Henningsen Reviewed-By: Gibson Fahnestock Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- test/parallel/test-http-eof-on-connect.js | 26 +++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/test/parallel/test-http-eof-on-connect.js b/test/parallel/test-http-eof-on-connect.js index f67e45ed403225..7e244354c1cb88 100644 --- a/test/parallel/test-http-eof-on-connect.js +++ b/test/parallel/test-http-eof-on-connect.js @@ -1,5 +1,27 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + 'use strict'; -require('../common'); + +const common = require('../common'); const net = require('net'); const http = require('http'); @@ -7,7 +29,7 @@ const http = require('http'); // It is separate from test-http-malformed-request.js because it is only // reproduceable on the first packet on the first connection to a server. -const server = http.createServer(function(req, res) {}); +const server = http.createServer(common.mustNotCall()); server.listen(0); server.on('listening', function() { From 6f4456340c3536da25661fd798643d57d8aa07af Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sat, 10 Jun 2017 20:42:35 -0700 Subject: [PATCH 34/82] test: add mustCall() to child-process test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add common.mustCall() check to test-child-process-stdio-big-write-end. PR-URL: https://github.com/nodejs/node/pull/13605 Reviewed-By: Luigi Pinca Reviewed-By: Refael Ackermann Reviewed-By: Colin Ihrig Reviewed-By: Yuta Hiroto Reviewed-By: Tobias Nießen Reviewed-By: James M Snell --- test/parallel/test-child-process-stdio-big-write-end.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/parallel/test-child-process-stdio-big-write-end.js b/test/parallel/test-child-process-stdio-big-write-end.js index 5e32314cc87a33..71333bdbd534ab 100644 --- a/test/parallel/test-child-process-stdio-big-write-end.js +++ b/test/parallel/test-child-process-stdio-big-write-end.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); let bufsize = 0; @@ -22,10 +22,10 @@ function parent() { child.stdout.on('data', function(c) { n += c; }); - child.stdout.on('end', function() { + child.stdout.on('end', common.mustCall(function() { assert.strictEqual(+n, sent); console.log('ok'); - }); + })); // Write until the buffer fills up. let buf; From 2f8aa8897d33a8dbe9d8a022c49e64e94c25e1aa Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 9 Jun 2017 21:23:23 -0700 Subject: [PATCH 35/82] test: use mustNotCall() in test-fs-watch Use common.mustNotCall() in test/sequential/test-fs-watch.js in situations where the call to watch() is expected to throw. PR-URL: https://github.com/nodejs/node/pull/13595 Reviewed-By: Yuta Hiroto Reviewed-By: Richard Lau Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: Gibson Fahnestock Reviewed-By: Refael Ackermann Reviewed-By: James M Snell --- test/sequential/test-fs-watch.js | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/test/sequential/test-fs-watch.js b/test/sequential/test-fs-watch.js index b99e86a7e65e4f..70c165ea7992be 100644 --- a/test/sequential/test-fs-watch.js +++ b/test/sequential/test-fs-watch.js @@ -1,3 +1,24 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + 'use strict'; const common = require('../common'); const assert = require('assert'); @@ -109,7 +130,7 @@ fs.watch(__filename, {persistent: false}, function() { // https://github.com/joyent/node/issues/6690 let oldhandle; assert.throws(function() { - const w = fs.watch(__filename, function(event, filename) { }); + const w = fs.watch(__filename, common.mustNotCall()); oldhandle = w._handle; w._handle = { close: w._handle.close }; w.close(); @@ -117,7 +138,7 @@ assert.throws(function() { oldhandle.close(); // clean up assert.throws(function() { - const w = fs.watchFile(__filename, {persistent: false}, common.noop); + const w = fs.watchFile(__filename, {persistent: false}, common.mustNotCall()); oldhandle = w._handle; w._handle = { stop: w._handle.stop }; w.stop(); From 9a9d4939a13da80349bed5b8312518f2a5f0552f Mon Sep 17 00:00:00 2001 From: jklepatch Date: Mon, 12 Jun 2017 11:12:49 +0800 Subject: [PATCH 36/82] test: make test-http(s)-set-timeout-server alike Make test-http(s)-set-timeout-server tests more similar and resolve the following issues: * `test-http-set-timeout-server.js` had a `secReceived` check in `serverResponseTimeoutWithPipeline()` that was added to prevent flakiness, but this did not exist in the https counterpart. * `test-https-set-timeout-server.js` utilized `common.mustCall()`, `common.mustNotCall()`, etc., while the http counterpart utilized the old method of checking flags on exit of the process. Refs: https://github.com/nodejs/node/issues/13588 PR-URL: https://github.com/nodejs/node/pull/13625 Reviewed-By: Rich Trott Reviewed-By: Colin Ihrig Reviewed-By: Alexey Orlenko --- test/parallel/test-http-set-timeout-server.js | 66 ++++--------------- .../test-https-set-timeout-server.js | 11 +++- 2 files changed, 22 insertions(+), 55 deletions(-) diff --git a/test/parallel/test-http-set-timeout-server.js b/test/parallel/test-http-set-timeout-server.js index 314b5f56b2601c..ebd7be5405bbbd 100644 --- a/test/parallel/test-http-set-timeout-server.js +++ b/test/parallel/test-http-set-timeout-server.js @@ -23,38 +23,28 @@ function run() { } test(function serverTimeout(cb) { - let caughtTimeout = false; - process.on('exit', function() { - assert(caughtTimeout); - }); const server = http.createServer(function(req, res) { // just do nothing, we should get a timeout event. }); server.listen(common.mustCall(function() { http.get({ port: server.address().port }).on('error', common.noop); })); - const s = server.setTimeout(50, function(socket) { - caughtTimeout = true; + const s = server.setTimeout(50, common.mustCall(function(socket) { socket.destroy(); server.close(); cb(); - }); + })); assert.ok(s instanceof http.Server); }); test(function serverRequestTimeout(cb) { - let caughtTimeout = false; - process.on('exit', function() { - assert(caughtTimeout); - }); const server = http.createServer(function(req, res) { // just do nothing, we should get a timeout event. - const s = req.setTimeout(50, function() { - caughtTimeout = true; - req.socket.destroy(); + const s = req.setTimeout(50, common.mustCall(function(socket) { + socket.destroy(); server.close(); cb(); - }); + })); assert.ok(s instanceof http.IncomingMessage); }); server.listen(common.mustCall(function() { @@ -67,18 +57,13 @@ test(function serverRequestTimeout(cb) { }); test(function serverResponseTimeout(cb) { - let caughtTimeout = false; - process.on('exit', function() { - assert(caughtTimeout); - }); const server = http.createServer(function(req, res) { // just do nothing, we should get a timeout event. - const s = res.setTimeout(50, function() { - caughtTimeout = true; - res.socket.destroy(); + const s = res.setTimeout(50, common.mustCall(function(socket) { + socket.destroy(); server.close(); cb(); - }); + })); assert.ok(s instanceof http.OutgoingMessage); }); server.listen(common.mustCall(function() { @@ -88,21 +73,11 @@ test(function serverResponseTimeout(cb) { }); test(function serverRequestNotTimeoutAfterEnd(cb) { - let caughtTimeoutOnRequest = false; - let caughtTimeoutOnResponse = false; - process.on('exit', function() { - assert(!caughtTimeoutOnRequest); - assert(caughtTimeoutOnResponse); - }); const server = http.createServer(function(req, res) { // just do nothing, we should get a timeout event. - const s = req.setTimeout(50, function(socket) { - caughtTimeoutOnRequest = true; - }); + const s = req.setTimeout(50, common.mustNotCall()); assert.ok(s instanceof http.IncomingMessage); - res.on('timeout', function(socket) { - caughtTimeoutOnResponse = true; - }); + res.on('timeout', common.mustCall()); }); server.on('timeout', function(socket) { socket.destroy(); @@ -148,29 +123,16 @@ test(function serverResponseTimeoutWithPipeline(cb) { }); test(function idleTimeout(cb) { - let caughtTimeoutOnRequest = false; - let caughtTimeoutOnResponse = false; - let caughtTimeoutOnServer = false; - process.on('exit', function() { - assert(!caughtTimeoutOnRequest); - assert(!caughtTimeoutOnResponse); - assert(caughtTimeoutOnServer); - }); const server = http.createServer(function(req, res) { - req.on('timeout', function(socket) { - caughtTimeoutOnRequest = true; - }); - res.on('timeout', function(socket) { - caughtTimeoutOnResponse = true; - }); + req.on('timeout', common.mustNotCall()); + res.on('timeout', common.mustNotCall()); res.end(); }); - const s = server.setTimeout(50, function(socket) { - caughtTimeoutOnServer = true; + const s = server.setTimeout(50, common.mustCall(function(socket) { socket.destroy(); server.close(); cb(); - }); + })); assert.ok(s instanceof http.Server); server.listen(common.mustCall(function() { const port = server.address().port; diff --git a/test/sequential/test-https-set-timeout-server.js b/test/sequential/test-https-set-timeout-server.js index b1a597e34de345..a2da563464352f 100644 --- a/test/sequential/test-https-set-timeout-server.js +++ b/test/sequential/test-https-set-timeout-server.js @@ -116,19 +116,24 @@ test(function serverRequestNotTimeoutAfterEnd(cb) { test(function serverResponseTimeoutWithPipeline(cb) { let caughtTimeout = ''; + let secReceived = false; process.on('exit', function() { assert.strictEqual(caughtTimeout, '/2'); }); const server = https.createServer(serverOptions, function(req, res) { + if (req.url === '/2') + secReceived = true; res.setTimeout(50, function() { caughtTimeout += req.url; }); if (req.url === '/1') res.end(); }); server.on('timeout', function(socket) { - socket.destroy(); - server.close(); - cb(); + if (secReceived) { + socket.destroy(); + server.close(); + cb(); + } }); server.listen(0, function() { const options = { From 8fd52972e3f0e17bc24ea10954993224b85d15d2 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 19 Jun 2017 11:56:52 -0700 Subject: [PATCH 37/82] test: refactor test-http-set-timeout-server * Use `common.mustCall()` to track callback invocations * Remove console.log() statements unrelated to the test * Add blank line to conform with test-writing guide PR-URL: https://github.com/nodejs/node/pull/13802 Reviewed-By: Benjamin Gruenbaum Reviewed-By: Colin Ihrig Reviewed-By: Refael Ackermann --- test/parallel/test-http-set-timeout-server.js | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/test/parallel/test-http-set-timeout-server.js b/test/parallel/test-http-set-timeout-server.js index ebd7be5405bbbd..b2b15d4838d1c0 100644 --- a/test/parallel/test-http-set-timeout-server.js +++ b/test/parallel/test-http-set-timeout-server.js @@ -1,5 +1,6 @@ 'use strict'; const common = require('../common'); + const assert = require('assert'); const http = require('http'); const net = require('net'); @@ -9,16 +10,13 @@ const tests = []; function test(fn) { if (!tests.length) process.nextTick(run); - tests.push(fn); + tests.push(common.mustCall(fn)); } function run() { const fn = tests.shift(); if (fn) { - console.log('# %s', fn.name); fn(run); - } else { - console.log('ok'); } } @@ -27,7 +25,7 @@ test(function serverTimeout(cb) { // just do nothing, we should get a timeout event. }); server.listen(common.mustCall(function() { - http.get({ port: server.address().port }).on('error', common.noop); + http.get({ port: server.address().port }).on('error', common.mustCall()); })); const s = server.setTimeout(50, common.mustCall(function(socket) { socket.destroy(); @@ -50,7 +48,7 @@ test(function serverRequestTimeout(cb) { server.listen(common.mustCall(function() { const port = server.address().port; const req = http.request({ port: port, method: 'POST' }); - req.on('error', common.noop); + req.on('error', common.mustCall()); req.write('Hello'); // req is in progress })); @@ -68,7 +66,7 @@ test(function serverResponseTimeout(cb) { }); server.listen(common.mustCall(function() { const port = server.address().port; - http.get({ port: port }).on('error', common.noop); + http.get({ port: port }).on('error', common.mustCall()); })); }); @@ -86,7 +84,7 @@ test(function serverRequestNotTimeoutAfterEnd(cb) { }); server.listen(common.mustCall(function() { const port = server.address().port; - http.get({ port: port }).on('error', common.noop); + http.get({ port: port }).on('error', common.mustCall()); })); }); From 9fd05e46d224d2d3a4eb73a52a1f2f7039360eb8 Mon Sep 17 00:00:00 2001 From: Vse Mozhet Byt Date: Thu, 15 Jun 2017 03:33:50 +0300 Subject: [PATCH 38/82] test: remove needless RegExp flags * /m is needless if ^ and $ are not used * /g is needless in split() * /g is needless in test() with one-time RegExp/String PR-URL: https://github.com/nodejs/node/pull/13690 Reviewed-By: Colin Ihrig Reviewed-By: Joyee Cheung Reviewed-By: Daniel Bevenius Reviewed-By: Yuta Hiroto Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- test/parallel/test-http-full-response.js | 8 ++++---- .../test-http-outgoing-first-chunk-singlebyte-encoding.js | 2 +- test/parallel/test-tls-client-verify.js | 2 +- test/parallel/test-tls-server-verify.js | 4 ++-- test/pummel/test-keep-alive.js | 4 ++-- test/pummel/test-tls-securepair-client.js | 4 ++-- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/test/parallel/test-http-full-response.js b/test/parallel/test-http-full-response.js index 0e834cee5b8932..292368ae16662c 100644 --- a/test/parallel/test-http-full-response.js +++ b/test/parallel/test-http-full-response.js @@ -21,7 +21,7 @@ function runAb(opts, callback) { const command = `ab ${opts} http://127.0.0.1:${server.address().port}/`; exec(command, function(err, stdout, stderr) { if (err) { - if (/ab|apr/mi.test(stderr)) { + if (/ab|apr/i.test(stderr)) { common.skip(`problem spawning \`ab\`.\n${stderr}`); process.reallyExit(0); } @@ -29,13 +29,13 @@ function runAb(opts, callback) { return; } - let m = /Document Length:\s*(\d+) bytes/mi.exec(stdout); + let m = /Document Length:\s*(\d+) bytes/i.exec(stdout); const documentLength = parseInt(m[1]); - m = /Complete requests:\s*(\d+)/mi.exec(stdout); + m = /Complete requests:\s*(\d+)/i.exec(stdout); const completeRequests = parseInt(m[1]); - m = /HTML transferred:\s*(\d+) bytes/mi.exec(stdout); + m = /HTML transferred:\s*(\d+) bytes/i.exec(stdout); const htmlTransfered = parseInt(m[1]); assert.strictEqual(bodyLength, documentLength); diff --git a/test/parallel/test-http-outgoing-first-chunk-singlebyte-encoding.js b/test/parallel/test-http-outgoing-first-chunk-singlebyte-encoding.js index 214287a6ffc157..f1af1dc718bd9a 100644 --- a/test/parallel/test-http-outgoing-first-chunk-singlebyte-encoding.js +++ b/test/parallel/test-http-outgoing-first-chunk-singlebyte-encoding.js @@ -24,7 +24,7 @@ for (const enc of ['utf8', 'utf16le', 'latin1', 'UTF-8']) { const headerEnd = received.indexOf('\r\n\r\n', 'utf8'); assert.notStrictEqual(headerEnd, -1); - const header = received.toString('utf8', 0, headerEnd).split(/\r\n/g); + const header = received.toString('utf8', 0, headerEnd).split(/\r\n/); const body = received.toString(enc, headerEnd + 4); assert.strictEqual(header[0], 'HTTP/1.1 200 OK'); diff --git a/test/parallel/test-tls-client-verify.js b/test/parallel/test-tls-client-verify.js index 643126488da869..453e4f71493cf8 100644 --- a/test/parallel/test-tls-client-verify.js +++ b/test/parallel/test-tls-client-verify.js @@ -10,7 +10,7 @@ const tls = require('tls'); const fs = require('fs'); -const hosterr = /Hostname\/IP doesn't match certificate's altnames/g; +const hosterr = /Hostname\/IP doesn't match certificate's altnames/; const testCases = [{ ca: ['ca1-cert'], key: 'agent2-key', diff --git a/test/parallel/test-tls-server-verify.js b/test/parallel/test-tls-server-verify.js index eba57d65de295e..fd816ce0f9b294 100644 --- a/test/parallel/test-tls-server-verify.js +++ b/test/parallel/test-tls-server-verify.js @@ -196,7 +196,7 @@ function runClient(prefix, port, options, cb) { client.stdout.on('data', function(d) { out += d; - if (!goodbye && /_unauthed/g.test(out)) { + if (!goodbye && /_unauthed/.test(out)) { console.error(`${prefix} * unauthed`); goodbye = true; client.kill(); @@ -204,7 +204,7 @@ function runClient(prefix, port, options, cb) { rejected = false; } - if (!goodbye && /_authed/g.test(out)) { + if (!goodbye && /_authed/.test(out)) { console.error(`${prefix} * authed`); goodbye = true; client.kill(); diff --git a/test/pummel/test-keep-alive.js b/test/pummel/test-keep-alive.js index a9e91e201bb19b..f8ea1e8d4d79ab 100644 --- a/test/pummel/test-keep-alive.js +++ b/test/pummel/test-keep-alive.js @@ -58,10 +58,10 @@ function runAb(opts, callback) { return; } - let matches = /Requests\/sec:\s*(\d+)\./mi.exec(stdout); + let matches = /Requests\/sec:\s*(\d+)\./i.exec(stdout); const reqSec = parseInt(matches[1]); - matches = /Keep-Alive requests:\s*(\d+)/mi.exec(stdout); + matches = /Keep-Alive requests:\s*(\d+)/i.exec(stdout); let keepAliveRequests; if (matches) { keepAliveRequests = parseInt(matches[1]); diff --git a/test/pummel/test-tls-securepair-client.js b/test/pummel/test-tls-securepair-client.js index 0b2e45302b5cc2..234ee6a09117b0 100644 --- a/test/pummel/test-tls-securepair-client.js +++ b/test/pummel/test-tls-securepair-client.js @@ -63,7 +63,7 @@ function test(keyfn, certfn, check, next) { console.error(state); switch (state) { case 'WAIT-ACCEPT': - if (/ACCEPT/g.test(serverStdoutBuffer)) { + if (/ACCEPT/.test(serverStdoutBuffer)) { // Give s_server half a second to start up. setTimeout(startClient, 500); state = 'WAIT-HELLO'; @@ -71,7 +71,7 @@ function test(keyfn, certfn, check, next) { break; case 'WAIT-HELLO': - if (/hello/g.test(serverStdoutBuffer)) { + if (/hello/.test(serverStdoutBuffer)) { // End the current SSL connection and exit. // See s_server(1ssl). From ade84b4cce863ba116b0db4ebcfe5161875374f3 Mon Sep 17 00:00:00 2001 From: Vse Mozhet Byt Date: Fri, 16 Jun 2017 03:07:07 +0300 Subject: [PATCH 39/82] test: use string instead of RegExp in split() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/13710 Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: James M Snell Reviewed-By: Gibson Fahnestock Reviewed-By: Michaël Zasso --- .../test-http-outgoing-first-chunk-singlebyte-encoding.js | 2 +- test/parallel/test-repl-setprompt.js | 2 +- test/parallel/test-stdin-script-child.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/parallel/test-http-outgoing-first-chunk-singlebyte-encoding.js b/test/parallel/test-http-outgoing-first-chunk-singlebyte-encoding.js index f1af1dc718bd9a..7249230cfadbb7 100644 --- a/test/parallel/test-http-outgoing-first-chunk-singlebyte-encoding.js +++ b/test/parallel/test-http-outgoing-first-chunk-singlebyte-encoding.js @@ -24,7 +24,7 @@ for (const enc of ['utf8', 'utf16le', 'latin1', 'UTF-8']) { const headerEnd = received.indexOf('\r\n\r\n', 'utf8'); assert.notStrictEqual(headerEnd, -1); - const header = received.toString('utf8', 0, headerEnd).split(/\r\n/); + const header = received.toString('utf8', 0, headerEnd).split('\r\n'); const body = received.toString(enc, headerEnd + 4); assert.strictEqual(header[0], 'HTTP/1.1 200 OK'); diff --git a/test/parallel/test-repl-setprompt.js b/test/parallel/test-repl-setprompt.js index 8dcc4fe94452da..55e643306df70f 100644 --- a/test/parallel/test-repl-setprompt.js +++ b/test/parallel/test-repl-setprompt.js @@ -23,6 +23,6 @@ child.stdin.end(`e.setPrompt("${p}");${os.EOL}`); child.on('close', function(code, signal) { assert.strictEqual(code, 0); assert.ok(!signal); - const lines = data.split(/\n/); + const lines = data.split('\n'); assert.strictEqual(lines.pop(), p); }); diff --git a/test/parallel/test-stdin-script-child.js b/test/parallel/test-stdin-script-child.js index 81eb3ea5b4aaac..f215682fe4c345 100644 --- a/test/parallel/test-stdin-script-child.js +++ b/test/parallel/test-stdin-script-child.js @@ -18,7 +18,7 @@ child.stdout.on('data', function(c) { child.stderr.setEncoding('utf8'); child.stderr.on('data', function(c) { - console.error(`> ${c.trim().split(/\n/).join('\n> ')}`); + console.error(`> ${c.trim().split('\n').join('\n> ')}`); }); child.on('close', common.mustCall(function(c) { From ed2a8d10716bdbf71157a201fd40ac35d13de0db Mon Sep 17 00:00:00 2001 From: Rob Wu Date: Wed, 21 Jun 2017 11:13:13 +0200 Subject: [PATCH 40/82] doc: add missing zlib link to stream API docs This seems to have been removed inadvertently by 330c8d743e33a83f85389ea8a64e3d3854ea0048 in PR 12925. PR-URL: https://github.com/nodejs/node/pull/13838 Reviewed-By: Vse Mozhet Byt Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- doc/api/stream.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/api/stream.md b/doc/api/stream.md index 69efa51158ff9e..f8be9d4a3dff8d 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -2060,6 +2060,7 @@ readable buffer so there is nothing for a user to consume. [HTTP responses, on the server]: http.html#http_class_http_serverresponse [http-incoming-message]: http.html#http_class_http_incomingmessage [Readable]: #stream_class_stream_readable +[zlib]: zlib.html [stream-_flush]: #stream_transform_flush_callback [stream-_read]: #stream_readable_read_size_1 [stream-_transform]: #stream_transform_transform_chunk_encoding_callback From 11327544dfb0cfe432bc3399b251ebc9bce05a62 Mon Sep 17 00:00:00 2001 From: Steven Winston Date: Wed, 21 Jun 2017 23:53:52 +0300 Subject: [PATCH 41/82] test: remove unnecessary Buffer import MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Removed require('buffer') from - test/disabled/test-sendfd.js - test/internet/test-dgram-broadcast-multi-process.js - test/pummel/test-https-no-reader.js PR-URL: https://github.com/nodejs/node/pull/13860 Refs: https://github.com/nodejs/node/issues/13836 Reviewed-By: Benjamin Gruenbaum Reviewed-By: Refael Ackermann Reviewed-By: James M Snell Reviewed-By: Timothy Gu Reviewed-By: Colin Ihrig Reviewed-By: Tobias Nießen Reviewed-By: Alexey Orlenko Reviewed-By: Michael Dawson Reviewed-By: Vse Mozhet Byt --- test/disabled/test-sendfd.js | 15 ++++++++------- .../test-dgram-broadcast-multi-process.js | 1 - test/pummel/test-https-no-reader.js | 1 - 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/test/disabled/test-sendfd.js b/test/disabled/test-sendfd.js index 9e3a01733f69a7..8de6045cb27d90 100644 --- a/test/disabled/test-sendfd.js +++ b/test/disabled/test-sendfd.js @@ -29,12 +29,13 @@ var common = require('../common'); var assert = require('assert'); -var buffer = require('buffer'); -var child_process = require('child_process'); -var fs = require('fs'); -var net = require('net'); -var netBinding = process.binding('net'); -var path = require('path'); +const buffer = require('buffer'); +const child_process = require('child_process'); +const fs = require('fs'); +const net = require('net'); + +const netBinding = process.binding('net'); +const path = require('path'); var DATA = { 'ppid' : process.pid, @@ -91,7 +92,7 @@ var srv = net.createServer(function(s) { var str = JSON.stringify(DATA) + '\n'; DATA.ord = DATA.ord + 1; - var buf = buffer.Buffer.allocUnsafe(str.length); + var buf = Buffer.allocUnsafe(str.length); buf.write(JSON.stringify(DATA) + '\n', 'utf8'); s.write(str, 'utf8', pipeFDs[1]); diff --git a/test/internet/test-dgram-broadcast-multi-process.js b/test/internet/test-dgram-broadcast-multi-process.js index c05d0cf5b9512e..392ded3a710c29 100644 --- a/test/internet/test-dgram-broadcast-multi-process.js +++ b/test/internet/test-dgram-broadcast-multi-process.js @@ -4,7 +4,6 @@ const assert = require('assert'); const dgram = require('dgram'); const util = require('util'); const networkInterfaces = require('os').networkInterfaces(); -const Buffer = require('buffer').Buffer; const fork = require('child_process').fork; const LOCAL_BROADCAST_HOST = '255.255.255.255'; const TIMEOUT = common.platformTimeout(5000); diff --git a/test/pummel/test-https-no-reader.js b/test/pummel/test-https-no-reader.js index a08676277af6ce..437b4e3c4acefe 100644 --- a/test/pummel/test-https-no-reader.js +++ b/test/pummel/test-https-no-reader.js @@ -8,7 +8,6 @@ if (!common.hasCrypto) { } const https = require('https'); -const Buffer = require('buffer').Buffer; const fs = require('fs'); const path = require('path'); From 0925c8e97eb1d0b3c5fba60ab4d6c9253f9f255c Mon Sep 17 00:00:00 2001 From: sallen450 Date: Thu, 22 Jun 2017 00:49:58 +0800 Subject: [PATCH 42/82] test: remove require('buffer') on 6 fs test files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * test/parallel/test-fs-mkdtemp.js * test/parallel/test-fs-read-zero-length.js * test/parallel/test-fs-read.js * test/parallel/test-fs-whatwg-url.js * test/parallel/test-fs-write-string-coerce.js * test/parallel/test-fs-write.js PR-URL: https://github.com/nodejs/node/pull/13845 Refs: https://github.com/nodejs/node/issues/13836 Reviewed-By: James M Snell Reviewed-By: Anna Henningsen Reviewed-By: Benjamin Gruenbaum Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig Reviewed-By: Tobias Nießen Reviewed-By: Alexey Orlenko Reviewed-By: Michael Dawson Reviewed-By: Vse Mozhet Byt --- test/parallel/test-fs-mkdtemp.js | 1 - test/parallel/test-fs-write-string-coerce.js | 1 - test/parallel/test-fs-write.js | 1 - 3 files changed, 3 deletions(-) diff --git a/test/parallel/test-fs-mkdtemp.js b/test/parallel/test-fs-mkdtemp.js index d4773aa37b7bf5..5ce340afa5ad0f 100644 --- a/test/parallel/test-fs-mkdtemp.js +++ b/test/parallel/test-fs-mkdtemp.js @@ -4,7 +4,6 @@ const common = require('../common'); const assert = require('assert'); const fs = require('fs'); const path = require('path'); -const Buffer = require('buffer').Buffer; common.refreshTmpDir(); diff --git a/test/parallel/test-fs-write-string-coerce.js b/test/parallel/test-fs-write-string-coerce.js index afeab5b05464ea..e257dfc0c73ee0 100644 --- a/test/parallel/test-fs-write-string-coerce.js +++ b/test/parallel/test-fs-write-string-coerce.js @@ -2,7 +2,6 @@ const common = require('../common'); const assert = require('assert'); const path = require('path'); -const Buffer = require('buffer').Buffer; const fs = require('fs'); common.refreshTmpDir(); diff --git a/test/parallel/test-fs-write.js b/test/parallel/test-fs-write.js index 9960a91a4f7515..c792de880bc321 100644 --- a/test/parallel/test-fs-write.js +++ b/test/parallel/test-fs-write.js @@ -2,7 +2,6 @@ const common = require('../common'); const assert = require('assert'); const path = require('path'); -const Buffer = require('buffer').Buffer; const fs = require('fs'); const fn = path.join(common.tmpDir, 'write.txt'); const fn2 = path.join(common.tmpDir, 'write2.txt'); From 4449faa3d65f5822c9bfa0af9d9a364ebb52a6d3 Mon Sep 17 00:00:00 2001 From: OriLev Date: Wed, 21 Jun 2017 21:40:25 +0300 Subject: [PATCH 43/82] test: remove require('buffer') from 4 buffer tests Remove superfluous import from: * test/parallel/test-buffer-alloc.js * test/parallel/test-buffer-arraybuffer.js * test/parallel/test-buffer-badhex.js * test/parallel/test-buffer-bytelength.js Refs: https://github.com/nodejs/node/issues/13836 PR-URL: https://github.com/nodejs/node/pull/13855 Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig Reviewed-By: Vse Mozhet Byt Reviewed-By: Alexey Orlenko Reviewed-By: James M Snell --- test/parallel/test-buffer-alloc.js | 1 - test/parallel/test-buffer-arraybuffer.js | 1 - test/parallel/test-buffer-badhex.js | 1 - test/parallel/test-buffer-bytelength.js | 1 - 4 files changed, 4 deletions(-) diff --git a/test/parallel/test-buffer-alloc.js b/test/parallel/test-buffer-alloc.js index 7ebe34b21edb1e..39ce4c4a928109 100644 --- a/test/parallel/test-buffer-alloc.js +++ b/test/parallel/test-buffer-alloc.js @@ -3,7 +3,6 @@ const common = require('../common'); const assert = require('assert'); const vm = require('vm'); -const Buffer = require('buffer').Buffer; const SlowBuffer = require('buffer').SlowBuffer; const b = Buffer.allocUnsafe(1024); diff --git a/test/parallel/test-buffer-arraybuffer.js b/test/parallel/test-buffer-arraybuffer.js index 8f32a2de3c8971..d1e6eaa07033c4 100644 --- a/test/parallel/test-buffer-arraybuffer.js +++ b/test/parallel/test-buffer-arraybuffer.js @@ -3,7 +3,6 @@ require('../common'); const assert = require('assert'); -const Buffer = require('buffer').Buffer; const LENGTH = 16; const ab = new ArrayBuffer(LENGTH); diff --git a/test/parallel/test-buffer-badhex.js b/test/parallel/test-buffer-badhex.js index c3d151ba18c694..94de97181d38e0 100644 --- a/test/parallel/test-buffer-badhex.js +++ b/test/parallel/test-buffer-badhex.js @@ -1,7 +1,6 @@ 'use strict'; require('../common'); const assert = require('assert'); -const Buffer = require('buffer').Buffer; // Test hex strings and bad hex strings { diff --git a/test/parallel/test-buffer-bytelength.js b/test/parallel/test-buffer-bytelength.js index 9bb3b759e0208f..17fe2931aa8585 100644 --- a/test/parallel/test-buffer-bytelength.js +++ b/test/parallel/test-buffer-bytelength.js @@ -2,7 +2,6 @@ require('../common'); const assert = require('assert'); -const Buffer = require('buffer').Buffer; const SlowBuffer = require('buffer').SlowBuffer; const vm = require('vm'); From 2cb42432e2328c10c4b8145ada04002ec18d7274 Mon Sep 17 00:00:00 2001 From: Zongmin Lei Date: Thu, 22 Jun 2017 01:22:33 +0800 Subject: [PATCH 44/82] test: remove `require('buffer')` from 4 test files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove superfluous import from: * test/parallel/test-buffer-fakes.js * test/parallel/test-buffer-includes.js * test/parallel/test-buffer-indexof.js * test/parallel/test-buffer-new.js Refs: https://github.com/nodejs/node/issues/13836 PR-URL: https://github.com/nodejs/node/pull/13846 Reviewed-By: Vse Mozhet Byt Reviewed-By: Alexey Orlenko Reviewed-By: Colin Ihrig Reviewed-By: Benjamin Gruenbaum Reviewed-By: Luigi Pinca Reviewed-By: Jackson Tian Reviewed-By: Refael Ackermann Reviewed-By: James M Snell Reviewed-By: Tobias Nießen --- test/parallel/test-buffer-fakes.js | 1 - test/parallel/test-buffer-includes.js | 2 -- test/parallel/test-buffer-indexof.js | 2 -- test/parallel/test-buffer-new.js | 1 - 4 files changed, 6 deletions(-) diff --git a/test/parallel/test-buffer-fakes.js b/test/parallel/test-buffer-fakes.js index 758ebbf0053732..d126d39aa95263 100644 --- a/test/parallel/test-buffer-fakes.js +++ b/test/parallel/test-buffer-fakes.js @@ -2,7 +2,6 @@ require('../common'); const assert = require('assert'); -const Buffer = require('buffer').Buffer; function FakeBuffer() { } Object.setPrototypeOf(FakeBuffer, Buffer); diff --git a/test/parallel/test-buffer-includes.js b/test/parallel/test-buffer-includes.js index 112cf546502372..142602ab46cb9f 100644 --- a/test/parallel/test-buffer-includes.js +++ b/test/parallel/test-buffer-includes.js @@ -2,8 +2,6 @@ require('../common'); const assert = require('assert'); -const Buffer = require('buffer').Buffer; - const b = Buffer.from('abcdef'); const buf_a = Buffer.from('a'); const buf_bc = Buffer.from('bc'); diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index e389b09e384500..7aab6e609e56d7 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -2,8 +2,6 @@ require('../common'); const assert = require('assert'); -const Buffer = require('buffer').Buffer; - const b = Buffer.from('abcdef'); const buf_a = Buffer.from('a'); const buf_bc = Buffer.from('bc'); diff --git a/test/parallel/test-buffer-new.js b/test/parallel/test-buffer-new.js index 919f31238d2d18..95dd922a271a1a 100644 --- a/test/parallel/test-buffer-new.js +++ b/test/parallel/test-buffer-new.js @@ -2,6 +2,5 @@ require('../common'); const assert = require('assert'); -const Buffer = require('buffer').Buffer; assert.throws(() => new Buffer(42, 'utf8'), /first argument must be a string/); From 846c10cde43dd477fc1cae6201bdeb4692d20afa Mon Sep 17 00:00:00 2001 From: lena Date: Wed, 21 Jun 2017 20:59:12 +0300 Subject: [PATCH 45/82] test: remove unnecessary require('buffer').Buffer Remove unnecessary imports from: * test/parallel/test-buffer-nopendingdep-map.js * test/parallel/test-buffer-pending-deprecation.js * test/parallel/test-buffer-sharedarraybuffer.js * test/parallel/test-buffer-slow.js * test/parallel/test-buffer-tojson.js * test/parallel/test-buffer-zero-fill.js Refs: https://github.com/nodejs/node/issues/13836 PR-URL: https://github.com/nodejs/node/pull/13851 Reviewed-By: Vse Mozhet Byt Reviewed-By: Benjamin Gruenbaum Reviewed-By: Alexey Orlenko Reviewed-By: Refael Ackermann Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- test/parallel/test-buffer-sharedarraybuffer.js | 1 - test/parallel/test-buffer-slow.js | 1 - 2 files changed, 2 deletions(-) diff --git a/test/parallel/test-buffer-sharedarraybuffer.js b/test/parallel/test-buffer-sharedarraybuffer.js index f1bac72079b313..582841d679c8d1 100644 --- a/test/parallel/test-buffer-sharedarraybuffer.js +++ b/test/parallel/test-buffer-sharedarraybuffer.js @@ -4,7 +4,6 @@ require('../common'); const assert = require('assert'); -const Buffer = require('buffer').Buffer; const sab = new SharedArrayBuffer(24); const arr1 = new Uint16Array(sab); diff --git a/test/parallel/test-buffer-slow.js b/test/parallel/test-buffer-slow.js index 69981d4dc38b73..7d37c709e380f0 100644 --- a/test/parallel/test-buffer-slow.js +++ b/test/parallel/test-buffer-slow.js @@ -3,7 +3,6 @@ require('../common'); const assert = require('assert'); const buffer = require('buffer'); -const Buffer = buffer.Buffer; const SlowBuffer = buffer.SlowBuffer; const ones = [1, 1, 1, 1]; From ea2a7f828439e9fefd0ac2dec8eafac5904f0057 Mon Sep 17 00:00:00 2001 From: XadillaX Date: Thu, 22 Jun 2017 00:38:31 +0800 Subject: [PATCH 46/82] test: remove `require('buffer')` from 4 test files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We don't use the global Buffer throughout the lib/ to avoid circular dependency issues in core, but we actually don't need to require it on test files. So remove them on: + test/parallel/test-stream-uint8array.js + test/parallel/test-stream2-finish-pipe.js + test/parallel/test-tls-session-cache.js + test/parallel/test-vm-cached-data.js Refs: https://github.com/nodejs/node/issues/13836 PR-URL: https://github.com/nodejs/node/pull/13844 Reviewed-By: Vse Mozhet Byt Reviewed-By: Alexey Orlenko Reviewed-By: Colin Ihrig Reviewed-By: Benjamin Gruenbaum Reviewed-By: Luigi Pinca Reviewed-By: Timothy Gu Reviewed-By: James M Snell Reviewed-By: Tobias Nießen Reviewed-By: Michael Dawson --- test/parallel/test-stream2-finish-pipe.js | 1 - test/parallel/test-vm-cached-data.js | 1 - 2 files changed, 2 deletions(-) diff --git a/test/parallel/test-stream2-finish-pipe.js b/test/parallel/test-stream2-finish-pipe.js index 87edf5a5fa6437..d3e84eb6b47398 100644 --- a/test/parallel/test-stream2-finish-pipe.js +++ b/test/parallel/test-stream2-finish-pipe.js @@ -1,7 +1,6 @@ 'use strict'; require('../common'); const stream = require('stream'); -const Buffer = require('buffer').Buffer; const r = new stream.Readable(); r._read = function(size) { diff --git a/test/parallel/test-vm-cached-data.js b/test/parallel/test-vm-cached-data.js index c4fa55cb0b2a6d..cedc68bea06372 100644 --- a/test/parallel/test-vm-cached-data.js +++ b/test/parallel/test-vm-cached-data.js @@ -3,7 +3,6 @@ require('../common'); const assert = require('assert'); const vm = require('vm'); const spawnSync = require('child_process').spawnSync; -const Buffer = require('buffer').Buffer; function getSource(tag) { return `(function ${tag}() { return '${tag}'; })`; From 3ebe45859e4806fb54d3378418edf41e42beb077 Mon Sep 17 00:00:00 2001 From: Daniel Bevenius Date: Wed, 21 Jun 2017 10:20:56 +0200 Subject: [PATCH 47/82] build: clean up config_fips.gypi Currently when configuring the project using --openssl-fips a gyp include file name config_fips.gypi will be created. If the project is later configured but without the --openssl-fips flag an error will occur. For example: $ ./configure --openssl-fips=bogus $ ./configure && make -j8 ... /node/deps/openssl/fips/fipsld: line 8: /bin/fipsld: No such file or directory Error 127 This commit suggests removing the generate config_fips.gypi when the --openssl-fips flag is not give on the command line. PR-URL: https://github.com/nodejs/node/pull/13837 Reviewed-By: Refael Ackermann Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- configure | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/configure b/configure index 1c2ee81cdafb4c..7074021cf5bfee 100755 --- a/configure +++ b/configure @@ -973,7 +973,10 @@ def configure_openssl(o): ] else: o['variables']['openssl_fips'] = '' - + try: + os.remove('config_fips.gypi') + except OSError: + pass if options.without_ssl: def without_ssl_error(option): From 73ba4239c4e1b84c8579a2f450320bb577d8662e Mon Sep 17 00:00:00 2001 From: Julien Klepatch Date: Tue, 20 Jun 2017 23:43:57 +0800 Subject: [PATCH 48/82] test: make http(s)-set-timeout-server more similar Make test-http(s)-set-timeout-server tests more similar and resolve the following issues: * `test-https-set-timeout-server.js` was missing some `assert` statements, including with `http` module * Both files were missing some calls to `common.mustCall()` * Both files were calling `createServer()` in different ways PR-URL: https://github.com/nodejs/node/pull/13822 Refs: https://github.com/nodejs/node/issues/13588 Refs: https://github.com/nodejs/node/pull/13625 Reviewed-By: Luigi Pinca Reviewed-By: Alexey Orlenko Reviewed-By: James M Snell --- test/parallel/test-http-set-timeout-server.js | 74 +++++----- .../test-https-set-timeout-server.js | 127 ++++++++++-------- 2 files changed, 114 insertions(+), 87 deletions(-) diff --git a/test/parallel/test-http-set-timeout-server.js b/test/parallel/test-http-set-timeout-server.js index b2b15d4838d1c0..8c16ac922186bb 100644 --- a/test/parallel/test-http-set-timeout-server.js +++ b/test/parallel/test-http-set-timeout-server.js @@ -21,22 +21,24 @@ function run() { } test(function serverTimeout(cb) { - const server = http.createServer(function(req, res) { + const server = http.createServer(common.mustCall(function(req, res) { // just do nothing, we should get a timeout event. - }); - server.listen(common.mustCall(function() { - http.get({ port: server.address().port }).on('error', common.mustCall()); })); - const s = server.setTimeout(50, common.mustCall(function(socket) { - socket.destroy(); - server.close(); - cb(); + server.listen(common.mustCall(function() { + const s = server.setTimeout(50, common.mustCall(function(socket) { + socket.destroy(); + server.close(); + cb(); + })); + assert.ok(s instanceof http.Server); + http.get({ + port: server.address().port + }).on('error', common.mustCall()); })); - assert.ok(s instanceof http.Server); }); test(function serverRequestTimeout(cb) { - const server = http.createServer(function(req, res) { + const server = http.createServer(common.mustCall(function(req, res) { // just do nothing, we should get a timeout event. const s = req.setTimeout(50, common.mustCall(function(socket) { socket.destroy(); @@ -44,10 +46,12 @@ test(function serverRequestTimeout(cb) { cb(); })); assert.ok(s instanceof http.IncomingMessage); - }); + })); server.listen(common.mustCall(function() { - const port = server.address().port; - const req = http.request({ port: port, method: 'POST' }); + const req = http.request({ + port: server.address().port, + method: 'POST' + }); req.on('error', common.mustCall()); req.write('Hello'); // req is in progress @@ -55,7 +59,7 @@ test(function serverRequestTimeout(cb) { }); test(function serverResponseTimeout(cb) { - const server = http.createServer(function(req, res) { + const server = http.createServer(common.mustCall(function(req, res) { // just do nothing, we should get a timeout event. const s = res.setTimeout(50, common.mustCall(function(socket) { socket.destroy(); @@ -63,28 +67,30 @@ test(function serverResponseTimeout(cb) { cb(); })); assert.ok(s instanceof http.OutgoingMessage); - }); + })); server.listen(common.mustCall(function() { - const port = server.address().port; - http.get({ port: port }).on('error', common.mustCall()); + http.get({ + port: server.address().port + }).on('error', common.mustCall()); })); }); test(function serverRequestNotTimeoutAfterEnd(cb) { - const server = http.createServer(function(req, res) { + const server = http.createServer(common.mustCall(function(req, res) { // just do nothing, we should get a timeout event. const s = req.setTimeout(50, common.mustNotCall()); assert.ok(s instanceof http.IncomingMessage); res.on('timeout', common.mustCall()); - }); - server.on('timeout', function(socket) { + })); + server.on('timeout', common.mustCall(function(socket) { socket.destroy(); server.close(); cb(); - }); + })); server.listen(common.mustCall(function() { - const port = server.address().port; - http.get({ port: port }).on('error', common.mustCall()); + http.get({ + port: server.address().port + }).on('error', common.mustCall()); })); }); @@ -103,16 +109,19 @@ test(function serverResponseTimeoutWithPipeline(cb) { assert.ok(s instanceof http.OutgoingMessage); if (req.url === '/1') res.end(); }); - server.on('timeout', function(socket) { + server.on('timeout', common.mustCall(function(socket) { if (secReceived) { socket.destroy(); server.close(); cb(); } - }); + })); server.listen(common.mustCall(function() { - const port = server.address().port; - const c = net.connect({ port: port, allowHalfOpen: true }, function() { + const options = { + port: server.address().port, + allowHalfOpen: true, + }; + const c = net.connect(options, function() { c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); c.write('GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n'); c.write('GET /3 HTTP/1.1\r\nHost: localhost\r\n\r\n'); @@ -121,11 +130,11 @@ test(function serverResponseTimeoutWithPipeline(cb) { }); test(function idleTimeout(cb) { - const server = http.createServer(function(req, res) { + const server = http.createServer(common.mustCall(function(req, res) { req.on('timeout', common.mustNotCall()); res.on('timeout', common.mustNotCall()); res.end(); - }); + })); const s = server.setTimeout(50, common.mustCall(function(socket) { socket.destroy(); server.close(); @@ -133,8 +142,11 @@ test(function idleTimeout(cb) { })); assert.ok(s instanceof http.Server); server.listen(common.mustCall(function() { - const port = server.address().port; - const c = net.connect({ port: port, allowHalfOpen: true }, function() { + const options = { + port: server.address().port, + allowHalfOpen: true, + }; + const c = net.connect(options, function() { c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); // Keep-Alive }); diff --git a/test/sequential/test-https-set-timeout-server.js b/test/sequential/test-https-set-timeout-server.js index a2da563464352f..a9467877d09a14 100644 --- a/test/sequential/test-https-set-timeout-server.js +++ b/test/sequential/test-https-set-timeout-server.js @@ -6,7 +6,9 @@ if (!common.hasCrypto) { common.skip('missing crypto'); return; } + const https = require('https'); +const http = require('http'); const tls = require('tls'); const fs = require('fs'); @@ -35,10 +37,13 @@ function run() { } test(function serverTimeout(cb) { - const server = https.createServer(serverOptions, function(req, res) { - // just do nothing, we should get a timeout event. - }); - server.listen(0, common.mustCall(function() { + const server = https.createServer( + serverOptions, + common.mustCall(function(req, res) { + // just do nothing, we should get a + // timeout event. + })); + server.listen(common.mustCall(function() { const s = server.setTimeout(50, common.mustCall(function(socket) { socket.destroy(); server.close(); @@ -46,72 +51,79 @@ test(function serverTimeout(cb) { })); assert.ok(s instanceof https.Server); https.get({ - port: this.address().port, + port: server.address().port, rejectUnauthorized: false }).on('error', common.noop); })); }); test(function serverRequestTimeout(cb) { - function handler(req, res) { - // just do nothing, we should get a timeout event. - req.setTimeout(50, common.mustCall(function() { - req.socket.destroy(); - server.close(); - cb(); + const server = https.createServer( + serverOptions, + common.mustCall(function(req, res) { + // just do nothing, we should get a + // timeout event. + const s = req.setTimeout( + 50, + common.mustCall(function(socket) { + socket.destroy(); + server.close(); + cb(); + })); + assert.ok(s instanceof http.IncomingMessage); })); - } - - let server = https.createServer(serverOptions, common.mustCall(handler)); - server.listen(0, function() { + server.listen(common.mustCall(function() { const req = https.request({ - port: this.address().port, + port: server.address().port, method: 'POST', rejectUnauthorized: false }); req.on('error', common.noop); req.write('Hello'); // req is in progress - }); + })); }); test(function serverResponseTimeout(cb) { - function handler(req, res) { - // just do nothing, we should get a timeout event. - res.setTimeout(50, common.mustCall(function() { - res.socket.destroy(); - server.close(); - cb(); + const server = https.createServer( + serverOptions, + common.mustCall(function(req, res) { + // just do nothing, we should get a timeout event. + const s = res.setTimeout(50, common.mustCall(function(socket) { + socket.destroy(); + server.close(); + cb(); + })); + assert.ok(s instanceof http.OutgoingMessage); })); - } - - let server = https.createServer(serverOptions, common.mustCall(handler)); - server.listen(0, function() { + server.listen(common.mustCall(function() { https.get({ - port: this.address().port, + port: server.address().port, rejectUnauthorized: false - }).on('error', common.noop); - }); + }).on('error', common.mustCall()); + })); }); test(function serverRequestNotTimeoutAfterEnd(cb) { - function handler(req, res) { - // just do nothing, we should get a timeout event. - req.setTimeout(50, common.mustNotCall()); - res.on('timeout', common.mustCall(function(socket) {})); - } - const server = https.createServer(serverOptions, common.mustCall(handler)); - server.on('timeout', function(socket) { + const server = https.createServer( + serverOptions, + common.mustCall(function(req, res) { + // just do nothing, we should get a timeout event. + const s = req.setTimeout(50, common.mustNotCall()); + assert.ok(s instanceof http.IncomingMessage); + res.on('timeout', common.mustCall()); + })); + server.on('timeout', common.mustCall(function(socket) { socket.destroy(); server.close(); cb(); - }); - server.listen(0, function() { + })); + server.listen(common.mustCall(function() { https.get({ - port: this.address().port, + port: server.address().port, rejectUnauthorized: false - }).on('error', common.noop); - }); + }).on('error', common.mustCall()); + })); }); test(function serverResponseTimeoutWithPipeline(cb) { @@ -123,9 +135,10 @@ test(function serverResponseTimeoutWithPipeline(cb) { const server = https.createServer(serverOptions, function(req, res) { if (req.url === '/2') secReceived = true; - res.setTimeout(50, function() { + const s = res.setTimeout(50, function() { caughtTimeout += req.url; }); + assert.ok(s instanceof http.OutgoingMessage); if (req.url === '/1') res.end(); }); server.on('timeout', function(socket) { @@ -135,9 +148,9 @@ test(function serverResponseTimeoutWithPipeline(cb) { cb(); } }); - server.listen(0, function() { + server.listen(common.mustCall(function() { const options = { - port: this.address().port, + port: server.address().port, allowHalfOpen: true, rejectUnauthorized: false }; @@ -146,24 +159,26 @@ test(function serverResponseTimeoutWithPipeline(cb) { c.write('GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n'); c.write('GET /3 HTTP/1.1\r\nHost: localhost\r\n\r\n'); }); - }); + })); }); test(function idleTimeout(cb) { - const server = https.createServer(serverOptions, - common.mustCall(function(req, res) { - req.on('timeout', common.mustNotCall()); - res.on('timeout', common.mustNotCall()); - res.end(); - })); - server.setTimeout(50, common.mustCall(function(socket) { + const server = https.createServer( + serverOptions, + common.mustCall(function(req, res) { + req.on('timeout', common.mustNotCall()); + res.on('timeout', common.mustNotCall()); + res.end(); + })); + const s = server.setTimeout(50, common.mustCall(function(socket) { socket.destroy(); server.close(); cb(); })); - server.listen(0, function() { + assert.ok(s instanceof https.Server); + server.listen(common.mustCall(function() { const options = { - port: this.address().port, + port: server.address().port, allowHalfOpen: true, rejectUnauthorized: false }; @@ -171,5 +186,5 @@ test(function idleTimeout(cb) { this.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); // Keep-Alive }); - }); + })); }); From 16998a1ae62c339b4ed91951d995b53b3405ec48 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Thu, 22 Jun 2017 21:59:11 -0700 Subject: [PATCH 49/82] test: refactor test-tls-env-extra-ca * Use `common.mustCall()` to guarantee callback invocations * Order modules according to test writing guide PR-URL: https://github.com/nodejs/node/pull/13886 Reviewed-By: Yuta Hiroto Reviewed-By: Benjamin Gruenbaum Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: Richard Lau --- test/parallel/test-tls-env-extra-ca.js | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/test/parallel/test-tls-env-extra-ca.js b/test/parallel/test-tls-env-extra-ca.js index 4580f1579f6213..e2de272184e5f4 100644 --- a/test/parallel/test-tls-env-extra-ca.js +++ b/test/parallel/test-tls-env-extra-ca.js @@ -9,18 +9,19 @@ if (!common.hasCrypto) { } const assert = require('assert'); +const fs = require('fs'); const tls = require('tls'); + const fork = require('child_process').fork; -const fs = require('fs'); if (process.env.CHILD) { const copts = { port: process.env.PORT, - checkServerIdentity: common.noop, + checkServerIdentity: common.mustCall(), }; - const client = tls.connect(copts, function() { + const client = tls.connect(copts, common.mustCall(function() { client.end('hi'); - }); + })); return; } @@ -29,10 +30,10 @@ const options = { cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`), }; -const server = tls.createServer(options, function(s) { +const server = tls.createServer(options, common.mustCall(function(s) { s.end('bye'); server.close(); -}).listen(0, common.mustCall(function() { +})).listen(0, common.mustCall(function() { const env = { CHILD: 'yes', PORT: this.address().port, From 772927eb699551946a458b2f061467922f9710df Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 23 Jun 2017 15:04:07 -0700 Subject: [PATCH 50/82] test: refactor test-tls-invoked-queued * use common.mustCall()/common.mustNotCall() as appropriate * reorder require() statements per test writing guide * add comment PR-URL: https://github.com/nodejs/node/pull/13893 Reviewed-By: Refael Ackermann Reviewed-By: Richard Lau Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- test/parallel/test-tls-invoke-queued.js | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/test/parallel/test-tls-invoke-queued.js b/test/parallel/test-tls-invoke-queued.js index 2a8037c8d74119..6bbf2369ff18a0 100644 --- a/test/parallel/test-tls-invoke-queued.js +++ b/test/parallel/test-tls-invoke-queued.js @@ -1,31 +1,31 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -const tls = require('tls'); +const assert = require('assert'); const fs = require('fs'); - +const tls = require('tls'); let received = ''; const server = tls.createServer({ key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`), cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`) -}, function(c) { - c._write('hello ', null, function() { - c._write('world!', null, function() { +}, common.mustCall(function(c) { + c._write('hello ', null, common.mustCall(function() { + c._write('world!', null, common.mustCall(function() { c.destroy(); - }); - c._write(' gosh', null, common.noop); - }); + })); + // Data on next _write() will be written but callback will not be invoked + c._write(' gosh', null, common.mustNotCall()); + })); server.close(); -}).listen(0, common.mustCall(function() { +})).listen(0, common.mustCall(function() { const c = tls.connect(this.address().port, { rejectUnauthorized: false }, common.mustCall(function() { From 7a2de19a5245c00f8bb710f12cfbcba52c8723f8 Mon Sep 17 00:00:00 2001 From: Daniel Bevenius Date: Sun, 18 Jun 2017 14:15:00 +0200 Subject: [PATCH 51/82] test: skip fips tests using OpenSSL config file The motivation for this commit is that we are building Node with --shared-openssl and in our case the system OpenSSL version supports FIPS. The tests in test-crypto-fips that toggle fips mode on/off using the config file option might succeed and return 1 instead of an error being thrown from OpenSSL (which is what happens for a default build but the error is not processed/displayed in any way at the moment): openssl config failed: error:060B10A7:digital envelope routines:ALG_MODULE_INIT:fips mode not supported Note that this only concerns the test that use the configuration file option which is different from when calling the fips setter as the handling of the configuration file is handled by OpenSSL, so it is not possible for us to try to call the fips setter as that would throw an error ("Error: Cannot set FIPS mode in a non-FIPS build."). The suggestion is to skips these tests when --shared-openssl is used. PR-URL: https://github.com/nodejs/node/pull/13786 Reviewed-By: Michael Dawson Reviewed-By: James M Snell --- test/parallel/test-crypto-fips.js | 64 ++++++++++++++++++++----------- 1 file changed, 41 insertions(+), 23 deletions(-) diff --git a/test/parallel/test-crypto-fips.js b/test/parallel/test-crypto-fips.js index b5d89593b923d2..6dffbe3e1352b3 100644 --- a/test/parallel/test-crypto-fips.js +++ b/test/parallel/test-crypto-fips.js @@ -21,6 +21,10 @@ function compiledWithFips() { return process.config.variables.openssl_fips ? true : false; } +function sharedOpenSSL() { + return process.config.variables.node_shared_openssl; +} + function addToEnv(newVar, value) { const envCopy = {}; for (const e in process.env) { @@ -85,29 +89,43 @@ testHelper( 'require("crypto").fips', process.env); -// OpenSSL config file should be able to turn on FIPS mode -testHelper( - 'stdout', - [`--openssl-config=${CNF_FIPS_ON}`], - compiledWithFips() ? FIPS_ENABLED : FIPS_DISABLED, - 'require("crypto").fips', - process.env); - -// OPENSSL_CONF should be able to turn on FIPS mode -testHelper( - 'stdout', - [], - compiledWithFips() ? FIPS_ENABLED : FIPS_DISABLED, - 'require("crypto").fips', - addToEnv('OPENSSL_CONF', CNF_FIPS_ON)); - -// --openssl-config option should override OPENSSL_CONF -testHelper( - 'stdout', - [`--openssl-config=${CNF_FIPS_ON}`], - compiledWithFips() ? FIPS_ENABLED : FIPS_DISABLED, - 'require("crypto").fips', - addToEnv('OPENSSL_CONF', CNF_FIPS_OFF)); +// If Node was configured using --shared-openssl fips support might be +// available depending on how OpenSSL was built. If fips support is +// available the tests that toggle the fips_mode on/off using the config +// file option will succeed and return 1 instead of 0. +// +// Note that this case is different from when calling the fips setter as the +// configuration file is handled by OpenSSL, so it is not possible for us +// to try to call the fips setter, to try to detect this situation, as +// that would throw an error: +// ("Error: Cannot set FIPS mode in a non-FIPS build."). +// Due to this uncertanty the following tests are skipped when configured +// with --shared-openssl. +if (!sharedOpenSSL()) { + // OpenSSL config file should be able to turn on FIPS mode + testHelper( + 'stdout', + [`--openssl-config=${CNF_FIPS_ON}`], + compiledWithFips() ? FIPS_ENABLED : FIPS_DISABLED, + 'require("crypto").fips', + process.env); + + // OPENSSL_CONF should be able to turn on FIPS mode + testHelper( + 'stdout', + [], + compiledWithFips() ? FIPS_ENABLED : FIPS_DISABLED, + 'require("crypto").fips', + addToEnv('OPENSSL_CONF', CNF_FIPS_ON)); + + // --openssl-config option should override OPENSSL_CONF + testHelper( + 'stdout', + [`--openssl-config=${CNF_FIPS_ON}`], + compiledWithFips() ? FIPS_ENABLED : FIPS_DISABLED, + 'require("crypto").fips', + addToEnv('OPENSSL_CONF', CNF_FIPS_OFF)); +} testHelper( 'stdout', From 1a50b56e524a3fdca1bfe228a53245dd10c791f6 Mon Sep 17 00:00:00 2001 From: Chris Young Date: Mon, 19 Jun 2017 18:23:09 -0700 Subject: [PATCH 52/82] doc: fixed formatting issue in cli docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Removed some bad escape characters PR-URL: https://github.com/nodejs/node/pull/13808 Fixes: https://github.com/nodejs/node/issues/13805 Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Timothy Gu Reviewed-By: Colin Ihrig Reviewed-By: Tobias Nießen Reviewed-By: Yuta Hiroto Reviewed-By: Michael Dawson Reviewed-By: Gibson Fahnestock --- doc/api/cli.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/cli.md b/doc/api/cli.md index 16fabfacf663e1..92b5b6a5fae1b6 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -359,7 +359,7 @@ added: v6.11.0 Load an OpenSSL configuration file on startup. Among other uses, this can be used to enable FIPS-compliant crypto if Node.js is built with `./configure -\-\-openssl\-fips`. +--openssl-fips`. If the [`--openssl-config`][] command line option is used, the environment variable is ignored. From 059e9ad4488a437abe70ec0f30f832ab3e2943d9 Mon Sep 17 00:00:00 2001 From: Ezequiel Garcia Date: Mon, 19 Jun 2017 20:18:12 -0300 Subject: [PATCH 53/82] test: remove unneeded HandleScope usage These methods are Javascript-accessible so they get an implicit HandleScope. The extra scope is unneeded and can be dropped. PR-URL: https://github.com/nodejs/node/pull/13859 Reviewed-By: Ben Noordhuis Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Signed-off-by: Ezequiel Garcia --- test/addons/async-hello-world/binding.cc | 1 - test/addons/hello-world-function-export/binding.cc | 1 - test/addons/hello-world/binding.cc | 1 - test/addons/repl-domain-abort/binding.cc | 2 -- 4 files changed, 5 deletions(-) diff --git a/test/addons/async-hello-world/binding.cc b/test/addons/async-hello-world/binding.cc index 70fee63aa5e648..da2bd417cd9a6f 100644 --- a/test/addons/async-hello-world/binding.cc +++ b/test/addons/async-hello-world/binding.cc @@ -55,7 +55,6 @@ void AfterAsync(uv_work_t* r) { void Method(const v8::FunctionCallbackInfo& args) { v8::Isolate* isolate = args.GetIsolate(); - v8::HandleScope scope(isolate); async_req* req = new async_req; req->req.data = req; diff --git a/test/addons/hello-world-function-export/binding.cc b/test/addons/hello-world-function-export/binding.cc index c113e0489bde0e..9a93a806e7156e 100644 --- a/test/addons/hello-world-function-export/binding.cc +++ b/test/addons/hello-world-function-export/binding.cc @@ -3,7 +3,6 @@ void Method(const v8::FunctionCallbackInfo& args) { v8::Isolate* isolate = args.GetIsolate(); - v8::HandleScope scope(isolate); args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, "world")); } diff --git a/test/addons/hello-world/binding.cc b/test/addons/hello-world/binding.cc index 5651dc8f50a317..83823ae8363cd9 100644 --- a/test/addons/hello-world/binding.cc +++ b/test/addons/hello-world/binding.cc @@ -3,7 +3,6 @@ void Method(const v8::FunctionCallbackInfo& args) { v8::Isolate* isolate = args.GetIsolate(); - v8::HandleScope scope(isolate); args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, "world")); } diff --git a/test/addons/repl-domain-abort/binding.cc b/test/addons/repl-domain-abort/binding.cc index a507b6fd01e1d1..0c37359e2142ff 100644 --- a/test/addons/repl-domain-abort/binding.cc +++ b/test/addons/repl-domain-abort/binding.cc @@ -4,14 +4,12 @@ using v8::Function; using v8::FunctionCallbackInfo; using v8::Local; -using v8::HandleScope; using v8::Isolate; using v8::Object; using v8::Value; void Method(const FunctionCallbackInfo& args) { Isolate* isolate = args.GetIsolate(); - HandleScope scope(isolate); node::MakeCallback(isolate, isolate->GetCurrentContext()->Global(), args[0].As(), From 4cfc47eac1fbdbcefbcdc832ee3697c1523e2973 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Sun, 25 Jun 2017 21:31:54 +0200 Subject: [PATCH 54/82] doc: fix mistake in path.relative The docs implied that the parameters `from` and `to` are invalid only if neither of them is a string; in fact, they are invalid as soon as one of them is not a string. PR-URL: https://github.com/nodejs/node/pull/13912 Reviewed-By: Refael Ackermann Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig Reviewed-By: David Cai Reviewed-By: Michael Dawson Reviewed-By: Vse Mozhet Byt --- doc/api/path.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/path.md b/doc/api/path.md index 27ca6be6fed7ac..dfe68f1d3cfcb6 100644 --- a/doc/api/path.md +++ b/doc/api/path.md @@ -447,7 +447,7 @@ path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb'); // Returns: '..\\..\\impl\\bbb' ``` -A [`TypeError`][] is thrown if neither `from` nor `to` is a string. +A [`TypeError`][] is thrown if either `from` or `to` is not a string. ## path.resolve([...paths])