test: minor refactoring

Add punctuation and comments about code that should not throw.
Also remove a obsolete test and refactor some tests.

PR-URL: https://github.com/nodejs/node/pull/18669
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
Ruben Bridgewater 2018-02-10 02:33:08 +01:00
parent caee112e52
commit 644fdd60d4
No known key found for this signature in database
GPG Key ID: F07496B3EB3C1762
51 changed files with 166 additions and 205 deletions

View File

@ -30,5 +30,5 @@ const sub = require('./submodule');
const mod = require(path.join(i, 'binding.node')); const mod = require(path.join(i, 'binding.node'));
assert.notStrictEqual(mod, null); assert.notStrictEqual(mod, null);
assert.strictEqual(mod.hello(), 'world'); assert.strictEqual(mod.hello(), 'world');
sub.test(i); sub.test(i); // Should not throw.
}); });

View File

@ -579,11 +579,8 @@ process.on('exit', function() {
assert.ok(getaddrinfoCallbackCalled); assert.ok(getaddrinfoCallbackCalled);
}); });
// Should not throw.
dns.lookup(addresses.INET6_HOST, 6, common.mustCall()); dns.lookup(addresses.INET6_HOST, 6, common.mustCall());
dns.lookup(addresses.INET_HOST, {}, common.mustCall()); dns.lookup(addresses.INET_HOST, {}, common.mustCall());
dns.lookupService('0.0.0.0', '0', common.mustCall()); dns.lookupService('0.0.0.0', '0', common.mustCall());
dns.lookupService('0.0.0.0', 0, common.mustCall()); dns.lookupService('0.0.0.0', 0, common.mustCall());

View File

@ -492,8 +492,8 @@ assertOnlyDeepEqual([1, , , 3], [1, , , 3, , , ]);
// Handle NaN // Handle NaN
assert.throws(() => { assert.deepEqual(NaN, NaN); }, assert.AssertionError); assert.throws(() => { assert.deepEqual(NaN, NaN); }, assert.AssertionError);
{ assert.deepStrictEqual(NaN, NaN); } assert.deepStrictEqual(NaN, NaN);
{ assert.deepStrictEqual({ a: NaN }, { a: NaN }); } assert.deepStrictEqual({ a: NaN }, { a: NaN });
assert.deepStrictEqual([ 1, 2, NaN, 4 ], [ 1, 2, NaN, 4 ]); assert.deepStrictEqual([ 1, 2, NaN, 4 ], [ 1, 2, NaN, 4 ]);
// Handle boxed primitives // Handle boxed primitives

View File

@ -67,6 +67,7 @@ assert.throws(
} }
); );
// Should not throw.
assert.ifError(null); assert.ifError(null);
assert.ifError(); assert.ifError();
assert.ifError(undefined); assert.ifError(undefined);

View File

@ -62,7 +62,7 @@ assert.throws(() => b.write('test', 'utf8', 0),
/is no longer supported/); /is no longer supported/);
// try to create 0-length buffers // Try to create 0-length buffers. Should not throw.
Buffer.from(''); Buffer.from('');
Buffer.from('', 'ascii'); Buffer.from('', 'ascii');
Buffer.from('', 'latin1'); Buffer.from('', 'latin1');
@ -107,7 +107,7 @@ b.copy(Buffer.alloc(1), 0, 2048, 2048);
assert.strictEqual(writeTest.toString(), 'nodejs'); assert.strictEqual(writeTest.toString(), 'nodejs');
} }
// Offset points to the end of the buffer // Offset points to the end of the buffer and does not throw.
// (see https://github.com/nodejs/node/issues/8127). // (see https://github.com/nodejs/node/issues/8127).
Buffer.alloc(1).write('', 1, 0); Buffer.alloc(1).write('', 1, 0);
@ -992,10 +992,10 @@ common.expectsError(() => {
assert.strictEqual(ubuf.buffer.byteLength, 10); assert.strictEqual(ubuf.buffer.byteLength, 10);
} }
// Regression test // Regression test to verify that an empty ArrayBuffer does not throw.
Buffer.from(new ArrayBuffer()); Buffer.from(new ArrayBuffer());
// Test that ArrayBuffer from a different context is detected correctly // Test that ArrayBuffer from a different context is detected correctly.
const arrayBuf = vm.runInNewContext('new ArrayBuffer()'); const arrayBuf = vm.runInNewContext('new ArrayBuffer()');
Buffer.from(arrayBuf); Buffer.from(arrayBuf);
Buffer.from({ buffer: arrayBuf }); Buffer.from({ buffer: arrayBuf });

View File

@ -2,7 +2,7 @@
const common = require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
Buffer.allocUnsafe(10); Buffer.allocUnsafe(10); // Should not throw.
const err = common.expectsError({ const err = common.expectsError({
code: 'ERR_INVALID_ARG_TYPE', code: 'ERR_INVALID_ARG_TYPE',
@ -14,4 +14,4 @@ assert.throws(function() {
Buffer.from(10, 'hex'); Buffer.from(10, 'hex');
}, err); }, err);
Buffer.from('deadbeaf', 'hex'); Buffer.from('deadbeaf', 'hex'); // Should not throw.

View File

@ -11,7 +11,7 @@ assert(MAX_STRING_LENGTH <= MAX_LENGTH);
assert.throws(() => ' '.repeat(MAX_STRING_LENGTH + 1), assert.throws(() => ' '.repeat(MAX_STRING_LENGTH + 1),
/^RangeError: Invalid string length$/); /^RangeError: Invalid string length$/);
' '.repeat(MAX_STRING_LENGTH); ' '.repeat(MAX_STRING_LENGTH); // Should not throw.
// Legacy values match: // Legacy values match:
assert.strictEqual(kMaxLength, MAX_LENGTH); assert.strictEqual(kMaxLength, MAX_LENGTH);

View File

@ -92,7 +92,7 @@ const bb = Buffer.allocUnsafe(10);
bb.fill('hello crazy world'); bb.fill('hello crazy world');
// try to copy from before the beginning of b // Try to copy from before the beginning of b. Should not throw.
b.copy(c, 0, 100, 10); b.copy(c, 0, 100, 10);
// copy throws at negative sourceStart // copy throws at negative sourceStart

View File

@ -22,8 +22,7 @@ arr2[1] = 6000;
assert.deepStrictEqual(arr_buf, ar_buf); assert.deepStrictEqual(arr_buf, ar_buf);
// Checks for calling Buffer.byteLength on a SharedArrayBuffer // Checks for calling Buffer.byteLength on a SharedArrayBuffer.
assert.strictEqual(Buffer.byteLength(sab), sab.byteLength); assert.strictEqual(Buffer.byteLength(sab), sab.byteLength);
Buffer.from({ buffer: sab }); Buffer.from({ buffer: sab }); // Should not throw.

View File

@ -77,9 +77,8 @@ expectedSameBufs.forEach(([buf1, buf2]) => {
const utf16Buf = Buffer.from('0123456789', 'utf16le'); const utf16Buf = Buffer.from('0123456789', 'utf16le');
assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer.from('012', 'utf16le')); assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer.from('012', 'utf16le'));
// try to slice a zero length Buffer // Try to slice a zero length Buffer.
// see https://github.com/joyent/node/issues/5881 // See https://github.com/joyent/node/issues/5881
Buffer.alloc(0).slice(0, 1);
assert.strictEqual(Buffer.alloc(0).slice(0, 1).length, 0); assert.strictEqual(Buffer.alloc(0).slice(0, 1).length, 0);
{ {

View File

@ -40,13 +40,13 @@ assert.throws(function() {
child.on('error', common.mustNotCall()); child.on('error', common.mustNotCall());
}, TypeError); }, TypeError);
// verify that valid argument combinations do not throw // Verify that valid argument combinations do not throw.
spawn(cmd); spawn(cmd);
spawn(cmd, []); spawn(cmd, []);
spawn(cmd, {}); spawn(cmd, {});
spawn(cmd, [], {}); spawn(cmd, [], {});
// verify that invalid argument combinations throw // Verify that invalid argument combinations throw.
assert.throws(function() { assert.throws(function() {
spawn(); spawn();
}, invalidArgTypeError); }, invalidArgTypeError);
@ -76,7 +76,7 @@ assert.throws(function() {
spawn(cmd, [], 1); spawn(cmd, [], 1);
}, invalidArgTypeError); }, invalidArgTypeError);
// Argument types for combinatorics // Argument types for combinatorics.
const a = []; const a = [];
const o = {}; const o = {};
function c() {} function c() {}
@ -94,7 +94,7 @@ spawn(cmd, a);
spawn(cmd, a, o); spawn(cmd, a, o);
spawn(cmd, o); spawn(cmd, o);
// Variants of undefined as explicit 'no argument' at a position // Variants of undefined as explicit 'no argument' at a position.
spawn(cmd, u, o); spawn(cmd, u, o);
spawn(cmd, a, u); spawn(cmd, a, u);
@ -105,7 +105,7 @@ assert.throws(function() { spawn(cmd, s); }, invalidArgTypeError);
assert.throws(function() { spawn(cmd, a, s); }, invalidArgTypeError); assert.throws(function() { spawn(cmd, a, s); }, invalidArgTypeError);
// verify that execFile has same argument parsing behavior as spawn // Verify that execFile has same argument parsing behavior as spawn.
// //
// function execFile(file=f [,args=a] [, options=o] [, callback=c]) has valid // function execFile(file=f [,args=a] [, options=o] [, callback=c]) has valid
// combinations: // combinations:
@ -126,7 +126,7 @@ execFile(cmd, o);
execFile(cmd, o, c); execFile(cmd, o, c);
execFile(cmd, c); execFile(cmd, c);
// Variants of undefined as explicit 'no argument' at a position // Variants of undefined as explicit 'no argument' at a position.
execFile(cmd, u, o, c); execFile(cmd, u, o, c);
execFile(cmd, a, u, c); execFile(cmd, a, u, c);
execFile(cmd, a, o, u); execFile(cmd, a, o, u);
@ -148,9 +148,9 @@ execFile(cmd, o, n);
execFile(cmd, c, u); execFile(cmd, c, u);
execFile(cmd, c, n); execFile(cmd, c, n);
// string is invalid in arg position (this may seem strange, but is // String is invalid in arg position (this may seem strange, but is
// consistent across node API, cf. `net.createServer('not options', 'not // consistent across node API, cf. `net.createServer('not options', 'not
// callback')` // callback')`.
assert.throws(function() { execFile(cmd, s, o, c); }, invalidArgValueError); assert.throws(function() { execFile(cmd, s, o, c); }, invalidArgValueError);
assert.throws(function() { execFile(cmd, a, s, c); }, invalidArgValueError); assert.throws(function() { execFile(cmd, a, s, c); }, invalidArgValueError);
assert.throws(function() { execFile(cmd, a, o, s); }, invalidArgValueError); assert.throws(function() { execFile(cmd, a, o, s); }, invalidArgValueError);
@ -162,10 +162,10 @@ assert.throws(function() { execFile(cmd, a, u, s); }, invalidArgValueError);
assert.throws(function() { execFile(cmd, a, n, s); }, invalidArgValueError); assert.throws(function() { execFile(cmd, a, n, s); }, invalidArgValueError);
assert.throws(function() { execFile(cmd, u, o, s); }, invalidArgValueError); assert.throws(function() { execFile(cmd, u, o, s); }, invalidArgValueError);
assert.throws(function() { execFile(cmd, n, o, s); }, invalidArgValueError); assert.throws(function() { execFile(cmd, n, o, s); }, invalidArgValueError);
execFile(cmd, c, s);
execFile(cmd, c, s); // Should not throw.
// verify that fork has same argument parsing behavior as spawn // Verify that fork has same argument parsing behavior as spawn.
// //
// function fork(file=f [,args=a] [, options=o]) has valid combinations: // function fork(file=f [,args=a] [, options=o]) has valid combinations:
// (f) // (f)

View File

@ -11,6 +11,5 @@ for (const method of ['dir', 'log', 'warn']) {
}); });
const c = new Console(out, out, true); const c = new Console(out, out, true);
c[method]('abc'); // Should not throw.
c[method]('abc');
} }

View File

@ -28,15 +28,15 @@ const Console = require('console').Console;
const out = new Stream(); const out = new Stream();
const err = new Stream(); const err = new Stream();
// ensure the Console instance doesn't write to the // Ensure the Console instance doesn't write to the
// process' "stdout" or "stderr" streams // process' "stdout" or "stderr" streams.
process.stdout.write = process.stderr.write = common.mustNotCall(); process.stdout.write = process.stderr.write = common.mustNotCall();
// make sure that the "Console" function exists // Make sure that the "Console" function exists.
assert.strictEqual('function', typeof Console); assert.strictEqual('function', typeof Console);
// make sure that the Console constructor throws // Make sure that the Console constructor throws
// when not given a writable stream instance // when not given a writable stream instance.
common.expectsError( common.expectsError(
() => { new Console(); }, () => { new Console(); },
{ {
@ -46,7 +46,7 @@ common.expectsError(
} }
); );
// Console constructor should throw if stderr exists but is not writable // Console constructor should throw if stderr exists but is not writable.
common.expectsError( common.expectsError(
() => { () => {
out.write = () => {}; out.write = () => {};
@ -77,7 +77,7 @@ out.write = common.mustCall((d) => {
c.dir({ foo: 1 }); c.dir({ foo: 1 });
// ensure that the console functions are bound to the console instance // Ensure that the console functions are bound to the console instance.
let called = 0; let called = 0;
out.write = common.mustCall((d) => { out.write = common.mustCall((d) => {
called++; called++;
@ -86,7 +86,7 @@ out.write = common.mustCall((d) => {
[1, 2, 3].forEach(c.log); [1, 2, 3].forEach(c.log);
// Console() detects if it is called without `new` keyword // Console() detects if it is called without `new` keyword.
Console(out, err); Console(out, err);
// Instance that does not ignore the stream errors. // Instance that does not ignore the stream errors.

View File

@ -5,7 +5,7 @@ require('../common');
const { test, assert_equals, assert_true, assert_false } = const { test, assert_equals, assert_true, assert_false } =
require('../common/wpt'); require('../common/wpt');
global.console = global.console; global.console = global.console; // Should not throw.
const self = global; const self = global;

View File

@ -12,8 +12,7 @@ for (const method of ['dir', 'log', 'warn']) {
}); });
const c = new Console(out, out, true); const c = new Console(out, out, true);
c[method]('abc'); // Should not throw.
c[method]('abc');
} }
{ {
@ -24,8 +23,7 @@ for (const method of ['dir', 'log', 'warn']) {
}); });
const c = new Console(out, out, true); const c = new Console(out, out, true);
c[method]('abc'); // Should not throw.
c[method]('abc');
} }
{ {
@ -36,7 +34,6 @@ for (const method of ['dir', 'log', 'warn']) {
}); });
const c = new Console(out, out, true); const c = new Console(out, out, true);
c[method]('abc'); // Should not throw.
c[method]('abc');
} }
} }

View File

@ -29,11 +29,7 @@ const crypto = require('crypto');
crypto.DEFAULT_ENCODING = 'buffer'; crypto.DEFAULT_ENCODING = 'buffer';
// Input data.
/*
* Input data
*/
const ODD_LENGTH_PLAIN = 'Hello node world!'; const ODD_LENGTH_PLAIN = 'Hello node world!';
const EVEN_LENGTH_PLAIN = 'Hello node world!AbC09876dDeFgHi'; const EVEN_LENGTH_PLAIN = 'Hello node world!AbC09876dDeFgHi';
@ -42,10 +38,7 @@ const IV_PLAIN = 'blahFizz2011Buzz';
const CIPHER_NAME = 'aes-128-cbc'; const CIPHER_NAME = 'aes-128-cbc';
// Expected result data.
/*
* Expected result data
*/
// echo -n 'Hello node world!' | \ // echo -n 'Hello node world!' | \
// openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \ // openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \
@ -67,10 +60,7 @@ const EVEN_LENGTH_ENCRYPTED_NOPAD =
'7f57859550d4d2fdb9806da2a750461ab46e71b3d78ebe2d9684dfc87f7575b9'; '7f57859550d4d2fdb9806da2a750461ab46e71b3d78ebe2d9684dfc87f7575b9';
/* // Helper wrappers.
* Helper wrappers
*/
function enc(plain, pad) { function enc(plain, pad) {
const encrypt = crypto.createCipheriv(CIPHER_NAME, KEY_PLAIN, IV_PLAIN); const encrypt = crypto.createCipheriv(CIPHER_NAME, KEY_PLAIN, IV_PLAIN);
encrypt.setAutoPadding(pad); encrypt.setAutoPadding(pad);
@ -87,16 +77,12 @@ function dec(encd, pad) {
return plain; return plain;
} }
// Test encryption
/*
* Test encryption
*/
assert.strictEqual(enc(ODD_LENGTH_PLAIN, true), ODD_LENGTH_ENCRYPTED); assert.strictEqual(enc(ODD_LENGTH_PLAIN, true), ODD_LENGTH_ENCRYPTED);
assert.strictEqual(enc(EVEN_LENGTH_PLAIN, true), EVEN_LENGTH_ENCRYPTED); assert.strictEqual(enc(EVEN_LENGTH_PLAIN, true), EVEN_LENGTH_ENCRYPTED);
assert.throws(function() { assert.throws(function() {
// input must have block length % // Input must have block length %.
enc(ODD_LENGTH_PLAIN, false); enc(ODD_LENGTH_PLAIN, false);
}, /data not multiple of block length/); }, /data not multiple of block length/);
@ -104,24 +90,20 @@ assert.strictEqual(
enc(EVEN_LENGTH_PLAIN, false), EVEN_LENGTH_ENCRYPTED_NOPAD enc(EVEN_LENGTH_PLAIN, false), EVEN_LENGTH_ENCRYPTED_NOPAD
); );
// Test decryption.
/*
* Test decryption
*/
assert.strictEqual(dec(ODD_LENGTH_ENCRYPTED, true), ODD_LENGTH_PLAIN); assert.strictEqual(dec(ODD_LENGTH_ENCRYPTED, true), ODD_LENGTH_PLAIN);
assert.strictEqual(dec(EVEN_LENGTH_ENCRYPTED, true), EVEN_LENGTH_PLAIN); assert.strictEqual(dec(EVEN_LENGTH_ENCRYPTED, true), EVEN_LENGTH_PLAIN);
// returns including original padding // Returns including original padding.
assert.strictEqual(dec(ODD_LENGTH_ENCRYPTED, false).length, 32); assert.strictEqual(dec(ODD_LENGTH_ENCRYPTED, false).length, 32);
assert.strictEqual(dec(EVEN_LENGTH_ENCRYPTED, false).length, 48); assert.strictEqual(dec(EVEN_LENGTH_ENCRYPTED, false).length, 48);
assert.throws(function() { assert.throws(function() {
// must have at least 1 byte of padding (PKCS): // Must have at least 1 byte of padding (PKCS):
assert.strictEqual(dec(EVEN_LENGTH_ENCRYPTED_NOPAD, true), EVEN_LENGTH_PLAIN); assert.strictEqual(dec(EVEN_LENGTH_ENCRYPTED_NOPAD, true), EVEN_LENGTH_PLAIN);
}, /bad decrypt/); }, /bad decrypt/);
// no-pad encrypted string should return the same: // No-pad encrypted string should return the same:
assert.strictEqual( assert.strictEqual(
dec(EVEN_LENGTH_ENCRYPTED_NOPAD, false), EVEN_LENGTH_PLAIN dec(EVEN_LENGTH_ENCRYPTED_NOPAD, false), EVEN_LENGTH_PLAIN
); );

View File

@ -100,9 +100,7 @@ common.expectsError(
// Should not get FATAL ERROR with empty password and salt // Should not get FATAL ERROR with empty password and salt
// https://github.com/nodejs/node/issues/8571 // https://github.com/nodejs/node/issues/8571
crypto.pbkdf2('', '', 1, 32, 'sha256', common.mustCall((e) => { crypto.pbkdf2('', '', 1, 32, 'sha256', common.mustCall(assert.ifError));
assert.ifError(e);
}));
common.expectsError( common.expectsError(
() => crypto.pbkdf2('password', 'salt', 8, 8, common.mustNotCall()), () => crypto.pbkdf2('password', 'salt', 8, 8, common.mustNotCall()),

View File

@ -256,7 +256,6 @@ const input = 'I AM THE WALRUS';
// against // against
const sign = crypto.createSign('SHA1'); const sign = crypto.createSign('SHA1');
sign.update(input); sign.update(input);
const signOptions = { key: dsaKeyPemEncrypted, passphrase: 'password' }; const signOptions = { key: dsaKeyPemEncrypted, passphrase: 'password' };
const signature = sign.sign(signOptions, 'hex'); const signature = sign.sign(signOptions, 'hex');

View File

@ -13,5 +13,4 @@ common.expectsError(
); );
process.setUncaughtExceptionCaptureCallback(null); process.setUncaughtExceptionCaptureCallback(null);
require('domain'); // Should not throw.
require('domain');

View File

@ -118,8 +118,8 @@ common.expectsError(
type: TypeError type: TypeError
}); });
// Regular access should not throw.
fs.accessSync(__filename); fs.accessSync(__filename);
const mode = fs.F_OK | fs.R_OK | fs.W_OK; const mode = fs.F_OK | fs.R_OK | fs.W_OK;
fs.accessSync(readWriteFile, mode); fs.accessSync(readWriteFile, mode);

View File

@ -9,17 +9,13 @@ const path = require('path');
const tmpdir = require('../common/tmpdir'); const tmpdir = require('../common/tmpdir');
tmpdir.refresh(); tmpdir.refresh();
fs.access(Buffer.from(tmpdir.path), common.mustCall((err) => { fs.access(Buffer.from(tmpdir.path), common.mustCall(assert.ifError));
assert.ifError(err);
}));
const buf = Buffer.from(path.join(tmpdir.path, 'a.txt')); const buf = Buffer.from(path.join(tmpdir.path, 'a.txt'));
fs.open(buf, 'w+', common.mustCall((err, fd) => { fs.open(buf, 'w+', common.mustCall((err, fd) => {
assert.ifError(err); assert.ifError(err);
assert(fd); assert(fd);
fs.close(fd, common.mustCall((err) => { fs.close(fd, common.mustCall(assert.ifError));
assert.ifError(err);
}));
})); }));
common.expectsError( common.expectsError(

View File

@ -4,7 +4,7 @@ const fixtures = require('../common/fixtures');
const fs = require('fs'); const fs = require('fs');
const example = fixtures.path('x.txt'); const example = fixtures.path('x.txt');
// Should not throw.
fs.createReadStream(example, undefined); fs.createReadStream(example, undefined);
fs.createReadStream(example, null); fs.createReadStream(example, null);
fs.createReadStream(example, 'utf8'); fs.createReadStream(example, 'utf8');

View File

@ -8,7 +8,7 @@ const tmpdir = require('../common/tmpdir');
const example = path.join(tmpdir.path, 'dummy'); const example = path.join(tmpdir.path, 'dummy');
tmpdir.refresh(); tmpdir.refresh();
// Should not throw.
fs.createWriteStream(example, undefined); fs.createWriteStream(example, undefined);
fs.createWriteStream(example, null); fs.createWriteStream(example, null);
fs.createWriteStream(example, 'utf8'); fs.createWriteStream(example, 'utf8');

View File

@ -35,6 +35,7 @@ server.listen(0, function() {
} }
); );
// Should not throw.
const options = { const options = {
port: server.address().port, port: server.address().port,
headers: { 'testing_123': 123 } headers: { 'testing_123': 123 }

View File

@ -5,8 +5,6 @@ if (!common.hasCrypto)
common.skip('missing crypto'); common.skip('missing crypto');
const assert = require('assert'); const assert = require('assert');
process.binding('http2');
const binding = process.binding('http2'); const binding = process.binding('http2');
const http2 = require('http2'); const http2 = require('http2');

View File

@ -19,10 +19,10 @@ server.listen(0, common.mustCall(() => {
req.close(1); req.close(1);
assert.strictEqual(req.closed, true); assert.strictEqual(req.closed, true);
// make sure that destroy is called // Make sure that destroy is called.
req._destroy = common.mustCall(req._destroy.bind(req)); req._destroy = common.mustCall(req._destroy.bind(req));
// second call doesn't do anything // Second call doesn't do anything.
req.close(8); req.close(8);
req.on('close', common.mustCall((code) => { req.on('close', common.mustCall((code) => {

View File

@ -27,6 +27,7 @@ server.listen(0, common.mustCall(function() {
assert.strictEqual(response.statusCode, expectedDefaultStatusCode); assert.strictEqual(response.statusCode, expectedDefaultStatusCode);
// Setting the response.statusCode should not throw.
response.statusCode = realStatusCodes.ok; response.statusCode = realStatusCodes.ok;
response.statusCode = realStatusCodes.multipleChoices; response.statusCode = realStatusCodes.multipleChoices;
response.statusCode = realStatusCodes.badRequest; response.statusCode = realStatusCodes.badRequest;

View File

@ -26,6 +26,7 @@ assert.deepStrictEqual(val, check);
['maxHeaderListSize', 0], ['maxHeaderListSize', 0],
['maxHeaderListSize', 2 ** 32 - 1] ['maxHeaderListSize', 2 ** 32 - 1]
].forEach((i) => { ].forEach((i) => {
// Valid options should not throw.
http2.getPackedSettings({ [i[0]]: i[1] }); http2.getPackedSettings({ [i[0]]: i[1] });
}); });
@ -85,7 +86,7 @@ http2.getPackedSettings({ enablePush: false });
assert.deepStrictEqual(packed, check); assert.deepStrictEqual(packed, check);
} }
// check for not passing settings // Check for not passing settings.
{ {
const packed = http2.getPackedSettings(); const packed = http2.getPackedSettings();
assert.strictEqual(packed.length, 0); assert.strictEqual(packed.length, 0);
@ -143,7 +144,7 @@ http2.getPackedSettings({ enablePush: false });
assert.strictEqual(settings.enablePush, true); assert.strictEqual(settings.enablePush, true);
} }
//check for what happens if passing {validate: true} and no errors happen // Verify that passing {validate: true} does not throw.
{ {
const packed = Buffer.from([ const packed = Buffer.from([
0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0x00, 0x03, 0x00, 0x00,
@ -154,7 +155,7 @@ http2.getPackedSettings({ enablePush: false });
http2.getUnpackedSettings(packed, { validate: true }); http2.getUnpackedSettings(packed, { validate: true });
} }
// check for maxFrameSize failing the max number // Check for maxFrameSize failing the max number.
{ {
const packed = Buffer.from([0x00, 0x05, 0x01, 0x00, 0x00, 0x00]); const packed = Buffer.from([0x00, 0x05, 0x01, 0x00, 0x00, 0x00]);
@ -167,7 +168,7 @@ http2.getPackedSettings({ enablePush: false });
}); });
} }
// check for maxConcurrentStreams failing the max number // Check for maxConcurrentStreams failing the max number.
{ {
const packed = Buffer.from([0x00, 0x03, 0xFF, 0xFF, 0xFF, 0xFF]); const packed = Buffer.from([0x00, 0x03, 0xFF, 0xFF, 0xFF, 0xFF]);

View File

@ -19,20 +19,20 @@ const options = {
cert: commonFixtures.readKey('agent2-cert.pem') cert: commonFixtures.readKey('agent2-cert.pem')
}; };
// There should not be any throws // There should not be any throws.
const serverTLS = http2.createSecureServer(options, () => {}); const serverTLS = http2.createSecureServer(options, () => {});
serverTLS.listen(0, common.mustCall(() => serverTLS.close())); serverTLS.listen(0, common.mustCall(() => serverTLS.close()));
// There should not be an error event reported either // There should not be an error event reported either.
serverTLS.on('error', common.mustNotCall()); serverTLS.on('error', common.mustNotCall());
const server = http2.createServer(options, common.mustNotCall()); const server = http2.createServer(options, common.mustNotCall());
server.listen(0, common.mustCall(() => server.close())); server.listen(0, common.mustCall(() => server.close()));
// There should not be an error event reported either // There should not be an error event reported either.
server.on('error', common.mustNotCall()); server.on('error', common.mustNotCall());
// Test the plaintext server socket timeout // Test the plaintext server socket timeout.
{ {
let client; let client;
const server = http2.createServer(); const server = http2.createServer();
@ -48,7 +48,7 @@ server.on('error', common.mustNotCall());
})); }));
} }
// Test the secure server socket timeout // Test the secure server socket timeout.
{ {
let client; let client;
const server = http2.createSecureServer(options); const server = http2.createSecureServer(options);

View File

@ -51,6 +51,7 @@ server.on('stream', common.mustCall(function(stream, headers) {
common.expectsError(() => (socket.resume = undefined), errMsg); common.expectsError(() => (socket.resume = undefined), errMsg);
common.expectsError(() => (socket.write = undefined), errMsg); common.expectsError(() => (socket.write = undefined), errMsg);
// Resetting the socket listeners to their own value should not throw.
socket.on = socket.on; socket.on = socket.on;
socket.once = socket.once; socket.once = socket.once;

View File

@ -1,7 +0,0 @@
'use strict';
const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
require('http2');

View File

@ -6,5 +6,4 @@ if (!common.hasCrypto)
const assert = require('assert'); const assert = require('assert');
const https = require('https'); const https = require('https');
https.Agent();
assert.ok(https.Agent() instanceof https.Agent); assert.ok(https.Agent() instanceof https.Agent);

View File

@ -34,12 +34,12 @@ const wptToASCIITests = require('../fixtures/url-toascii.js');
if (output === null) { if (output === null) {
assert.throws(() => icu.toASCII(input), assert.throws(() => icu.toASCII(input),
errMessage, `ToASCII ${caseComment}`); errMessage, `ToASCII ${caseComment}`);
icu.toASCII(input, true); icu.toASCII(input, true); // Should not throw.
} else { } else {
assert.strictEqual(icu.toASCII(input), output, `ToASCII ${caseComment}`); assert.strictEqual(icu.toASCII(input), output, `ToASCII ${caseComment}`);
assert.strictEqual(icu.toASCII(input, true), output, assert.strictEqual(icu.toASCII(input, true), output,
`ToASCII ${caseComment} in lenient mode`); `ToASCII ${caseComment} in lenient mode`);
} }
icu.toUnicode(input); icu.toUnicode(input); // Should not throw.
} }
} }

View File

@ -4,8 +4,10 @@
const common = require('../common'); const common = require('../common');
const fs = require('internal/fs'); const fs = require('internal/fs');
// Valid encodings and no args should not throw.
fs.assertEncoding(); fs.assertEncoding();
fs.assertEncoding('utf8'); fs.assertEncoding('utf8');
common.expectsError( common.expectsError(
() => fs.assertEncoding('foo'), () => fs.assertEncoding('foo'),
{ code: 'ERR_INVALID_OPT_VALUE_ENCODING', type: TypeError } { code: 'ERR_INVALID_OPT_VALUE_ENCODING', type: TypeError }

View File

@ -12,12 +12,13 @@ const kDecoratedPrivateSymbolIndex = binding['decorated_private_symbol'];
const decorateErrorStack = internalUtil.decorateErrorStack; const decorateErrorStack = internalUtil.decorateErrorStack;
// Verify that decorateErrorStack does not throw with non-objects.
decorateErrorStack(); decorateErrorStack();
decorateErrorStack(null); decorateErrorStack(null);
decorateErrorStack(1); decorateErrorStack(1);
decorateErrorStack(true); decorateErrorStack(true);
// Verify that a stack property is not added to non-Errors // Verify that a stack property is not added to non-Errors.
const obj = {}; const obj = {};
decorateErrorStack(obj); decorateErrorStack(obj);
assert.strictEqual(obj.stack, undefined); assert.strictEqual(obj.stack, undefined);
@ -46,12 +47,12 @@ try {
assert(typeof err, 'object'); assert(typeof err, 'object');
checkStack(err.stack); checkStack(err.stack);
// Verify that the stack is only decorated once // Verify that the stack is only decorated once.
decorateErrorStack(err); decorateErrorStack(err);
decorateErrorStack(err); decorateErrorStack(err);
checkStack(err.stack); checkStack(err.stack);
// Verify that the stack is only decorated once for uncaught exceptions // Verify that the stack is only decorated once for uncaught exceptions.
const args = [ const args = [
'-e', '-e',
`require('${badSyntaxPath}')` `require('${badSyntaxPath}')`
@ -59,14 +60,14 @@ const args = [
const result = spawnSync(process.argv[0], args, { encoding: 'utf8' }); const result = spawnSync(process.argv[0], args, { encoding: 'utf8' });
checkStack(result.stderr); checkStack(result.stderr);
// Verify that the stack is unchanged when there is no arrow message // Verify that the stack is unchanged when there is no arrow message.
err = new Error('foo'); err = new Error('foo');
let originalStack = err.stack; let originalStack = err.stack;
decorateErrorStack(err); decorateErrorStack(err);
assert.strictEqual(originalStack, err.stack); assert.strictEqual(originalStack, err.stack);
// Verify that the arrow message is added to the start of the stack when it // Verify that the arrow message is added to the start of the stack when it
// exists // exists.
const arrowMessage = 'arrow_message'; const arrowMessage = 'arrow_message';
err = new Error('foo'); err = new Error('foo');
originalStack = err.stack; originalStack = err.stack;

View File

@ -59,4 +59,4 @@ fs.writeFileSync(path.join(moduleB, 'package.json'),
fs.writeFileSync(path.join(moduleB, 'index.js'), fs.writeFileSync(path.join(moduleB, 'index.js'),
'module.exports = 1;', 'utf8'); 'module.exports = 1;', 'utf8');
require(path.join(app, 'index')); require(path.join(app, 'index')); // Should not throw.

View File

@ -34,6 +34,8 @@ server.listen(0, common.mustCall(function() {
c.on('close', common.mustCall(function() { c.on('close', common.mustCall(function() {
console.error('connection closed'); console.error('connection closed');
assert.strictEqual(c._handle, null); assert.strictEqual(c._handle, null);
// Calling functions / accessing properties of a closed socket should not
// throw.
c.setNoDelay(); c.setNoDelay();
c.setKeepAlive(); c.setKeepAlive();
c.bufferSize; c.bufferSize;

View File

@ -30,11 +30,11 @@ const server = net.createServer(function(socket) {
server.listen(0, common.mustCall(function() { server.listen(0, common.mustCall(function() {
const client = net.createConnection(this.address().port); const client = net.createConnection(this.address().port);
server.close(); server.close();
// server connection event has not yet fired // Server connection event has not yet fired client is still attempting to
// client is still attempting to connect // connect. Accessing properties should not throw in this case.
client.remoteAddress; client.remoteAddress;
client.remoteFamily; client.remoteFamily;
client.remotePort; client.remotePort;
// exit now, do not wait for the client error event // Exit now, do not wait for the client error event.
process.exit(0); process.exit(0);
})); }));

View File

@ -64,7 +64,7 @@ assert.strictEqual(typeof performance.timeOrigin, 'number');
{ {
performance.mark('A'); performance.mark('A');
[undefined, null, 'foo', 'initialize', 1].forEach((i) => { [undefined, null, 'foo', 'initialize', 1].forEach((i) => {
performance.measure('test', i, 'A'); performance.measure('test', i, 'A'); // Should not throw.
}); });
[undefined, null, 'foo', 1].forEach((i) => { [undefined, null, 'foo', 1].forEach((i) => {

View File

@ -21,6 +21,7 @@ assert.throws(() => {
// If we're not running as super user... // If we're not running as super user...
if (process.getuid() !== 0) { if (process.getuid() !== 0) {
// Should not throw.
process.getegid(); process.getegid();
process.geteuid(); process.geteuid();

View File

@ -39,6 +39,7 @@ assert.throws(() => {
// If we're not running as super user... // If we're not running as super user...
if (process.getuid() !== 0) { if (process.getuid() !== 0) {
// Should not throw.
process.getgid(); process.getgid();
process.getuid(); process.getuid();

View File

@ -300,7 +300,7 @@ assert.strictEqual('foo=', qs.stringify({ foo: Infinity }));
assert.strictEqual(f, 'a=b&q=x%3Dy%26y%3Dz'); assert.strictEqual(f, 'a=b&q=x%3Dy%26y%3Dz');
} }
qs.parse(undefined); qs.parse(undefined); // Should not throw.
// nested in colon // nested in colon
{ {

View File

@ -61,6 +61,7 @@ assert.deepStrictEqual(writable.data, CSI.kClearLine);
assert.deepStrictEqual(writable.data, set[2]); assert.deepStrictEqual(writable.data, set[2]);
}); });
// Undefined or null as stream should not throw.
readline.cursorTo(null); readline.cursorTo(null);
readline.cursorTo(); readline.cursorTo();

View File

@ -27,13 +27,9 @@ common.expectsError(
} }
); );
{ { // Should not throw.
const m = new MyWritable({ objectMode: true }).on('error', (e) => { const m = new MyWritable({ objectMode: true }).on('error', assert);
assert.ok(e); m.write(null, assert);
});
m.write(null, (err) => {
assert.ok(err);
});
} }
common.expectsError( common.expectsError(
@ -47,25 +43,19 @@ common.expectsError(
} }
); );
{ { // Should not throw.
const m = new MyWritable().on('error', (e) => { const m = new MyWritable().on('error', assert);
assert.ok(e); m.write(false, assert);
});
m.write(false, (err) => {
assert.ok(err);
});
} }
{ { // Should not throw.
const m = new MyWritable({ objectMode: true }); const m = new MyWritable({ objectMode: true });
m.write(false, (err) => assert.ifError(err)); m.write(false, assert.ifError);
} }
{ { // Should not throw.
const m = new MyWritable({ objectMode: true }).on('error', (e) => { const m = new MyWritable({ objectMode: true }).on('error', (e) => {
assert.ifError(e || new Error('should not get here')); assert.ifError(e || new Error('should not get here'));
}); });
m.write(false, (err) => { m.write(false, assert.ifError);
assert.ifError(err);
});
} }

View File

@ -30,6 +30,7 @@ let checks = 0;
const LONG_TIME = 10 * 1000; const LONG_TIME = 10 * 1000;
const SHORT_TIME = 100; const SHORT_TIME = 100;
// Should not throw.
setTimeout(() => {}, 10).unref().ref().unref(); setTimeout(() => {}, 10).unref().ref().unref();
setInterval(() => {}, 10).unref().ref().unref(); setInterval(() => {}, 10).unref().ref().unref();

View File

@ -146,7 +146,7 @@ for (const showHidden of [true, false]) {
' y: 1337 }'); ' y: 1337 }');
} }
// Now do the same checks but from a different context // Now do the same checks but from a different context.
for (const showHidden of [true, false]) { for (const showHidden of [true, false]) {
const ab = vm.runInNewContext('new ArrayBuffer(4)'); const ab = vm.runInNewContext('new ArrayBuffer(4)');
const dv = vm.runInNewContext('new DataView(ab, 1, 2)', { ab }); const dv = vm.runInNewContext('new DataView(ab, 1, 2)', { ab });
@ -211,7 +211,7 @@ for (const showHidden of [true, false]) {
); );
}); });
// Now check that declaring a TypedArray in a different context works the same // Now check that declaring a TypedArray in a different context works the same.
[ Float32Array, [ Float32Array,
Float64Array, Float64Array,
Int16Array, Int16Array,
@ -252,7 +252,7 @@ assert.strictEqual(
}), { showHidden: true }), }), { showHidden: true }),
'{ visible: 1, [hidden]: 2 }' '{ visible: 1, [hidden]: 2 }'
); );
// Objects without prototype // Objects without prototype.
assert.strictEqual( assert.strictEqual(
util.inspect(Object.create(null, { util.inspect(Object.create(null, {
name: { value: 'Tim', enumerable: true }, name: { value: 'Tim', enumerable: true },
@ -269,7 +269,7 @@ assert.strictEqual(
'{ name: \'Tim\' }' '{ name: \'Tim\' }'
); );
// Dynamic properties // Dynamic properties.
{ {
assert.strictEqual( assert.strictEqual(
util.inspect({ get readonly() {} }), util.inspect({ get readonly() {} }),
@ -289,7 +289,7 @@ assert.strictEqual(
assert.strictEqual(util.inspect(value), '{ a: [Circular] }'); assert.strictEqual(util.inspect(value), '{ a: [Circular] }');
} }
// Array with dynamic properties // Array with dynamic properties.
{ {
const value = [1, 2, 3]; const value = [1, 2, 3];
Object.defineProperty( Object.defineProperty(
@ -312,7 +312,7 @@ assert.strictEqual(
'[ 1, 2, 3, growingLength: [Getter], \'-1\': -1 ]'); '[ 1, 2, 3, growingLength: [Getter], \'-1\': -1 ]');
} }
// Array with inherited number properties // Array with inherited number properties.
{ {
class CustomArray extends Array {} class CustomArray extends Array {}
CustomArray.prototype[5] = 'foo'; CustomArray.prototype[5] = 'foo';
@ -320,7 +320,7 @@ assert.strictEqual(
assert.strictEqual(util.inspect(arr), 'CustomArray [ <50 empty items> ]'); assert.strictEqual(util.inspect(arr), 'CustomArray [ <50 empty items> ]');
} }
// Array with extra properties // Array with extra properties.
{ {
const arr = [1, 2, 3, , ]; const arr = [1, 2, 3, , ];
arr.foo = 'bar'; arr.foo = 'bar';
@ -352,10 +352,10 @@ assert.strictEqual(
assert.strictEqual(util.inspect(arr3), "[ '-1': -1 ]"); assert.strictEqual(util.inspect(arr3), "[ '-1': -1 ]");
} }
// Indices out of bounds // Indices out of bounds.
{ {
const arr = []; const arr = [];
arr[2 ** 32] = true; // not a valid array index arr[2 ** 32] = true; // Not a valid array index.
assert.strictEqual(util.inspect(arr), "[ '4294967296': true ]"); assert.strictEqual(util.inspect(arr), "[ '4294967296': true ]");
arr[0] = true; arr[0] = true;
arr[10] = true; arr[10] = true;
@ -375,28 +375,28 @@ assert.strictEqual(
].join('\n ')); ].join('\n '));
} }
// Function with properties // Function with properties.
{ {
const value = () => {}; const value = () => {};
value.aprop = 42; value.aprop = 42;
assert.strictEqual(util.inspect(value), '{ [Function: value] aprop: 42 }'); assert.strictEqual(util.inspect(value), '{ [Function: value] aprop: 42 }');
} }
// Anonymous function with properties // Anonymous function with properties.
{ {
const value = (() => function() {})(); const value = (() => function() {})();
value.aprop = 42; value.aprop = 42;
assert.strictEqual(util.inspect(value), '{ [Function] aprop: 42 }'); assert.strictEqual(util.inspect(value), '{ [Function] aprop: 42 }');
} }
// Regular expressions with properties // Regular expressions with properties.
{ {
const value = /123/ig; const value = /123/ig;
value.aprop = 42; value.aprop = 42;
assert.strictEqual(util.inspect(value), '{ /123/gi aprop: 42 }'); assert.strictEqual(util.inspect(value), '{ /123/gi aprop: 42 }');
} }
// Dates with properties // Dates with properties.
{ {
const value = new Date('Sun, 14 Feb 2010 11:48:40 GMT'); const value = new Date('Sun, 14 Feb 2010 11:48:40 GMT');
value.aprop = 42; value.aprop = 42;
@ -404,7 +404,7 @@ assert.strictEqual(
'{ 2010-02-14T11:48:40.000Z aprop: 42 }'); '{ 2010-02-14T11:48:40.000Z aprop: 42 }');
} }
// test the internal isDate implementation // Test the internal isDate implementation.
{ {
const Date2 = vm.runInNewContext('Date'); const Date2 = vm.runInNewContext('Date');
const d = new Date2(); const d = new Date2();
@ -414,13 +414,13 @@ assert.strictEqual(
assert.strictEqual(orig, after); assert.strictEqual(orig, after);
} }
// test positive/negative zero // Test positive/negative zero.
assert.strictEqual(util.inspect(0), '0'); assert.strictEqual(util.inspect(0), '0');
assert.strictEqual(util.inspect(-0), '-0'); assert.strictEqual(util.inspect(-0), '-0');
// edge case from check // Edge case from check.
assert.strictEqual(util.inspect(-5e-324), '-5e-324'); assert.strictEqual(util.inspect(-5e-324), '-5e-324');
// test for sparse array // Test for sparse array.
{ {
const a = ['foo', 'bar', 'baz']; const a = ['foo', 'bar', 'baz'];
assert.strictEqual(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]'); assert.strictEqual(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]');
@ -444,7 +444,7 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324');
); );
} }
// test for Array constructor in different context // Test for Array constructor in different context.
{ {
const map = new Map(); const map = new Map();
map.set(1, 2); map.set(1, 2);
@ -457,7 +457,7 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324');
assert.strictEqual(util.inspect(valsOutput), '[ [ 1, 2 ] ]'); assert.strictEqual(util.inspect(valsOutput), '[ [ 1, 2 ] ]');
} }
// test for other constructors in different context // Test for other constructors in different context.
{ {
let obj = vm.runInNewContext('(function(){return {}})()', {}); let obj = vm.runInNewContext('(function(){return {}})()', {});
assert.strictEqual(util.inspect(obj), '{}'); assert.strictEqual(util.inspect(obj), '{}');
@ -469,7 +469,7 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324');
assert.strictEqual(util.inspect(obj), 'Promise { <pending> }'); assert.strictEqual(util.inspect(obj), 'Promise { <pending> }');
} }
// test for property descriptors // Test for property descriptors.
{ {
const getter = Object.create(null, { const getter = Object.create(null, {
a: { a: {
@ -495,7 +495,7 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324');
); );
} }
// exceptions should print the error message, not '{}' // Exceptions should print the error message, not '{}'.
{ {
const errors = []; const errors = [];
errors.push(new Error()); errors.push(new Error());
@ -516,7 +516,7 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324');
assert(ex.includes('[message]')); assert(ex.includes('[message]'));
} }
// Doesn't capture stack trace // Doesn't capture stack trace.
{ {
function BadCustomError(msg) { function BadCustomError(msg) {
Error.call(this); Error.call(this);
@ -533,7 +533,6 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324');
} }
// GH-1941 // GH-1941
// should not throw:
assert.strictEqual(util.inspect(Object.create(Date.prototype)), 'Date {}'); assert.strictEqual(util.inspect(Object.create(Date.prototype)), 'Date {}');
// GH-1944 // GH-1944
@ -543,20 +542,20 @@ assert.strictEqual(util.inspect(Object.create(Date.prototype)), 'Date {}');
util.inspect(d); util.inspect(d);
} }
// Should not throw.
{ {
const d = new Date(); const d = new Date();
d.toISOString = null; d.toISOString = null;
util.inspect(d); util.inspect(d);
} }
// Should not throw.
const r = /regexp/; const r = /regexp/;
r.toString = null; r.toString = null;
util.inspect(r); util.inspect(r);
// bug with user-supplied inspect function returns non-string // Bug with user-supplied inspect function returns non-string.
util.inspect([{ util.inspect([{ inspect: () => 123 }]);
inspect: () => 123
}]);
// GH-2225 // GH-2225
{ {
@ -592,7 +591,7 @@ util.inspect([{
); );
} }
// util.inspect.styles and util.inspect.colors // Test util.inspect.styles and util.inspect.colors.
{ {
function testColorStyle(style, input, implicit) { function testColorStyle(style, input, implicit) {
const colorName = util.inspect.styles[style]; const colorName = util.inspect.styles[style];
@ -619,12 +618,10 @@ util.inspect([{
testColorStyle('regexp', /regexp/); testColorStyle('regexp', /regexp/);
} }
// an object with "hasOwnProperty" overwritten should not throw // An object with "hasOwnProperty" overwritten should not throw.
util.inspect({ util.inspect({ hasOwnProperty: null });
hasOwnProperty: null
});
// new API, accepts an "options" object // New API, accepts an "options" object.
{ {
const subject = { foo: 'bar', hello: 31, a: { b: { c: { d: 0 } } } }; const subject = { foo: 'bar', hello: 31, a: { b: { c: { d: 0 } } } };
Object.defineProperty(subject, 'hidden', { enumerable: false, value: null }); Object.defineProperty(subject, 'hidden', { enumerable: false, value: null });
@ -664,7 +661,7 @@ util.inspect({
} }
{ {
// "customInspect" option can enable/disable calling inspect() on objects // "customInspect" option can enable/disable calling inspect() on objects.
const subject = { inspect: () => 123 }; const subject = { inspect: () => 123 };
assert.strictEqual( assert.strictEqual(
@ -684,7 +681,7 @@ util.inspect({
true true
); );
// custom inspect() functions should be able to return other Objects // Custom inspect() functions should be able to return other Objects.
subject.inspect = () => ({ foo: 'bar' }); subject.inspect = () => ({ foo: 'bar' });
assert.strictEqual(util.inspect(subject), '{ foo: \'bar\' }'); assert.strictEqual(util.inspect(subject), '{ foo: \'bar\' }');
@ -697,7 +694,7 @@ util.inspect({
} }
{ {
// "customInspect" option can enable/disable calling [util.inspect.custom]() // "customInspect" option can enable/disable calling [util.inspect.custom]().
const subject = { [util.inspect.custom]: () => 123 }; const subject = { [util.inspect.custom]: () => 123 };
assert.strictEqual( assert.strictEqual(
@ -709,7 +706,7 @@ util.inspect({
false false
); );
// a custom [util.inspect.custom]() should be able to return other Objects // A custom [util.inspect.custom]() should be able to return other Objects.
subject[util.inspect.custom] = () => ({ foo: 'bar' }); subject[util.inspect.custom] = () => ({ foo: 'bar' });
assert.strictEqual(util.inspect(subject), '{ foo: \'bar\' }'); assert.strictEqual(util.inspect(subject), '{ foo: \'bar\' }');
@ -722,7 +719,7 @@ util.inspect({
} }
{ {
// [util.inspect.custom] takes precedence over inspect // [util.inspect.custom] takes precedence over inspect.
const subject = { const subject = {
[util.inspect.custom]() { return 123; }, [util.inspect.custom]() { return 123; },
inspect() { return 456; } inspect() { return 456; }
@ -757,7 +754,7 @@ util.inspect({
`{ a: 123,\n [Symbol(${UIC})]: [Function: [${UIC}]] }`); `{ a: 123,\n [Symbol(${UIC})]: [Function: [${UIC}]] }`);
} }
// util.inspect with "colors" option should produce as many lines as without it // util.inspect with "colors" option should produce as many lines as without it.
{ {
function testLines(input) { function testLines(input) {
const countLines = (str) => (str.match(/\n/g) || []).length; const countLines = (str) => (str.match(/\n/g) || []).length;
@ -781,7 +778,7 @@ util.inspect({
}); });
} }
// test boxed primitives output the correct values // Test boxed primitives output the correct values.
assert.strictEqual(util.inspect(new String('test')), '[String: \'test\']'); assert.strictEqual(util.inspect(new String('test')), '[String: \'test\']');
assert.strictEqual( assert.strictEqual(
util.inspect(Object(Symbol('test'))), util.inspect(Object(Symbol('test'))),
@ -794,7 +791,7 @@ assert.strictEqual(util.inspect(new Number(-0)), '[Number: -0]');
assert.strictEqual(util.inspect(new Number(-1.1)), '[Number: -1.1]'); assert.strictEqual(util.inspect(new Number(-1.1)), '[Number: -1.1]');
assert.strictEqual(util.inspect(new Number(13.37)), '[Number: 13.37]'); assert.strictEqual(util.inspect(new Number(13.37)), '[Number: 13.37]');
// test boxed primitives with own properties // Test boxed primitives with own properties.
{ {
const str = new String('baz'); const str = new String('baz');
str.foo = 'bar'; str.foo = 'bar';
@ -809,7 +806,7 @@ assert.strictEqual(util.inspect(new Number(13.37)), '[Number: 13.37]');
assert.strictEqual(util.inspect(num), '{ [Number: 13.37] foo: \'bar\' }'); assert.strictEqual(util.inspect(num), '{ [Number: 13.37] foo: \'bar\' }');
} }
// test es6 Symbol // Test es6 Symbol.
if (typeof Symbol !== 'undefined') { if (typeof Symbol !== 'undefined') {
assert.strictEqual(util.inspect(Symbol()), 'Symbol()'); assert.strictEqual(util.inspect(Symbol()), 'Symbol()');
assert.strictEqual(util.inspect(Symbol(123)), 'Symbol(123)'); assert.strictEqual(util.inspect(Symbol(123)), 'Symbol(123)');
@ -845,7 +842,7 @@ if (typeof Symbol !== 'undefined') {
'[ 1, 2, 3, [Symbol(symbol)]: 42 ]'); '[ 1, 2, 3, [Symbol(symbol)]: 42 ]');
} }
// test Set // Test Set.
{ {
assert.strictEqual(util.inspect(new Set()), 'Set {}'); assert.strictEqual(util.inspect(new Set()), 'Set {}');
assert.strictEqual(util.inspect(new Set([1, 2, 3])), 'Set { 1, 2, 3 }'); assert.strictEqual(util.inspect(new Set([1, 2, 3])), 'Set { 1, 2, 3 }');
@ -857,14 +854,14 @@ if (typeof Symbol !== 'undefined') {
); );
} }
// Test circular Set // Test circular Set.
{ {
const set = new Set(); const set = new Set();
set.add(set); set.add(set);
assert.strictEqual(util.inspect(set), 'Set { [Circular] }'); assert.strictEqual(util.inspect(set), 'Set { [Circular] }');
} }
// test Map // Test Map.
{ {
assert.strictEqual(util.inspect(new Map()), 'Map {}'); assert.strictEqual(util.inspect(new Map()), 'Map {}');
assert.strictEqual(util.inspect(new Map([[1, 'a'], [2, 'b'], [3, 'c']])), assert.strictEqual(util.inspect(new Map([[1, 'a'], [2, 'b'], [3, 'c']])),
@ -875,7 +872,7 @@ if (typeof Symbol !== 'undefined') {
'Map { \'foo\' => null, [size]: 1, bar: 42 }'); 'Map { \'foo\' => null, [size]: 1, bar: 42 }');
} }
// Test circular Map // Test circular Map.
{ {
const map = new Map(); const map = new Map();
map.set(map, 'map'); map.set(map, 'map');
@ -887,14 +884,14 @@ if (typeof Symbol !== 'undefined') {
assert.strictEqual(util.inspect(map), "Map { 'map' => [Circular] }"); assert.strictEqual(util.inspect(map), "Map { 'map' => [Circular] }");
} }
// test Promise // Test Promise.
{ {
const resolved = Promise.resolve(3); const resolved = Promise.resolve(3);
assert.strictEqual(util.inspect(resolved), 'Promise { 3 }'); assert.strictEqual(util.inspect(resolved), 'Promise { 3 }');
const rejected = Promise.reject(3); const rejected = Promise.reject(3);
assert.strictEqual(util.inspect(rejected), 'Promise { <rejected> 3 }'); assert.strictEqual(util.inspect(rejected), 'Promise { <rejected> 3 }');
// squelch UnhandledPromiseRejection // Squelch UnhandledPromiseRejection.
rejected.catch(() => {}); rejected.catch(() => {});
const pending = new Promise(() => {}); const pending = new Promise(() => {});
@ -916,33 +913,33 @@ if (typeof Symbol !== 'undefined') {
global.Promise = oldPromise; global.Promise = oldPromise;
} }
// Test Map iterators // Test Map iterators.
{ {
const map = new Map([['foo', 'bar']]); const map = new Map([['foo', 'bar']]);
assert.strictEqual(util.inspect(map.keys()), '[Map Iterator] { \'foo\' }'); assert.strictEqual(util.inspect(map.keys()), '[Map Iterator] { \'foo\' }');
assert.strictEqual(util.inspect(map.values()), '[Map Iterator] { \'bar\' }'); assert.strictEqual(util.inspect(map.values()), '[Map Iterator] { \'bar\' }');
assert.strictEqual(util.inspect(map.entries()), assert.strictEqual(util.inspect(map.entries()),
'[Map Iterator] { [ \'foo\', \'bar\' ] }'); '[Map Iterator] { [ \'foo\', \'bar\' ] }');
// make sure the iterator doesn't get consumed // Make sure the iterator doesn't get consumed.
const keys = map.keys(); const keys = map.keys();
assert.strictEqual(util.inspect(keys), '[Map Iterator] { \'foo\' }'); assert.strictEqual(util.inspect(keys), '[Map Iterator] { \'foo\' }');
assert.strictEqual(util.inspect(keys), '[Map Iterator] { \'foo\' }'); assert.strictEqual(util.inspect(keys), '[Map Iterator] { \'foo\' }');
} }
// Test Set iterators // Test Set iterators.
{ {
const aSet = new Set([1, 3]); const aSet = new Set([1, 3]);
assert.strictEqual(util.inspect(aSet.keys()), '[Set Iterator] { 1, 3 }'); assert.strictEqual(util.inspect(aSet.keys()), '[Set Iterator] { 1, 3 }');
assert.strictEqual(util.inspect(aSet.values()), '[Set Iterator] { 1, 3 }'); assert.strictEqual(util.inspect(aSet.values()), '[Set Iterator] { 1, 3 }');
assert.strictEqual(util.inspect(aSet.entries()), assert.strictEqual(util.inspect(aSet.entries()),
'[Set Iterator] { [ 1, 1 ], [ 3, 3 ] }'); '[Set Iterator] { [ 1, 1 ], [ 3, 3 ] }');
// make sure the iterator doesn't get consumed // Make sure the iterator doesn't get consumed.
const keys = aSet.keys(); const keys = aSet.keys();
assert.strictEqual(util.inspect(keys), '[Set Iterator] { 1, 3 }'); assert.strictEqual(util.inspect(keys), '[Set Iterator] { 1, 3 }');
assert.strictEqual(util.inspect(keys), '[Set Iterator] { 1, 3 }'); assert.strictEqual(util.inspect(keys), '[Set Iterator] { 1, 3 }');
} }
// Test alignment of items in container // Test alignment of items in container.
// Assumes that the first numeric character is the start of an item. // Assumes that the first numeric character is the start of an item.
{ {
function checkAlignment(container) { function checkAlignment(container) {
@ -977,7 +974,7 @@ if (typeof Symbol !== 'undefined') {
} }
// Test display of constructors // Test display of constructors.
{ {
class ObjectSubclass {} class ObjectSubclass {}
class ArraySubclass extends Array {} class ArraySubclass extends Array {}
@ -1003,7 +1000,7 @@ if (typeof Symbol !== 'undefined') {
); );
} }
// Empty and circular before depth // Empty and circular before depth.
{ {
const arr = [[[[]]]]; const arr = [[[[]]]];
assert.strictEqual(util.inspect(arr, { depth: 2 }), '[ [ [ [] ] ] ]'); assert.strictEqual(util.inspect(arr, { depth: 2 }), '[ [ [ [] ] ] ]');
@ -1099,14 +1096,14 @@ if (typeof Symbol !== 'undefined') {
assert.strictEqual(twoLines, '{ foo: \'abc\',\n bar: \'xyz\' }'); assert.strictEqual(twoLines, '{ foo: \'abc\',\n bar: \'xyz\' }');
} }
// util.inspect.defaultOptions tests // util.inspect.defaultOptions tests.
{ {
const arr = new Array(101).fill(); const arr = new Array(101).fill();
const obj = { a: { a: { a: { a: 1 } } } }; const obj = { a: { a: { a: { a: 1 } } } };
const oldOptions = Object.assign({}, util.inspect.defaultOptions); const oldOptions = Object.assign({}, util.inspect.defaultOptions);
// Set single option through property assignment // Set single option through property assignment.
util.inspect.defaultOptions.maxArrayLength = null; util.inspect.defaultOptions.maxArrayLength = null;
assert(!/1 more item/.test(util.inspect(arr))); assert(!/1 more item/.test(util.inspect(arr)));
util.inspect.defaultOptions.maxArrayLength = oldOptions.maxArrayLength; util.inspect.defaultOptions.maxArrayLength = oldOptions.maxArrayLength;
@ -1120,7 +1117,7 @@ if (typeof Symbol !== 'undefined') {
JSON.stringify(oldOptions) JSON.stringify(oldOptions)
); );
// Set multiple options through object assignment // Set multiple options through object assignment.
util.inspect.defaultOptions = { maxArrayLength: null, depth: 2 }; util.inspect.defaultOptions = { maxArrayLength: null, depth: 2 };
assert(!/1 more item/.test(util.inspect(arr))); assert(!/1 more item/.test(util.inspect(arr)));
assert(/Object/.test(util.inspect(obj))); assert(/Object/.test(util.inspect(obj)));

View File

@ -28,6 +28,7 @@ assert.throws(function() {
vm.createContext('string is not supported'); vm.createContext('string is not supported');
}, /^TypeError: sandbox must be an object$/); }, /^TypeError: sandbox must be an object$/);
// Should not throw.
vm.createContext({ a: 1 }); vm.createContext({ a: 1 });
vm.createContext([0, 1, 2, 3]); vm.createContext([0, 1, 2, 3]);

View File

@ -25,4 +25,5 @@ require('../common');
const vm = require('vm'); const vm = require('vm');
const ctx = vm.createContext(global); const ctx = vm.createContext(global);
// Should not throw.
vm.runInContext('!function() { var x = console.log; }()', ctx); vm.runInContext('!function() { var x = console.log; }()', ctx);

View File

@ -44,6 +44,7 @@ assert.strictEqual(readBuf.toString(), message);
fs.readSync(fd, readBuf, 0, 1, 0); fs.readSync(fd, readBuf, 0, 1, 0);
assert.strictEqual(readBuf[0], 0); assert.strictEqual(readBuf[0], 0);
// Verify that floating point positions do not throw.
fs.writeSync(fd, writeBuf, 0, writeBuf.length, 42.000001); fs.writeSync(fd, writeBuf, 0, writeBuf.length, 42.000001);
fs.close(fd); fs.close(fd);

View File

@ -68,6 +68,7 @@ assert.throws(
} }
); );
// Does not throw.
fs.watchFile(filepathOne, function() { fs.watchFile(filepathOne, function() {
fs.unwatchFile(filepathOne); fs.unwatchFile(filepathOne);
++watchSeenOne; ++watchSeenOne;
@ -91,7 +92,7 @@ assert.throws(
} }
); );
{ { // Does not throw.
function a() { function a() {
fs.unwatchFile(filepathTwo, a); fs.unwatchFile(filepathTwo, a);
++watchSeenTwo; ++watchSeenTwo;
@ -108,7 +109,7 @@ setTimeout(function() {
fs.writeFileSync(filepathTwoAbs, 'pardner'); fs.writeFileSync(filepathTwoAbs, 'pardner');
}, 1000); }, 1000);
{ { // Does not throw.
function b() { function b() {
fs.unwatchFile(filenameThree, b); fs.unwatchFile(filenameThree, b);
++watchSeenThree; ++watchSeenThree;
@ -130,7 +131,7 @@ setTimeout(function() {
fs.writeFileSync(filenameFour, 'hey'); fs.writeFileSync(filenameFour, 'hey');
}, 500); }, 500);
{ { // Does not throw.
function a() { function a() {
++watchSeenFour; ++watchSeenFour;
assert.strictEqual(1, watchSeenFour); assert.strictEqual(1, watchSeenFour);

View File

@ -56,4 +56,5 @@ common.expectsError(
); );
session.disconnect(); session.disconnect();
// Calling disconnect twice should not throw.
session.disconnect(); session.disconnect();