From 5fc201b878b1a73a9a8afbdc751a3d46cb4c6b18 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Wed, 7 Feb 2018 00:07:08 +0100 Subject: [PATCH 01/16] test: refactor assert test This adds puctiations to the comments, uses a capital letters for the first character, removes a few obsolete comments and switches to assert.ok when suitable. It also moves all `assert.deepEqual()` and `assert.deepStrictEqual()` tests to the appropriate file. PR-URL: https://github.com/nodejs/node/pull/18610 Reviewed-By: Joyee Cheung --- test/parallel/test-assert-deep.js | 298 ++++++++++++++++++++- test/parallel/test-assert.js | 430 ++++-------------------------- 2 files changed, 345 insertions(+), 383 deletions(-) diff --git a/test/parallel/test-assert-deep.js b/test/parallel/test-assert-deep.js index 8f08d571383a77..95c4ca5532d1bb 100644 --- a/test/parallel/test-assert-deep.js +++ b/test/parallel/test-assert-deep.js @@ -1,7 +1,9 @@ 'use strict'; + const common = require('../common'); const assert = require('assert'); const util = require('util'); +const { AssertionError } = assert; // Template tag function turning an error message into a RegExp // for assert.throws() @@ -25,7 +27,7 @@ function re(literals, ...values) { // That is why we discourage using deepEqual in our own tests. // Turn off no-restricted-properties because we are testing deepEqual! -/* eslint-disable no-restricted-properties */ +/* eslint-disable no-restricted-properties, prefer-common-expectserror */ const arr = new Uint8Array([120, 121, 122, 10]); const buf = Buffer.from(arr); @@ -545,4 +547,298 @@ assertDeepAndStrictEqual(-0, -0); assertDeepAndStrictEqual(a, b); } +assert.doesNotThrow( + () => assert.deepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14)), + 'deepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))'); + +assert.throws(() => assert.deepEqual(new Date(), new Date(2000, 3, 14)), + AssertionError, + 'deepEqual(new Date(), new Date(2000, 3, 14))'); + +assert.throws( + () => assert.notDeepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14)), + AssertionError, + 'notDeepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))' +); + +assert.doesNotThrow( + () => assert.notDeepEqual(new Date(), new Date(2000, 3, 14)), + 'notDeepEqual(new Date(), new Date(2000, 3, 14))' +); + +assert.deepEqual(/a/, /a/); +assert.deepEqual(/a/g, /a/g); +assert.deepEqual(/a/i, /a/i); +assert.deepEqual(/a/m, /a/m); +assert.deepEqual(/a/igm, /a/igm); +common.expectsError(() => assert.deepEqual(/ab/, /a/), + { + code: 'ERR_ASSERTION', + name: 'AssertionError [ERR_ASSERTION]', + message: '/ab/ deepEqual /a/' + }); +common.expectsError(() => assert.deepEqual(/a/g, /a/), + { + code: 'ERR_ASSERTION', + name: 'AssertionError [ERR_ASSERTION]', + message: '/a/g deepEqual /a/' + }); +common.expectsError(() => assert.deepEqual(/a/i, /a/), + { + code: 'ERR_ASSERTION', + name: 'AssertionError [ERR_ASSERTION]', + message: '/a/i deepEqual /a/' + }); +common.expectsError(() => assert.deepEqual(/a/m, /a/), + { + code: 'ERR_ASSERTION', + name: 'AssertionError [ERR_ASSERTION]', + message: '/a/m deepEqual /a/' + }); +common.expectsError(() => assert.deepEqual(/a/igm, /a/im), + { + code: 'ERR_ASSERTION', + name: 'AssertionError [ERR_ASSERTION]', + message: '/a/gim deepEqual /a/im' + }); + +{ + const re1 = /a/g; + re1.lastIndex = 3; + assert.doesNotThrow(() => assert.deepEqual(re1, /a/g)); +} + +assert.doesNotThrow(() => assert.deepEqual(4, '4'), 'deepEqual(4, \'4\')'); +assert.doesNotThrow(() => assert.deepEqual(true, 1), 'deepEqual(true, 1)'); +assert.throws(() => assert.deepEqual(4, '5'), + AssertionError, + 'deepEqual( 4, \'5\')'); + +// Having the same number of owned properties && the same set of keys. +assert.doesNotThrow(() => assert.deepEqual({ a: 4 }, { a: 4 })); +assert.doesNotThrow(() => assert.deepEqual({ a: 4, b: '2' }, { a: 4, b: '2' })); +assert.doesNotThrow(() => assert.deepEqual([4], ['4'])); +assert.throws( + () => assert.deepEqual({ a: 4 }, { a: 4, b: true }), AssertionError); +assert.doesNotThrow(() => assert.deepEqual(['a'], { 0: 'a' })); +assert.doesNotThrow(() => assert.deepEqual({ a: 4, b: '1' }, { b: '1', a: 4 })); +const a1 = [1, 2, 3]; +const a2 = [1, 2, 3]; +a1.a = 'test'; +a1.b = true; +a2.b = true; +a2.a = 'test'; +assert.throws(() => assert.deepEqual(Object.keys(a1), Object.keys(a2)), + AssertionError); +assert.doesNotThrow(() => assert.deepEqual(a1, a2)); + +// Having an identical prototype property. +const nbRoot = { + toString() { return `${this.first} ${this.last}`; } +}; + +function nameBuilder(first, last) { + this.first = first; + this.last = last; + return this; +} +nameBuilder.prototype = nbRoot; + +function nameBuilder2(first, last) { + this.first = first; + this.last = last; + return this; +} +nameBuilder2.prototype = nbRoot; + +const nb1 = new nameBuilder('Ryan', 'Dahl'); +let nb2 = new nameBuilder2('Ryan', 'Dahl'); + +assert.doesNotThrow(() => assert.deepEqual(nb1, nb2)); + +nameBuilder2.prototype = Object; +nb2 = new nameBuilder2('Ryan', 'Dahl'); +assert.doesNotThrow(() => assert.deepEqual(nb1, nb2)); + +// Primitives and object. +assert.throws(() => assert.deepEqual(null, {}), AssertionError); +assert.throws(() => assert.deepEqual(undefined, {}), AssertionError); +assert.throws(() => assert.deepEqual('a', ['a']), AssertionError); +assert.throws(() => assert.deepEqual('a', { 0: 'a' }), AssertionError); +assert.throws(() => assert.deepEqual(1, {}), AssertionError); +assert.throws(() => assert.deepEqual(true, {}), AssertionError); +assert.throws(() => assert.deepEqual(Symbol(), {}), AssertionError); + +// Primitive wrappers and object. +assert.doesNotThrow(() => assert.deepEqual(new String('a'), ['a']), + AssertionError); +assert.doesNotThrow(() => assert.deepEqual(new String('a'), { 0: 'a' }), + AssertionError); +assert.doesNotThrow(() => assert.deepEqual(new Number(1), {}), AssertionError); +assert.doesNotThrow(() => assert.deepEqual(new Boolean(true), {}), + AssertionError); + +// Same number of keys but different key names. +assert.throws(() => assert.deepEqual({ a: 1 }, { b: 1 }), AssertionError); + +assert.doesNotThrow( + () => assert.deepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14)), + 'deepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))' +); + +assert.throws( + () => assert.deepStrictEqual(new Date(), new Date(2000, 3, 14)), + AssertionError, + 'deepStrictEqual(new Date(), new Date(2000, 3, 14))' +); + +assert.throws( + () => assert.notDeepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14)), + AssertionError, + 'notDeepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))' +); + +assert.doesNotThrow( + () => assert.notDeepStrictEqual(new Date(), new Date(2000, 3, 14)), + 'notDeepStrictEqual(new Date(), new Date(2000, 3, 14))' +); + +assert.deepStrictEqual(/a/, /a/); +assert.deepStrictEqual(/a/g, /a/g); +assert.deepStrictEqual(/a/i, /a/i); +assert.deepStrictEqual(/a/m, /a/m); +assert.deepStrictEqual(/a/igm, /a/igm); +common.expectsError( + () => assert.deepStrictEqual(/ab/, /a/), + { + code: 'ERR_ASSERTION', + name: 'AssertionError [ERR_ASSERTION]', + message: '/ab/ deepStrictEqual /a/' + }); +common.expectsError( + () => assert.deepStrictEqual(/a/g, /a/), + { + code: 'ERR_ASSERTION', + name: 'AssertionError [ERR_ASSERTION]', + message: '/a/g deepStrictEqual /a/' + }); +common.expectsError( + () => assert.deepStrictEqual(/a/i, /a/), + { + code: 'ERR_ASSERTION', + name: 'AssertionError [ERR_ASSERTION]', + message: '/a/i deepStrictEqual /a/' + }); +common.expectsError( + () => assert.deepStrictEqual(/a/m, /a/), + { + code: 'ERR_ASSERTION', + name: 'AssertionError [ERR_ASSERTION]', + message: '/a/m deepStrictEqual /a/' + }); +common.expectsError( + () => assert.deepStrictEqual(/a/igm, /a/im), + { + code: 'ERR_ASSERTION', + name: 'AssertionError [ERR_ASSERTION]', + message: '/a/gim deepStrictEqual /a/im' + }); + +{ + const re1 = /a/; + re1.lastIndex = 3; + assert.doesNotThrow(() => assert.deepStrictEqual(re1, /a/)); +} + +assert.throws(() => assert.deepStrictEqual(4, '4'), + AssertionError, + 'deepStrictEqual(4, \'4\')'); + +assert.throws(() => assert.deepStrictEqual(true, 1), + AssertionError, + 'deepStrictEqual(true, 1)'); + +assert.throws(() => assert.deepStrictEqual(4, '5'), + AssertionError, + 'deepStrictEqual(4, \'5\')'); + +// Having the same number of owned properties && the same set of keys. +assert.deepStrictEqual({ a: 4 }, { a: 4 }); +assert.deepStrictEqual({ a: 4, b: '2' }, { a: 4, b: '2' }); +common.expectsError(() => assert.deepStrictEqual([4], ['4']), + { + code: 'ERR_ASSERTION', + name: 'AssertionError [ERR_ASSERTION]', + message: "[ 4 ] deepStrictEqual [ '4' ]" + }); +common.expectsError(() => assert.deepStrictEqual({ a: 4 }, { a: 4, b: true }), + { + code: 'ERR_ASSERTION', + name: 'AssertionError [ERR_ASSERTION]', + message: '{ a: 4 } deepStrictEqual { a: 4, b: true }' + }); +common.expectsError(() => assert.deepStrictEqual(['a'], { 0: 'a' }), + { + code: 'ERR_ASSERTION', + name: 'AssertionError [ERR_ASSERTION]', + message: "[ 'a' ] deepStrictEqual { '0': 'a' }" + }); + /* eslint-enable */ + +assert.doesNotThrow( + () => assert.deepStrictEqual({ a: 4, b: '1' }, { b: '1', a: 4 })); + +assert.throws( + () => assert.deepStrictEqual([0, 1, 2, 'a', 'b'], [0, 1, 2, 'b', 'a']), + AssertionError); + +assert.doesNotThrow(() => assert.deepStrictEqual(a1, a2)); + +// Prototype check. +function Constructor1(first, last) { + this.first = first; + this.last = last; +} + +function Constructor2(first, last) { + this.first = first; + this.last = last; +} + +const obj1 = new Constructor1('Ryan', 'Dahl'); +let obj2 = new Constructor2('Ryan', 'Dahl'); + +assert.throws(() => assert.deepStrictEqual(obj1, obj2), AssertionError); + +Constructor2.prototype = Constructor1.prototype; +obj2 = new Constructor2('Ryan', 'Dahl'); + +assert.doesNotThrow(() => assert.deepStrictEqual(obj1, obj2)); + +// primitives +assert.throws(() => assert.deepStrictEqual(4, '4'), AssertionError); +assert.throws(() => assert.deepStrictEqual(true, 1), AssertionError); +assert.throws(() => assert.deepStrictEqual(Symbol(), Symbol()), + AssertionError); + +const s = Symbol(); +assert.doesNotThrow(() => assert.deepStrictEqual(s, s)); + +// Primitives and object. +assert.throws(() => assert.deepStrictEqual(null, {}), AssertionError); +assert.throws(() => assert.deepStrictEqual(undefined, {}), AssertionError); +assert.throws(() => assert.deepStrictEqual('a', ['a']), AssertionError); +assert.throws(() => assert.deepStrictEqual('a', { 0: 'a' }), AssertionError); +assert.throws(() => assert.deepStrictEqual(1, {}), AssertionError); +assert.throws(() => assert.deepStrictEqual(true, {}), AssertionError); +assert.throws(() => assert.deepStrictEqual(Symbol(), {}), AssertionError); + +// Primitive wrappers and object. +assert.throws(() => assert.deepStrictEqual(new String('a'), ['a']), + AssertionError); +assert.throws(() => assert.deepStrictEqual(new String('a'), { 0: 'a' }), + AssertionError); +assert.throws(() => assert.deepStrictEqual(new Number(1), {}), AssertionError); +assert.throws(() => assert.deepStrictEqual(new Boolean(true), {}), + AssertionError); diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 96d5ff20a5ce26..85f96287877583 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -28,428 +28,100 @@ const assert = require('assert'); const { inspect } = require('util'); const a = assert; -function makeBlock(f) { - const args = Array.prototype.slice.call(arguments, 1); - return () => { - return f.apply(null, args); - }; -} - assert.ok(a.AssertionError.prototype instanceof Error, 'a.AssertionError instanceof Error'); -assert.throws(makeBlock(a, false), a.AssertionError, 'ok(false)'); +assert.throws(() => a(false), a.AssertionError, 'ok(false)'); -assert.doesNotThrow(makeBlock(a, true), a.AssertionError, 'ok(true)'); +assert.doesNotThrow(() => a(true), a.AssertionError, 'ok(true)'); -assert.doesNotThrow(makeBlock(a, 'test', 'ok(\'test\')')); +assert.doesNotThrow(() => a('test', 'ok(\'test\')')); -assert.throws(makeBlock(a.ok, false), - a.AssertionError, 'ok(false)'); +assert.throws(() => a.ok(false), a.AssertionError, 'ok(false)'); -assert.doesNotThrow(makeBlock(a.ok, true), - a.AssertionError, 'ok(true)'); +assert.doesNotThrow(() => a.ok(true), a.AssertionError, 'ok(true)'); -assert.doesNotThrow(makeBlock(a.ok, 'test'), 'ok(\'test\')'); +assert.doesNotThrow(() => a.ok('test'), 'ok(\'test\')'); -assert.throws(makeBlock(a.equal, true, false), +assert.throws(() => a.equal(true, false), a.AssertionError, 'equal(true, false)'); -assert.doesNotThrow(makeBlock(a.equal, null, null), - 'equal(null, null)'); +assert.doesNotThrow(() => a.equal(null, null), 'equal(null, null)'); -assert.doesNotThrow(makeBlock(a.equal, undefined, undefined), +assert.doesNotThrow(() => a.equal(undefined, undefined), 'equal(undefined, undefined)'); -assert.doesNotThrow(makeBlock(a.equal, null, undefined), - 'equal(null, undefined)'); +assert.doesNotThrow(() => a.equal(null, undefined), 'equal(null, undefined)'); -assert.doesNotThrow(makeBlock(a.equal, true, true), 'equal(true, true)'); +assert.doesNotThrow(() => a.equal(true, true), 'equal(true, true)'); -assert.doesNotThrow(makeBlock(a.equal, 2, '2'), 'equal(2, \'2\')'); +assert.doesNotThrow(() => a.equal(2, '2'), 'equal(2, \'2\')'); -assert.doesNotThrow(makeBlock(a.notEqual, true, false), - 'notEqual(true, false)'); +assert.doesNotThrow(() => a.notEqual(true, false), 'notEqual(true, false)'); -assert.throws(makeBlock(a.notEqual, true, true), +assert.throws(() => a.notEqual(true, true), a.AssertionError, 'notEqual(true, true)'); -assert.throws(makeBlock(a.strictEqual, 2, '2'), +assert.throws(() => a.strictEqual(2, '2'), a.AssertionError, 'strictEqual(2, \'2\')'); -assert.throws(makeBlock(a.strictEqual, null, undefined), +assert.throws(() => a.strictEqual(null, undefined), a.AssertionError, 'strictEqual(null, undefined)'); -assert.throws(makeBlock(a.notStrictEqual, 2, 2), +assert.throws(() => a.notStrictEqual(2, 2), a.AssertionError, 'notStrictEqual(2, 2)'); -assert.doesNotThrow(makeBlock(a.notStrictEqual, 2, '2'), - 'notStrictEqual(2, \'2\')'); - -// deepEqual joy! -assert.doesNotThrow(makeBlock(a.deepEqual, new Date(2000, 3, 14), - new Date(2000, 3, 14)), - 'deepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))'); - -assert.throws(makeBlock(a.deepEqual, new Date(), new Date(2000, 3, 14)), - a.AssertionError, - 'deepEqual(new Date(), new Date(2000, 3, 14))'); - -assert.throws( - makeBlock(a.notDeepEqual, new Date(2000, 3, 14), new Date(2000, 3, 14)), - a.AssertionError, - 'notDeepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))' -); - -assert.doesNotThrow(makeBlock( - a.notDeepEqual, - new Date(), - new Date(2000, 3, 14)), - 'notDeepEqual(new Date(), new Date(2000, 3, 14))' -); - -assert.doesNotThrow(makeBlock(a.deepEqual, /a/, /a/)); -assert.doesNotThrow(makeBlock(a.deepEqual, /a/g, /a/g)); -assert.doesNotThrow(makeBlock(a.deepEqual, /a/i, /a/i)); -assert.doesNotThrow(makeBlock(a.deepEqual, /a/m, /a/m)); -assert.doesNotThrow(makeBlock(a.deepEqual, /a/igm, /a/igm)); -assert.throws(makeBlock(a.deepEqual, /ab/, /a/), - common.expectsError({ - code: 'ERR_ASSERTION', - type: a.AssertionError, - message: /^\/ab\/ deepEqual \/a\/$/ - })); -assert.throws(makeBlock(a.deepEqual, /a/g, /a/), - common.expectsError({ - code: 'ERR_ASSERTION', - type: a.AssertionError, - message: /^\/a\/g deepEqual \/a\/$/ - })); -assert.throws(makeBlock(a.deepEqual, /a/i, /a/), - common.expectsError({ - code: 'ERR_ASSERTION', - type: a.AssertionError, - message: /^\/a\/i deepEqual \/a\/$/ - })); -assert.throws(makeBlock(a.deepEqual, /a/m, /a/), - common.expectsError({ - code: 'ERR_ASSERTION', - type: a.AssertionError, - message: /^\/a\/m deepEqual \/a\/$/ - })); -assert.throws(makeBlock(a.deepEqual, /a/igm, /a/im), - common.expectsError({ - code: 'ERR_ASSERTION', - type: a.AssertionError, - message: /^\/a\/gim deepEqual \/a\/im$/ - })); - -{ - const re1 = /a/g; - re1.lastIndex = 3; - assert.doesNotThrow(makeBlock(a.deepEqual, re1, /a/g)); -} - -assert.doesNotThrow(makeBlock(a.deepEqual, 4, '4'), 'deepEqual(4, \'4\')'); -assert.doesNotThrow(makeBlock(a.deepEqual, true, 1), 'deepEqual(true, 1)'); -assert.throws(makeBlock(a.deepEqual, 4, '5'), - a.AssertionError, - 'deepEqual( 4, \'5\')'); - -// having the same number of owned properties && the same set of keys -assert.doesNotThrow(makeBlock(a.deepEqual, { a: 4 }, { a: 4 })); -assert.doesNotThrow(makeBlock(a.deepEqual, { a: 4, b: '2' }, { a: 4, b: '2' })); -assert.doesNotThrow(makeBlock(a.deepEqual, [4], ['4'])); -assert.throws(makeBlock(a.deepEqual, { a: 4 }, { a: 4, b: true }), - a.AssertionError); -assert.doesNotThrow(makeBlock(a.deepEqual, ['a'], { 0: 'a' })); -//(although not necessarily the same order), -assert.doesNotThrow(makeBlock(a.deepEqual, { a: 4, b: '1' }, { b: '1', a: 4 })); -const a1 = [1, 2, 3]; -const a2 = [1, 2, 3]; -a1.a = 'test'; -a1.b = true; -a2.b = true; -a2.a = 'test'; -assert.throws(makeBlock(a.deepEqual, Object.keys(a1), Object.keys(a2)), - a.AssertionError); -assert.doesNotThrow(makeBlock(a.deepEqual, a1, a2)); - -// having an identical prototype property -const nbRoot = { - toString() { return `${this.first} ${this.last}`; } -}; - -function nameBuilder(first, last) { - this.first = first; - this.last = last; - return this; -} -nameBuilder.prototype = nbRoot; - -function nameBuilder2(first, last) { - this.first = first; - this.last = last; - return this; -} -nameBuilder2.prototype = nbRoot; - -const nb1 = new nameBuilder('Ryan', 'Dahl'); -let nb2 = new nameBuilder2('Ryan', 'Dahl'); - -assert.doesNotThrow(makeBlock(a.deepEqual, nb1, nb2)); - -nameBuilder2.prototype = Object; -nb2 = new nameBuilder2('Ryan', 'Dahl'); -assert.doesNotThrow(makeBlock(a.deepEqual, nb1, nb2)); - -// primitives and object -assert.throws(makeBlock(a.deepEqual, null, {}), a.AssertionError); -assert.throws(makeBlock(a.deepEqual, undefined, {}), a.AssertionError); -assert.throws(makeBlock(a.deepEqual, 'a', ['a']), a.AssertionError); -assert.throws(makeBlock(a.deepEqual, 'a', { 0: 'a' }), a.AssertionError); -assert.throws(makeBlock(a.deepEqual, 1, {}), a.AssertionError); -assert.throws(makeBlock(a.deepEqual, true, {}), a.AssertionError); -assert.throws(makeBlock(a.deepEqual, Symbol(), {}), a.AssertionError); - -// primitive wrappers and object -assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), ['a']), - a.AssertionError); -assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), { 0: 'a' }), - a.AssertionError); -assert.doesNotThrow(makeBlock(a.deepEqual, new Number(1), {}), - a.AssertionError); -assert.doesNotThrow(makeBlock(a.deepEqual, new Boolean(true), {}), - a.AssertionError); - -// same number of keys but different key names -assert.throws(makeBlock(a.deepEqual, { a: 1 }, { b: 1 }), a.AssertionError); - -//deepStrictEqual -assert.doesNotThrow( - makeBlock(a.deepStrictEqual, new Date(2000, 3, 14), new Date(2000, 3, 14)), - 'deepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))' -); - -assert.throws( - makeBlock(a.deepStrictEqual, new Date(), new Date(2000, 3, 14)), - a.AssertionError, - 'deepStrictEqual(new Date(), new Date(2000, 3, 14))' -); - -assert.throws( - makeBlock(a.notDeepStrictEqual, new Date(2000, 3, 14), new Date(2000, 3, 14)), - a.AssertionError, - 'notDeepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))' -); - -assert.doesNotThrow( - makeBlock(a.notDeepStrictEqual, new Date(), new Date(2000, 3, 14)), - 'notDeepStrictEqual(new Date(), new Date(2000, 3, 14))' -); - -assert.doesNotThrow(makeBlock(a.deepStrictEqual, /a/, /a/)); -assert.doesNotThrow(makeBlock(a.deepStrictEqual, /a/g, /a/g)); -assert.doesNotThrow(makeBlock(a.deepStrictEqual, /a/i, /a/i)); -assert.doesNotThrow(makeBlock(a.deepStrictEqual, /a/m, /a/m)); -assert.doesNotThrow(makeBlock(a.deepStrictEqual, /a/igm, /a/igm)); -assert.throws( - makeBlock(a.deepStrictEqual, /ab/, /a/), - common.expectsError({ - code: 'ERR_ASSERTION', - type: a.AssertionError, - message: /^\/ab\/ deepStrictEqual \/a\/$/ - })); -assert.throws( - makeBlock(a.deepStrictEqual, /a/g, /a/), - common.expectsError({ - code: 'ERR_ASSERTION', - type: a.AssertionError, - message: /^\/a\/g deepStrictEqual \/a\/$/ - })); -assert.throws( - makeBlock(a.deepStrictEqual, /a/i, /a/), - common.expectsError({ - code: 'ERR_ASSERTION', - type: a.AssertionError, - message: /^\/a\/i deepStrictEqual \/a\/$/ - })); -assert.throws( - makeBlock(a.deepStrictEqual, /a/m, /a/), - common.expectsError({ - code: 'ERR_ASSERTION', - type: a.AssertionError, - message: /^\/a\/m deepStrictEqual \/a\/$/ - })); -assert.throws( - makeBlock(a.deepStrictEqual, /a/igm, /a/im), - common.expectsError({ - code: 'ERR_ASSERTION', - type: a.AssertionError, - message: /^\/a\/gim deepStrictEqual \/a\/im$/ - })); - -{ - const re1 = /a/; - re1.lastIndex = 3; - assert.doesNotThrow(makeBlock(a.deepStrictEqual, re1, /a/)); -} - -assert.throws(makeBlock(a.deepStrictEqual, 4, '4'), - a.AssertionError, - 'deepStrictEqual(4, \'4\')'); - -assert.throws(makeBlock(a.deepStrictEqual, true, 1), - a.AssertionError, - 'deepStrictEqual(true, 1)'); - -assert.throws(makeBlock(a.deepStrictEqual, 4, '5'), - a.AssertionError, - 'deepStrictEqual(4, \'5\')'); - -// having the same number of owned properties && the same set of keys -assert.doesNotThrow(makeBlock(a.deepStrictEqual, { a: 4 }, { a: 4 })); -assert.doesNotThrow(makeBlock(a.deepStrictEqual, - { a: 4, b: '2' }, - { a: 4, b: '2' })); -assert.throws(makeBlock(a.deepStrictEqual, [4], ['4']), - common.expectsError({ - code: 'ERR_ASSERTION', - type: a.AssertionError, - message: /^\[ 4 ] deepStrictEqual \[ '4' ]$/ - })); -assert.throws(makeBlock(a.deepStrictEqual, { a: 4 }, { a: 4, b: true }), - common.expectsError({ - code: 'ERR_ASSERTION', - type: a.AssertionError, - message: /^{ a: 4 } deepStrictEqual { a: 4, b: true }$/ - })); -assert.throws(makeBlock(a.deepStrictEqual, ['a'], { 0: 'a' }), - common.expectsError({ - code: 'ERR_ASSERTION', - type: a.AssertionError, - message: /^\[ 'a' ] deepStrictEqual { '0': 'a' }$/ - })); -//(although not necessarily the same order), -assert.doesNotThrow(makeBlock(a.deepStrictEqual, - { a: 4, b: '1' }, - { b: '1', a: 4 })); - -assert.throws(makeBlock(a.deepStrictEqual, - [0, 1, 2, 'a', 'b'], - [0, 1, 2, 'b', 'a']), - a.AssertionError); - -assert.doesNotThrow(makeBlock(a.deepStrictEqual, a1, a2)); - -// Prototype check -function Constructor1(first, last) { - this.first = first; - this.last = last; -} - -function Constructor2(first, last) { - this.first = first; - this.last = last; -} - -const obj1 = new Constructor1('Ryan', 'Dahl'); -let obj2 = new Constructor2('Ryan', 'Dahl'); - -assert.throws(makeBlock(a.deepStrictEqual, obj1, obj2), a.AssertionError); - -Constructor2.prototype = Constructor1.prototype; -obj2 = new Constructor2('Ryan', 'Dahl'); - -assert.doesNotThrow(makeBlock(a.deepStrictEqual, obj1, obj2)); - -// primitives -assert.throws(makeBlock(assert.deepStrictEqual, 4, '4'), - a.AssertionError); -assert.throws(makeBlock(assert.deepStrictEqual, true, 1), - a.AssertionError); -assert.throws(makeBlock(assert.deepStrictEqual, Symbol(), Symbol()), - a.AssertionError); - -const s = Symbol(); -assert.doesNotThrow(makeBlock(assert.deepStrictEqual, s, s)); - +assert.doesNotThrow(() => a.notStrictEqual(2, '2'), 'notStrictEqual(2, \'2\')'); -// primitives and object -assert.throws(makeBlock(a.deepStrictEqual, null, {}), a.AssertionError); -assert.throws(makeBlock(a.deepStrictEqual, undefined, {}), a.AssertionError); -assert.throws(makeBlock(a.deepStrictEqual, 'a', ['a']), a.AssertionError); -assert.throws(makeBlock(a.deepStrictEqual, 'a', { 0: 'a' }), a.AssertionError); -assert.throws(makeBlock(a.deepStrictEqual, 1, {}), a.AssertionError); -assert.throws(makeBlock(a.deepStrictEqual, true, {}), a.AssertionError); -assert.throws(makeBlock(assert.deepStrictEqual, Symbol(), {}), - a.AssertionError); - - -// primitive wrappers and object -assert.throws(makeBlock(a.deepStrictEqual, new String('a'), ['a']), - a.AssertionError); -assert.throws(makeBlock(a.deepStrictEqual, new String('a'), { 0: 'a' }), - a.AssertionError); -assert.throws(makeBlock(a.deepStrictEqual, new Number(1), {}), - a.AssertionError); -assert.throws(makeBlock(a.deepStrictEqual, new Boolean(true), {}), - a.AssertionError); - - -// Testing the throwing +// Testing the throwing. function thrower(errorConstructor) { throw new errorConstructor({}); } -// the basic calls work -assert.throws(makeBlock(thrower, a.AssertionError), - a.AssertionError, 'message'); -assert.throws(makeBlock(thrower, a.AssertionError), a.AssertionError); +// The basic calls work. +assert.throws(() => thrower(a.AssertionError), a.AssertionError, 'message'); +assert.throws(() => thrower(a.AssertionError), a.AssertionError); // eslint-disable-next-line no-restricted-syntax -assert.throws(makeBlock(thrower, a.AssertionError)); +assert.throws(() => thrower(a.AssertionError)); -// if not passing an error, catch all. +// If not passing an error, catch all. // eslint-disable-next-line no-restricted-syntax -assert.throws(makeBlock(thrower, TypeError)); +assert.throws(() => thrower(TypeError)); -// when passing a type, only catch errors of the appropriate type +// When passing a type, only catch errors of the appropriate type. { let threw = false; try { - a.throws(makeBlock(thrower, TypeError), a.AssertionError); + a.throws(() => thrower(TypeError), a.AssertionError); } catch (e) { threw = true; assert.ok(e instanceof TypeError, 'type'); } - assert.strictEqual(true, threw, - 'a.throws with an explicit error is eating extra errors'); + assert.ok(threw, 'a.throws with an explicit error is eating extra errors'); } -// doesNotThrow should pass through all errors +// doesNotThrow should pass through all errors. { let threw = false; try { - a.doesNotThrow(makeBlock(thrower, TypeError), a.AssertionError); + a.doesNotThrow(() => thrower(TypeError), a.AssertionError); } catch (e) { threw = true; assert.ok(e instanceof TypeError); } - assert.strictEqual(true, threw, 'a.doesNotThrow with an explicit error is ' + - 'eating extra errors'); + assert(threw, 'a.doesNotThrow with an explicit error is eating extra errors'); } -// key difference is that throwing our correct error makes an assertion error +// Key difference is that throwing our correct error makes an assertion error. { let threw = false; try { - a.doesNotThrow(makeBlock(thrower, TypeError), TypeError); + a.doesNotThrow(() => thrower(TypeError), TypeError); } catch (e) { threw = true; assert.ok(e instanceof a.AssertionError); } - assert.strictEqual(true, threw, - 'a.doesNotThrow is not catching type matching errors'); + assert.ok(threw, 'a.doesNotThrow is not catching type matching errors'); } assert.throws(() => { assert.ifError(new Error('test error')); }, @@ -458,7 +130,7 @@ assert.doesNotThrow(() => { assert.ifError(null); }); assert.doesNotThrow(() => { assert.ifError(); }); common.expectsError( - () => assert.doesNotThrow(makeBlock(thrower, Error), 'user message'), + () => assert.doesNotThrow(() => thrower(Error), 'user message'), { type: a.AssertionError, code: 'ERR_ASSERTION', @@ -468,7 +140,7 @@ common.expectsError( ); common.expectsError( - () => assert.doesNotThrow(makeBlock(thrower, Error), 'user message'), + () => assert.doesNotThrow(() => thrower(Error), 'user message'), { code: 'ERR_ASSERTION', message: /Got unwanted exception: user message\n\[object Object\]/ @@ -476,14 +148,14 @@ common.expectsError( ); common.expectsError( - () => assert.doesNotThrow(makeBlock(thrower, Error)), + () => assert.doesNotThrow(() => thrower(Error)), { code: 'ERR_ASSERTION', message: /Got unwanted exception\.\n\[object Object\]/ } ); -// make sure that validating using constructor really works +// Make sure that validating using constructor really works. { let threw = false; try { @@ -499,11 +171,11 @@ common.expectsError( assert.ok(threw, 'wrong constructor validation'); } -// use a RegExp to validate error message -a.throws(makeBlock(thrower, TypeError), /\[object Object\]/); +// Use a RegExp to validate the error message. +a.throws(() => thrower(TypeError), /\[object Object\]/); -// use a fn to validate error object -a.throws(makeBlock(thrower, TypeError), (err) => { +// Use a fn to validate the error object. +a.throws(() => thrower(TypeError), (err) => { if ((err instanceof TypeError) && /\[object Object\]/.test(err)) { return true; } @@ -512,18 +184,12 @@ a.throws(makeBlock(thrower, TypeError), (err) => { // https://github.com/nodejs/node/issues/3188 { let threw = false; - let AnotherErrorType; try { const ES6Error = class extends Error {}; - AnotherErrorType = class extends Error {}; - const functionThatThrows = () => { - throw new AnotherErrorType('foo'); - }; - - assert.throws(functionThatThrows, ES6Error); + assert.throws(() => { throw new AnotherErrorType('foo'); }, ES6Error); } catch (e) { threw = true; assert(e instanceof AnotherErrorType, @@ -533,7 +199,7 @@ a.throws(makeBlock(thrower, TypeError), (err) => { assert.ok(threw); } -// check messages from assert.throws() +// Check messages from assert.throws(). { const noop = () => {}; assert.throws( @@ -638,7 +304,7 @@ try { let threw = false; const rangeError = new RangeError('my range'); - // verify custom errors + // Verify custom errors. try { assert.strictEqual(1, 2, rangeError); } catch (e) { @@ -649,7 +315,7 @@ try { assert.ok(threw); threw = false; - // verify AssertionError is the result from doesNotThrow with custom Error + // Verify AssertionError is the result from doesNotThrow with custom Error. try { assert.doesNotThrow(() => { throw new TypeError('wrong type'); @@ -664,7 +330,7 @@ try { } { - // Verify that throws() and doesNotThrow() throw on non-function block + // Verify that throws() and doesNotThrow() throw on non-function block. function typeName(value) { return value === null ? 'null' : typeof value; } @@ -715,7 +381,7 @@ assert.throws(() => { })); { - // bad args to AssertionError constructor should throw TypeError + // Bad args to AssertionError constructor should throw TypeError. const args = [1, true, false, '', null, Infinity, Symbol('test'), undefined]; const re = /^The "options" argument must be of type Object$/; args.forEach((input) => { From 9a063f9368bb098d96849572b9da1cae7d8dad8c Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Fri, 9 Feb 2018 02:32:04 +0100 Subject: [PATCH 02/16] test: remove assert.doesNotThrow() There is actually no reason to use `assert.doesNotThrow()` in the tests. If a test throws, just let the error bubble up right away instead of first catching it and then rethrowing it. PR-URL: https://github.com/nodejs/node/pull/18669 Reviewed-By: Ben Noordhuis Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: Matteo Collina --- test/addons-napi/test_general/test.js | 2 +- test/addons/symlinked-module/test.js | 2 +- test/internet/test-dgram-membership.js | 10 +- test/internet/test-dns.js | 12 +- test/parallel/test-assert-checktag.js | 8 +- test/parallel/test-assert-deep.js | 86 ++++++-------- test/parallel/test-assert.js | 36 +++--- test/parallel/test-buffer-alloc.js | 30 ++--- test/parallel/test-buffer-bad-overload.js | 8 +- test/parallel/test-buffer-constants.js | 2 +- test/parallel/test-buffer-copy.js | 2 +- test/parallel/test-buffer-fill.js | 10 +- test/parallel/test-buffer-inspect.js | 6 +- test/parallel/test-buffer-read.js | 6 +- .../parallel/test-buffer-sharedarraybuffer.js | 2 +- test/parallel/test-buffer-slice.js | 2 +- test/parallel/test-child-process-detached.js | 4 +- .../test-child-process-spawn-typeerror.js | 109 ++++++++---------- .../test-console-async-write-error.js | 5 +- test/parallel/test-console-instance.js | 4 +- .../parallel/test-console-sync-write-error.js | 13 +-- test/parallel/test-console.js | 20 ++-- test/parallel/test-crypto-binary-default.js | 4 +- test/parallel/test-crypto-cipher-decipher.js | 12 +- test/parallel/test-crypto-dh-odd-key.js | 2 +- test/parallel/test-crypto-dh.js | 4 +- test/parallel/test-crypto-padding.js | 26 ++--- test/parallel/test-crypto-pbkdf2.js | 8 +- test/parallel/test-crypto-rsa-dsa.js | 13 +-- test/parallel/test-crypto.js | 4 +- test/parallel/test-dgram-createSocket-type.js | 6 +- test/parallel/test-dns-lookup.js | 86 +++++++------- test/parallel/test-dns.js | 53 ++++----- ...ad-after-set-uncaught-exception-capture.js | 3 +- ...test-event-emitter-remove-all-listeners.js | 2 +- test/parallel/test-fs-access.js | 11 +- test/parallel/test-fs-buffer.js | 22 ++-- test/parallel/test-fs-exists.js | 3 +- test/parallel/test-fs-make-callback.js | 3 +- test/parallel/test-fs-makeStatsCallback.js | 5 +- test/parallel/test-fs-mkdtemp.js | 4 +- test/parallel/test-fs-options-immutable.js | 63 +++------- .../test-fs-read-stream-throw-type-error.js | 17 +-- .../test-fs-timestamp-parsing-error.js | 3 +- .../test-fs-write-stream-throw-type-error.js | 20 +--- ...est-http-client-reject-unexpected-agent.js | 2 +- test/parallel/test-http-header-read.js | 6 +- .../test-http-hostname-typechecking.js | 7 +- test/parallel/test-http-invalidheaderfield.js | 22 ++-- ...est-http-response-add-header-after-sent.js | 5 +- ...-http-response-remove-header-after-sent.js | 5 +- test/parallel/test-http2-binding.js | 2 +- ...t-http2-client-rststream-before-connect.js | 2 +- .../test-http2-compat-serverrequest-pause.js | 4 +- ...t-http2-compat-serverrequest-settimeout.js | 5 +- ...est-http2-compat-serverresponse-destroy.js | 5 +- ...at-serverresponse-headers-after-destroy.js | 8 +- ...-http2-compat-serverresponse-settimeout.js | 5 +- ...-http2-compat-serverresponse-statuscode.js | 10 +- test/parallel/test-http2-compat-socket.js | 2 +- test/parallel/test-http2-connect.js | 24 ++-- test/parallel/test-http2-getpackedsettings.js | 10 +- test/parallel/test-http2-server-startup.js | 25 ++-- test/parallel/test-http2-session-settings.js | 4 +- test/parallel/test-http2-socket-proxy.js | 4 +- test/parallel/test-http2-util-asserts.js | 5 +- test/parallel/test-http2-withflag.js | 3 +- test/parallel/test-https-agent-constructor.js | 2 +- .../test-https-options-boolean-check.js | 19 ++- test/parallel/test-icu-punycode.js | 5 +- test/parallel/test-internal-errors.js | 42 +++---- test/parallel/test-internal-fs.js | 5 +- .../test-internal-util-assertCrypto.js | 2 +- ...test-internal-util-decorate-error-stack.js | 10 +- .../test-module-symlinked-peer-modules.js | 5 +- test/parallel/test-net-after-close.js | 18 ++- .../parallel/test-net-connect-options-port.js | 21 ++-- test/parallel/test-net-during-close.js | 9 +- test/parallel/test-net-options-lookup.js | 5 +- ...t-net-server-call-listen-multiple-times.js | 15 +-- test/parallel/test-net-socket-timeout.js | 4 +- test/parallel/test-performanceobserver.js | 10 +- test/parallel/test-process-binding.js | 8 +- test/parallel/test-process-emitwarning.js | 2 +- test/parallel/test-process-env-symbols.js | 2 +- test/parallel/test-process-geteuid-getegid.js | 6 +- test/parallel/test-process-setuid-setgid.js | 6 +- test/parallel/test-querystring.js | 4 +- test/parallel/test-readline-csi.js | 12 +- test/parallel/test-readline-interface.js | 23 +--- test/parallel/test-repl-null.js | 6 +- .../test-repl-throw-null-or-undefined.js | 15 +-- test/parallel/test-stdio-closed.js | 2 +- test/parallel/test-stream-writable-null.js | 17 +-- ...-timers-clear-null-does-not-throw-error.js | 19 +-- test/parallel/test-timers-unref.js | 10 +- test/parallel/test-tls-client-abort.js | 8 +- test/parallel/test-tls-client-abort2.js | 5 +- test/parallel/test-tls-legacy-deprecated.js | 3 +- .../test-tls-options-boolean-check.js | 13 +-- test/parallel/test-util-inspect-proxy.js | 2 +- test/parallel/test-util-inspect.js | 32 +++-- test/parallel/test-uv-errno.js | 14 +-- test/parallel/test-v8-global-setter.js | 6 - test/parallel/test-vm-access-process-env.js | 8 +- test/parallel/test-vm-create-context-arg.js | 14 +-- test/parallel/test-vm-cross-context.js | 5 +- test/parallel/test-vm-proxy-failure-CP.js | 3 +- .../test-whatwg-encoding-textdecoder.js | 14 +-- .../test-whatwg-encoding-textencoder.js | 6 +- test/parallel/test-zlib-close-after-error.js | 2 +- .../test-zlib-deflate-constructors.js | 24 +--- test/parallel/test-zlib-flush-flags.js | 9 +- test/parallel/test-zlib-invalid-input.js | 8 +- test/parallel/test-zlib-truncated.js | 12 +- test/parallel/test-zlib.js | 4 +- test/pummel/test-fs-largefile.js | 4 +- test/pummel/test-fs-watch-file.js | 70 +++++------ .../sequential/test-child-process-execsync.js | 4 +- test/sequential/test-fs-watch.js | 68 +++++------ test/sequential/test-inspector-module.js | 11 +- test/sequential/test-performance.js | 2 +- test/sequential/test-tls-lookup.js | 5 +- 123 files changed, 584 insertions(+), 994 deletions(-) diff --git a/test/addons-napi/test_general/test.js b/test/addons-napi/test_general/test.js index bcaa13d894bedc..fa6240d384a0fd 100644 --- a/test/addons-napi/test_general/test.js +++ b/test/addons-napi/test_general/test.js @@ -81,7 +81,7 @@ const y = {}; test_general.wrap(y); test_general.removeWrap(y); // Wrapping twice succeeds if a remove_wrap() separates the instances -assert.doesNotThrow(() => test_general.wrap(y)); +test_general.wrap(y); // Ensure that removing a wrap and garbage collecting does not fire the // finalize callback. diff --git a/test/addons/symlinked-module/test.js b/test/addons/symlinked-module/test.js index e8c26544f2a38c..98eec17d0c8c95 100644 --- a/test/addons/symlinked-module/test.js +++ b/test/addons/symlinked-module/test.js @@ -30,5 +30,5 @@ const sub = require('./submodule'); const mod = require(path.join(i, 'binding.node')); assert.notStrictEqual(mod, null); assert.strictEqual(mod.hello(), 'world'); - assert.doesNotThrow(() => sub.test(i)); + sub.test(i); }); diff --git a/test/internet/test-dgram-membership.js b/test/internet/test-dgram-membership.js index 97bc1e648ad79e..d4bad5c2daa08c 100644 --- a/test/internet/test-dgram-membership.js +++ b/test/internet/test-dgram-membership.js @@ -10,7 +10,7 @@ const setup = dgram.createSocket.bind(dgram, { type: 'udp4', reuseAddr: true }); // addMembership() with valid socket and multicast address should not throw { const socket = setup(); - assert.doesNotThrow(() => { socket.addMembership(multicastAddress); }); + socket.addMembership(multicastAddress); socket.close(); } @@ -27,11 +27,7 @@ const setup = dgram.createSocket.bind(dgram, { type: 'udp4', reuseAddr: true }); // dropMembership() after addMembership() should not throw { const socket = setup(); - assert.doesNotThrow( - () => { - socket.addMembership(multicastAddress); - socket.dropMembership(multicastAddress); - } - ); + socket.addMembership(multicastAddress); + socket.dropMembership(multicastAddress); socket.close(); } diff --git a/test/internet/test-dns.js b/test/internet/test-dns.js index 20d44118d782a3..dadf14c0be36b1 100644 --- a/test/internet/test-dns.js +++ b/test/internet/test-dns.js @@ -580,14 +580,10 @@ process.on('exit', function() { }); -assert.doesNotThrow(() => - dns.lookup(addresses.INET6_HOST, 6, common.mustCall())); +dns.lookup(addresses.INET6_HOST, 6, common.mustCall()); -assert.doesNotThrow(() => - dns.lookup(addresses.INET_HOST, {}, common.mustCall())); +dns.lookup(addresses.INET_HOST, {}, common.mustCall()); -assert.doesNotThrow(() => - dns.lookupService('0.0.0.0', '0', common.mustCall())); +dns.lookupService('0.0.0.0', '0', common.mustCall()); -assert.doesNotThrow(() => - dns.lookupService('0.0.0.0', 0, common.mustCall())); +dns.lookupService('0.0.0.0', 0, common.mustCall()); diff --git a/test/parallel/test-assert-checktag.js b/test/parallel/test-assert-checktag.js index c4823243e7d3e9..632bfa03c6d4bf 100644 --- a/test/parallel/test-assert-checktag.js +++ b/test/parallel/test-assert-checktag.js @@ -30,8 +30,8 @@ function re(literals, ...values) { FakeDate.prototype = Date.prototype; const fake = new FakeDate(); - assert.doesNotThrow(() => assert.deepEqual(date, fake)); - assert.doesNotThrow(() => assert.deepEqual(fake, date)); + assert.deepEqual(date, fake); + assert.deepEqual(fake, date); // For deepStrictEqual we check the runtime type, // then reveal the fakeness of the fake date @@ -47,7 +47,7 @@ function re(literals, ...values) { for (const prop of Object.keys(global)) { fakeGlobal[prop] = global[prop]; } - assert.doesNotThrow(() => assert.deepEqual(fakeGlobal, global)); + assert.deepEqual(fakeGlobal, global); // Message will be truncated anyway, don't validate assert.throws(() => assert.deepStrictEqual(fakeGlobal, global), assert.AssertionError); @@ -59,7 +59,7 @@ function re(literals, ...values) { for (const prop of Object.keys(process)) { fakeProcess[prop] = process[prop]; } - assert.doesNotThrow(() => assert.deepEqual(fakeProcess, process)); + assert.deepEqual(fakeProcess, process); // Message will be truncated anyway, don't validate assert.throws(() => assert.deepStrictEqual(fakeProcess, process), assert.AssertionError); diff --git a/test/parallel/test-assert-deep.js b/test/parallel/test-assert-deep.js index 95c4ca5532d1bb..d9c9df5bb2c875 100644 --- a/test/parallel/test-assert-deep.js +++ b/test/parallel/test-assert-deep.js @@ -34,7 +34,7 @@ const buf = Buffer.from(arr); // They have different [[Prototype]] assert.throws(() => assert.deepStrictEqual(arr, buf), re`${arr} deepStrictEqual ${buf}`); -assert.doesNotThrow(() => assert.deepEqual(arr, buf)); +assert.deepEqual(arr, buf); { const buf2 = Buffer.from(arr); @@ -42,7 +42,7 @@ assert.doesNotThrow(() => assert.deepEqual(arr, buf)); assert.throws(() => assert.deepStrictEqual(buf2, buf), re`${buf2} deepStrictEqual ${buf}`); - assert.doesNotThrow(() => assert.deepEqual(buf2, buf)); + assert.deepEqual(buf2, buf); } { @@ -50,7 +50,7 @@ assert.doesNotThrow(() => assert.deepEqual(arr, buf)); arr2.prop = 5; assert.throws(() => assert.deepStrictEqual(arr, arr2), re`${arr} deepStrictEqual ${arr2}`); - assert.doesNotThrow(() => assert.deepEqual(arr, arr2)); + assert.deepEqual(arr, arr2); } const date = new Date('2016'); @@ -66,8 +66,8 @@ const date2 = new MyDate('2016'); // deepEqual returns true as long as the time are the same, // but deepStrictEqual checks own properties -assert.doesNotThrow(() => assert.deepEqual(date, date2)); -assert.doesNotThrow(() => assert.deepEqual(date2, date)); +assert.deepEqual(date, date2); +assert.deepEqual(date2, date); assert.throws(() => assert.deepStrictEqual(date, date2), re`${date} deepStrictEqual ${date2}`); assert.throws(() => assert.deepStrictEqual(date2, date), @@ -85,7 +85,7 @@ const re2 = new MyRegExp('test'); // deepEqual returns true as long as the regexp-specific properties // are the same, but deepStrictEqual checks all properties -assert.doesNotThrow(() => assert.deepEqual(re1, re2)); +assert.deepEqual(re1, re2); assert.throws(() => assert.deepStrictEqual(re1, re2), re`${re1} deepStrictEqual ${re2}`); @@ -148,11 +148,11 @@ function assertNotDeepOrStrict(a, b, err) { } function assertOnlyDeepEqual(a, b, err) { - assert.doesNotThrow(() => assert.deepEqual(a, b)); + assert.deepEqual(a, b); assert.throws(() => assert.deepStrictEqual(a, b), err || re`${a} deepStrictEqual ${b}`); - assert.doesNotThrow(() => assert.deepEqual(b, a)); + assert.deepEqual(b, a); assert.throws(() => assert.deepStrictEqual(b, a), err || re`${b} deepStrictEqual ${a}`); } @@ -492,10 +492,9 @@ assertOnlyDeepEqual([1, , , 3], [1, , , 3, , , ]); // Handle NaN assert.throws(() => { assert.deepEqual(NaN, NaN); }, assert.AssertionError); -assert.doesNotThrow(() => { assert.deepStrictEqual(NaN, NaN); }); -assert.doesNotThrow(() => { assert.deepStrictEqual({ a: NaN }, { a: NaN }); }); -assert.doesNotThrow( - () => { assert.deepStrictEqual([ 1, 2, NaN, 4 ], [ 1, 2, NaN, 4 ]); }); +{ assert.deepStrictEqual(NaN, NaN); } +{ assert.deepStrictEqual({ a: NaN }, { a: NaN }); } +assert.deepStrictEqual([ 1, 2, NaN, 4 ], [ 1, 2, NaN, 4 ]); // Handle boxed primitives { @@ -547,9 +546,7 @@ assertDeepAndStrictEqual(-0, -0); assertDeepAndStrictEqual(a, b); } -assert.doesNotThrow( - () => assert.deepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14)), - 'deepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))'); +assert.deepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14)); assert.throws(() => assert.deepEqual(new Date(), new Date(2000, 3, 14)), AssertionError, @@ -561,10 +558,7 @@ assert.throws( 'notDeepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))' ); -assert.doesNotThrow( - () => assert.notDeepEqual(new Date(), new Date(2000, 3, 14)), - 'notDeepEqual(new Date(), new Date(2000, 3, 14))' -); +assert.notDeepEqual(new Date(), new Date(2000, 3, 14)); assert.deepEqual(/a/, /a/); assert.deepEqual(/a/g, /a/g); @@ -605,23 +599,23 @@ common.expectsError(() => assert.deepEqual(/a/igm, /a/im), { const re1 = /a/g; re1.lastIndex = 3; - assert.doesNotThrow(() => assert.deepEqual(re1, /a/g)); + assert.deepEqual(re1, /a/g); } -assert.doesNotThrow(() => assert.deepEqual(4, '4'), 'deepEqual(4, \'4\')'); -assert.doesNotThrow(() => assert.deepEqual(true, 1), 'deepEqual(true, 1)'); +assert.deepEqual(4, '4'); +assert.deepEqual(true, 1); assert.throws(() => assert.deepEqual(4, '5'), AssertionError, 'deepEqual( 4, \'5\')'); // Having the same number of owned properties && the same set of keys. -assert.doesNotThrow(() => assert.deepEqual({ a: 4 }, { a: 4 })); -assert.doesNotThrow(() => assert.deepEqual({ a: 4, b: '2' }, { a: 4, b: '2' })); -assert.doesNotThrow(() => assert.deepEqual([4], ['4'])); +assert.deepEqual({ a: 4 }, { a: 4 }); +assert.deepEqual({ a: 4, b: '2' }, { a: 4, b: '2' }); +assert.deepEqual([4], ['4']); assert.throws( () => assert.deepEqual({ a: 4 }, { a: 4, b: true }), AssertionError); -assert.doesNotThrow(() => assert.deepEqual(['a'], { 0: 'a' })); -assert.doesNotThrow(() => assert.deepEqual({ a: 4, b: '1' }, { b: '1', a: 4 })); +assert.deepEqual(['a'], { 0: 'a' }); +assert.deepEqual({ a: 4, b: '1' }, { b: '1', a: 4 }); const a1 = [1, 2, 3]; const a2 = [1, 2, 3]; a1.a = 'test'; @@ -630,7 +624,7 @@ a2.b = true; a2.a = 'test'; assert.throws(() => assert.deepEqual(Object.keys(a1), Object.keys(a2)), AssertionError); -assert.doesNotThrow(() => assert.deepEqual(a1, a2)); +assert.deepEqual(a1, a2); // Having an identical prototype property. const nbRoot = { @@ -654,11 +648,11 @@ nameBuilder2.prototype = nbRoot; const nb1 = new nameBuilder('Ryan', 'Dahl'); let nb2 = new nameBuilder2('Ryan', 'Dahl'); -assert.doesNotThrow(() => assert.deepEqual(nb1, nb2)); +assert.deepEqual(nb1, nb2); nameBuilder2.prototype = Object; nb2 = new nameBuilder2('Ryan', 'Dahl'); -assert.doesNotThrow(() => assert.deepEqual(nb1, nb2)); +assert.deepEqual(nb1, nb2); // Primitives and object. assert.throws(() => assert.deepEqual(null, {}), AssertionError); @@ -670,21 +664,15 @@ assert.throws(() => assert.deepEqual(true, {}), AssertionError); assert.throws(() => assert.deepEqual(Symbol(), {}), AssertionError); // Primitive wrappers and object. -assert.doesNotThrow(() => assert.deepEqual(new String('a'), ['a']), - AssertionError); -assert.doesNotThrow(() => assert.deepEqual(new String('a'), { 0: 'a' }), - AssertionError); -assert.doesNotThrow(() => assert.deepEqual(new Number(1), {}), AssertionError); -assert.doesNotThrow(() => assert.deepEqual(new Boolean(true), {}), - AssertionError); +assert.deepEqual(new String('a'), ['a']); +assert.deepEqual(new String('a'), { 0: 'a' }); +assert.deepEqual(new Number(1), {}); +assert.deepEqual(new Boolean(true), {}); // Same number of keys but different key names. assert.throws(() => assert.deepEqual({ a: 1 }, { b: 1 }), AssertionError); -assert.doesNotThrow( - () => assert.deepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14)), - 'deepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))' -); +assert.deepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14)); assert.throws( () => assert.deepStrictEqual(new Date(), new Date(2000, 3, 14)), @@ -698,10 +686,7 @@ assert.throws( 'notDeepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))' ); -assert.doesNotThrow( - () => assert.notDeepStrictEqual(new Date(), new Date(2000, 3, 14)), - 'notDeepStrictEqual(new Date(), new Date(2000, 3, 14))' -); +assert.notDeepStrictEqual(new Date(), new Date(2000, 3, 14)); assert.deepStrictEqual(/a/, /a/); assert.deepStrictEqual(/a/g, /a/g); @@ -747,7 +732,7 @@ common.expectsError( { const re1 = /a/; re1.lastIndex = 3; - assert.doesNotThrow(() => assert.deepStrictEqual(re1, /a/)); + assert.deepStrictEqual(re1, /a/); } assert.throws(() => assert.deepStrictEqual(4, '4'), @@ -786,14 +771,13 @@ common.expectsError(() => assert.deepStrictEqual(['a'], { 0: 'a' }), /* eslint-enable */ -assert.doesNotThrow( - () => assert.deepStrictEqual({ a: 4, b: '1' }, { b: '1', a: 4 })); +assert.deepStrictEqual({ a: 4, b: '1' }, { b: '1', a: 4 }); assert.throws( () => assert.deepStrictEqual([0, 1, 2, 'a', 'b'], [0, 1, 2, 'b', 'a']), AssertionError); -assert.doesNotThrow(() => assert.deepStrictEqual(a1, a2)); +assert.deepStrictEqual(a1, a2); // Prototype check. function Constructor1(first, last) { @@ -814,7 +798,7 @@ assert.throws(() => assert.deepStrictEqual(obj1, obj2), AssertionError); Constructor2.prototype = Constructor1.prototype; obj2 = new Constructor2('Ryan', 'Dahl'); -assert.doesNotThrow(() => assert.deepStrictEqual(obj1, obj2)); +assert.deepStrictEqual(obj1, obj2); // primitives assert.throws(() => assert.deepStrictEqual(4, '4'), AssertionError); @@ -823,7 +807,7 @@ assert.throws(() => assert.deepStrictEqual(Symbol(), Symbol()), AssertionError); const s = Symbol(); -assert.doesNotThrow(() => assert.deepStrictEqual(s, s)); +assert.deepStrictEqual(s, s); // Primitives and object. assert.throws(() => assert.deepStrictEqual(null, {}), AssertionError); diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 85f96287877583..5f863b7c297a66 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -32,32 +32,22 @@ assert.ok(a.AssertionError.prototype instanceof Error, 'a.AssertionError instanceof Error'); assert.throws(() => a(false), a.AssertionError, 'ok(false)'); - -assert.doesNotThrow(() => a(true), a.AssertionError, 'ok(true)'); - -assert.doesNotThrow(() => a('test', 'ok(\'test\')')); - assert.throws(() => a.ok(false), a.AssertionError, 'ok(false)'); -assert.doesNotThrow(() => a.ok(true), a.AssertionError, 'ok(true)'); - -assert.doesNotThrow(() => a.ok('test'), 'ok(\'test\')'); +a(true); +a('test', 'ok(\'test\')'); +a.ok(true); +a.ok('test'); assert.throws(() => a.equal(true, false), a.AssertionError, 'equal(true, false)'); -assert.doesNotThrow(() => a.equal(null, null), 'equal(null, null)'); - -assert.doesNotThrow(() => a.equal(undefined, undefined), - 'equal(undefined, undefined)'); - -assert.doesNotThrow(() => a.equal(null, undefined), 'equal(null, undefined)'); - -assert.doesNotThrow(() => a.equal(true, true), 'equal(true, true)'); - -assert.doesNotThrow(() => a.equal(2, '2'), 'equal(2, \'2\')'); - -assert.doesNotThrow(() => a.notEqual(true, false), 'notEqual(true, false)'); +a.equal(null, null); +a.equal(undefined, undefined); +a.equal(null, undefined); +a.equal(true, true); +a.equal(2, '2'); +a.notEqual(true, false); assert.throws(() => a.notEqual(true, true), a.AssertionError, 'notEqual(true, true)'); @@ -71,7 +61,7 @@ assert.throws(() => a.strictEqual(null, undefined), assert.throws(() => a.notStrictEqual(2, 2), a.AssertionError, 'notStrictEqual(2, 2)'); -assert.doesNotThrow(() => a.notStrictEqual(2, '2'), 'notStrictEqual(2, \'2\')'); +a.notStrictEqual(2, '2'); // Testing the throwing. function thrower(errorConstructor) { @@ -126,8 +116,8 @@ assert.throws(() => thrower(TypeError)); assert.throws(() => { assert.ifError(new Error('test error')); }, /^Error: test error$/); -assert.doesNotThrow(() => { assert.ifError(null); }); -assert.doesNotThrow(() => { assert.ifError(); }); +assert.ifError(null); +assert.ifError(); common.expectsError( () => assert.doesNotThrow(() => thrower(Error), 'user message'), diff --git a/test/parallel/test-buffer-alloc.js b/test/parallel/test-buffer-alloc.js index 7143133cd103ff..7f062f6b58c68c 100644 --- a/test/parallel/test-buffer-alloc.js +++ b/test/parallel/test-buffer-alloc.js @@ -63,16 +63,16 @@ assert.throws(() => b.write('test', 'utf8', 0), // try to create 0-length buffers -assert.doesNotThrow(() => Buffer.from('')); -assert.doesNotThrow(() => Buffer.from('', 'ascii')); -assert.doesNotThrow(() => Buffer.from('', 'latin1')); -assert.doesNotThrow(() => Buffer.alloc(0)); -assert.doesNotThrow(() => Buffer.allocUnsafe(0)); -assert.doesNotThrow(() => new Buffer('')); -assert.doesNotThrow(() => new Buffer('', 'ascii')); -assert.doesNotThrow(() => new Buffer('', 'latin1')); -assert.doesNotThrow(() => new Buffer('', 'binary')); -assert.doesNotThrow(() => Buffer(0)); +Buffer.from(''); +Buffer.from('', 'ascii'); +Buffer.from('', 'latin1'); +Buffer.alloc(0); +Buffer.allocUnsafe(0); +new Buffer(''); +new Buffer('', 'ascii'); +new Buffer('', 'latin1'); +new Buffer('', 'binary'); +Buffer(0); // try to write a 0-length string beyond the end of b assert.throws(() => b.write('', 2048), RangeError); @@ -109,7 +109,7 @@ b.copy(Buffer.alloc(1), 0, 2048, 2048); // Offset points to the end of the buffer // (see https://github.com/nodejs/node/issues/8127). -assert.doesNotThrow(() => Buffer.alloc(1).write('', 1, 0)); +Buffer.alloc(1).write('', 1, 0); // ASCII slice test { @@ -963,7 +963,7 @@ assert.strictEqual(SlowBuffer.prototype.offset, undefined); Buffer.from('')); // Check pool offset after that by trying to write string into the pool. - assert.doesNotThrow(() => Buffer.from('abc')); + Buffer.from('abc'); } @@ -993,12 +993,12 @@ common.expectsError(() => { } // Regression test -assert.doesNotThrow(() => Buffer.from(new ArrayBuffer())); +Buffer.from(new ArrayBuffer()); // Test that ArrayBuffer from a different context is detected correctly const arrayBuf = vm.runInNewContext('new ArrayBuffer()'); -assert.doesNotThrow(() => Buffer.from(arrayBuf)); -assert.doesNotThrow(() => Buffer.from({ buffer: arrayBuf })); +Buffer.from(arrayBuf); +Buffer.from({ buffer: arrayBuf }); assert.throws(() => Buffer.alloc({ valueOf: () => 1 }), /"size" argument must be of type number/); diff --git a/test/parallel/test-buffer-bad-overload.js b/test/parallel/test-buffer-bad-overload.js index b442a3e8a29630..ec2703341b2f38 100644 --- a/test/parallel/test-buffer-bad-overload.js +++ b/test/parallel/test-buffer-bad-overload.js @@ -2,9 +2,7 @@ const common = require('../common'); const assert = require('assert'); -assert.doesNotThrow(function() { - Buffer.allocUnsafe(10); -}); +Buffer.allocUnsafe(10); const err = common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', @@ -16,6 +14,4 @@ assert.throws(function() { Buffer.from(10, 'hex'); }, err); -assert.doesNotThrow(function() { - Buffer.from('deadbeaf', 'hex'); -}); +Buffer.from('deadbeaf', 'hex'); diff --git a/test/parallel/test-buffer-constants.js b/test/parallel/test-buffer-constants.js index 820c8dc993ed8e..dbb6186b6de5ce 100644 --- a/test/parallel/test-buffer-constants.js +++ b/test/parallel/test-buffer-constants.js @@ -11,7 +11,7 @@ assert(MAX_STRING_LENGTH <= MAX_LENGTH); assert.throws(() => ' '.repeat(MAX_STRING_LENGTH + 1), /^RangeError: Invalid string length$/); -assert.doesNotThrow(() => ' '.repeat(MAX_STRING_LENGTH)); +' '.repeat(MAX_STRING_LENGTH); // Legacy values match: assert.strictEqual(kMaxLength, MAX_LENGTH); diff --git a/test/parallel/test-buffer-copy.js b/test/parallel/test-buffer-copy.js index 1b10dadb5b709b..324613a04fe525 100644 --- a/test/parallel/test-buffer-copy.js +++ b/test/parallel/test-buffer-copy.js @@ -93,7 +93,7 @@ bb.fill('hello crazy world'); // try to copy from before the beginning of b -assert.doesNotThrow(() => { b.copy(c, 0, 100, 10); }); +b.copy(c, 0, 100, 10); // copy throws at negative sourceStart assert.throws(function() { diff --git a/test/parallel/test-buffer-fill.js b/test/parallel/test-buffer-fill.js index 14f44767c4452a..4d9c018c7f7410 100644 --- a/test/parallel/test-buffer-fill.js +++ b/test/parallel/test-buffer-fill.js @@ -136,17 +136,13 @@ testBufs('61c8b462c8b563c8b6', 12, 1, 'hex'); { const buf = Buffer.allocUnsafe(SIZE); - assert.doesNotThrow(() => { - // Make sure this operation doesn't go on forever. - buf.fill('yKJh', 'hex'); - }); + // Make sure this operation doesn't go on forever. + buf.fill('yKJh', 'hex'); // Should not throw. } { const buf = Buffer.allocUnsafe(SIZE); - assert.doesNotThrow(() => { - buf.fill('\u0222', 'hex'); - }); + buf.fill('\u0222', 'hex'); // Should not throw. } // BASE64 diff --git a/test/parallel/test-buffer-inspect.js b/test/parallel/test-buffer-inspect.js index 6890e27a3fd5b9..aa703db67dfac4 100644 --- a/test/parallel/test-buffer-inspect.js +++ b/test/parallel/test-buffer-inspect.js @@ -51,10 +51,8 @@ assert.strictEqual(util.inspect(s), expected); buffer.INSPECT_MAX_BYTES = Infinity; -assert.doesNotThrow(function() { - assert.strictEqual(util.inspect(b), expected); - assert.strictEqual(util.inspect(s), expected); -}); +assert.strictEqual(util.inspect(b), expected); +assert.strictEqual(util.inspect(s), expected); b.inspect = undefined; assert.strictEqual(util.inspect(b), expected); diff --git a/test/parallel/test-buffer-read.js b/test/parallel/test-buffer-read.js index 8a8d239a6f30e1..3f9c20e194f6ca 100644 --- a/test/parallel/test-buffer-read.js +++ b/test/parallel/test-buffer-read.js @@ -15,11 +15,7 @@ function read(buff, funx, args, expected) { } ); - assert.doesNotThrow( - () => assert.strictEqual(buff[funx](...args, true), expected), - 'noAssert does not change return value for valid ranges' - ); - + assert.strictEqual(buff[funx](...args, true), expected); } // testing basic functionality of readDoubleBE() and readDoubleLE() diff --git a/test/parallel/test-buffer-sharedarraybuffer.js b/test/parallel/test-buffer-sharedarraybuffer.js index 4485aa8cfc6efe..536c3939365d98 100644 --- a/test/parallel/test-buffer-sharedarraybuffer.js +++ b/test/parallel/test-buffer-sharedarraybuffer.js @@ -26,4 +26,4 @@ assert.deepStrictEqual(arr_buf, ar_buf); assert.strictEqual(Buffer.byteLength(sab), sab.byteLength); -assert.doesNotThrow(() => Buffer.from({ buffer: sab })); +Buffer.from({ buffer: sab }); diff --git a/test/parallel/test-buffer-slice.js b/test/parallel/test-buffer-slice.js index 8f764da09d00b0..b55d082783cc28 100644 --- a/test/parallel/test-buffer-slice.js +++ b/test/parallel/test-buffer-slice.js @@ -79,7 +79,7 @@ const utf16Buf = Buffer.from('0123456789', 'utf16le'); assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer.from('012', 'utf16le')); // try to slice a zero length Buffer // see https://github.com/joyent/node/issues/5881 -assert.doesNotThrow(() => Buffer.alloc(0).slice(0, 1)); +Buffer.alloc(0).slice(0, 1); assert.strictEqual(Buffer.alloc(0).slice(0, 1).length, 0); { diff --git a/test/parallel/test-child-process-detached.js b/test/parallel/test-child-process-detached.js index f53983c29e791c..8242536d1f49ad 100644 --- a/test/parallel/test-child-process-detached.js +++ b/test/parallel/test-child-process-detached.js @@ -39,7 +39,5 @@ process.on('exit', function() { assert.throws(function() { process.kill(child.pid); }, /^Error: kill ESRCH$/); - assert.doesNotThrow(function() { - process.kill(persistentPid); - }); + process.kill(persistentPid); }); diff --git a/test/parallel/test-child-process-spawn-typeerror.js b/test/parallel/test-child-process-spawn-typeerror.js index 065d1345d54ad9..eede5fdd15d5c0 100644 --- a/test/parallel/test-child-process-spawn-typeerror.js +++ b/test/parallel/test-child-process-spawn-typeerror.js @@ -39,21 +39,10 @@ assert.throws(function() { }, TypeError); // verify that valid argument combinations do not throw -assert.doesNotThrow(function() { - spawn(cmd); -}); - -assert.doesNotThrow(function() { - spawn(cmd, []); -}); - -assert.doesNotThrow(function() { - spawn(cmd, {}); -}); - -assert.doesNotThrow(function() { - spawn(cmd, [], {}); -}); +spawn(cmd); +spawn(cmd, []); +spawn(cmd, {}); +spawn(cmd, [], {}); // verify that invalid argument combinations throw assert.throws(function() { @@ -98,14 +87,14 @@ const n = null; // (f, a) // (f, a, o) // (f, o) -assert.doesNotThrow(function() { spawn(cmd); }); -assert.doesNotThrow(function() { spawn(cmd, a); }); -assert.doesNotThrow(function() { spawn(cmd, a, o); }); -assert.doesNotThrow(function() { spawn(cmd, o); }); +spawn(cmd); +spawn(cmd, a); +spawn(cmd, a, o); +spawn(cmd, o); // Variants of undefined as explicit 'no argument' at a position -assert.doesNotThrow(function() { spawn(cmd, u, o); }); -assert.doesNotThrow(function() { spawn(cmd, a, u); }); +spawn(cmd, u, o); +spawn(cmd, a, u); assert.throws(function() { spawn(cmd, n, o); }, TypeError); assert.throws(function() { spawn(cmd, a, n); }, TypeError); @@ -126,36 +115,36 @@ assert.throws(function() { spawn(cmd, a, s); }, TypeError); // (f, o) // (f, o, c) // (f, c) -assert.doesNotThrow(function() { execFile(cmd); }); -assert.doesNotThrow(function() { execFile(cmd, a); }); -assert.doesNotThrow(function() { execFile(cmd, a, o); }); -assert.doesNotThrow(function() { execFile(cmd, a, o, c); }); -assert.doesNotThrow(function() { execFile(cmd, a, c); }); -assert.doesNotThrow(function() { execFile(cmd, o); }); -assert.doesNotThrow(function() { execFile(cmd, o, c); }); -assert.doesNotThrow(function() { execFile(cmd, c); }); +execFile(cmd); +execFile(cmd, a); +execFile(cmd, a, o); +execFile(cmd, a, o, c); +execFile(cmd, a, c); +execFile(cmd, o); +execFile(cmd, o, c); +execFile(cmd, c); // Variants of undefined as explicit 'no argument' at a position -assert.doesNotThrow(function() { execFile(cmd, u, o, c); }); -assert.doesNotThrow(function() { execFile(cmd, a, u, c); }); -assert.doesNotThrow(function() { execFile(cmd, a, o, u); }); -assert.doesNotThrow(function() { execFile(cmd, n, o, c); }); -assert.doesNotThrow(function() { execFile(cmd, a, n, c); }); -assert.doesNotThrow(function() { execFile(cmd, a, o, n); }); -assert.doesNotThrow(function() { execFile(cmd, u, u, u); }); -assert.doesNotThrow(function() { execFile(cmd, u, u, c); }); -assert.doesNotThrow(function() { execFile(cmd, u, o, u); }); -assert.doesNotThrow(function() { execFile(cmd, a, u, u); }); -assert.doesNotThrow(function() { execFile(cmd, n, n, n); }); -assert.doesNotThrow(function() { execFile(cmd, n, n, c); }); -assert.doesNotThrow(function() { execFile(cmd, n, o, n); }); -assert.doesNotThrow(function() { execFile(cmd, a, n, n); }); -assert.doesNotThrow(function() { execFile(cmd, a, u); }); -assert.doesNotThrow(function() { execFile(cmd, a, n); }); -assert.doesNotThrow(function() { execFile(cmd, o, u); }); -assert.doesNotThrow(function() { execFile(cmd, o, n); }); -assert.doesNotThrow(function() { execFile(cmd, c, u); }); -assert.doesNotThrow(function() { execFile(cmd, c, n); }); +execFile(cmd, u, o, c); +execFile(cmd, a, u, c); +execFile(cmd, a, o, u); +execFile(cmd, n, o, c); +execFile(cmd, a, n, c); +execFile(cmd, a, o, n); +execFile(cmd, u, u, u); +execFile(cmd, u, u, c); +execFile(cmd, u, o, u); +execFile(cmd, a, u, u); +execFile(cmd, n, n, n); +execFile(cmd, n, n, c); +execFile(cmd, n, o, n); +execFile(cmd, a, n, n); +execFile(cmd, a, u); +execFile(cmd, a, n); +execFile(cmd, o, u); +execFile(cmd, o, n); +execFile(cmd, c, u); +execFile(cmd, c, n); // string is invalid in arg position (this may seem strange, but is // consistent across node API, cf. `net.createServer('not options', 'not @@ -171,7 +160,7 @@ assert.throws(function() { execFile(cmd, a, u, s); }, TypeError); assert.throws(function() { execFile(cmd, a, n, s); }, TypeError); assert.throws(function() { execFile(cmd, u, o, s); }, TypeError); assert.throws(function() { execFile(cmd, n, o, s); }, TypeError); -assert.doesNotThrow(function() { execFile(cmd, c, s); }); +execFile(cmd, c, s); // verify that fork has same argument parsing behavior as spawn @@ -181,16 +170,16 @@ assert.doesNotThrow(function() { execFile(cmd, c, s); }); // (f, a) // (f, a, o) // (f, o) -assert.doesNotThrow(function() { fork(empty); }); -assert.doesNotThrow(function() { fork(empty, a); }); -assert.doesNotThrow(function() { fork(empty, a, o); }); -assert.doesNotThrow(function() { fork(empty, o); }); -assert.doesNotThrow(function() { fork(empty, u, u); }); -assert.doesNotThrow(function() { fork(empty, u, o); }); -assert.doesNotThrow(function() { fork(empty, a, u); }); -assert.doesNotThrow(function() { fork(empty, n, n); }); -assert.doesNotThrow(function() { fork(empty, n, o); }); -assert.doesNotThrow(function() { fork(empty, a, n); }); +fork(empty); +fork(empty, a); +fork(empty, a, o); +fork(empty, o); +fork(empty, u, u); +fork(empty, u, o); +fork(empty, a, u); +fork(empty, n, n); +fork(empty, n, o); +fork(empty, a, n); assert.throws(function() { fork(empty, s); }, TypeError); assert.throws(function() { fork(empty, a, s); }, TypeError); diff --git a/test/parallel/test-console-async-write-error.js b/test/parallel/test-console-async-write-error.js index 63e8bfbc881e4c..139c02d64bff4b 100644 --- a/test/parallel/test-console-async-write-error.js +++ b/test/parallel/test-console-async-write-error.js @@ -2,7 +2,6 @@ const common = require('../common'); const { Console } = require('console'); const { Writable } = require('stream'); -const assert = require('assert'); for (const method of ['dir', 'log', 'warn']) { const out = new Writable({ @@ -13,7 +12,5 @@ for (const method of ['dir', 'log', 'warn']) { const c = new Console(out, out, true); - assert.doesNotThrow(() => { - c[method]('abc'); - }); + c[method]('abc'); } diff --git a/test/parallel/test-console-instance.js b/test/parallel/test-console-instance.js index 7e931e0d3b30de..aa35afc648a432 100644 --- a/test/parallel/test-console-instance.js +++ b/test/parallel/test-console-instance.js @@ -87,9 +87,7 @@ out.write = common.mustCall((d) => { [1, 2, 3].forEach(c.log); // Console() detects if it is called without `new` keyword -assert.doesNotThrow(() => { - Console(out, err); -}); +Console(out, err); // Instance that does not ignore the stream errors. const c2 = new Console(out, err, false); diff --git a/test/parallel/test-console-sync-write-error.js b/test/parallel/test-console-sync-write-error.js index fb350d463bb35d..4d6c52e0dabca5 100644 --- a/test/parallel/test-console-sync-write-error.js +++ b/test/parallel/test-console-sync-write-error.js @@ -2,7 +2,6 @@ const common = require('../common'); const { Console } = require('console'); const { Writable } = require('stream'); -const assert = require('assert'); for (const method of ['dir', 'log', 'warn']) { { @@ -14,9 +13,7 @@ for (const method of ['dir', 'log', 'warn']) { const c = new Console(out, out, true); - assert.doesNotThrow(() => { - c[method]('abc'); - }); + c[method]('abc'); } { @@ -28,9 +25,7 @@ for (const method of ['dir', 'log', 'warn']) { const c = new Console(out, out, true); - assert.doesNotThrow(() => { - c[method]('abc'); - }); + c[method]('abc'); } { @@ -42,8 +37,6 @@ for (const method of ['dir', 'log', 'warn']) { const c = new Console(out, out, true); - assert.doesNotThrow(() => { - c[method]('abc'); - }); + c[method]('abc'); } } diff --git a/test/parallel/test-console.js b/test/parallel/test-console.js index c0ca672eba7141..234723285d1556 100644 --- a/test/parallel/test-console.js +++ b/test/parallel/test-console.js @@ -29,18 +29,14 @@ assert.ok(process.stderr.writable); assert.strictEqual(typeof process.stdout.fd, 'number'); assert.strictEqual(typeof process.stderr.fd, 'number'); -assert.doesNotThrow(function() { - process.once('warning', common.mustCall((warning) => { - assert(/no such label/.test(warning.message)); - })); +process.once('warning', common.mustCall((warning) => { + assert(/no such label/.test(warning.message)); +})); - console.timeEnd('no such label'); -}); +console.timeEnd('no such label'); -assert.doesNotThrow(function() { - console.time('label'); - console.timeEnd('label'); -}); +console.time('label'); +console.timeEnd('label'); // Check that the `Error` is a `TypeError` but do not check the message as it // will be different in different JavaScript engines. @@ -207,9 +203,7 @@ common.expectsError(() => { message: /^should throw$/ }); -assert.doesNotThrow(() => { - console.assert(true, 'this should not throw'); -}); +console.assert(true, 'this should not throw'); // hijack stderr to catch `process.emitWarning` which is using // `process.nextTick` diff --git a/test/parallel/test-crypto-binary-default.js b/test/parallel/test-crypto-binary-default.js index ffc29e7ac8b640..6cdc894753c3ac 100644 --- a/test/parallel/test-crypto-binary-default.js +++ b/test/parallel/test-crypto-binary-default.js @@ -46,9 +46,7 @@ const rsaPubPem = fixtures.readSync('test_rsa_pubkey.pem', 'ascii'); const rsaKeyPem = fixtures.readSync('test_rsa_privkey.pem', 'ascii'); // PFX tests -assert.doesNotThrow(function() { - tls.createSecureContext({ pfx: certPfx, passphrase: 'sample' }); -}); +tls.createSecureContext({ pfx: certPfx, passphrase: 'sample' }); assert.throws(function() { tls.createSecureContext({ pfx: certPfx }); diff --git a/test/parallel/test-crypto-cipher-decipher.js b/test/parallel/test-crypto-cipher-decipher.js index 1752d903cfcb09..7b207eb0ba4105 100644 --- a/test/parallel/test-crypto-cipher-decipher.js +++ b/test/parallel/test-crypto-cipher-decipher.js @@ -126,18 +126,18 @@ testCipher2(Buffer.from('0123456789abcdef')); let decipher = crypto.createDecipher('aes192', key); let txt; - assert.doesNotThrow(() => txt = decipher.update(ciph, 'base64', 'ucs2')); - assert.doesNotThrow(() => txt += decipher.final('ucs2')); + txt = decipher.update(ciph, 'base64', 'ucs2'); + txt += decipher.final('ucs2'); assert.strictEqual(txt, plaintext); decipher = crypto.createDecipher('aes192', key); - assert.doesNotThrow(() => txt = decipher.update(ciph, 'base64', 'ucs-2')); - assert.doesNotThrow(() => txt += decipher.final('ucs-2')); + txt = decipher.update(ciph, 'base64', 'ucs-2'); + txt += decipher.final('ucs-2'); assert.strictEqual(txt, plaintext); decipher = crypto.createDecipher('aes192', key); - assert.doesNotThrow(() => txt = decipher.update(ciph, 'base64', 'utf-16le')); - assert.doesNotThrow(() => txt += decipher.final('utf-16le')); + txt = decipher.update(ciph, 'base64', 'utf-16le'); + txt += decipher.final('utf-16le'); assert.strictEqual(txt, plaintext); } diff --git a/test/parallel/test-crypto-dh-odd-key.js b/test/parallel/test-crypto-dh-odd-key.js index 449c482d351c56..d5410daca6fb23 100644 --- a/test/parallel/test-crypto-dh-odd-key.js +++ b/test/parallel/test-crypto-dh-odd-key.js @@ -37,7 +37,7 @@ function test() { // FIPS requires a length of at least 1024 if (!common.hasFipsCrypto) { - assert.doesNotThrow(function() { test(); }); + test(); } else { assert.throws(function() { test(); }, /key size too small/); } diff --git a/test/parallel/test-crypto-dh.js b/test/parallel/test-crypto-dh.js index 30d54e2ae46aa2..515959b6948cb5 100644 --- a/test/parallel/test-crypto-dh.js +++ b/test/parallel/test-crypto-dh.js @@ -363,9 +363,7 @@ if (availableCurves.has('prime256v1') && availableHashes.has('sha256')) { 'AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2\n' + 'pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng==\n' + '-----END EC PRIVATE KEY-----'; - assert.doesNotThrow(() => { - crypto.createSign('SHA256').sign(ecPrivateKey); - }); + crypto.createSign('SHA256').sign(ecPrivateKey); } // invalid test: curve argument is undefined diff --git a/test/parallel/test-crypto-padding.js b/test/parallel/test-crypto-padding.js index 6ad504d12c2ced..ae85f7d2c3614a 100644 --- a/test/parallel/test-crypto-padding.js +++ b/test/parallel/test-crypto-padding.js @@ -100,11 +100,9 @@ assert.throws(function() { enc(ODD_LENGTH_PLAIN, false); }, /data not multiple of block length/); -assert.doesNotThrow(function() { - assert.strictEqual( - enc(EVEN_LENGTH_PLAIN, false), EVEN_LENGTH_ENCRYPTED_NOPAD - ); -}); +assert.strictEqual( + enc(EVEN_LENGTH_PLAIN, false), EVEN_LENGTH_ENCRYPTED_NOPAD +); /* @@ -114,20 +112,16 @@ assert.doesNotThrow(function() { assert.strictEqual(dec(ODD_LENGTH_ENCRYPTED, true), ODD_LENGTH_PLAIN); assert.strictEqual(dec(EVEN_LENGTH_ENCRYPTED, true), EVEN_LENGTH_PLAIN); -assert.doesNotThrow(function() { - // returns including original padding - assert.strictEqual(dec(ODD_LENGTH_ENCRYPTED, false).length, 32); - assert.strictEqual(dec(EVEN_LENGTH_ENCRYPTED, false).length, 48); -}); +// returns including original padding +assert.strictEqual(dec(ODD_LENGTH_ENCRYPTED, false).length, 32); +assert.strictEqual(dec(EVEN_LENGTH_ENCRYPTED, false).length, 48); assert.throws(function() { // must have at least 1 byte of padding (PKCS): assert.strictEqual(dec(EVEN_LENGTH_ENCRYPTED_NOPAD, true), EVEN_LENGTH_PLAIN); }, /bad decrypt/); -assert.doesNotThrow(function() { - // no-pad encrypted string should return the same: - assert.strictEqual( - dec(EVEN_LENGTH_ENCRYPTED_NOPAD, false), EVEN_LENGTH_PLAIN - ); -}); +// no-pad encrypted string should return the same: +assert.strictEqual( + dec(EVEN_LENGTH_ENCRYPTED_NOPAD, false), EVEN_LENGTH_PLAIN +); diff --git a/test/parallel/test-crypto-pbkdf2.js b/test/parallel/test-crypto-pbkdf2.js index af8acd42c7c7fd..1bb1c6cd71215e 100644 --- a/test/parallel/test-crypto-pbkdf2.js +++ b/test/parallel/test-crypto-pbkdf2.js @@ -99,11 +99,9 @@ common.expectsError( // Should not get FATAL ERROR with empty password and salt // https://github.com/nodejs/node/issues/8571 -assert.doesNotThrow(() => { - crypto.pbkdf2('', '', 1, 32, 'sha256', common.mustCall((e) => { - assert.ifError(e); - })); -}); +crypto.pbkdf2('', '', 1, 32, 'sha256', common.mustCall((e) => { + assert.ifError(e); +})); common.expectsError( () => crypto.pbkdf2('password', 'salt', 8, 8, common.mustNotCall()), diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index e0aa1ef872b89c..5a6ecdd66f41bf 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -153,10 +153,8 @@ assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); // Test RSA key signing/verification with encrypted key rsaSign = crypto.createSign('SHA1'); rsaSign.update(rsaPubPem); -assert.doesNotThrow(() => { - const signOptions = { key: rsaKeyPemEncrypted, passphrase: 'password' }; - rsaSignature = rsaSign.sign(signOptions, 'hex'); -}); +const signOptions = { key: rsaKeyPemEncrypted, passphrase: 'password' }; +rsaSignature = rsaSign.sign(signOptions, 'hex'); assert.strictEqual(rsaSignature, expectedSignature); rsaVerify = crypto.createVerify('SHA1'); @@ -259,11 +257,8 @@ const input = 'I AM THE WALRUS'; const sign = crypto.createSign('SHA1'); sign.update(input); - let signature; - assert.doesNotThrow(() => { - const signOptions = { key: dsaKeyPemEncrypted, passphrase: 'password' }; - signature = sign.sign(signOptions, 'hex'); - }); + const signOptions = { key: dsaKeyPemEncrypted, passphrase: 'password' }; + const signature = sign.sign(signOptions, 'hex'); const verify = crypto.createVerify('SHA1'); verify.update(input); diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js index 1156fe688cb8d2..1fc3db74828ca6 100644 --- a/test/parallel/test-crypto.js +++ b/test/parallel/test-crypto.js @@ -56,9 +56,7 @@ assert.throws(function() { }); // PFX tests -assert.doesNotThrow(function() { - tls.createSecureContext({ pfx: certPfx, passphrase: 'sample' }); -}); +tls.createSecureContext({ pfx: certPfx, passphrase: 'sample' }); assert.throws(function() { tls.createSecureContext({ pfx: certPfx }); diff --git a/test/parallel/test-dgram-createSocket-type.js b/test/parallel/test-dgram-createSocket-type.js index 19f4dad9208212..9c5a20eaab3191 100644 --- a/test/parallel/test-dgram-createSocket-type.js +++ b/test/parallel/test-dgram-createSocket-type.js @@ -34,10 +34,8 @@ invalidTypes.forEach((invalidType) => { // Error must not be thrown with valid types validTypes.forEach((validType) => { - assert.doesNotThrow(() => { - const socket = dgram.createSocket(validType); - socket.close(); - }); + const socket = dgram.createSocket(validType); + socket.close(); }); // Ensure buffer sizes can be set diff --git a/test/parallel/test-dns-lookup.js b/test/parallel/test-dns-lookup.js index 516f6ac0c145ec..d006355742e55b 100644 --- a/test/parallel/test-dns-lookup.js +++ b/test/parallel/test-dns-lookup.js @@ -53,55 +53,47 @@ common.expectsError(() => { message: 'The value "20" is invalid for option "family"' }); -assert.doesNotThrow(() => { - dns.lookup(false, { - hints: 0, - family: 0, - all: true - }, common.mustCall((error, result, addressType) => { - assert.ifError(error); - assert.deepStrictEqual(result, []); - assert.strictEqual(addressType, undefined); - })); -}); +dns.lookup(false, { + hints: 0, + family: 0, + all: true +}, common.mustCall((error, result, addressType) => { + assert.ifError(error); + assert.deepStrictEqual(result, []); + assert.strictEqual(addressType, undefined); +})); -assert.doesNotThrow(() => { - dns.lookup('127.0.0.1', { - hints: 0, - family: 4, - all: true - }, common.mustCall((error, result, addressType) => { - assert.ifError(error); - assert.deepStrictEqual(result, [{ - address: '127.0.0.1', - family: 4 - }]); - assert.strictEqual(addressType, undefined); - })); -}); +dns.lookup('127.0.0.1', { + hints: 0, + family: 4, + all: true +}, common.mustCall((error, result, addressType) => { + assert.ifError(error); + assert.deepStrictEqual(result, [{ + address: '127.0.0.1', + family: 4 + }]); + assert.strictEqual(addressType, undefined); +})); -assert.doesNotThrow(() => { - dns.lookup('127.0.0.1', { - hints: 0, - family: 4, - all: false - }, common.mustCall((error, result, addressType) => { - assert.ifError(error); - assert.deepStrictEqual(result, '127.0.0.1'); - assert.strictEqual(addressType, 4); - })); -}); +dns.lookup('127.0.0.1', { + hints: 0, + family: 4, + all: false +}, common.mustCall((error, result, addressType) => { + assert.ifError(error); + assert.deepStrictEqual(result, '127.0.0.1'); + assert.strictEqual(addressType, 4); +})); -assert.doesNotThrow(() => { - let tickValue = 0; +let tickValue = 0; - dns.lookup('example.com', common.mustCall((error, result, addressType) => { - assert(error); - assert.strictEqual(tickValue, 1); - assert.strictEqual(error.code, 'ENOENT'); - })); +dns.lookup('example.com', common.mustCall((error, result, addressType) => { + assert(error); + assert.strictEqual(tickValue, 1); + assert.strictEqual(error.code, 'ENOENT'); +})); - // Make sure that the error callback is called - // on next tick. - tickValue = 1; -}); +// Make sure that the error callback is called +// on next tick. +tickValue = 1; diff --git a/test/parallel/test-dns.js b/test/parallel/test-dns.js index dba14b397bc27c..839d434f9e1d65 100644 --- a/test/parallel/test-dns.js +++ b/test/parallel/test-dns.js @@ -29,7 +29,7 @@ const existing = dns.getServers(); assert(existing.length > 0); // Verify that setServers() handles arrays with holes and other oddities -assert.doesNotThrow(() => { +{ const servers = []; servers[0] = '127.0.0.1'; @@ -37,9 +37,9 @@ assert.doesNotThrow(() => { dns.setServers(servers); assert.deepStrictEqual(dns.getServers(), ['127.0.0.1', '0.0.0.0']); -}); +} -assert.doesNotThrow(() => { +{ const servers = ['127.0.0.1', '192.168.1.1']; servers[3] = '127.1.0.1'; @@ -60,13 +60,13 @@ assert.doesNotThrow(() => { '192.168.1.1', '0.0.0.0' ]); -}); +} const goog = [ '8.8.8.8', '8.8.4.4', ]; -assert.doesNotThrow(() => dns.setServers(goog)); +dns.setServers(goog); assert.deepStrictEqual(dns.getServers(), goog); common.expectsError(() => dns.setServers(['foobar']), { code: 'ERR_INVALID_IP_ADDRESS', @@ -84,7 +84,7 @@ const goog6 = [ '2001:4860:4860::8888', '2001:4860:4860::8844', ]; -assert.doesNotThrow(() => dns.setServers(goog6)); +dns.setServers(goog6); assert.deepStrictEqual(dns.getServers(), goog6); goog6.push('4.4.4.4'); @@ -106,7 +106,7 @@ const portsExpected = [ dns.setServers(ports); assert.deepStrictEqual(dns.getServers(), portsExpected); -assert.doesNotThrow(() => dns.setServers([])); +dns.setServers([]); assert.deepStrictEqual(dns.getServers(), []); common.expectsError(() => { @@ -146,16 +146,11 @@ common.expectsError(() => { assert.strictEqual(family, 4); }; - assert.doesNotThrow(() => dns.lookup('', common.mustCall(checkCallback))); - - assert.doesNotThrow(() => dns.lookup(null, common.mustCall(checkCallback))); - - assert.doesNotThrow(() => dns.lookup(undefined, - common.mustCall(checkCallback))); - - assert.doesNotThrow(() => dns.lookup(0, common.mustCall(checkCallback))); - - assert.doesNotThrow(() => dns.lookup(NaN, common.mustCall(checkCallback))); + dns.lookup('', common.mustCall(checkCallback)); + dns.lookup(null, common.mustCall(checkCallback)); + dns.lookup(undefined, common.mustCall(checkCallback)); + dns.lookup(0, common.mustCall(checkCallback)); + dns.lookup(NaN, common.mustCall(checkCallback)); } /* @@ -186,24 +181,18 @@ common.expectsError(() => dns.lookup('nodejs.org', 4), { type: TypeError }); -assert.doesNotThrow(() => dns.lookup('', { family: 4, hints: 0 }, - common.mustCall())); +dns.lookup('', { family: 4, hints: 0 }, common.mustCall()); -assert.doesNotThrow(() => { - dns.lookup('', { - family: 6, - hints: dns.ADDRCONFIG - }, common.mustCall()); -}); +dns.lookup('', { + family: 6, + hints: dns.ADDRCONFIG +}, common.mustCall()); -assert.doesNotThrow(() => dns.lookup('', { hints: dns.V4MAPPED }, - common.mustCall())); +dns.lookup('', { hints: dns.V4MAPPED }, common.mustCall()); -assert.doesNotThrow(() => { - dns.lookup('', { - hints: dns.ADDRCONFIG | dns.V4MAPPED - }, common.mustCall()); -}); +dns.lookup('', { + hints: dns.ADDRCONFIG | dns.V4MAPPED +}, common.mustCall()); common.expectsError(() => dns.lookupService('0.0.0.0'), { code: 'ERR_MISSING_ARGS', diff --git a/test/parallel/test-domain-load-after-set-uncaught-exception-capture.js b/test/parallel/test-domain-load-after-set-uncaught-exception-capture.js index 9e438368d63207..c2fa523cc17019 100644 --- a/test/parallel/test-domain-load-after-set-uncaught-exception-capture.js +++ b/test/parallel/test-domain-load-after-set-uncaught-exception-capture.js @@ -1,6 +1,5 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); process.setUncaughtExceptionCaptureCallback(common.mustNotCall()); @@ -15,4 +14,4 @@ common.expectsError( process.setUncaughtExceptionCaptureCallback(null); -assert.doesNotThrow(() => require('domain')); +require('domain'); diff --git a/test/parallel/test-event-emitter-remove-all-listeners.js b/test/parallel/test-event-emitter-remove-all-listeners.js index 6ab277ce4ed6be..3dfe65a8b4bfd0 100644 --- a/test/parallel/test-event-emitter-remove-all-listeners.js +++ b/test/parallel/test-event-emitter-remove-all-listeners.js @@ -81,7 +81,7 @@ function expect(expected) { // Check for regression where removeAllListeners() throws when // there exists a 'removeListener' listener, but there exists // no listeners for the provided event type. - assert.doesNotThrow(ee.removeAllListeners.bind(ee, 'foo')); + ee.removeAllListeners.bind(ee, 'foo'); } { diff --git a/test/parallel/test-fs-access.js b/test/parallel/test-fs-access.js index 867c19cc3cfa1e..a55f75f649f383 100644 --- a/test/parallel/test-fs-access.js +++ b/test/parallel/test-fs-access.js @@ -105,15 +105,10 @@ common.expectsError( type: TypeError }); -assert.doesNotThrow(() => { - fs.accessSync(__filename); -}); +fs.accessSync(__filename); -assert.doesNotThrow(() => { - const mode = fs.F_OK | fs.R_OK | fs.W_OK; - - fs.accessSync(readWriteFile, mode); -}); +const mode = fs.F_OK | fs.R_OK | fs.W_OK; +fs.accessSync(readWriteFile, mode); assert.throws( () => { fs.accessSync(doesNotExist); }, diff --git a/test/parallel/test-fs-buffer.js b/test/parallel/test-fs-buffer.js index 84234e8a7a0bd7..0b7b67cefe4d86 100644 --- a/test/parallel/test-fs-buffer.js +++ b/test/parallel/test-fs-buffer.js @@ -9,22 +9,18 @@ const path = require('path'); const tmpdir = require('../common/tmpdir'); tmpdir.refresh(); -assert.doesNotThrow(() => { - fs.access(Buffer.from(tmpdir.path), common.mustCall((err) => { - assert.ifError(err); - })); -}); +fs.access(Buffer.from(tmpdir.path), common.mustCall((err) => { + assert.ifError(err); +})); -assert.doesNotThrow(() => { - const buf = Buffer.from(path.join(tmpdir.path, 'a.txt')); - fs.open(buf, 'w+', common.mustCall((err, fd) => { +const buf = Buffer.from(path.join(tmpdir.path, 'a.txt')); +fs.open(buf, 'w+', common.mustCall((err, fd) => { + assert.ifError(err); + assert(fd); + fs.close(fd, common.mustCall((err) => { assert.ifError(err); - assert(fd); - fs.close(fd, common.mustCall((err) => { - assert.ifError(err); - })); })); -}); +})); assert.throws(() => { fs.accessSync(true); diff --git a/test/parallel/test-fs-exists.js b/test/parallel/test-fs-exists.js index 331c8c04e38e78..b5c3dc154684e3 100644 --- a/test/parallel/test-fs-exists.js +++ b/test/parallel/test-fs-exists.js @@ -30,7 +30,8 @@ fs.exists(f, common.mustCall(function(y) { assert.strictEqual(y, true); })); -assert.doesNotThrow(() => fs.exists(f)); +// Does not throw +fs.exists(f); fs.exists(`${f}-NO`, common.mustCall(function(y) { assert.strictEqual(y, false); diff --git a/test/parallel/test-fs-make-callback.js b/test/parallel/test-fs-make-callback.js index ca948ede182759..9d4a6121a36a65 100644 --- a/test/parallel/test-fs-make-callback.js +++ b/test/parallel/test-fs-make-callback.js @@ -1,6 +1,5 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const fs = require('fs'); const callbackThrowValues = [null, true, false, 0, 1, 'foo', /foo/, [], {}]; @@ -20,7 +19,7 @@ function testMakeCallback(cb) { common.expectWarning('DeprecationWarning', warn); // Passing undefined/nothing calls rethrow() internally, which emits a warning -assert.doesNotThrow(testMakeCallback()); +testMakeCallback()(); function invalidCallbackThrowsTests() { callbackThrowValues.forEach((value) => { diff --git a/test/parallel/test-fs-makeStatsCallback.js b/test/parallel/test-fs-makeStatsCallback.js index 0982fcc3c7d38c..ec03b593fa2a2c 100644 --- a/test/parallel/test-fs-makeStatsCallback.js +++ b/test/parallel/test-fs-makeStatsCallback.js @@ -1,6 +1,5 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const fs = require('fs'); const callbackThrowValues = [null, true, false, 0, 1, 'foo', /foo/, [], {}]; const warn = 'Calling an asynchronous function without callback is deprecated.'; @@ -15,10 +14,10 @@ function testMakeStatsCallback(cb) { common.expectWarning('DeprecationWarning', warn); // Verify the case where a callback function is provided -assert.doesNotThrow(testMakeStatsCallback(common.mustCall())); +testMakeStatsCallback(common.mustCall())(); // Passing undefined/nothing calls rethrow() internally, which emits a warning -assert.doesNotThrow(testMakeStatsCallback()); +testMakeStatsCallback()(); function invalidCallbackThrowsTests() { callbackThrowValues.forEach((value) => { diff --git a/test/parallel/test-fs-mkdtemp.js b/test/parallel/test-fs-mkdtemp.js index b27ab864173dd2..27e2f1c08c227d 100644 --- a/test/parallel/test-fs-mkdtemp.js +++ b/test/parallel/test-fs-mkdtemp.js @@ -32,5 +32,5 @@ fs.mkdtemp(path.join(tmpdir.path, 'bar.'), {}, common.mustCall(handler)); // Making sure that not passing a callback doesn't crash, as a default function // is passed internally. -assert.doesNotThrow(() => fs.mkdtemp(path.join(tmpdir.path, 'bar-'))); -assert.doesNotThrow(() => fs.mkdtemp(path.join(tmpdir.path, 'bar-'), {})); +fs.mkdtemp(path.join(tmpdir.path, 'bar-')); +fs.mkdtemp(path.join(tmpdir.path, 'bar-'), {}); diff --git a/test/parallel/test-fs-options-immutable.js b/test/parallel/test-fs-options-immutable.js index ca5079b07dab3f..3555c82f1962f3 100644 --- a/test/parallel/test-fs-options-immutable.js +++ b/test/parallel/test-fs-options-immutable.js @@ -17,19 +17,11 @@ const options = Object.freeze({}); const tmpdir = require('../common/tmpdir'); tmpdir.refresh(); -{ - assert.doesNotThrow(() => - fs.readFile(__filename, options, common.mustCall(errHandler)) - ); - assert.doesNotThrow(() => fs.readFileSync(__filename, options)); -} +fs.readFile(__filename, options, common.mustCall(errHandler)); +fs.readFileSync(__filename, options); -{ - assert.doesNotThrow(() => - fs.readdir(__dirname, options, common.mustCall(errHandler)) - ); - assert.doesNotThrow(() => fs.readdirSync(__dirname, options)); -} +fs.readdir(__dirname, options, common.mustCall(errHandler)); +fs.readdirSync(__dirname, options); if (common.canCreateSymLink()) { const sourceFile = path.resolve(tmpdir.path, 'test-readlink'); @@ -38,63 +30,46 @@ if (common.canCreateSymLink()) { fs.writeFileSync(sourceFile, ''); fs.symlinkSync(sourceFile, linkFile); - assert.doesNotThrow(() => - fs.readlink(linkFile, options, common.mustCall(errHandler)) - ); - assert.doesNotThrow(() => fs.readlinkSync(linkFile, options)); + fs.readlink(linkFile, options, common.mustCall(errHandler)); + fs.readlinkSync(linkFile, options); } { const fileName = path.resolve(tmpdir.path, 'writeFile'); - assert.doesNotThrow(() => fs.writeFileSync(fileName, 'ABCD', options)); - assert.doesNotThrow(() => - fs.writeFile(fileName, 'ABCD', options, common.mustCall(errHandler)) - ); + fs.writeFileSync(fileName, 'ABCD', options); + fs.writeFile(fileName, 'ABCD', options, common.mustCall(errHandler)); } { const fileName = path.resolve(tmpdir.path, 'appendFile'); - assert.doesNotThrow(() => fs.appendFileSync(fileName, 'ABCD', options)); - assert.doesNotThrow(() => - fs.appendFile(fileName, 'ABCD', options, common.mustCall(errHandler)) - ); + fs.appendFileSync(fileName, 'ABCD', options); + fs.appendFile(fileName, 'ABCD', options, common.mustCall(errHandler)); } { - let watch; - assert.doesNotThrow(() => { - watch = fs.watch(__filename, options, common.mustNotCall()); - }); + const watch = fs.watch(__filename, options, common.mustNotCall()); watch.close(); } { - assert.doesNotThrow( - () => fs.watchFile(__filename, options, common.mustNotCall()) - ); + fs.watchFile(__filename, options, common.mustNotCall()); fs.unwatchFile(__filename); } { - assert.doesNotThrow(() => fs.realpathSync(__filename, options)); - assert.doesNotThrow(() => - fs.realpath(__filename, options, common.mustCall(errHandler)) - ); + fs.realpathSync(__filename, options); + fs.realpath(__filename, options, common.mustCall(errHandler)); } { const tempFileName = path.resolve(tmpdir.path, 'mkdtemp-'); - assert.doesNotThrow(() => fs.mkdtempSync(tempFileName, options)); - assert.doesNotThrow(() => - fs.mkdtemp(tempFileName, options, common.mustCall(errHandler)) - ); + fs.mkdtempSync(tempFileName, options); + fs.mkdtemp(tempFileName, options, common.mustCall(errHandler)); } { const fileName = path.resolve(tmpdir.path, 'streams'); - assert.doesNotThrow(() => { - fs.WriteStream(fileName, options).once('open', common.mustCall(() => { - assert.doesNotThrow(() => fs.ReadStream(fileName, options)); - })); - }); + fs.WriteStream(fileName, options).once('open', common.mustCall(() => { + fs.ReadStream(fileName, options); + })); } diff --git a/test/parallel/test-fs-read-stream-throw-type-error.js b/test/parallel/test-fs-read-stream-throw-type-error.js index 26fd47372ebf0c..b01a0a588f5699 100644 --- a/test/parallel/test-fs-read-stream-throw-type-error.js +++ b/test/parallel/test-fs-read-stream-throw-type-error.js @@ -1,23 +1,14 @@ 'use strict'; const common = require('../common'); const fixtures = require('../common/fixtures'); -const assert = require('assert'); const fs = require('fs'); const example = fixtures.path('x.txt'); -assert.doesNotThrow(function() { - fs.createReadStream(example, undefined); -}); -assert.doesNotThrow(function() { - fs.createReadStream(example, null); -}); -assert.doesNotThrow(function() { - fs.createReadStream(example, 'utf8'); -}); -assert.doesNotThrow(function() { - fs.createReadStream(example, { encoding: 'utf8' }); -}); +fs.createReadStream(example, undefined); +fs.createReadStream(example, null); +fs.createReadStream(example, 'utf8'); +fs.createReadStream(example, { encoding: 'utf8' }); const createReadStreamErr = (path, opt) => { common.expectsError( diff --git a/test/parallel/test-fs-timestamp-parsing-error.js b/test/parallel/test-fs-timestamp-parsing-error.js index 3680b5fece13c9..2dcd4f518427e3 100644 --- a/test/parallel/test-fs-timestamp-parsing-error.js +++ b/test/parallel/test-fs-timestamp-parsing-error.js @@ -1,7 +1,6 @@ 'use strict'; const common = require('../common'); const fs = require('fs'); -const assert = require('assert'); [Infinity, -Infinity, NaN].forEach((input) => { common.expectsError( @@ -25,5 +24,5 @@ common.expectsError( const okInputs = [1, -1, '1', '-1', Date.now()]; okInputs.forEach((input) => { - assert.doesNotThrow(() => fs._toUnixTimestamp(input)); + fs._toUnixTimestamp(input); }); diff --git a/test/parallel/test-fs-write-stream-throw-type-error.js b/test/parallel/test-fs-write-stream-throw-type-error.js index 73312afa6b6423..553d399e238508 100644 --- a/test/parallel/test-fs-write-stream-throw-type-error.js +++ b/test/parallel/test-fs-write-stream-throw-type-error.js @@ -1,6 +1,5 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const fs = require('fs'); const path = require('path'); @@ -10,21 +9,10 @@ const example = path.join(tmpdir.path, 'dummy'); tmpdir.refresh(); -assert.doesNotThrow(() => { - fs.createWriteStream(example, undefined); -}); - -assert.doesNotThrow(() => { - fs.createWriteStream(example, null); -}); - -assert.doesNotThrow(() => { - fs.createWriteStream(example, 'utf8'); -}); - -assert.doesNotThrow(() => { - fs.createWriteStream(example, { encoding: 'utf8' }); -}); +fs.createWriteStream(example, undefined); +fs.createWriteStream(example, null); +fs.createWriteStream(example, 'utf8'); +fs.createWriteStream(example, { encoding: 'utf8' }); const createWriteStreamErr = (path, opt) => { common.expectsError( diff --git a/test/parallel/test-http-client-reject-unexpected-agent.js b/test/parallel/test-http-client-reject-unexpected-agent.js index 407084c030e67d..50e5d2b57a7b96 100644 --- a/test/parallel/test-http-client-reject-unexpected-agent.js +++ b/test/parallel/test-http-client-reject-unexpected-agent.js @@ -59,7 +59,7 @@ server.listen(0, baseOptions.host, common.mustCall(function() { }); acceptableAgentOptions.forEach((agent) => { - assert.doesNotThrow(() => createRequest(agent)); + createRequest(agent); }); })); diff --git a/test/parallel/test-http-header-read.js b/test/parallel/test-http-header-read.js index dcdabb12d83ab0..0cc7b5cae1c071 100644 --- a/test/parallel/test-http-header-read.js +++ b/test/parallel/test-http-header-read.js @@ -37,11 +37,7 @@ const s = http.createServer(function(req, res) { res.end('hello world\n'); // This checks that after the headers have been sent, getHeader works // and does not throw an exception (Issue 752) - assert.doesNotThrow( - function() { - assert.strictEqual(plain, res.getHeader(contentType)); - } - ); + assert.strictEqual(plain, res.getHeader(contentType)); }); s.listen(0, runTest); diff --git a/test/parallel/test-http-hostname-typechecking.js b/test/parallel/test-http-hostname-typechecking.js index 12fe72005a41a6..72440391fa2938 100644 --- a/test/parallel/test-http-hostname-typechecking.js +++ b/test/parallel/test-http-hostname-typechecking.js @@ -1,7 +1,6 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const http = require('http'); // All of these values should cause http.request() to throw synchronously @@ -36,8 +35,6 @@ vals.forEach((v) => { // Only testing for 'hostname' validation so ignore connection errors. const dontCare = () => {}; ['', undefined, null].forEach((v) => { - assert.doesNotThrow(() => { - http.request({ hostname: v }).on('error', dontCare).end(); - http.request({ host: v }).on('error', dontCare).end(); - }); + http.request({ hostname: v }).on('error', dontCare).end(); + http.request({ host: v }).on('error', dontCare).end(); }); diff --git a/test/parallel/test-http-invalidheaderfield.js b/test/parallel/test-http-invalidheaderfield.js index 9e844e8a425af0..528fc825868ed7 100644 --- a/test/parallel/test-http-invalidheaderfield.js +++ b/test/parallel/test-http-invalidheaderfield.js @@ -9,9 +9,7 @@ const ee = new EventEmitter(); let count = 3; const server = http.createServer(function(req, res) { - assert.doesNotThrow(function() { - res.setHeader('testing_123', 123); - }); + res.setHeader('testing_123', 123); assert.throws(function() { res.setHeader('testing 123', 123); }, TypeError); @@ -37,17 +35,13 @@ server.listen(0, function() { } ); - assert.doesNotThrow( - function() { - const options = { - port: server.address().port, - headers: { 'testing_123': 123 } - }; - http.get(options, function() { - ee.emit('done'); - }); - }, TypeError - ); + const options = { + port: server.address().port, + headers: { 'testing_123': 123 } + }; + http.get(options, function() { + ee.emit('done'); + }); }); ee.on('done', function() { diff --git a/test/parallel/test-http-response-add-header-after-sent.js b/test/parallel/test-http-response-add-header-after-sent.js index 8329d3ea7ee55b..a4d3f629e24b3d 100644 --- a/test/parallel/test-http-response-add-header-after-sent.js +++ b/test/parallel/test-http-response-add-header-after-sent.js @@ -1,12 +1,9 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const http = require('http'); const server = http.createServer((req, res) => { - assert.doesNotThrow(() => { - res.setHeader('header1', 1); - }); + res.setHeader('header1', 1); res.write('abc'); common.expectsError( () => res.setHeader('header2', 2), diff --git a/test/parallel/test-http-response-remove-header-after-sent.js b/test/parallel/test-http-response-remove-header-after-sent.js index e6adffc1445234..52acd3d1059ef3 100644 --- a/test/parallel/test-http-response-remove-header-after-sent.js +++ b/test/parallel/test-http-response-remove-header-after-sent.js @@ -1,12 +1,9 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const http = require('http'); const server = http.createServer((req, res) => { - assert.doesNotThrow(() => { - res.removeHeader('header1', 1); - }); + res.removeHeader('header1', 1); res.write('abc'); common.expectsError( () => res.removeHeader('header2', 2), diff --git a/test/parallel/test-http2-binding.js b/test/parallel/test-http2-binding.js index 8935e569f500c6..1b8501dcbeca2f 100644 --- a/test/parallel/test-http2-binding.js +++ b/test/parallel/test-http2-binding.js @@ -5,7 +5,7 @@ if (!common.hasCrypto) common.skip('missing crypto'); const assert = require('assert'); -assert.doesNotThrow(() => process.binding('http2')); +process.binding('http2'); const binding = process.binding('http2'); const http2 = require('http2'); diff --git a/test/parallel/test-http2-client-rststream-before-connect.js b/test/parallel/test-http2-client-rststream-before-connect.js index b0faaa5de2a398..177b13a16eed98 100644 --- a/test/parallel/test-http2-client-rststream-before-connect.js +++ b/test/parallel/test-http2-client-rststream-before-connect.js @@ -23,7 +23,7 @@ server.listen(0, common.mustCall(() => { req._destroy = common.mustCall(req._destroy.bind(req)); // second call doesn't do anything - assert.doesNotThrow(() => req.close(8)); + req.close(8); req.on('close', common.mustCall((code) => { assert.strictEqual(req.destroyed, true); diff --git a/test/parallel/test-http2-compat-serverrequest-pause.js b/test/parallel/test-http2-compat-serverrequest-pause.js index 62a23997c75bd8..9c81e8ff6140c7 100644 --- a/test/parallel/test-http2-compat-serverrequest-pause.js +++ b/test/parallel/test-http2-compat-serverrequest-pause.js @@ -28,8 +28,8 @@ server.on('request', common.mustCall((req, res) => { // shouldn't throw if underlying Http2Stream no longer exists res.on('finish', common.mustCall(() => process.nextTick(() => { - assert.doesNotThrow(() => req.pause()); - assert.doesNotThrow(() => req.resume()); + req.pause(); + req.resume(); }))); })); diff --git a/test/parallel/test-http2-compat-serverrequest-settimeout.js b/test/parallel/test-http2-compat-serverrequest-settimeout.js index f7189161802301..81184d70752563 100644 --- a/test/parallel/test-http2-compat-serverrequest-settimeout.js +++ b/test/parallel/test-http2-compat-serverrequest-settimeout.js @@ -3,7 +3,6 @@ const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); -const assert = require('assert'); const http2 = require('http2'); const msecs = common.platformTimeout(1); @@ -16,9 +15,7 @@ server.on('request', (req, res) => { res.on('finish', common.mustCall(() => { req.setTimeout(msecs, common.mustNotCall()); process.nextTick(() => { - assert.doesNotThrow( - () => req.setTimeout(msecs, common.mustNotCall()) - ); + req.setTimeout(msecs, common.mustNotCall()); server.close(); }); })); diff --git a/test/parallel/test-http2-compat-serverresponse-destroy.js b/test/parallel/test-http2-compat-serverresponse-destroy.js index 54214737840061..f890346dbf4303 100644 --- a/test/parallel/test-http2-compat-serverresponse-destroy.js +++ b/test/parallel/test-http2-compat-serverresponse-destroy.js @@ -3,7 +3,6 @@ const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); -const assert = require('assert'); const http2 = require('http2'); const Countdown = require('../common/countdown'); @@ -22,9 +21,9 @@ const server = http2.createServer(common.mustCall((req, res) => { res.on('error', common.mustNotCall()); res.on('finish', common.mustCall(() => { - assert.doesNotThrow(() => res.destroy(nextError)); + res.destroy(nextError); process.nextTick(() => { - assert.doesNotThrow(() => res.destroy(nextError)); + res.destroy(nextError); }); })); diff --git a/test/parallel/test-http2-compat-serverresponse-headers-after-destroy.js b/test/parallel/test-http2-compat-serverresponse-headers-after-destroy.js index 99e3ccc948184e..206bd1c9d43e06 100644 --- a/test/parallel/test-http2-compat-serverresponse-headers-after-destroy.js +++ b/test/parallel/test-http2-compat-serverresponse-headers-after-destroy.js @@ -15,12 +15,12 @@ server.listen(0, common.mustCall(function() { server.once('request', common.mustCall(function(request, response) { response.on('finish', common.mustCall(() => { assert.strictEqual(response.headersSent, false); - assert.doesNotThrow(() => response.setHeader('test', 'value')); - assert.doesNotThrow(() => response.removeHeader('test', 'value')); + response.setHeader('test', 'value'); + response.removeHeader('test', 'value'); process.nextTick(() => { - assert.doesNotThrow(() => response.setHeader('test', 'value')); - assert.doesNotThrow(() => response.removeHeader('test', 'value')); + response.setHeader('test', 'value'); + response.removeHeader('test', 'value'); server.close(); }); diff --git a/test/parallel/test-http2-compat-serverresponse-settimeout.js b/test/parallel/test-http2-compat-serverresponse-settimeout.js index bb09633727ccf7..220a84a754d651 100644 --- a/test/parallel/test-http2-compat-serverresponse-settimeout.js +++ b/test/parallel/test-http2-compat-serverresponse-settimeout.js @@ -3,7 +3,6 @@ const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); -const assert = require('assert'); const http2 = require('http2'); const msecs = common.platformTimeout(1); @@ -16,9 +15,7 @@ server.on('request', (req, res) => { res.on('finish', common.mustCall(() => { res.setTimeout(msecs, common.mustNotCall()); process.nextTick(() => { - assert.doesNotThrow( - () => res.setTimeout(msecs, common.mustNotCall()) - ); + res.setTimeout(msecs, common.mustNotCall()); server.close(); }); })); diff --git a/test/parallel/test-http2-compat-serverresponse-statuscode.js b/test/parallel/test-http2-compat-serverresponse-statuscode.js index ecb6da5df68c11..4c51616ef618fc 100644 --- a/test/parallel/test-http2-compat-serverresponse-statuscode.js +++ b/test/parallel/test-http2-compat-serverresponse-statuscode.js @@ -27,12 +27,10 @@ server.listen(0, common.mustCall(function() { assert.strictEqual(response.statusCode, expectedDefaultStatusCode); - assert.doesNotThrow(function() { - response.statusCode = realStatusCodes.ok; - response.statusCode = realStatusCodes.multipleChoices; - response.statusCode = realStatusCodes.badRequest; - response.statusCode = realStatusCodes.internalServerError; - }); + response.statusCode = realStatusCodes.ok; + response.statusCode = realStatusCodes.multipleChoices; + response.statusCode = realStatusCodes.badRequest; + response.statusCode = realStatusCodes.internalServerError; common.expectsError(function() { response.statusCode = realStatusCodes.continue; diff --git a/test/parallel/test-http2-compat-socket.js b/test/parallel/test-http2-compat-socket.js index 80c8b1d30d10b3..e46bc4ef54751a 100644 --- a/test/parallel/test-http2-compat-socket.js +++ b/test/parallel/test-http2-compat-socket.js @@ -45,7 +45,7 @@ server.on('request', common.mustCall(function(request, response) { request.on('end', common.mustCall(() => { assert.strictEqual(request.socket.readable, false); - assert.doesNotThrow(() => response.socket.destroy()); + response.socket.destroy(); })); response.on('finish', common.mustCall(() => { assert.ok(request.socket); diff --git a/test/parallel/test-http2-connect.js b/test/parallel/test-http2-connect.js index 894c51fe3d9330..9b628db5aeebaa 100644 --- a/test/parallel/test-http2-connect.js +++ b/test/parallel/test-http2-connect.js @@ -3,7 +3,6 @@ const { mustCall, hasCrypto, skip, expectsError } = require('../common'); if (!hasCrypto) skip('missing crypto'); -const { doesNotThrow, throws } = require('assert'); const { createServer, connect } = require('http2'); { const server = createServer(); @@ -13,10 +12,11 @@ const { createServer, connect } = require('http2'); const listener = () => mustCall(); const clients = new Set(); - doesNotThrow(() => clients.add(connect(authority))); - doesNotThrow(() => clients.add(connect(authority, options))); - doesNotThrow(() => clients.add(connect(authority, options, listener()))); - doesNotThrow(() => clients.add(connect(authority, listener()))); + // Should not throw. + clients.add(connect(authority)); + clients.add(connect(authority, options)); + clients.add(connect(authority, options, listener())); + clients.add(connect(authority, listener())); for (const client of clients) { client.once('connect', mustCall((headers) => { @@ -33,20 +33,18 @@ const { createServer, connect } = require('http2'); // check for https as protocol { const authority = 'https://localhost'; - doesNotThrow(() => { - // A socket error may or may not be reported, keep this as a non-op - // instead of a mustCall or mustNotCall - connect(authority).on('error', () => {}); - }); + // A socket error may or may not be reported, keep this as a non-op + // instead of a mustCall or mustNotCall + connect(authority).on('error', () => {}); } // check for error for an invalid protocol (not http or https) { const authority = 'ssh://localhost'; - throws(() => { + expectsError(() => { connect(authority); - }, expectsError({ + }, { code: 'ERR_HTTP2_UNSUPPORTED_PROTOCOL', type: Error - })); + }); } diff --git a/test/parallel/test-http2-getpackedsettings.js b/test/parallel/test-http2-getpackedsettings.js index 9ae2512b2cea06..b02d6b4933bbfa 100644 --- a/test/parallel/test-http2-getpackedsettings.js +++ b/test/parallel/test-http2-getpackedsettings.js @@ -26,11 +26,11 @@ assert.deepStrictEqual(val, check); ['maxHeaderListSize', 0], ['maxHeaderListSize', 2 ** 32 - 1] ].forEach((i) => { - assert.doesNotThrow(() => http2.getPackedSettings({ [i[0]]: i[1] })); + http2.getPackedSettings({ [i[0]]: i[1] }); }); -assert.doesNotThrow(() => http2.getPackedSettings({ enablePush: true })); -assert.doesNotThrow(() => http2.getPackedSettings({ enablePush: false })); +http2.getPackedSettings({ enablePush: true }); +http2.getPackedSettings({ enablePush: false }); [ ['headerTableSize', -1], @@ -151,9 +151,7 @@ assert.doesNotThrow(() => http2.getPackedSettings({ enablePush: false })); 0x00, 0x00, 0x00, 0x64, 0x00, 0x06, 0x00, 0x00, 0x00, 0x64, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01]); - assert.doesNotThrow(() => { - http2.getUnpackedSettings(packed, { validate: true }); - }); + http2.getUnpackedSettings(packed, { validate: true }); } // check for maxFrameSize failing the max number diff --git a/test/parallel/test-http2-server-startup.js b/test/parallel/test-http2-server-startup.js index 0731b83a20b651..12b9cd72cba147 100644 --- a/test/parallel/test-http2-server-startup.js +++ b/test/parallel/test-http2-server-startup.js @@ -10,7 +10,6 @@ const commonFixtures = require('../common/fixtures'); if (!common.hasCrypto) common.skip('missing crypto'); -const assert = require('assert'); const http2 = require('http2'); const tls = require('tls'); const net = require('net'); @@ -21,25 +20,17 @@ const options = { }; // There should not be any throws -assert.doesNotThrow(() => { +const serverTLS = http2.createSecureServer(options, () => {}); +serverTLS.listen(0, common.mustCall(() => serverTLS.close())); - const serverTLS = http2.createSecureServer(options, () => {}); +// There should not be an error event reported either +serverTLS.on('error', common.mustNotCall()); - serverTLS.listen(0, common.mustCall(() => serverTLS.close())); +const server = http2.createServer(options, common.mustNotCall()); +server.listen(0, common.mustCall(() => server.close())); - // There should not be an error event reported either - serverTLS.on('error', common.mustNotCall()); -}); - -// There should not be any throws -assert.doesNotThrow(() => { - const server = http2.createServer(options, common.mustNotCall()); - - server.listen(0, common.mustCall(() => server.close())); - - // There should not be an error event reported either - server.on('error', common.mustNotCall()); -}); +// There should not be an error event reported either +server.on('error', common.mustNotCall()); // Test the plaintext server socket timeout { diff --git a/test/parallel/test-http2-session-settings.js b/test/parallel/test-http2-session-settings.js index 75fcc1942104ac..6061808082519d 100644 --- a/test/parallel/test-http2-session-settings.js +++ b/test/parallel/test-http2-session-settings.js @@ -76,9 +76,7 @@ server.listen( // State will only be valid after connect event is emitted req.on('ready', common.mustCall(() => { - assert.doesNotThrow(() => { - client.settings({ maxHeaderListSize: 1 }, common.mustCall()); - }); + client.settings({ maxHeaderListSize: 1 }, common.mustCall()); // Verify valid error ranges [ diff --git a/test/parallel/test-http2-socket-proxy.js b/test/parallel/test-http2-socket-proxy.js index 2d90ef7e952a55..e954439d78c07c 100644 --- a/test/parallel/test-http2-socket-proxy.js +++ b/test/parallel/test-http2-socket-proxy.js @@ -47,8 +47,8 @@ server.on('stream', common.mustCall(function(stream, headers) { common.expectsError(() => (socket.resume = undefined), errMsg); common.expectsError(() => (socket.write = undefined), errMsg); - assert.doesNotThrow(() => (socket.on = socket.on)); - assert.doesNotThrow(() => (socket.once = socket.once)); + socket.on = socket.on; + socket.once = socket.once; stream.respond(); diff --git a/test/parallel/test-http2-util-asserts.js b/test/parallel/test-http2-util-asserts.js index 1e7a0113f4a850..bfed09de4f72b8 100644 --- a/test/parallel/test-http2-util-asserts.js +++ b/test/parallel/test-http2-util-asserts.js @@ -2,7 +2,6 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const { assertIsObject, assertWithinRange, @@ -15,7 +14,7 @@ const { new Date(), new (class Foo {})() ].forEach((i) => { - assert.doesNotThrow(() => assertIsObject(i, 'foo', 'Object')); + assertIsObject(i, 'foo', 'Object'); }); [ @@ -34,7 +33,7 @@ const { }); }); -assert.doesNotThrow(() => assertWithinRange('foo', 1, 0, 2)); +assertWithinRange('foo', 1, 0, 2); common.expectsError(() => assertWithinRange('foo', 1, 2, 3), { diff --git a/test/parallel/test-http2-withflag.js b/test/parallel/test-http2-withflag.js index 0a01efc517b916..3cc5c69c681c50 100644 --- a/test/parallel/test-http2-withflag.js +++ b/test/parallel/test-http2-withflag.js @@ -3,6 +3,5 @@ const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); -const assert = require('assert'); -assert.doesNotThrow(() => require('http2')); +require('http2'); diff --git a/test/parallel/test-https-agent-constructor.js b/test/parallel/test-https-agent-constructor.js index 29bb9eaa98067d..571160bbb845dd 100644 --- a/test/parallel/test-https-agent-constructor.js +++ b/test/parallel/test-https-agent-constructor.js @@ -6,5 +6,5 @@ if (!common.hasCrypto) const assert = require('assert'); const https = require('https'); -assert.doesNotThrow(() => { https.Agent(); }); +https.Agent(); assert.ok(https.Agent() instanceof https.Agent); diff --git a/test/parallel/test-https-options-boolean-check.js b/test/parallel/test-https-options-boolean-check.js index 04baf403df98cb..fa223aa8872bd6 100644 --- a/test/parallel/test-https-options-boolean-check.js +++ b/test/parallel/test-https-options-boolean-check.js @@ -6,7 +6,6 @@ const fixtures = require('../common/fixtures'); if (!common.hasCrypto) common.skip('missing crypto'); -const assert = require('assert'); const https = require('https'); function toArrayBuffer(buf) { @@ -65,11 +64,9 @@ const invalidCertRE = /^The "cert" argument must be one of type string, Buffer, [[{ pem: keyBuff }], false], [[{ pem: keyBuff }, { pem: keyBuff }], false] ].forEach((params) => { - assert.doesNotThrow(() => { - https.createServer({ - key: params[0], - cert: params[1] - }); + https.createServer({ + key: params[0], + cert: params[1] }); }); @@ -124,12 +121,10 @@ const invalidCertRE = /^The "cert" argument must be one of type string, Buffer, [keyBuff, certBuff, caArrDataView], [keyBuff, certBuff, false], ].forEach((params) => { - assert.doesNotThrow(() => { - https.createServer({ - key: params[0], - cert: params[1], - ca: params[2] - }); + https.createServer({ + key: params[0], + cert: params[1], + ca: params[2] }); }); diff --git a/test/parallel/test-icu-punycode.js b/test/parallel/test-icu-punycode.js index 7abcae461774c0..3ca30a6d168ba9 100644 --- a/test/parallel/test-icu-punycode.js +++ b/test/parallel/test-icu-punycode.js @@ -34,13 +34,12 @@ const wptToASCIITests = require('../fixtures/url-toascii.js'); if (output === null) { assert.throws(() => icu.toASCII(input), errMessage, `ToASCII ${caseComment}`); - assert.doesNotThrow(() => icu.toASCII(input, true), - `ToASCII ${caseComment} in lenient mode`); + icu.toASCII(input, true); } else { assert.strictEqual(icu.toASCII(input), output, `ToASCII ${caseComment}`); assert.strictEqual(icu.toASCII(input, true), output, `ToASCII ${caseComment} in lenient mode`); } - assert.doesNotThrow(() => icu.toUnicode(input), `ToUnicode ${caseComment}`); + icu.toUnicode(input); } } diff --git a/test/parallel/test-internal-errors.js b/test/parallel/test-internal-errors.js index ae5e2672285688..680fedc585d161 100644 --- a/test/parallel/test-internal-errors.js +++ b/test/parallel/test-internal-errors.js @@ -138,32 +138,24 @@ common.expectsError( message: invalidKey('true') }); - // Tests for common.expectsError -assert.doesNotThrow(() => { - common.expectsError(() => { - throw new errors.TypeError('TEST_ERROR_1', 'a'); - }, { code: 'TEST_ERROR_1' }); -}); - -assert.doesNotThrow(() => { - common.expectsError(() => { - throw new errors.TypeError('TEST_ERROR_1', 'a'); - }, { code: 'TEST_ERROR_1', - type: TypeError, - message: /^Error for testing/ }); -}); - -assert.doesNotThrow(() => { - common.expectsError(() => { - throw new errors.TypeError('TEST_ERROR_1', 'a'); - }, { code: 'TEST_ERROR_1', type: TypeError }); -}); - -assert.doesNotThrow(() => { - common.expectsError(() => { - throw new errors.TypeError('TEST_ERROR_1', 'a'); - }, { code: 'TEST_ERROR_1', type: Error }); +common.expectsError(() => { + throw new errors.TypeError('TEST_ERROR_1', 'a'); +}, { code: 'TEST_ERROR_1' }); +common.expectsError(() => { + throw new errors.TypeError('TEST_ERROR_1', 'a'); +}, { code: 'TEST_ERROR_1', + type: TypeError, + message: /^Error for testing/ }); +common.expectsError(() => { + throw new errors.TypeError('TEST_ERROR_1', 'a'); +}, { code: 'TEST_ERROR_1', type: TypeError }); +common.expectsError(() => { + throw new errors.TypeError('TEST_ERROR_1', 'a'); +}, { + code: 'TEST_ERROR_1', + type: TypeError, + message: 'Error for testing purposes: a' }); common.expectsError(() => { diff --git a/test/parallel/test-internal-fs.js b/test/parallel/test-internal-fs.js index fe6c50194d1c72..3f270f93d5359b 100644 --- a/test/parallel/test-internal-fs.js +++ b/test/parallel/test-internal-fs.js @@ -2,11 +2,10 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const fs = require('internal/fs'); -assert.doesNotThrow(() => fs.assertEncoding()); -assert.doesNotThrow(() => fs.assertEncoding('utf8')); +fs.assertEncoding(); +fs.assertEncoding('utf8'); common.expectsError( () => fs.assertEncoding('foo'), { code: 'ERR_INVALID_OPT_VALUE_ENCODING', type: TypeError } diff --git a/test/parallel/test-internal-util-assertCrypto.js b/test/parallel/test-internal-util-assertCrypto.js index d01eab3a237ded..035519c9c9ef7a 100644 --- a/test/parallel/test-internal-util-assertCrypto.js +++ b/test/parallel/test-internal-util-assertCrypto.js @@ -11,5 +11,5 @@ if (!process.versions.openssl) { }); assert.throws(() => util.assertCrypto(), expectedError); } else { - assert.doesNotThrow(() => util.assertCrypto()); + util.assertCrypto(); } diff --git a/test/parallel/test-internal-util-decorate-error-stack.js b/test/parallel/test-internal-util-decorate-error-stack.js index a0682161ae2c69..155a2718f90c55 100644 --- a/test/parallel/test-internal-util-decorate-error-stack.js +++ b/test/parallel/test-internal-util-decorate-error-stack.js @@ -12,12 +12,10 @@ const kDecoratedPrivateSymbolIndex = binding.decorated_private_symbol; const decorateErrorStack = internalUtil.decorateErrorStack; -assert.doesNotThrow(function() { - decorateErrorStack(); - decorateErrorStack(null); - decorateErrorStack(1); - decorateErrorStack(true); -}); +decorateErrorStack(); +decorateErrorStack(null); +decorateErrorStack(1); +decorateErrorStack(true); // Verify that a stack property is not added to non-Errors const obj = {}; diff --git a/test/parallel/test-module-symlinked-peer-modules.js b/test/parallel/test-module-symlinked-peer-modules.js index 27e67b31d182e5..09ba4b17b55f3b 100644 --- a/test/parallel/test-module-symlinked-peer-modules.js +++ b/test/parallel/test-module-symlinked-peer-modules.js @@ -11,7 +11,6 @@ const common = require('../common'); const fs = require('fs'); const path = require('path'); -const assert = require('assert'); const tmpdir = require('../common/tmpdir'); tmpdir.refresh(); @@ -60,6 +59,4 @@ fs.writeFileSync(path.join(moduleB, 'package.json'), fs.writeFileSync(path.join(moduleB, 'index.js'), 'module.exports = 1;', 'utf8'); -assert.doesNotThrow(() => { - require(path.join(app, 'index')); -}); +require(path.join(app, 'index')); diff --git a/test/parallel/test-net-after-close.js b/test/parallel/test-net-after-close.js index 1594d36f9075a3..23e265c09a954a 100644 --- a/test/parallel/test-net-after-close.js +++ b/test/parallel/test-net-after-close.js @@ -34,16 +34,14 @@ server.listen(0, common.mustCall(function() { c.on('close', common.mustCall(function() { console.error('connection closed'); assert.strictEqual(c._handle, null); - assert.doesNotThrow(function() { - c.setNoDelay(); - c.setKeepAlive(); - c.bufferSize; - c.pause(); - c.resume(); - c.address(); - c.remoteAddress; - c.remotePort; - }); + c.setNoDelay(); + c.setKeepAlive(); + c.bufferSize; + c.pause(); + c.resume(); + c.address(); + c.remoteAddress; + c.remotePort; server.close(); })); })); diff --git a/test/parallel/test-net-connect-options-port.js b/test/parallel/test-net-connect-options-port.js index 8152424c52c8fc..ea3fadf7211af6 100644 --- a/test/parallel/test-net-connect-options-port.js +++ b/test/parallel/test-net-connect-options-port.js @@ -171,27 +171,26 @@ function canConnect(port) { // connect(port, cb) and connect(port) const portArgBlocks = doConnect([port], noop); for (const block of portArgBlocks) { - assert.doesNotThrow(block, `${block.name}(${port})`); + block(); } // connect(port, host, cb) and connect(port, host) const portHostArgBlocks = doConnect([port, 'localhost'], noop); for (const block of portHostArgBlocks) { - assert.doesNotThrow(block, `${block.name}(${port})`); + block(); } // connect({port}, cb) and connect({port}) const portOptBlocks = doConnect([{ port }], noop); for (const block of portOptBlocks) { - assert.doesNotThrow(block, `${block.name}({port: ${port}})`); + block(); } // connect({port, host}, cb) and connect({port, host}) const portHostOptBlocks = doConnect([{ port: port, host: 'localhost' }], noop); for (const block of portHostOptBlocks) { - assert.doesNotThrow(block, - `${block.name}({port: ${port}, host: 'localhost'})`); + block(); } } @@ -205,25 +204,19 @@ function asyncFailToConnect(port) { // connect(port, cb) and connect(port) const portArgBlocks = doConnect([port], dont); for (const block of portArgBlocks) { - assert.doesNotThrow(function() { - block().on('error', onError()); - }, `${block.name}(${port})`); + block().on('error', onError()); } // connect({port}, cb) and connect({port}) const portOptBlocks = doConnect([{ port }], dont); for (const block of portOptBlocks) { - assert.doesNotThrow(function() { - block().on('error', onError()); - }, `${block.name}({port: ${port}})`); + block().on('error', onError()); } // connect({port, host}, cb) and connect({port, host}) const portHostOptBlocks = doConnect([{ port: port, host: 'localhost' }], dont); for (const block of portHostOptBlocks) { - assert.doesNotThrow(function() { - block().on('error', onError()); - }, `${block.name}({port: ${port}, host: 'localhost'})`); + block().on('error', onError()); } } diff --git a/test/parallel/test-net-during-close.js b/test/parallel/test-net-during-close.js index a85863955e7728..11c3dab00f2ec6 100644 --- a/test/parallel/test-net-during-close.js +++ b/test/parallel/test-net-during-close.js @@ -21,7 +21,6 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const net = require('net'); const server = net.createServer(function(socket) { @@ -33,11 +32,9 @@ server.listen(0, common.mustCall(function() { server.close(); // server connection event has not yet fired // client is still attempting to connect - assert.doesNotThrow(function() { - client.remoteAddress; - client.remoteFamily; - client.remotePort; - }); + client.remoteAddress; + client.remoteFamily; + client.remotePort; // exit now, do not wait for the client error event process.exit(0); })); diff --git a/test/parallel/test-net-options-lookup.js b/test/parallel/test-net-options-lookup.js index 0551a241147e84..0b4e18f12f04f0 100644 --- a/test/parallel/test-net-options-lookup.js +++ b/test/parallel/test-net-options-lookup.js @@ -1,6 +1,5 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const net = require('net'); ['foobar', 1, {}, []].forEach((input) => connectThrows(input)); @@ -30,7 +29,5 @@ function connectDoesNotThrow(input) { lookup: input }; - assert.doesNotThrow(() => { - net.connect(opts); - }); + net.connect(opts); } diff --git a/test/parallel/test-net-server-call-listen-multiple-times.js b/test/parallel/test-net-server-call-listen-multiple-times.js index 05099dadc86bdf..4b1a8d07334ac2 100644 --- a/test/parallel/test-net-server-call-listen-multiple-times.js +++ b/test/parallel/test-net-server-call-listen-multiple-times.js @@ -1,7 +1,6 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const net = require('net'); // First test. Check that after error event you can listen right away. @@ -16,12 +15,10 @@ const net = require('net'); })); server.on('error', common.mustCall((e) => { - assert.doesNotThrow( - () => server.listen(common.mustCall(() => { - dummyServer.close(); - server.close(); - })) - ); + server.listen(common.mustCall(() => { + dummyServer.close(); + server.close(); + })); })); } @@ -44,8 +41,6 @@ const net = require('net'); server.listen(common.mustCall(() => { server.close(); - assert.doesNotThrow( - () => server.listen(common.mustCall(() => server.close())) - ); + server.listen(common.mustCall(() => server.close())); })); } diff --git a/test/parallel/test-net-socket-timeout.js b/test/parallel/test-net-socket-timeout.js index de4a7ed37ccf20..51224f3b7ecdcf 100644 --- a/test/parallel/test-net-socket-timeout.js +++ b/test/parallel/test-net-socket-timeout.js @@ -46,9 +46,7 @@ for (let i = 0; i < badRangeDelays.length; i++) { } for (let i = 0; i < validDelays.length; i++) { - assert.doesNotThrow(function() { - s.setTimeout(validDelays[i], () => {}); - }); + s.setTimeout(validDelays[i], () => {}); } const server = net.Server(); diff --git a/test/parallel/test-performanceobserver.js b/test/parallel/test-performanceobserver.js index af83d199da9186..2a6299952271e1 100644 --- a/test/parallel/test-performanceobserver.js +++ b/test/parallel/test-performanceobserver.js @@ -77,7 +77,7 @@ assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_FUNCTION], 0); countdown.dec(); } assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_MARK], 1); - assert.doesNotThrow(() => observer.observe({ entryTypes: ['mark'] })); + observer.observe({ entryTypes: ['mark'] }); assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_MARK], 2); performance.mark('test1'); performance.mark('test2'); @@ -125,13 +125,9 @@ assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_FUNCTION], 0); } } - assert.doesNotThrow(() => { - observer.observe({ entryTypes: ['mark', 'measure'], buffered: true }); - }); + observer.observe({ entryTypes: ['mark', 'measure'], buffered: true }); // Do this twice to make sure it doesn't throw - assert.doesNotThrow(() => { - observer.observe({ entryTypes: ['mark', 'measure'], buffered: true }); - }); + observer.observe({ entryTypes: ['mark', 'measure'], buffered: true }); // Even tho we called twice, count should be 1 assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_MARK], 2); performance.mark('test1'); diff --git a/test/parallel/test-process-binding.js b/test/parallel/test-process-binding.js index 475891aa5d30d8..3715826bb27615 100644 --- a/test/parallel/test-process-binding.js +++ b/test/parallel/test-process-binding.js @@ -9,10 +9,4 @@ assert.throws( /No such module: test/ ); -assert.doesNotThrow(function() { - process.binding('buffer'); -}, function(err) { - if (err instanceof Error) { - return true; - } -}, 'unexpected error'); +process.binding('buffer'); diff --git a/test/parallel/test-process-emitwarning.js b/test/parallel/test-process-emitwarning.js index 06772c7be6c210..e07fcd253c4128 100644 --- a/test/parallel/test-process-emitwarning.js +++ b/test/parallel/test-process-emitwarning.js @@ -44,7 +44,7 @@ class CustomWarning extends Error { [testMsg, { type: testType, code: testCode, detail: null }], [testMsg, { type: testType, code: testCode, detail: 1 }] ].forEach((i) => { - assert.doesNotThrow(() => process.emitWarning.apply(null, i)); + process.emitWarning.apply(null, i); }); const warningNoToString = new CustomWarning(); diff --git a/test/parallel/test-process-env-symbols.js b/test/parallel/test-process-env-symbols.js index 51e8eafbeacf51..855c791c0fb033 100644 --- a/test/parallel/test-process-env-symbols.js +++ b/test/parallel/test-process-env-symbols.js @@ -28,4 +28,4 @@ assert.strictEqual(symbol in process.env, false); assert.strictEqual(delete process.env[symbol], true); // Checks that well-known symbols like `Symbol.toStringTag` won’t throw. -assert.doesNotThrow(() => Object.prototype.toString.call(process.env)); +Object.prototype.toString.call(process.env); diff --git a/test/parallel/test-process-geteuid-getegid.js b/test/parallel/test-process-geteuid-getegid.js index 8dab52389b0384..96e8765eb99015 100644 --- a/test/parallel/test-process-geteuid-getegid.js +++ b/test/parallel/test-process-geteuid-getegid.js @@ -21,10 +21,8 @@ assert.throws(() => { // If we're not running as super user... if (process.getuid() !== 0) { - assert.doesNotThrow(() => { - process.getegid(); - process.geteuid(); - }); + process.getegid(); + process.geteuid(); assert.throws(() => { process.setegid('nobody'); diff --git a/test/parallel/test-process-setuid-setgid.js b/test/parallel/test-process-setuid-setgid.js index e0db8ee00222dd..0060e3b1ca4af4 100644 --- a/test/parallel/test-process-setuid-setgid.js +++ b/test/parallel/test-process-setuid-setgid.js @@ -39,10 +39,8 @@ assert.throws(() => { // If we're not running as super user... if (process.getuid() !== 0) { - assert.doesNotThrow(() => { - process.getgid(); - process.getuid(); - }); + process.getgid(); + process.getuid(); assert.throws( () => { process.setgid('nobody'); }, diff --git a/test/parallel/test-querystring.js b/test/parallel/test-querystring.js index 5b314fd661d75b..b0ed9c4ea1d30c 100644 --- a/test/parallel/test-querystring.js +++ b/test/parallel/test-querystring.js @@ -300,9 +300,7 @@ assert.strictEqual('foo=', qs.stringify({ foo: Infinity })); assert.strictEqual(f, 'a=b&q=x%3Dy%26y%3Dz'); } -assert.doesNotThrow(() => { - qs.parse(undefined); -}); +qs.parse(undefined); // nested in colon { diff --git a/test/parallel/test-readline-csi.js b/test/parallel/test-readline-csi.js index a3316a8800e4e3..54ca6bde97bbe9 100644 --- a/test/parallel/test-readline-csi.js +++ b/test/parallel/test-readline-csi.js @@ -61,15 +61,15 @@ assert.deepStrictEqual(writable.data, CSI.kClearLine); assert.deepStrictEqual(writable.data, set[2]); }); -assert.doesNotThrow(() => readline.cursorTo(null)); -assert.doesNotThrow(() => readline.cursorTo()); +readline.cursorTo(null); +readline.cursorTo(); writable.data = ''; -assert.doesNotThrow(() => readline.cursorTo(writable, 'a')); +readline.cursorTo(writable, 'a'); assert.strictEqual(writable.data, ''); writable.data = ''; -assert.doesNotThrow(() => readline.cursorTo(writable, 'a', 'b')); +readline.cursorTo(writable, 'a', 'b'); assert.strictEqual(writable.data, ''); writable.data = ''; @@ -83,9 +83,9 @@ common.expectsError( assert.strictEqual(writable.data, ''); writable.data = ''; -assert.doesNotThrow(() => readline.cursorTo(writable, 1, 'a')); +readline.cursorTo(writable, 1, 'a'); assert.strictEqual(writable.data, '\x1b[2G'); writable.data = ''; -assert.doesNotThrow(() => readline.cursorTo(writable, 1, 2)); +readline.cursorTo(writable, 1, 2); assert.strictEqual(writable.data, '\x1b[3;2H'); diff --git a/test/parallel/test-readline-interface.js b/test/parallel/test-readline-interface.js index fe33e244cebd20..30afba843a2d98 100644 --- a/test/parallel/test-readline-interface.js +++ b/test/parallel/test-readline-interface.js @@ -823,23 +823,12 @@ function isWarned(emitter) { fi.emit('data', 'asdf\n'); assert.ok(called); - assert.doesNotThrow(function() { - rli.setPrompt('ddd> '); - }); - - assert.doesNotThrow(function() { - rli.prompt(); - }); - - assert.doesNotThrow(function() { - rli.write('really shouldnt be seeing this'); - }); - - assert.doesNotThrow(function() { - rli.question('What do you think of node.js? ', function(answer) { - console.log('Thank you for your valuable feedback:', answer); - rli.close(); - }); + rli.setPrompt('ddd> '); + rli.prompt(); + rli.write('really shouldnt be seeing this'); + rli.question('What do you think of node.js? ', function(answer) { + console.log('Thank you for your valuable feedback:', answer); + rli.close(); }); } diff --git a/test/parallel/test-repl-null.js b/test/parallel/test-repl-null.js index 66d09b28f28b84..18009558eda4b5 100644 --- a/test/parallel/test-repl-null.js +++ b/test/parallel/test-repl-null.js @@ -1,7 +1,6 @@ 'use strict'; require('../common'); const repl = require('repl'); -const assert = require('assert'); const replserver = new repl.REPLServer(); @@ -10,8 +9,5 @@ replserver._inTemplateLiteral = true; // `null` gets treated like an empty string. (Should it? You have to do some // strange business to get it into the REPL. Maybe it should really throw?) -assert.doesNotThrow(() => { - replserver.emit('line', null); -}); - +replserver.emit('line', null); replserver.emit('line', '.exit'); diff --git a/test/parallel/test-repl-throw-null-or-undefined.js b/test/parallel/test-repl-throw-null-or-undefined.js index fd2fd202b5bcb6..3b4657ce98c0f3 100644 --- a/test/parallel/test-repl-throw-null-or-undefined.js +++ b/test/parallel/test-repl-throw-null-or-undefined.js @@ -3,16 +3,11 @@ require('../common'); // This test ensures that the repl does not // crash or emit error when throwing `null|undefined` -// ie `throw null` or `throw undefined` +// ie `throw null` or `throw undefined`. -const assert = require('assert'); -const repl = require('repl'); - -const r = repl.start(); - -assert.doesNotThrow(() => { - r.write('throw null\n'); - r.write('throw undefined\n'); -}, TypeError, 'repl crashes/throw error on `throw null|undefined`'); +const r = require('repl').start(); +// Should not throw. +r.write('throw null\n'); +r.write('throw undefined\n'); r.write('.exit\n'); diff --git a/test/parallel/test-stdio-closed.js b/test/parallel/test-stdio-closed.js index 7a6625f494d3a6..c21bbc2eac12b7 100644 --- a/test/parallel/test-stdio-closed.js +++ b/test/parallel/test-stdio-closed.js @@ -22,7 +22,7 @@ if (common.isWindows) { } if (process.argv[2] === 'child') { - [0, 1, 2].forEach((i) => assert.doesNotThrow(() => fs.fstatSync(i))); + [0, 1, 2].forEach((i) => fs.fstatSync(i)); return; } diff --git a/test/parallel/test-stream-writable-null.js b/test/parallel/test-stream-writable-null.js index f1b91dee211005..706141821be175 100644 --- a/test/parallel/test-stream-writable-null.js +++ b/test/parallel/test-stream-writable-null.js @@ -27,14 +27,14 @@ common.expectsError( } ); -assert.doesNotThrow(() => { +{ const m = new MyWritable({ objectMode: true }).on('error', (e) => { assert.ok(e); }); m.write(null, (err) => { assert.ok(err); }); -}); +} common.expectsError( () => { @@ -47,24 +47,25 @@ common.expectsError( } ); -assert.doesNotThrow(() => { +{ const m = new MyWritable().on('error', (e) => { assert.ok(e); }); m.write(false, (err) => { assert.ok(err); }); -}); +} -assert.doesNotThrow(() => { +{ const m = new MyWritable({ objectMode: true }); m.write(false, (err) => assert.ifError(err)); -}); -assert.doesNotThrow(() => { +} + +{ const m = new MyWritable({ objectMode: true }).on('error', (e) => { assert.ifError(e || new Error('should not get here')); }); m.write(false, (err) => { assert.ifError(err); }); -}); +} diff --git a/test/parallel/test-timers-clear-null-does-not-throw-error.js b/test/parallel/test-timers-clear-null-does-not-throw-error.js index a15072a4c63f46..89d433c191abe1 100644 --- a/test/parallel/test-timers-clear-null-does-not-throw-error.js +++ b/test/parallel/test-timers-clear-null-does-not-throw-error.js @@ -1,18 +1,11 @@ 'use strict'; require('../common'); -const assert = require('assert'); // This test makes sure clearing timers with // 'null' or no input does not throw error - -assert.doesNotThrow(() => clearInterval(null)); - -assert.doesNotThrow(() => clearInterval()); - -assert.doesNotThrow(() => clearTimeout(null)); - -assert.doesNotThrow(() => clearTimeout()); - -assert.doesNotThrow(() => clearImmediate(null)); - -assert.doesNotThrow(() => clearImmediate()); +clearInterval(null); +clearInterval(); +clearTimeout(null); +clearTimeout(); +clearImmediate(null); +clearImmediate(); diff --git a/test/parallel/test-timers-unref.js b/test/parallel/test-timers-unref.js index 9e5a4228ba92ed..d8624d8d9c9099 100644 --- a/test/parallel/test-timers-unref.js +++ b/test/parallel/test-timers-unref.js @@ -22,7 +22,6 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); let unref_interval = false; let unref_timer = false; @@ -31,13 +30,8 @@ let checks = 0; const LONG_TIME = 10 * 1000; const SHORT_TIME = 100; -assert.doesNotThrow(() => { - setTimeout(() => {}, 10).unref().ref().unref(); -}, 'ref and unref are chainable'); - -assert.doesNotThrow(() => { - setInterval(() => {}, 10).unref().ref().unref(); -}, 'ref and unref are chainable'); +setTimeout(() => {}, 10).unref().ref().unref(); +setInterval(() => {}, 10).unref().ref().unref(); setInterval(common.mustNotCall('Interval should not fire'), LONG_TIME).unref(); setTimeout(common.mustNotCall('Timer should not fire'), LONG_TIME).unref(); diff --git a/test/parallel/test-tls-client-abort.js b/test/parallel/test-tls-client-abort.js index be81420d154c08..09f252db308881 100644 --- a/test/parallel/test-tls-client-abort.js +++ b/test/parallel/test-tls-client-abort.js @@ -24,7 +24,6 @@ const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); -const assert = require('assert'); const tls = require('tls'); const fixtures = require('../common/fixtures'); @@ -32,8 +31,5 @@ const cert = fixtures.readSync('test_cert.pem'); const key = fixtures.readSync('test_key.pem'); const conn = tls.connect({ cert, key, port: 0 }, common.mustNotCall()); -conn.on('error', function() { -}); -assert.doesNotThrow(function() { - conn.destroy(); -}); +conn.on('error', function() {}); +conn.destroy(); diff --git a/test/parallel/test-tls-client-abort2.js b/test/parallel/test-tls-client-abort2.js index 59b592d2556699..b253e6696c6b5c 100644 --- a/test/parallel/test-tls-client-abort2.js +++ b/test/parallel/test-tls-client-abort2.js @@ -24,12 +24,9 @@ const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); -const assert = require('assert'); const tls = require('tls'); const conn = tls.connect(0, common.mustNotCall()); conn.on('error', common.mustCall(function() { - assert.doesNotThrow(function() { - conn.destroy(); - }); + conn.destroy(); })); diff --git a/test/parallel/test-tls-legacy-deprecated.js b/test/parallel/test-tls-legacy-deprecated.js index 3b1919010e40e6..c2560daf21407c 100644 --- a/test/parallel/test-tls-legacy-deprecated.js +++ b/test/parallel/test-tls-legacy-deprecated.js @@ -4,7 +4,6 @@ const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); -const assert = require('assert'); const tls = require('tls'); common.expectWarning( @@ -12,4 +11,4 @@ common.expectWarning( 'tls.createSecurePair() is deprecated. Please use tls.TLSSocket instead.' ); -assert.doesNotThrow(() => tls.createSecurePair()); +tls.createSecurePair(); diff --git a/test/parallel/test-tls-options-boolean-check.js b/test/parallel/test-tls-options-boolean-check.js index b84d9b8b1732c4..53f595e0de50e5 100644 --- a/test/parallel/test-tls-options-boolean-check.js +++ b/test/parallel/test-tls-options-boolean-check.js @@ -6,7 +6,6 @@ const fixtures = require('../common/fixtures'); if (!common.hasCrypto) common.skip('missing crypto'); -const assert = require('assert'); const tls = require('tls'); function toArrayBuffer(buf) { @@ -65,9 +64,7 @@ const invalidCertRE = /^The "cert" argument must be one of type string, Buffer, [[{ pem: keyBuff }], false], [[{ pem: keyBuff }, { pem: keyBuff }], false] ].forEach(([key, cert]) => { - assert.doesNotThrow(() => { - tls.createServer({ key, cert }); - }); + tls.createServer({ key, cert }); }); // Checks to ensure tls.createServer predictably throws an error @@ -118,9 +115,7 @@ const invalidCertRE = /^The "cert" argument must be one of type string, Buffer, [keyBuff, certBuff, caArrDataView], [keyBuff, certBuff, false], ].forEach(([key, cert, ca]) => { - assert.doesNotThrow(() => { - tls.createServer({ key, cert, ca }); - }); + tls.createServer({ key, cert, ca }); }); // Checks to ensure tls.createServer throws an error for CA assignment @@ -168,7 +163,5 @@ const invalidCertRE = /^The "cert" argument must be one of type string, Buffer, ['', '', ''], [0, 0, 0] ].forEach(([key, cert, ca]) => { - assert.doesNotThrow(() => { - tls.createSecureContext({ key, cert, ca }); - }); + tls.createSecureContext({ key, cert, ca }); }); diff --git a/test/parallel/test-util-inspect-proxy.js b/test/parallel/test-util-inspect-proxy.js index 63527986b1cbf1..d7fb28ddc77282 100644 --- a/test/parallel/test-util-inspect-proxy.js +++ b/test/parallel/test-util-inspect-proxy.js @@ -13,7 +13,7 @@ const handler = { const proxyObj = new Proxy(target, handler); // Inspecting the proxy should not actually walk it's properties -assert.doesNotThrow(() => util.inspect(proxyObj, opts)); +util.inspect(proxyObj, opts); // getProxyDetails is an internal method, not intended for public use. // This is here to test that the internals are working correctly. diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 83f6b469d68055..9133887a7570a7 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -538,30 +538,26 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324'); assert.strictEqual(util.inspect(Object.create(Date.prototype)), 'Date {}'); // GH-1944 -assert.doesNotThrow(() => { +{ const d = new Date(); d.toUTCString = null; util.inspect(d); -}); +} -assert.doesNotThrow(() => { +{ const d = new Date(); d.toISOString = null; util.inspect(d); -}); +} -assert.doesNotThrow(() => { - const r = /regexp/; - r.toString = null; - util.inspect(r); -}); +const r = /regexp/; +r.toString = null; +util.inspect(r); // bug with user-supplied inspect function returns non-string -assert.doesNotThrow(() => { - util.inspect([{ - inspect: () => 123 - }]); -}); +util.inspect([{ + inspect: () => 123 +}]); // GH-2225 { @@ -625,10 +621,8 @@ assert.doesNotThrow(() => { } // an object with "hasOwnProperty" overwritten should not throw -assert.doesNotThrow(() => { - util.inspect({ - hasOwnProperty: null - }); +util.inspect({ + hasOwnProperty: null }); // new API, accepts an "options" object @@ -1158,7 +1152,7 @@ if (typeof Symbol !== 'undefined') { ); } -assert.doesNotThrow(() => util.inspect(process)); +util.inspect(process); // Should not throw. /* eslint-enable accessor-pairs */ // Setting custom inspect property to a non-function should do nothing. diff --git a/test/parallel/test-uv-errno.js b/test/parallel/test-uv-errno.js index 28f43db94a247d..c3ac40e3c94e0a 100644 --- a/test/parallel/test-uv-errno.js +++ b/test/parallel/test-uv-errno.js @@ -14,14 +14,12 @@ keys.forEach((key) => { if (!key.startsWith('UV_')) return; - assert.doesNotThrow(() => { - const err = _errnoException(uv[key], 'test'); - const name = uv.errname(uv[key]); - assert.strictEqual(getSystemErrorName(uv[key]), name); - assert.strictEqual(err.code, name); - assert.strictEqual(err.code, err.errno); - assert.strictEqual(err.message, `test ${name}`); - }); + const err = _errnoException(uv[key], 'test'); + const name = uv.errname(uv[key]); + assert.strictEqual(getSystemErrorName(uv[key]), name); + assert.strictEqual(err.code, name); + assert.strictEqual(err.code, err.errno); + assert.strictEqual(err.message, `test ${name}`); }); [0, 1, 'test', {}, [], Infinity, -Infinity, NaN].forEach((key) => { diff --git a/test/parallel/test-v8-global-setter.js b/test/parallel/test-v8-global-setter.js index f4631cf75ca239..5ee765d6e16bc4 100644 --- a/test/parallel/test-v8-global-setter.js +++ b/test/parallel/test-v8-global-setter.js @@ -21,14 +21,8 @@ 'use strict'; require('../common'); -const assert = require('assert'); - -assert.doesNotThrow(function() { - require('vm').runInNewContext('"use strict"; var v = 1; v = 2'); -}); // This test ensures v8 correctly sets a property on the global object if it // has a setter interceptor in strict mode. // https://github.com/nodejs/node-v0.x-archive/issues/6235 - require('vm').runInNewContext('"use strict"; var v = 1; v = 2'); diff --git a/test/parallel/test-vm-access-process-env.js b/test/parallel/test-vm-access-process-env.js index a2f3cb5741de45..c6b18ec9026cd0 100644 --- a/test/parallel/test-vm-access-process-env.js +++ b/test/parallel/test-vm-access-process-env.js @@ -28,8 +28,6 @@ require('../common'); const assert = require('assert'); const vm = require('vm'); -assert.doesNotThrow(function() { - const context = vm.createContext({ process }); - const result = vm.runInContext('process.env["PATH"]', context); - assert.notStrictEqual(undefined, result); -}); +const context = vm.createContext({ process }); +const result = vm.runInContext('process.env["PATH"]', context); +assert.notStrictEqual(undefined, result); diff --git a/test/parallel/test-vm-create-context-arg.js b/test/parallel/test-vm-create-context-arg.js index 8675add90cfcc6..f5497153815de3 100644 --- a/test/parallel/test-vm-create-context-arg.js +++ b/test/parallel/test-vm-create-context-arg.js @@ -28,13 +28,9 @@ assert.throws(function() { vm.createContext('string is not supported'); }, /^TypeError: sandbox must be an object$/); -assert.doesNotThrow(function() { - vm.createContext({ a: 1 }); - vm.createContext([0, 1, 2, 3]); -}); +vm.createContext({ a: 1 }); +vm.createContext([0, 1, 2, 3]); -assert.doesNotThrow(function() { - const sandbox = {}; - vm.createContext(sandbox); - vm.createContext(sandbox); -}); +const sandbox = {}; +vm.createContext(sandbox); +vm.createContext(sandbox); diff --git a/test/parallel/test-vm-cross-context.js b/test/parallel/test-vm-cross-context.js index 5d45387e5d76e5..785cc9d7bd06bb 100644 --- a/test/parallel/test-vm-cross-context.js +++ b/test/parallel/test-vm-cross-context.js @@ -21,11 +21,8 @@ 'use strict'; require('../common'); -const assert = require('assert'); const vm = require('vm'); const ctx = vm.createContext(global); -assert.doesNotThrow(function() { - vm.runInContext('!function() { var x = console.log; }()', ctx); -}); +vm.runInContext('!function() { var x = console.log; }()', ctx); diff --git a/test/parallel/test-vm-proxy-failure-CP.js b/test/parallel/test-vm-proxy-failure-CP.js index 343948ac4c6377..93027576d85e80 100644 --- a/test/parallel/test-vm-proxy-failure-CP.js +++ b/test/parallel/test-vm-proxy-failure-CP.js @@ -1,6 +1,5 @@ 'use strict'; require('../common'); -const assert = require('assert'); const vm = require('vm'); // Check that we do not accidentally query attributes. @@ -13,4 +12,4 @@ const handler = { const sandbox = new Proxy({ foo: 'bar' }, handler); const context = vm.createContext(sandbox); -assert.doesNotThrow(() => vm.runInContext('', context)); +vm.runInContext('', context); diff --git a/test/parallel/test-whatwg-encoding-textdecoder.js b/test/parallel/test-whatwg-encoding-textdecoder.js index 5f9499930a07a0..e87364de1e91f7 100644 --- a/test/parallel/test-whatwg-encoding-textdecoder.js +++ b/test/parallel/test-whatwg-encoding-textdecoder.js @@ -63,8 +63,8 @@ if (common.hasIntl) { ['unicode-1-1-utf-8', 'utf8', 'utf-8'].forEach((i) => { const dec = new TextDecoder(i, { fatal: true }); - assert.doesNotThrow(() => dec.decode(buf.slice(0, 8), { stream: true })); - assert.doesNotThrow(() => dec.decode(buf.slice(8))); + dec.decode(buf.slice(0, 8), { stream: true }); + dec.decode(buf.slice(8)); }); } else { common.expectsError( @@ -107,11 +107,11 @@ if (common.hasIntl) { message: 'Value of "this" must be of type TextDecoder' }; - assert.doesNotThrow(() => inspectFn.call(instance, Infinity, {})); - assert.doesNotThrow(() => decodeFn.call(instance)); - assert.doesNotThrow(() => encodingGetter.call(instance)); - assert.doesNotThrow(() => fatalGetter.call(instance)); - assert.doesNotThrow(() => ignoreBOMGetter.call(instance)); + inspectFn.call(instance, Infinity, {}); + decodeFn.call(instance); + encodingGetter.call(instance); + fatalGetter.call(instance); + ignoreBOMGetter.call(instance); const invalidThisArgs = [{}, [], true, 1, '', new TextEncoder()]; invalidThisArgs.forEach((i) => { diff --git a/test/parallel/test-whatwg-encoding-textencoder.js b/test/parallel/test-whatwg-encoding-textencoder.js index 4096a02432e900..5514b714bd9b6e 100644 --- a/test/parallel/test-whatwg-encoding-textencoder.js +++ b/test/parallel/test-whatwg-encoding-textencoder.js @@ -48,9 +48,9 @@ assert(TextEncoder); message: 'Value of "this" must be of type TextEncoder' }; - assert.doesNotThrow(() => inspectFn.call(instance, Infinity, {})); - assert.doesNotThrow(() => encodeFn.call(instance)); - assert.doesNotThrow(() => encodingGetter.call(instance)); + inspectFn.call(instance, Infinity, {}); + encodeFn.call(instance); + encodingGetter.call(instance); const invalidThisArgs = [{}, [], true, 1, '', new TextDecoder()]; invalidThisArgs.forEach((i) => { diff --git a/test/parallel/test-zlib-close-after-error.js b/test/parallel/test-zlib-close-after-error.js index 8e21d159337c51..63d418be09946d 100644 --- a/test/parallel/test-zlib-close-after-error.js +++ b/test/parallel/test-zlib-close-after-error.js @@ -9,7 +9,7 @@ const decompress = zlib.createGunzip(15); decompress.on('error', common.mustCall((err) => { assert.strictEqual(decompress._closed, true); - assert.doesNotThrow(() => decompress.close()); + decompress.close(); })); assert.strictEqual(decompress._closed, false); diff --git a/test/parallel/test-zlib-deflate-constructors.js b/test/parallel/test-zlib-deflate-constructors.js index 090fbb8d07777e..97ece1e8afe387 100644 --- a/test/parallel/test-zlib-deflate-constructors.js +++ b/test/parallel/test-zlib-deflate-constructors.js @@ -93,25 +93,11 @@ common.expectsError( ); // Does not throw if opts.strategy is valid -assert.doesNotThrow( - () => { new zlib.Deflate({ strategy: zlib.constants.Z_FILTERED }); } -); - -assert.doesNotThrow( - () => { new zlib.Deflate({ strategy: zlib.constants.Z_HUFFMAN_ONLY }); } -); - -assert.doesNotThrow( - () => { new zlib.Deflate({ strategy: zlib.constants.Z_RLE }); } -); - -assert.doesNotThrow( - () => { new zlib.Deflate({ strategy: zlib.constants.Z_FIXED }); } -); - -assert.doesNotThrow( - () => { new zlib.Deflate({ strategy: zlib.constants.Z_DEFAULT_STRATEGY }); } -); +new zlib.Deflate({ strategy: zlib.constants.Z_FILTERED }); +new zlib.Deflate({ strategy: zlib.constants.Z_HUFFMAN_ONLY }); +new zlib.Deflate({ strategy: zlib.constants.Z_RLE }); +new zlib.Deflate({ strategy: zlib.constants.Z_FIXED }); +new zlib.Deflate({ strategy: zlib.constants.Z_DEFAULT_STRATEGY }); // Throws if opt.strategy is the wrong type. common.expectsError( diff --git a/test/parallel/test-zlib-flush-flags.js b/test/parallel/test-zlib-flush-flags.js index 25cfad70e3e3d5..fa9293cfc43175 100644 --- a/test/parallel/test-zlib-flush-flags.js +++ b/test/parallel/test-zlib-flush-flags.js @@ -1,11 +1,8 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const zlib = require('zlib'); -assert.doesNotThrow(() => { - zlib.createGzip({ flush: zlib.constants.Z_SYNC_FLUSH }); -}); +zlib.createGzip({ flush: zlib.constants.Z_SYNC_FLUSH }); common.expectsError( () => zlib.createGzip({ flush: 'foobar' }), @@ -23,9 +20,7 @@ common.expectsError( } ); -assert.doesNotThrow(() => { - zlib.createGzip({ finishFlush: zlib.constants.Z_SYNC_FLUSH }); -}); +zlib.createGzip({ finishFlush: zlib.constants.Z_SYNC_FLUSH }); common.expectsError( () => zlib.createGzip({ finishFlush: 'foobar' }), diff --git a/test/parallel/test-zlib-invalid-input.js b/test/parallel/test-zlib-invalid-input.js index 758e489ca078a9..1b081d919e9068 100644 --- a/test/parallel/test-zlib-invalid-input.js +++ b/test/parallel/test-zlib-invalid-input.js @@ -43,11 +43,9 @@ const unzips = [ nonStringInputs.forEach(common.mustCall((input) => { // zlib.gunzip should not throw an error when called with bad input. - assert.doesNotThrow(function() { - zlib.gunzip(input, function(err, buffer) { - // zlib.gunzip should pass the error to the callback. - assert.ok(err); - }); + zlib.gunzip(input, function(err, buffer) { + // zlib.gunzip should pass the error to the callback. + assert.ok(err); }); }, nonStringInputs.length)); diff --git a/test/parallel/test-zlib-truncated.js b/test/parallel/test-zlib-truncated.js index 678bfedd41c154..e04ef7e3d8367a 100644 --- a/test/parallel/test-zlib-truncated.js +++ b/test/parallel/test-zlib-truncated.js @@ -29,10 +29,8 @@ const errMessage = /unexpected end of file/; const toUTF8 = (buffer) => buffer.toString('utf-8'); // sync sanity - assert.doesNotThrow(function() { - const decompressed = zlib[methods.decompSync](compressed); - assert.strictEqual(toUTF8(decompressed), inputString); - }); + const decompressed = zlib[methods.decompSync](compressed); + assert.strictEqual(toUTF8(decompressed), inputString); // async sanity zlib[methods.decomp](compressed, function(err, result) { @@ -53,10 +51,8 @@ const errMessage = /unexpected end of file/; const syncFlushOpt = { finishFlush: zlib.constants.Z_SYNC_FLUSH }; // sync truncated input test, finishFlush = Z_SYNC_FLUSH - assert.doesNotThrow(function() { - const result = toUTF8(zlib[methods.decompSync](truncated, syncFlushOpt)); - assert.strictEqual(result, inputString.substr(0, result.length)); - }); + const result = toUTF8(zlib[methods.decompSync](truncated, syncFlushOpt)); + assert.strictEqual(result, inputString.substr(0, result.length)); // async truncated input test, finishFlush = Z_SYNC_FLUSH zlib[methods.decomp](truncated, syncFlushOpt, function(err, decompressed) { diff --git a/test/parallel/test-zlib.js b/test/parallel/test-zlib.js index a36e8166ab726a..1b6855a0b92062 100644 --- a/test/parallel/test-zlib.js +++ b/test/parallel/test-zlib.js @@ -152,9 +152,7 @@ class SlowStream extends stream.Stream { } // windowBits: 8 shouldn't throw -assert.doesNotThrow(() => { - zlib.createDeflateRaw({ windowBits: 8 }); -}, 'windowsBits set to 8 should follow legacy zlib behavior'); +zlib.createDeflateRaw({ windowBits: 8 }); { const node = fs.createReadStream(fixtures.path('person.jpg')); diff --git a/test/pummel/test-fs-largefile.js b/test/pummel/test-fs-largefile.js index 786e325ce3333d..369f8311925474 100644 --- a/test/pummel/test-fs-largefile.js +++ b/test/pummel/test-fs-largefile.js @@ -44,9 +44,7 @@ assert.strictEqual(readBuf.toString(), message); fs.readSync(fd, readBuf, 0, 1, 0); assert.strictEqual(readBuf[0], 0); -assert.doesNotThrow( - () => { fs.writeSync(fd, writeBuf, 0, writeBuf.length, 42.000001); } -); +fs.writeSync(fd, writeBuf, 0, writeBuf.length, 42.000001); fs.close(fd); // Normally, we don't clean up tmp files at the end of a test, but we'll make an diff --git a/test/pummel/test-fs-watch-file.js b/test/pummel/test-fs-watch-file.js index c893c9dfa6e268..62abf0c18fc969 100644 --- a/test/pummel/test-fs-watch-file.js +++ b/test/pummel/test-fs-watch-file.js @@ -68,14 +68,10 @@ assert.throws( } ); -assert.doesNotThrow( - function() { - fs.watchFile(filepathOne, function() { - fs.unwatchFile(filepathOne); - ++watchSeenOne; - }); - } -); +fs.watchFile(filepathOne, function() { + fs.unwatchFile(filepathOne); + ++watchSeenOne; +}); setTimeout(function() { fs.writeFileSync(filepathOne, 'world'); @@ -95,36 +91,32 @@ assert.throws( } ); -assert.doesNotThrow( - function() { - function a() { - fs.unwatchFile(filepathTwo, a); - ++watchSeenTwo; - } - function b() { - fs.unwatchFile(filepathTwo, b); - ++watchSeenTwo; - } - fs.watchFile(filepathTwo, a); - fs.watchFile(filepathTwo, b); +{ + function a() { + fs.unwatchFile(filepathTwo, a); + ++watchSeenTwo; } -); + function b() { + fs.unwatchFile(filepathTwo, b); + ++watchSeenTwo; + } + fs.watchFile(filepathTwo, a); + fs.watchFile(filepathTwo, b); +} setTimeout(function() { fs.writeFileSync(filepathTwoAbs, 'pardner'); }, 1000); -assert.doesNotThrow( - function() { - function b() { - fs.unwatchFile(filenameThree, b); - ++watchSeenThree; - } - fs.watchFile(filenameThree, common.mustNotCall()); - fs.watchFile(filenameThree, b); - fs.unwatchFile(filenameThree, common.mustNotCall()); +{ + function b() { + fs.unwatchFile(filenameThree, b); + ++watchSeenThree; } -); + fs.watchFile(filenameThree, common.mustNotCall()); + fs.watchFile(filenameThree, b); + fs.unwatchFile(filenameThree, common.mustNotCall()); +} setTimeout(function() { fs.writeFileSync(filenameThree, 'pardner'); @@ -138,13 +130,11 @@ setTimeout(function() { fs.writeFileSync(filenameFour, 'hey'); }, 500); -assert.doesNotThrow( - function() { - function a() { - ++watchSeenFour; - assert.strictEqual(1, watchSeenFour); - fs.unwatchFile(`.${path.sep}${filenameFour}`, a); - } - fs.watchFile(filenameFour, a); +{ + function a() { + ++watchSeenFour; + assert.strictEqual(1, watchSeenFour); + fs.unwatchFile(`.${path.sep}${filenameFour}`, a); } -); + fs.watchFile(filenameFour, a); +} diff --git a/test/sequential/test-child-process-execsync.js b/test/sequential/test-child-process-execsync.js index 133217dcdf7c3f..fff5b8e9f0a98b 100644 --- a/test/sequential/test-child-process-execsync.js +++ b/test/sequential/test-child-process-execsync.js @@ -144,6 +144,4 @@ assert.strictEqual(ret, `${msg}\n`); } // Verify the shell option works properly -assert.doesNotThrow(() => { - execFileSync(process.execPath, [], execOpts); -}); +execFileSync(process.execPath, [], execOpts); diff --git a/test/sequential/test-fs-watch.js b/test/sequential/test-fs-watch.js index 31708ee6144c7d..b672e9c75395dd 100644 --- a/test/sequential/test-fs-watch.js +++ b/test/sequential/test-fs-watch.js @@ -42,19 +42,15 @@ tmpdir.refresh(); fs.writeFileSync(filepath, 'hello'); - assert.doesNotThrow( - function() { - const watcher = fs.watch(filepath); - watcher.on('change', common.mustCall(function(event, filename) { - assert.strictEqual(event, 'change'); - - if (expectFilePath) { - assert.strictEqual(filename, 'watch.txt'); - } - watcher.close(); - })); + const watcher = fs.watch(filepath); + watcher.on('change', common.mustCall(function(event, filename) { + assert.strictEqual(event, 'change'); + + if (expectFilePath) { + assert.strictEqual(filename, 'watch.txt'); } - ); + watcher.close(); + })); setImmediate(function() { fs.writeFileSync(filepath, 'world'); @@ -68,19 +64,15 @@ tmpdir.refresh(); fs.writeFileSync(filepathAbs, 'howdy'); - assert.doesNotThrow( - function() { - const watcher = - fs.watch('hasOwnProperty', common.mustCall(function(event, filename) { - assert.strictEqual(event, 'change'); - - if (expectFilePath) { - assert.strictEqual(filename, 'hasOwnProperty'); - } - watcher.close(); - })); - } - ); + const watcher = + fs.watch('hasOwnProperty', common.mustCall(function(event, filename) { + assert.strictEqual(event, 'change'); + + if (expectFilePath) { + assert.strictEqual(filename, 'hasOwnProperty'); + } + watcher.close(); + })); setImmediate(function() { fs.writeFileSync(filepathAbs, 'pardner'); @@ -91,21 +83,17 @@ tmpdir.refresh(); const testsubdir = fs.mkdtempSync(testDir + path.sep); const filepath = path.join(testsubdir, 'newfile.txt'); - assert.doesNotThrow( - function() { - const watcher = - fs.watch(testsubdir, common.mustCall(function(event, filename) { - const renameEv = common.isSunOS || common.isAIX ? 'change' : 'rename'; - assert.strictEqual(event, renameEv); - if (expectFilePath) { - assert.strictEqual(filename, 'newfile.txt'); - } else { - assert.strictEqual(filename, null); - } - watcher.close(); - })); - } - ); + const watcher = + fs.watch(testsubdir, common.mustCall(function(event, filename) { + const renameEv = common.isSunOS || common.isAIX ? 'change' : 'rename'; + assert.strictEqual(event, renameEv); + if (expectFilePath) { + assert.strictEqual(filename, 'newfile.txt'); + } else { + assert.strictEqual(filename, null); + } + watcher.close(); + })); setImmediate(function() { const fd = fs.openSync(filepath, 'w'); diff --git a/test/sequential/test-inspector-module.js b/test/sequential/test-inspector-module.js index af0154f7cec8de..5b793bf3b43d55 100644 --- a/test/sequential/test-inspector-module.js +++ b/test/sequential/test-inspector-module.js @@ -4,7 +4,6 @@ const common = require('../common'); common.skipIfInspectorDisabled(); -const assert = require('assert'); const { Session } = require('inspector'); const session = new Session(); @@ -18,10 +17,8 @@ common.expectsError( } ); -assert.doesNotThrow(() => session.connect()); - -assert.doesNotThrow( - () => session.post('Runtime.evaluate', { expression: '2 + 2' })); +session.connect(); +session.post('Runtime.evaluate', { expression: '2 + 2' }); [1, {}, [], true, Infinity, undefined].forEach((i) => { common.expectsError( @@ -58,5 +55,5 @@ common.expectsError( } ); -assert.doesNotThrow(() => session.disconnect()); -assert.doesNotThrow(() => session.disconnect()); +session.disconnect(); +session.disconnect(); diff --git a/test/sequential/test-performance.js b/test/sequential/test-performance.js index d262e1f1f149d1..80bfe217a0518e 100644 --- a/test/sequential/test-performance.js +++ b/test/sequential/test-performance.js @@ -70,7 +70,7 @@ assert(inited < 20000); { performance.mark('A'); [undefined, null, 'foo', 'initialize', 1].forEach((i) => { - assert.doesNotThrow(() => performance.measure('test', i, 'A')); + performance.measure('test', i, 'A'); }); [undefined, null, 'foo', 1].forEach((i) => { diff --git a/test/sequential/test-tls-lookup.js b/test/sequential/test-tls-lookup.js index ff759cf2fe6bea..568ba1350675e1 100644 --- a/test/sequential/test-tls-lookup.js +++ b/test/sequential/test-tls-lookup.js @@ -3,7 +3,6 @@ const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); -const assert = require('assert'); const tls = require('tls'); ['foobar', 1, {}, []].forEach(function connectThrows(input) { @@ -30,7 +29,5 @@ function connectDoesNotThrow(input) { lookup: input }; - assert.doesNotThrow(function() { - tls.connect(opts); - }); + tls.connect(opts); } From 9e9f331f43db21c2618943cfc448da27b6b01e0e Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Sat, 10 Feb 2018 02:33:08 +0100 Subject: [PATCH 03/16] 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 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: Matteo Collina --- test/addons/symlinked-module/test.js | 2 +- test/internet/test-dns.js | 5 +- test/parallel/test-assert-deep.js | 4 +- test/parallel/test-buffer-alloc.js | 8 +- test/parallel/test-buffer-bad-overload.js | 4 +- test/parallel/test-buffer-constants.js | 2 +- test/parallel/test-buffer-copy.js | 2 +- .../parallel/test-buffer-sharedarraybuffer.js | 5 +- test/parallel/test-buffer-slice.js | 5 +- .../test-child-process-spawn-typeerror.js | 19 ++- .../test-console-async-write-error.js | 3 +- test/parallel/test-console-instance.js | 16 +-- .../parallel/test-console-sync-write-error.js | 9 +- test/parallel/test-crypto-padding.js | 36 ++---- test/parallel/test-crypto-pbkdf2.js | 4 +- test/parallel/test-crypto-rsa-dsa.js | 1 - ...ad-after-set-uncaught-exception-capture.js | 3 +- test/parallel/test-fs-access.js | 2 +- test/parallel/test-fs-buffer.js | 8 +- .../test-fs-read-stream-throw-type-error.js | 2 +- .../test-fs-write-stream-throw-type-error.js | 2 +- test/parallel/test-http-invalidheaderfield.js | 1 + test/parallel/test-http2-binding.js | 2 - ...t-http2-client-rststream-before-connect.js | 4 +- ...-http2-compat-serverresponse-statuscode.js | 1 + test/parallel/test-http2-getpackedsettings.js | 9 +- test/parallel/test-http2-server-startup.js | 10 +- test/parallel/test-http2-socket-proxy.js | 1 + test/parallel/test-http2-withflag.js | 7 -- test/parallel/test-https-agent-constructor.js | 1 - test/parallel/test-icu-punycode.js | 4 +- test/parallel/test-internal-fs.js | 2 + ...test-internal-util-decorate-error-stack.js | 11 +- .../test-module-symlinked-peer-modules.js | 2 +- test/parallel/test-net-after-close.js | 2 + test/parallel/test-net-during-close.js | 6 +- test/parallel/test-process-geteuid-getegid.js | 1 + test/parallel/test-process-setuid-setgid.js | 1 + test/parallel/test-querystring.js | 2 +- test/parallel/test-readline-csi.js | 1 + test/parallel/test-stream-writable-null.js | 30 ++--- test/parallel/test-timers-unref.js | 1 + test/parallel/test-util-inspect.js | 113 +++++++++--------- test/parallel/test-vm-create-context-arg.js | 1 + test/parallel/test-vm-cross-context.js | 1 + test/pummel/test-fs-largefile.js | 1 + test/pummel/test-fs-watch-file.js | 7 +- test/sequential/test-inspector-module.js | 1 + test/sequential/test-performance.js | 2 +- 49 files changed, 163 insertions(+), 204 deletions(-) delete mode 100644 test/parallel/test-http2-withflag.js diff --git a/test/addons/symlinked-module/test.js b/test/addons/symlinked-module/test.js index 98eec17d0c8c95..cbd01e938fe25f 100644 --- a/test/addons/symlinked-module/test.js +++ b/test/addons/symlinked-module/test.js @@ -30,5 +30,5 @@ const sub = require('./submodule'); const mod = require(path.join(i, 'binding.node')); assert.notStrictEqual(mod, null); assert.strictEqual(mod.hello(), 'world'); - sub.test(i); + sub.test(i); // Should not throw. }); diff --git a/test/internet/test-dns.js b/test/internet/test-dns.js index dadf14c0be36b1..f1b7b4ff056833 100644 --- a/test/internet/test-dns.js +++ b/test/internet/test-dns.js @@ -579,11 +579,8 @@ process.on('exit', function() { assert.ok(getaddrinfoCallbackCalled); }); - +// Should not throw. dns.lookup(addresses.INET6_HOST, 6, 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()); diff --git a/test/parallel/test-assert-deep.js b/test/parallel/test-assert-deep.js index d9c9df5bb2c875..d0aacfdf516f4c 100644 --- a/test/parallel/test-assert-deep.js +++ b/test/parallel/test-assert-deep.js @@ -492,8 +492,8 @@ assertOnlyDeepEqual([1, , , 3], [1, , , 3, , , ]); // Handle NaN assert.throws(() => { assert.deepEqual(NaN, NaN); }, assert.AssertionError); -{ assert.deepStrictEqual(NaN, NaN); } -{ assert.deepStrictEqual({ a: NaN }, { a: NaN }); } +assert.deepStrictEqual(NaN, NaN); +assert.deepStrictEqual({ a: NaN }, { a: NaN }); assert.deepStrictEqual([ 1, 2, NaN, 4 ], [ 1, 2, NaN, 4 ]); // Handle boxed primitives diff --git a/test/parallel/test-buffer-alloc.js b/test/parallel/test-buffer-alloc.js index 7f062f6b58c68c..20e91377cd7fdf 100644 --- a/test/parallel/test-buffer-alloc.js +++ b/test/parallel/test-buffer-alloc.js @@ -62,7 +62,7 @@ assert.throws(() => b.write('test', 'utf8', 0), /is no longer supported/); -// try to create 0-length buffers +// Try to create 0-length buffers. Should not throw. Buffer.from(''); Buffer.from('', 'ascii'); Buffer.from('', 'latin1'); @@ -107,7 +107,7 @@ b.copy(Buffer.alloc(1), 0, 2048, 2048); 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). Buffer.alloc(1).write('', 1, 0); @@ -992,10 +992,10 @@ common.expectsError(() => { assert.strictEqual(ubuf.buffer.byteLength, 10); } -// Regression test +// Regression test to verify that an empty ArrayBuffer does not throw. 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()'); Buffer.from(arrayBuf); Buffer.from({ buffer: arrayBuf }); diff --git a/test/parallel/test-buffer-bad-overload.js b/test/parallel/test-buffer-bad-overload.js index ec2703341b2f38..63acb8ebfb6d49 100644 --- a/test/parallel/test-buffer-bad-overload.js +++ b/test/parallel/test-buffer-bad-overload.js @@ -2,7 +2,7 @@ const common = require('../common'); const assert = require('assert'); -Buffer.allocUnsafe(10); +Buffer.allocUnsafe(10); // Should not throw. const err = common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', @@ -14,4 +14,4 @@ assert.throws(function() { Buffer.from(10, 'hex'); }, err); -Buffer.from('deadbeaf', 'hex'); +Buffer.from('deadbeaf', 'hex'); // Should not throw. diff --git a/test/parallel/test-buffer-constants.js b/test/parallel/test-buffer-constants.js index dbb6186b6de5ce..f6f0dbddc39d3e 100644 --- a/test/parallel/test-buffer-constants.js +++ b/test/parallel/test-buffer-constants.js @@ -11,7 +11,7 @@ assert(MAX_STRING_LENGTH <= MAX_LENGTH); assert.throws(() => ' '.repeat(MAX_STRING_LENGTH + 1), /^RangeError: Invalid string length$/); -' '.repeat(MAX_STRING_LENGTH); +' '.repeat(MAX_STRING_LENGTH); // Should not throw. // Legacy values match: assert.strictEqual(kMaxLength, MAX_LENGTH); diff --git a/test/parallel/test-buffer-copy.js b/test/parallel/test-buffer-copy.js index 324613a04fe525..5c82f4de28dbee 100644 --- a/test/parallel/test-buffer-copy.js +++ b/test/parallel/test-buffer-copy.js @@ -92,7 +92,7 @@ const bb = Buffer.allocUnsafe(10); 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); // copy throws at negative sourceStart diff --git a/test/parallel/test-buffer-sharedarraybuffer.js b/test/parallel/test-buffer-sharedarraybuffer.js index 536c3939365d98..0252847c054c1d 100644 --- a/test/parallel/test-buffer-sharedarraybuffer.js +++ b/test/parallel/test-buffer-sharedarraybuffer.js @@ -22,8 +22,7 @@ arr2[1] = 6000; 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); -Buffer.from({ buffer: sab }); +Buffer.from({ buffer: sab }); // Should not throw. diff --git a/test/parallel/test-buffer-slice.js b/test/parallel/test-buffer-slice.js index b55d082783cc28..6175370a9bccee 100644 --- a/test/parallel/test-buffer-slice.js +++ b/test/parallel/test-buffer-slice.js @@ -77,9 +77,8 @@ expectedSameBufs.forEach(([buf1, buf2]) => { const utf16Buf = Buffer.from('0123456789', 'utf16le'); assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer.from('012', 'utf16le')); -// try to slice a zero length Buffer -// see https://github.com/joyent/node/issues/5881 -Buffer.alloc(0).slice(0, 1); +// Try to slice a zero length Buffer. +// See https://github.com/joyent/node/issues/5881 assert.strictEqual(Buffer.alloc(0).slice(0, 1).length, 0); { diff --git a/test/parallel/test-child-process-spawn-typeerror.js b/test/parallel/test-child-process-spawn-typeerror.js index eede5fdd15d5c0..9855c0cfd99fa6 100644 --- a/test/parallel/test-child-process-spawn-typeerror.js +++ b/test/parallel/test-child-process-spawn-typeerror.js @@ -38,13 +38,13 @@ assert.throws(function() { child.on('error', common.mustNotCall()); }, 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, [], {}); -// verify that invalid argument combinations throw +// Verify that invalid argument combinations throw. assert.throws(function() { spawn(); }, invalidFileMsg); @@ -74,7 +74,7 @@ assert.throws(function() { spawn(cmd, [], 1); }, invalidOptionsMsg); -// Argument types for combinatorics +// Argument types for combinatorics. const a = []; const o = {}; function c() {} @@ -92,7 +92,7 @@ spawn(cmd, a); spawn(cmd, a, 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, a, u); @@ -103,7 +103,7 @@ assert.throws(function() { spawn(cmd, s); }, TypeError); assert.throws(function() { spawn(cmd, a, s); }, TypeError); -// 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 // combinations: @@ -124,7 +124,7 @@ execFile(cmd, o); execFile(cmd, o, 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, a, u, c); execFile(cmd, a, o, u); @@ -146,7 +146,7 @@ execFile(cmd, o, n); execFile(cmd, c, u); 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 // callback')` assert.throws(function() { execFile(cmd, s, o, c); }, TypeError); @@ -160,10 +160,9 @@ assert.throws(function() { execFile(cmd, a, u, s); }, TypeError); assert.throws(function() { execFile(cmd, a, n, s); }, TypeError); assert.throws(function() { execFile(cmd, u, o, s); }, TypeError); assert.throws(function() { execFile(cmd, n, o, s); }, TypeError); -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: // (f) diff --git a/test/parallel/test-console-async-write-error.js b/test/parallel/test-console-async-write-error.js index 139c02d64bff4b..be76c89832f611 100644 --- a/test/parallel/test-console-async-write-error.js +++ b/test/parallel/test-console-async-write-error.js @@ -11,6 +11,5 @@ for (const method of ['dir', 'log', 'warn']) { }); const c = new Console(out, out, true); - - c[method]('abc'); + c[method]('abc'); // Should not throw. } diff --git a/test/parallel/test-console-instance.js b/test/parallel/test-console-instance.js index aa35afc648a432..2fd07ac41219a9 100644 --- a/test/parallel/test-console-instance.js +++ b/test/parallel/test-console-instance.js @@ -28,15 +28,15 @@ const Console = require('console').Console; const out = new Stream(); const err = new Stream(); -// ensure the Console instance doesn't write to the -// process' "stdout" or "stderr" streams +// Ensure the Console instance doesn't write to the +// process' "stdout" or "stderr" streams. 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); -// make sure that the Console constructor throws -// when not given a writable stream instance +// Make sure that the Console constructor throws +// when not given a writable stream instance. common.expectsError( () => { 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( () => { out.write = () => {}; @@ -77,7 +77,7 @@ out.write = common.mustCall((d) => { 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; out.write = common.mustCall((d) => { called++; @@ -86,7 +86,7 @@ out.write = common.mustCall((d) => { [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); // Instance that does not ignore the stream errors. diff --git a/test/parallel/test-console-sync-write-error.js b/test/parallel/test-console-sync-write-error.js index 4d6c52e0dabca5..bf916ff5b84e8d 100644 --- a/test/parallel/test-console-sync-write-error.js +++ b/test/parallel/test-console-sync-write-error.js @@ -12,8 +12,7 @@ for (const method of ['dir', 'log', 'warn']) { }); const c = new Console(out, out, true); - - c[method]('abc'); + c[method]('abc'); // Should not throw. } { @@ -24,8 +23,7 @@ for (const method of ['dir', 'log', 'warn']) { }); const c = new Console(out, out, true); - - c[method]('abc'); + c[method]('abc'); // Should not throw. } { @@ -36,7 +34,6 @@ for (const method of ['dir', 'log', 'warn']) { }); const c = new Console(out, out, true); - - c[method]('abc'); + c[method]('abc'); // Should not throw. } } diff --git a/test/parallel/test-crypto-padding.js b/test/parallel/test-crypto-padding.js index ae85f7d2c3614a..00b600efb735e8 100644 --- a/test/parallel/test-crypto-padding.js +++ b/test/parallel/test-crypto-padding.js @@ -29,11 +29,7 @@ const crypto = require('crypto'); crypto.DEFAULT_ENCODING = 'buffer'; - -/* - * Input data - */ - +// Input data. const ODD_LENGTH_PLAIN = 'Hello node world!'; const EVEN_LENGTH_PLAIN = 'Hello node world!AbC09876dDeFgHi'; @@ -42,10 +38,7 @@ const IV_PLAIN = 'blahFizz2011Buzz'; const CIPHER_NAME = 'aes-128-cbc'; - -/* - * Expected result data - */ +// Expected result data. // echo -n 'Hello node world!' | \ // openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \ @@ -67,10 +60,7 @@ const EVEN_LENGTH_ENCRYPTED_NOPAD = '7f57859550d4d2fdb9806da2a750461ab46e71b3d78ebe2d9684dfc87f7575b9'; -/* - * Helper wrappers - */ - +// Helper wrappers. function enc(plain, pad) { const encrypt = crypto.createCipheriv(CIPHER_NAME, KEY_PLAIN, IV_PLAIN); encrypt.setAutoPadding(pad); @@ -87,16 +77,12 @@ function dec(encd, pad) { return plain; } - -/* - * Test encryption - */ - +// Test encryption assert.strictEqual(enc(ODD_LENGTH_PLAIN, true), ODD_LENGTH_ENCRYPTED); assert.strictEqual(enc(EVEN_LENGTH_PLAIN, true), EVEN_LENGTH_ENCRYPTED); assert.throws(function() { - // input must have block length % + // Input must have block length %. enc(ODD_LENGTH_PLAIN, false); }, /data not multiple of block length/); @@ -104,24 +90,20 @@ assert.strictEqual( 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(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(EVEN_LENGTH_ENCRYPTED, false).length, 48); 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); }, /bad decrypt/); -// no-pad encrypted string should return the same: +// No-pad encrypted string should return the same: assert.strictEqual( dec(EVEN_LENGTH_ENCRYPTED_NOPAD, false), EVEN_LENGTH_PLAIN ); diff --git a/test/parallel/test-crypto-pbkdf2.js b/test/parallel/test-crypto-pbkdf2.js index 1bb1c6cd71215e..a9a23e155ffb2f 100644 --- a/test/parallel/test-crypto-pbkdf2.js +++ b/test/parallel/test-crypto-pbkdf2.js @@ -99,9 +99,7 @@ common.expectsError( // Should not get FATAL ERROR with empty password and salt // https://github.com/nodejs/node/issues/8571 -crypto.pbkdf2('', '', 1, 32, 'sha256', common.mustCall((e) => { - assert.ifError(e); -})); +crypto.pbkdf2('', '', 1, 32, 'sha256', common.mustCall(assert.ifError)); common.expectsError( () => crypto.pbkdf2('password', 'salt', 8, 8, common.mustNotCall()), diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index 5a6ecdd66f41bf..744dc5657b089d 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -256,7 +256,6 @@ const input = 'I AM THE WALRUS'; // against const sign = crypto.createSign('SHA1'); sign.update(input); - const signOptions = { key: dsaKeyPemEncrypted, passphrase: 'password' }; const signature = sign.sign(signOptions, 'hex'); diff --git a/test/parallel/test-domain-load-after-set-uncaught-exception-capture.js b/test/parallel/test-domain-load-after-set-uncaught-exception-capture.js index c2fa523cc17019..697d4d30806ee7 100644 --- a/test/parallel/test-domain-load-after-set-uncaught-exception-capture.js +++ b/test/parallel/test-domain-load-after-set-uncaught-exception-capture.js @@ -13,5 +13,4 @@ common.expectsError( ); process.setUncaughtExceptionCaptureCallback(null); - -require('domain'); +require('domain'); // Should not throw. diff --git a/test/parallel/test-fs-access.js b/test/parallel/test-fs-access.js index a55f75f649f383..9d5160f6170cad 100644 --- a/test/parallel/test-fs-access.js +++ b/test/parallel/test-fs-access.js @@ -105,8 +105,8 @@ common.expectsError( type: TypeError }); +// Regular access should not throw. fs.accessSync(__filename); - const mode = fs.F_OK | fs.R_OK | fs.W_OK; fs.accessSync(readWriteFile, mode); diff --git a/test/parallel/test-fs-buffer.js b/test/parallel/test-fs-buffer.js index 0b7b67cefe4d86..f1c3484ce3a8d0 100644 --- a/test/parallel/test-fs-buffer.js +++ b/test/parallel/test-fs-buffer.js @@ -9,17 +9,13 @@ const path = require('path'); const tmpdir = require('../common/tmpdir'); tmpdir.refresh(); -fs.access(Buffer.from(tmpdir.path), common.mustCall((err) => { - assert.ifError(err); -})); +fs.access(Buffer.from(tmpdir.path), common.mustCall(assert.ifError)); const buf = Buffer.from(path.join(tmpdir.path, 'a.txt')); fs.open(buf, 'w+', common.mustCall((err, fd) => { assert.ifError(err); assert(fd); - fs.close(fd, common.mustCall((err) => { - assert.ifError(err); - })); + fs.close(fd, common.mustCall(assert.ifError)); })); assert.throws(() => { diff --git a/test/parallel/test-fs-read-stream-throw-type-error.js b/test/parallel/test-fs-read-stream-throw-type-error.js index b01a0a588f5699..c2b0d5452c55e3 100644 --- a/test/parallel/test-fs-read-stream-throw-type-error.js +++ b/test/parallel/test-fs-read-stream-throw-type-error.js @@ -4,7 +4,7 @@ const fixtures = require('../common/fixtures'); const fs = require('fs'); const example = fixtures.path('x.txt'); - +// Should not throw. fs.createReadStream(example, undefined); fs.createReadStream(example, null); fs.createReadStream(example, 'utf8'); diff --git a/test/parallel/test-fs-write-stream-throw-type-error.js b/test/parallel/test-fs-write-stream-throw-type-error.js index 553d399e238508..c80f647b3d622e 100644 --- a/test/parallel/test-fs-write-stream-throw-type-error.js +++ b/test/parallel/test-fs-write-stream-throw-type-error.js @@ -8,7 +8,7 @@ const tmpdir = require('../common/tmpdir'); const example = path.join(tmpdir.path, 'dummy'); tmpdir.refresh(); - +// Should not throw. fs.createWriteStream(example, undefined); fs.createWriteStream(example, null); fs.createWriteStream(example, 'utf8'); diff --git a/test/parallel/test-http-invalidheaderfield.js b/test/parallel/test-http-invalidheaderfield.js index 528fc825868ed7..01315ba69044a2 100644 --- a/test/parallel/test-http-invalidheaderfield.js +++ b/test/parallel/test-http-invalidheaderfield.js @@ -35,6 +35,7 @@ server.listen(0, function() { } ); + // Should not throw. const options = { port: server.address().port, headers: { 'testing_123': 123 } diff --git a/test/parallel/test-http2-binding.js b/test/parallel/test-http2-binding.js index 1b8501dcbeca2f..f267e2e6c1481e 100644 --- a/test/parallel/test-http2-binding.js +++ b/test/parallel/test-http2-binding.js @@ -5,8 +5,6 @@ if (!common.hasCrypto) common.skip('missing crypto'); const assert = require('assert'); -process.binding('http2'); - const binding = process.binding('http2'); const http2 = require('http2'); diff --git a/test/parallel/test-http2-client-rststream-before-connect.js b/test/parallel/test-http2-client-rststream-before-connect.js index 177b13a16eed98..10d7520ac125fe 100644 --- a/test/parallel/test-http2-client-rststream-before-connect.js +++ b/test/parallel/test-http2-client-rststream-before-connect.js @@ -19,10 +19,10 @@ server.listen(0, common.mustCall(() => { req.close(1); 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)); - // second call doesn't do anything + // Second call doesn't do anything. req.close(8); req.on('close', common.mustCall((code) => { diff --git a/test/parallel/test-http2-compat-serverresponse-statuscode.js b/test/parallel/test-http2-compat-serverresponse-statuscode.js index 4c51616ef618fc..dd92db8d96597a 100644 --- a/test/parallel/test-http2-compat-serverresponse-statuscode.js +++ b/test/parallel/test-http2-compat-serverresponse-statuscode.js @@ -27,6 +27,7 @@ server.listen(0, common.mustCall(function() { assert.strictEqual(response.statusCode, expectedDefaultStatusCode); + // Setting the response.statusCode should not throw. response.statusCode = realStatusCodes.ok; response.statusCode = realStatusCodes.multipleChoices; response.statusCode = realStatusCodes.badRequest; diff --git a/test/parallel/test-http2-getpackedsettings.js b/test/parallel/test-http2-getpackedsettings.js index b02d6b4933bbfa..56b96321139630 100644 --- a/test/parallel/test-http2-getpackedsettings.js +++ b/test/parallel/test-http2-getpackedsettings.js @@ -26,6 +26,7 @@ assert.deepStrictEqual(val, check); ['maxHeaderListSize', 0], ['maxHeaderListSize', 2 ** 32 - 1] ].forEach((i) => { + // Valid options should not throw. http2.getPackedSettings({ [i[0]]: i[1] }); }); @@ -85,7 +86,7 @@ http2.getPackedSettings({ enablePush: false }); assert.deepStrictEqual(packed, check); } -// check for not passing settings +// Check for not passing settings. { const packed = http2.getPackedSettings(); assert.strictEqual(packed.length, 0); @@ -143,7 +144,7 @@ http2.getPackedSettings({ enablePush: false }); 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([ 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0x00, 0x03, 0x00, 0x00, @@ -154,7 +155,7 @@ http2.getPackedSettings({ enablePush: false }); 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]); @@ -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]); diff --git a/test/parallel/test-http2-server-startup.js b/test/parallel/test-http2-server-startup.js index 12b9cd72cba147..4ebcc21c27aa8e 100644 --- a/test/parallel/test-http2-server-startup.js +++ b/test/parallel/test-http2-server-startup.js @@ -19,20 +19,20 @@ const options = { cert: commonFixtures.readKey('agent2-cert.pem') }; -// There should not be any throws +// There should not be any throws. const serverTLS = http2.createSecureServer(options, () => {}); 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()); const server = http2.createServer(options, common.mustNotCall()); 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()); -// Test the plaintext server socket timeout +// Test the plaintext server socket timeout. { let client; 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; const server = http2.createSecureServer(options); diff --git a/test/parallel/test-http2-socket-proxy.js b/test/parallel/test-http2-socket-proxy.js index e954439d78c07c..912ec673ba79cc 100644 --- a/test/parallel/test-http2-socket-proxy.js +++ b/test/parallel/test-http2-socket-proxy.js @@ -47,6 +47,7 @@ server.on('stream', common.mustCall(function(stream, headers) { common.expectsError(() => (socket.resume = undefined), errMsg); common.expectsError(() => (socket.write = undefined), errMsg); + // Resetting the socket listeners to their own value should not throw. socket.on = socket.on; socket.once = socket.once; diff --git a/test/parallel/test-http2-withflag.js b/test/parallel/test-http2-withflag.js deleted file mode 100644 index 3cc5c69c681c50..00000000000000 --- a/test/parallel/test-http2-withflag.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -const common = require('../common'); -if (!common.hasCrypto) - common.skip('missing crypto'); - -require('http2'); diff --git a/test/parallel/test-https-agent-constructor.js b/test/parallel/test-https-agent-constructor.js index 571160bbb845dd..69156ba0f64de9 100644 --- a/test/parallel/test-https-agent-constructor.js +++ b/test/parallel/test-https-agent-constructor.js @@ -6,5 +6,4 @@ if (!common.hasCrypto) const assert = require('assert'); const https = require('https'); -https.Agent(); assert.ok(https.Agent() instanceof https.Agent); diff --git a/test/parallel/test-icu-punycode.js b/test/parallel/test-icu-punycode.js index 3ca30a6d168ba9..82c15287982631 100644 --- a/test/parallel/test-icu-punycode.js +++ b/test/parallel/test-icu-punycode.js @@ -34,12 +34,12 @@ const wptToASCIITests = require('../fixtures/url-toascii.js'); if (output === null) { assert.throws(() => icu.toASCII(input), errMessage, `ToASCII ${caseComment}`); - icu.toASCII(input, true); + icu.toASCII(input, true); // Should not throw. } else { assert.strictEqual(icu.toASCII(input), output, `ToASCII ${caseComment}`); assert.strictEqual(icu.toASCII(input, true), output, `ToASCII ${caseComment} in lenient mode`); } - icu.toUnicode(input); + icu.toUnicode(input); // Should not throw. } } diff --git a/test/parallel/test-internal-fs.js b/test/parallel/test-internal-fs.js index 3f270f93d5359b..9bc0a98b099f75 100644 --- a/test/parallel/test-internal-fs.js +++ b/test/parallel/test-internal-fs.js @@ -4,8 +4,10 @@ const common = require('../common'); const fs = require('internal/fs'); +// Valid encodings and no args should not throw. fs.assertEncoding(); fs.assertEncoding('utf8'); + common.expectsError( () => fs.assertEncoding('foo'), { code: 'ERR_INVALID_OPT_VALUE_ENCODING', type: TypeError } diff --git a/test/parallel/test-internal-util-decorate-error-stack.js b/test/parallel/test-internal-util-decorate-error-stack.js index 155a2718f90c55..5694d746c667f4 100644 --- a/test/parallel/test-internal-util-decorate-error-stack.js +++ b/test/parallel/test-internal-util-decorate-error-stack.js @@ -12,12 +12,13 @@ const kDecoratedPrivateSymbolIndex = binding.decorated_private_symbol; const decorateErrorStack = internalUtil.decorateErrorStack; +// Verify that decorateErrorStack does not throw with non-objects. decorateErrorStack(); decorateErrorStack(null); decorateErrorStack(1); 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 = {}; decorateErrorStack(obj); assert.strictEqual(obj.stack, undefined); @@ -46,12 +47,12 @@ try { assert(typeof err, 'object'); checkStack(err.stack); -// Verify that the stack is only decorated once +// Verify that the stack is only decorated once. decorateErrorStack(err); decorateErrorStack(err); 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 = [ '-e', `require('${badSyntaxPath}')` @@ -59,14 +60,14 @@ const args = [ const result = spawnSync(process.argv[0], args, { encoding: 'utf8' }); 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'); let originalStack = err.stack; decorateErrorStack(err); assert.strictEqual(originalStack, err.stack); // Verify that the arrow message is added to the start of the stack when it -// exists +// exists. const arrowMessage = 'arrow_message'; err = new Error('foo'); originalStack = err.stack; diff --git a/test/parallel/test-module-symlinked-peer-modules.js b/test/parallel/test-module-symlinked-peer-modules.js index 09ba4b17b55f3b..fb02a8a94d5d66 100644 --- a/test/parallel/test-module-symlinked-peer-modules.js +++ b/test/parallel/test-module-symlinked-peer-modules.js @@ -59,4 +59,4 @@ fs.writeFileSync(path.join(moduleB, 'package.json'), fs.writeFileSync(path.join(moduleB, 'index.js'), 'module.exports = 1;', 'utf8'); -require(path.join(app, 'index')); +require(path.join(app, 'index')); // Should not throw. diff --git a/test/parallel/test-net-after-close.js b/test/parallel/test-net-after-close.js index 23e265c09a954a..0750ba0f435512 100644 --- a/test/parallel/test-net-after-close.js +++ b/test/parallel/test-net-after-close.js @@ -34,6 +34,8 @@ server.listen(0, common.mustCall(function() { c.on('close', common.mustCall(function() { console.error('connection closed'); assert.strictEqual(c._handle, null); + // Calling functions / accessing properties of a closed socket should not + // throw. c.setNoDelay(); c.setKeepAlive(); c.bufferSize; diff --git a/test/parallel/test-net-during-close.js b/test/parallel/test-net-during-close.js index 11c3dab00f2ec6..7bceb64041f2cc 100644 --- a/test/parallel/test-net-during-close.js +++ b/test/parallel/test-net-during-close.js @@ -30,11 +30,11 @@ const server = net.createServer(function(socket) { server.listen(0, common.mustCall(function() { const client = net.createConnection(this.address().port); server.close(); - // server connection event has not yet fired - // client is still attempting to connect + // Server connection event has not yet fired client is still attempting to + // connect. Accessing properties should not throw in this case. client.remoteAddress; client.remoteFamily; 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); })); diff --git a/test/parallel/test-process-geteuid-getegid.js b/test/parallel/test-process-geteuid-getegid.js index 96e8765eb99015..41e37874a41b59 100644 --- a/test/parallel/test-process-geteuid-getegid.js +++ b/test/parallel/test-process-geteuid-getegid.js @@ -21,6 +21,7 @@ assert.throws(() => { // If we're not running as super user... if (process.getuid() !== 0) { + // Should not throw. process.getegid(); process.geteuid(); diff --git a/test/parallel/test-process-setuid-setgid.js b/test/parallel/test-process-setuid-setgid.js index 0060e3b1ca4af4..41fef8c9c819fa 100644 --- a/test/parallel/test-process-setuid-setgid.js +++ b/test/parallel/test-process-setuid-setgid.js @@ -39,6 +39,7 @@ assert.throws(() => { // If we're not running as super user... if (process.getuid() !== 0) { + // Should not throw. process.getgid(); process.getuid(); diff --git a/test/parallel/test-querystring.js b/test/parallel/test-querystring.js index b0ed9c4ea1d30c..2090d76b75ee34 100644 --- a/test/parallel/test-querystring.js +++ b/test/parallel/test-querystring.js @@ -300,7 +300,7 @@ assert.strictEqual('foo=', qs.stringify({ foo: Infinity })); assert.strictEqual(f, 'a=b&q=x%3Dy%26y%3Dz'); } -qs.parse(undefined); +qs.parse(undefined); // Should not throw. // nested in colon { diff --git a/test/parallel/test-readline-csi.js b/test/parallel/test-readline-csi.js index 54ca6bde97bbe9..f5c2d3044c5cdf 100644 --- a/test/parallel/test-readline-csi.js +++ b/test/parallel/test-readline-csi.js @@ -61,6 +61,7 @@ assert.deepStrictEqual(writable.data, CSI.kClearLine); assert.deepStrictEqual(writable.data, set[2]); }); +// Undefined or null as stream should not throw. readline.cursorTo(null); readline.cursorTo(); diff --git a/test/parallel/test-stream-writable-null.js b/test/parallel/test-stream-writable-null.js index 706141821be175..63e122a3b496e1 100644 --- a/test/parallel/test-stream-writable-null.js +++ b/test/parallel/test-stream-writable-null.js @@ -27,13 +27,9 @@ common.expectsError( } ); -{ - const m = new MyWritable({ objectMode: true }).on('error', (e) => { - assert.ok(e); - }); - m.write(null, (err) => { - assert.ok(err); - }); +{ // Should not throw. + const m = new MyWritable({ objectMode: true }).on('error', assert); + m.write(null, assert); } common.expectsError( @@ -47,25 +43,19 @@ common.expectsError( } ); -{ - const m = new MyWritable().on('error', (e) => { - assert.ok(e); - }); - m.write(false, (err) => { - assert.ok(err); - }); +{ // Should not throw. + const m = new MyWritable().on('error', assert); + m.write(false, assert); } -{ +{ // Should not throw. 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) => { assert.ifError(e || new Error('should not get here')); }); - m.write(false, (err) => { - assert.ifError(err); - }); + m.write(false, assert.ifError); } diff --git a/test/parallel/test-timers-unref.js b/test/parallel/test-timers-unref.js index d8624d8d9c9099..8c4891f1ed6459 100644 --- a/test/parallel/test-timers-unref.js +++ b/test/parallel/test-timers-unref.js @@ -30,6 +30,7 @@ let checks = 0; const LONG_TIME = 10 * 1000; const SHORT_TIME = 100; +// Should not throw. setTimeout(() => {}, 10).unref().ref().unref(); setInterval(() => {}, 10).unref().ref().unref(); diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 9133887a7570a7..ec9afc677b67bc 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -146,7 +146,7 @@ for (const showHidden of [true, false]) { ' 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]) { const ab = vm.runInNewContext('new ArrayBuffer(4)'); 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, Float64Array, Int16Array, @@ -252,7 +252,7 @@ assert.strictEqual( }), { showHidden: true }), '{ visible: 1, [hidden]: 2 }' ); -// Objects without prototype +// Objects without prototype. assert.strictEqual( util.inspect(Object.create(null, { name: { value: 'Tim', enumerable: true }, @@ -269,7 +269,7 @@ assert.strictEqual( '{ name: \'Tim\' }' ); -// Dynamic properties +// Dynamic properties. { assert.strictEqual( util.inspect({ get readonly() {} }), @@ -288,7 +288,7 @@ assert.strictEqual( assert.strictEqual(util.inspect(value), '{ a: [Circular] }'); } -// Array with dynamic properties +// Array with dynamic properties. { const value = [1, 2, 3]; Object.defineProperty( @@ -311,7 +311,7 @@ assert.strictEqual( '[ 1, 2, 3, growingLength: [Getter], \'-1\': -1 ]'); } -// Array with inherited number properties +// Array with inherited number properties. { class CustomArray extends Array {} CustomArray.prototype[5] = 'foo'; @@ -319,7 +319,7 @@ assert.strictEqual( assert.strictEqual(util.inspect(arr), 'CustomArray [ <50 empty items> ]'); } -// Array with extra properties +// Array with extra properties. { const arr = [1, 2, 3, , ]; arr.foo = 'bar'; @@ -351,10 +351,10 @@ assert.strictEqual( assert.strictEqual(util.inspect(arr3), "[ '-1': -1 ]"); } -// Indices out of bounds +// Indices out of bounds. { 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 ]"); arr[0] = true; arr[10] = true; @@ -374,28 +374,28 @@ assert.strictEqual( ].join('\n ')); } -// Function with properties +// Function with properties. { const value = () => {}; value.aprop = 42; assert.strictEqual(util.inspect(value), '{ [Function: value] aprop: 42 }'); } -// Anonymous function with properties +// Anonymous function with properties. { const value = (() => function() {})(); value.aprop = 42; assert.strictEqual(util.inspect(value), '{ [Function] aprop: 42 }'); } -// Regular expressions with properties +// Regular expressions with properties. { const value = /123/ig; value.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'); value.aprop = 42; @@ -403,7 +403,7 @@ assert.strictEqual( '{ 2010-02-14T11:48:40.000Z aprop: 42 }'); } -// test the internal isDate implementation +// Test the internal isDate implementation. { const Date2 = vm.runInNewContext('Date'); const d = new Date2(); @@ -413,13 +413,13 @@ assert.strictEqual( assert.strictEqual(orig, after); } -// test positive/negative zero +// Test positive/negative zero. 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'); -// test for sparse array +// Test for sparse array. { const a = ['foo', 'bar', 'baz']; assert.strictEqual(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]'); @@ -443,7 +443,7 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324'); ); } -// test for Array constructor in different context +// Test for Array constructor in different context. { const Debug = vm.runInDebugContext('Debug'); const map = new Map(); @@ -458,7 +458,7 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324'); 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 {}})()', {}); assert.strictEqual(util.inspect(obj), '{}'); @@ -470,7 +470,7 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324'); assert.strictEqual(util.inspect(obj), 'Promise { }'); } -// test for property descriptors +// Test for property descriptors. { const getter = Object.create(null, { a: { @@ -496,7 +496,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 = []; errors.push(new Error()); @@ -517,7 +517,7 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324'); assert(ex.includes('[message]')); } -// Doesn't capture stack trace +// Doesn't capture stack trace. { function BadCustomError(msg) { Error.call(this); @@ -534,7 +534,6 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324'); } // GH-1941 -// should not throw: assert.strictEqual(util.inspect(Object.create(Date.prototype)), 'Date {}'); // GH-1944 @@ -544,20 +543,20 @@ assert.strictEqual(util.inspect(Object.create(Date.prototype)), 'Date {}'); util.inspect(d); } +// Should not throw. { const d = new Date(); d.toISOString = null; util.inspect(d); } +// Should not throw. const r = /regexp/; r.toString = null; util.inspect(r); -// bug with user-supplied inspect function returns non-string -util.inspect([{ - inspect: () => 123 -}]); +// Bug with user-supplied inspect function returns non-string. +util.inspect([{ inspect: () => 123 }]); // GH-2225 { @@ -593,7 +592,7 @@ util.inspect([{ ); } -// util.inspect.styles and util.inspect.colors +// Test util.inspect.styles and util.inspect.colors. { function testColorStyle(style, input, implicit) { const colorName = util.inspect.styles[style]; @@ -620,12 +619,10 @@ util.inspect([{ testColorStyle('regexp', /regexp/); } -// an object with "hasOwnProperty" overwritten should not throw -util.inspect({ - hasOwnProperty: null -}); +// An object with "hasOwnProperty" overwritten should not throw. +util.inspect({ 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 } } } }; Object.defineProperty(subject, 'hidden', { enumerable: false, value: null }); @@ -665,7 +662,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 }; assert.strictEqual( @@ -685,7 +682,7 @@ util.inspect({ 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' }); assert.strictEqual(util.inspect(subject), '{ foo: \'bar\' }'); @@ -698,7 +695,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 }; assert.strictEqual( @@ -710,7 +707,7 @@ util.inspect({ 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' }); assert.strictEqual(util.inspect(subject), '{ foo: \'bar\' }'); @@ -723,7 +720,7 @@ util.inspect({ } { - // [util.inspect.custom] takes precedence over inspect + // [util.inspect.custom] takes precedence over inspect. const subject = { [util.inspect.custom]() { return 123; }, inspect() { return 456; } @@ -758,7 +755,7 @@ util.inspect({ `{ 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) { const countLines = (str) => (str.match(/\n/g) || []).length; @@ -782,7 +779,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(Object(Symbol('test'))), @@ -795,7 +792,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(13.37)), '[Number: 13.37]'); -// test boxed primitives with own properties +// Test boxed primitives with own properties. { const str = new String('baz'); str.foo = 'bar'; @@ -810,7 +807,7 @@ assert.strictEqual(util.inspect(new Number(13.37)), '[Number: 13.37]'); assert.strictEqual(util.inspect(num), '{ [Number: 13.37] foo: \'bar\' }'); } -// test es6 Symbol +// Test es6 Symbol. if (typeof Symbol !== 'undefined') { assert.strictEqual(util.inspect(Symbol()), 'Symbol()'); assert.strictEqual(util.inspect(Symbol(123)), 'Symbol(123)'); @@ -846,7 +843,7 @@ if (typeof Symbol !== 'undefined') { '[ 1, 2, 3, [Symbol(symbol)]: 42 ]'); } -// test Set +// Test Set. { assert.strictEqual(util.inspect(new Set()), 'Set {}'); assert.strictEqual(util.inspect(new Set([1, 2, 3])), 'Set { 1, 2, 3 }'); @@ -858,14 +855,14 @@ if (typeof Symbol !== 'undefined') { ); } -// Test circular Set +// Test circular Set. { const set = new Set(); set.add(set); assert.strictEqual(util.inspect(set), 'Set { [Circular] }'); } -// test Map +// Test Map. { assert.strictEqual(util.inspect(new Map()), 'Map {}'); assert.strictEqual(util.inspect(new Map([[1, 'a'], [2, 'b'], [3, 'c']])), @@ -876,7 +873,7 @@ if (typeof Symbol !== 'undefined') { 'Map { \'foo\' => null, [size]: 1, bar: 42 }'); } -// Test circular Map +// Test circular Map. { const map = new Map(); map.set(map, 'map'); @@ -888,14 +885,14 @@ if (typeof Symbol !== 'undefined') { assert.strictEqual(util.inspect(map), "Map { 'map' => [Circular] }"); } -// test Promise +// Test Promise. { const resolved = Promise.resolve(3); assert.strictEqual(util.inspect(resolved), 'Promise { 3 }'); const rejected = Promise.reject(3); assert.strictEqual(util.inspect(rejected), 'Promise { 3 }'); - // squelch UnhandledPromiseRejection + // Squelch UnhandledPromiseRejection. rejected.catch(() => {}); const pending = new Promise(() => {}); @@ -917,33 +914,33 @@ if (typeof Symbol !== 'undefined') { global.Promise = oldPromise; } -// Test Map iterators +// Test Map iterators. { const map = new Map([['foo', 'bar']]); assert.strictEqual(util.inspect(map.keys()), 'MapIterator { \'foo\' }'); assert.strictEqual(util.inspect(map.values()), 'MapIterator { \'bar\' }'); assert.strictEqual(util.inspect(map.entries()), 'MapIterator { [ \'foo\', \'bar\' ] }'); - // make sure the iterator doesn't get consumed + // Make sure the iterator doesn't get consumed. const keys = map.keys(); assert.strictEqual(util.inspect(keys), 'MapIterator { \'foo\' }'); assert.strictEqual(util.inspect(keys), 'MapIterator { \'foo\' }'); } -// Test Set iterators +// Test Set iterators. { const aSet = new Set([1, 3]); assert.strictEqual(util.inspect(aSet.keys()), 'SetIterator { 1, 3 }'); assert.strictEqual(util.inspect(aSet.values()), 'SetIterator { 1, 3 }'); assert.strictEqual(util.inspect(aSet.entries()), 'SetIterator { [ 1, 1 ], [ 3, 3 ] }'); - // make sure the iterator doesn't get consumed + // Make sure the iterator doesn't get consumed. const keys = aSet.keys(); assert.strictEqual(util.inspect(keys), 'SetIterator { 1, 3 }'); assert.strictEqual(util.inspect(keys), 'SetIterator { 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. { function checkAlignment(container) { @@ -978,7 +975,7 @@ if (typeof Symbol !== 'undefined') { } -// Test display of constructors +// Test display of constructors. { class ObjectSubclass {} class ArraySubclass extends Array {} @@ -1004,7 +1001,7 @@ if (typeof Symbol !== 'undefined') { ); } -// Empty and circular before depth +// Empty and circular before depth. { const arr = [[[[]]]]; assert.strictEqual(util.inspect(arr), '[ [ [ [] ] ] ]'); @@ -1100,14 +1097,14 @@ if (typeof Symbol !== 'undefined') { assert.strictEqual(twoLines, '{ foo: \'abc\',\n bar: \'xyz\' }'); } -// util.inspect.defaultOptions tests +// util.inspect.defaultOptions tests. { const arr = new Array(101).fill(); const obj = { a: { a: { a: { a: 1 } } } }; const oldOptions = Object.assign({}, util.inspect.defaultOptions); - // Set single option through property assignment + // Set single option through property assignment. util.inspect.defaultOptions.maxArrayLength = null; assert(!/1 more item/.test(util.inspect(arr))); util.inspect.defaultOptions.maxArrayLength = oldOptions.maxArrayLength; @@ -1121,7 +1118,7 @@ if (typeof Symbol !== 'undefined') { JSON.stringify(oldOptions) ); - // Set multiple options through object assignment + // Set multiple options through object assignment. util.inspect.defaultOptions = { maxArrayLength: null, depth: null }; assert(!/1 more item/.test(util.inspect(arr))); assert(!/Object/.test(util.inspect(obj))); diff --git a/test/parallel/test-vm-create-context-arg.js b/test/parallel/test-vm-create-context-arg.js index f5497153815de3..2bcdc8573fe311 100644 --- a/test/parallel/test-vm-create-context-arg.js +++ b/test/parallel/test-vm-create-context-arg.js @@ -28,6 +28,7 @@ assert.throws(function() { vm.createContext('string is not supported'); }, /^TypeError: sandbox must be an object$/); +// Should not throw. vm.createContext({ a: 1 }); vm.createContext([0, 1, 2, 3]); diff --git a/test/parallel/test-vm-cross-context.js b/test/parallel/test-vm-cross-context.js index 785cc9d7bd06bb..b7cf1309d3689f 100644 --- a/test/parallel/test-vm-cross-context.js +++ b/test/parallel/test-vm-cross-context.js @@ -25,4 +25,5 @@ require('../common'); const vm = require('vm'); const ctx = vm.createContext(global); +// Should not throw. vm.runInContext('!function() { var x = console.log; }()', ctx); diff --git a/test/pummel/test-fs-largefile.js b/test/pummel/test-fs-largefile.js index 369f8311925474..2e9dda0495bd6e 100644 --- a/test/pummel/test-fs-largefile.js +++ b/test/pummel/test-fs-largefile.js @@ -44,6 +44,7 @@ assert.strictEqual(readBuf.toString(), message); fs.readSync(fd, readBuf, 0, 1, 0); assert.strictEqual(readBuf[0], 0); +// Verify that floating point positions do not throw. fs.writeSync(fd, writeBuf, 0, writeBuf.length, 42.000001); fs.close(fd); diff --git a/test/pummel/test-fs-watch-file.js b/test/pummel/test-fs-watch-file.js index 62abf0c18fc969..e9d208778faf3f 100644 --- a/test/pummel/test-fs-watch-file.js +++ b/test/pummel/test-fs-watch-file.js @@ -68,6 +68,7 @@ assert.throws( } ); +// Does not throw. fs.watchFile(filepathOne, function() { fs.unwatchFile(filepathOne); ++watchSeenOne; @@ -91,7 +92,7 @@ assert.throws( } ); -{ +{ // Does not throw. function a() { fs.unwatchFile(filepathTwo, a); ++watchSeenTwo; @@ -108,7 +109,7 @@ setTimeout(function() { fs.writeFileSync(filepathTwoAbs, 'pardner'); }, 1000); -{ +{ // Does not throw. function b() { fs.unwatchFile(filenameThree, b); ++watchSeenThree; @@ -130,7 +131,7 @@ setTimeout(function() { fs.writeFileSync(filenameFour, 'hey'); }, 500); -{ +{ // Does not throw. function a() { ++watchSeenFour; assert.strictEqual(1, watchSeenFour); diff --git a/test/sequential/test-inspector-module.js b/test/sequential/test-inspector-module.js index 5b793bf3b43d55..f97d71297971f7 100644 --- a/test/sequential/test-inspector-module.js +++ b/test/sequential/test-inspector-module.js @@ -56,4 +56,5 @@ common.expectsError( ); session.disconnect(); +// Calling disconnect twice should not throw. session.disconnect(); diff --git a/test/sequential/test-performance.js b/test/sequential/test-performance.js index 80bfe217a0518e..770ca7bf6407be 100644 --- a/test/sequential/test-performance.js +++ b/test/sequential/test-performance.js @@ -70,7 +70,7 @@ assert(inited < 20000); { performance.mark('A'); [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) => { From 3b0db4571263c34fecd5d504c4e55130aa43cb16 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 12 Feb 2018 12:25:04 +0100 Subject: [PATCH 04/16] tools: add assert.doesNotThrow eslint rule Prohibit the usage of `assert.doesNotThrow()`. PR-URL: https://github.com/nodejs/node/pull/18669 Reviewed-By: Ben Noordhuis Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: Matteo Collina --- .eslintrc.yaml | 5 ++++- benchmark/assert/throws.js | 1 + doc/api/assert.md | 3 +++ test/parallel/test-assert.js | 12 ++++++------ 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/.eslintrc.yaml b/.eslintrc.yaml index 0e7e9ccfcb73b8..96436055ffcee5 100644 --- a/.eslintrc.yaml +++ b/.eslintrc.yaml @@ -137,8 +137,11 @@ rules: no-mixed-spaces-and-tabs: error no-multiple-empty-lines: [error, {max: 2, maxEOF: 0, maxBOF: 0}] no-restricted-syntax: [error, { + selector: "CallExpression[callee.object.name='assert'][callee.property.name='doesNotThrow']", + message: "Please replace `assert.doesNotThrow()` and add a comment next to the code instead." + }, { selector: "CallExpression[callee.object.name='assert'][callee.property.name='throws'][arguments.1.type='Literal']:not([arguments.1.regex])", - message: "use a regular expression for second argument of assert.throws()" + message: "Use a regular expression for second argument of assert.throws()" }, { selector: "CallExpression[callee.object.name='assert'][callee.property.name='throws'][arguments.length<2]", message: "assert.throws() must be invoked with at least two arguments." diff --git a/benchmark/assert/throws.js b/benchmark/assert/throws.js index bffde7cbc1fd94..2409d19206e353 100644 --- a/benchmark/assert/throws.js +++ b/benchmark/assert/throws.js @@ -26,6 +26,7 @@ function main({ n, method }) { case 'doesNotThrow': bench.start(); for (i = 0; i < n; ++i) { + // eslint-disable-next-line no-restricted-syntax assert.doesNotThrow(doesNotThrow); } bench.end(n); diff --git a/doc/api/assert.md b/doc/api/assert.md index d9b7fd56829f64..c1bcc9ebb31a5b 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -346,6 +346,7 @@ to the caller. The following, for instance, will throw the [`TypeError`][] because there is no matching error type in the assertion: + ```js assert.doesNotThrow( () => { @@ -358,6 +359,7 @@ assert.doesNotThrow( However, the following will result in an `AssertionError` with the message 'Got unwanted exception (TypeError)..': + ```js assert.doesNotThrow( () => { @@ -371,6 +373,7 @@ If an `AssertionError` is thrown and a value is provided for the `message` parameter, the value of `message` will be appended to the `AssertionError` message: + ```js assert.doesNotThrow( () => { diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 5f863b7c297a66..6375311fa6e31c 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -120,7 +120,7 @@ assert.ifError(null); assert.ifError(); common.expectsError( - () => assert.doesNotThrow(() => thrower(Error), 'user message'), + () => a.doesNotThrow(() => thrower(Error), 'user message'), { type: a.AssertionError, code: 'ERR_ASSERTION', @@ -130,7 +130,7 @@ common.expectsError( ); common.expectsError( - () => assert.doesNotThrow(() => thrower(Error), 'user message'), + () => a.doesNotThrow(() => thrower(Error), 'user message'), { code: 'ERR_ASSERTION', message: /Got unwanted exception: user message\n\[object Object\]/ @@ -138,7 +138,7 @@ common.expectsError( ); common.expectsError( - () => assert.doesNotThrow(() => thrower(Error)), + () => a.doesNotThrow(() => thrower(Error)), { code: 'ERR_ASSERTION', message: /Got unwanted exception\.\n\[object Object\]/ @@ -307,7 +307,7 @@ try { // Verify AssertionError is the result from doesNotThrow with custom Error. try { - assert.doesNotThrow(() => { + a.doesNotThrow(() => { throw new TypeError('wrong type'); }, TypeError, rangeError); } catch (e) { @@ -645,7 +645,7 @@ common.expectsError( ); common.expectsError( - () => assert.doesNotThrow(() => { throw new Error(); }, { foo: 'bar' }), + () => a.doesNotThrow(() => { throw new Error(); }, { foo: 'bar' }), { type: TypeError, code: 'ERR_INVALID_ARG_TYPE', @@ -676,7 +676,7 @@ common.expectsError( assert.throws(() => { throw undefined; }, /undefined/); common.expectsError( // eslint-disable-next-line no-throw-literal - () => assert.doesNotThrow(() => { throw undefined; }), + () => a.doesNotThrow(() => { throw undefined; }), { type: assert.AssertionError, code: 'ERR_ASSERTION', From a60b423a75fe3c0e26f120afc0d9d03676b8024a Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Tue, 13 Feb 2018 03:01:46 +0100 Subject: [PATCH 05/16] tools: enable no-unsafe-finally This enables the `no-unsafe-finally` eslint rule to make sure we have a proper control flow in try / catch. PR-URL: https://github.com/nodejs/node/pull/18745 Reviewed-By: Ben Noordhuis Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- .eslintrc.yaml | 1 + lib/timers.js | 32 ++++++++++++++++---------------- test/common/index.js | 14 +++----------- 3 files changed, 20 insertions(+), 27 deletions(-) diff --git a/.eslintrc.yaml b/.eslintrc.yaml index 96436055ffcee5..99489d2e7d8589 100644 --- a/.eslintrc.yaml +++ b/.eslintrc.yaml @@ -157,6 +157,7 @@ rules: }] no-tabs: error no-trailing-spaces: error + no-unsafe-finally: error object-curly-spacing: [error, always] one-var-declaration-per-line: error operator-linebreak: [error, after] diff --git a/lib/timers.js b/lib/timers.js index 46cd770fc643bd..c82d6cfdbb11e9 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -314,24 +314,24 @@ function tryOnTimeout(timer, list) { } } - if (!threw) return; - - // Postpone all later list events to next tick. We need to do this - // so that the events are called in the order they were created. - const lists = list._unrefed === true ? unrefedLists : refedLists; - for (var key in lists) { - if (key > list.msecs) { - lists[key].nextTick = true; + if (threw) { + // Postpone all later list events to next tick. We need to do this + // so that the events are called in the order they were created. + const lists = list._unrefed === true ? unrefedLists : refedLists; + for (var key in lists) { + if (key > list.msecs) { + lists[key].nextTick = true; + } } + // We need to continue processing after domain error handling + // is complete, but not by using whatever domain was left over + // when the timeout threw its exception. + const domain = process.domain; + process.domain = null; + // If we threw, we need to process the rest of the list in nextTick. + process.nextTick(listOnTimeoutNT, list); + process.domain = domain; } - // We need to continue processing after domain error handling - // is complete, but not by using whatever domain was left over - // when the timeout threw its exception. - const domain = process.domain; - process.domain = null; - // If we threw, we need to process the rest of the list in nextTick. - process.nextTick(listOnTimeoutNT, list); - process.domain = domain; } } diff --git a/test/common/index.js b/test/common/index.js index eb4d5a5251cab8..165014e585c49f 100644 --- a/test/common/index.js +++ b/test/common/index.js @@ -514,21 +514,13 @@ exports.canCreateSymLink = function() { const whoamiPath = path.join(process.env.SystemRoot, 'System32', 'whoami.exe'); - let err = false; - let output = ''; - try { - output = execSync(`${whoamiPath} /priv`, { timout: 1000 }); + const output = execSync(`${whoamiPath} /priv`, { timout: 1000 }); + return output.includes('SeCreateSymbolicLinkPrivilege'); } catch (e) { - err = true; - } finally { - if (err || !output.includes('SeCreateSymbolicLinkPrivilege')) { - return false; - } + return false; } } - - return true; }; exports.getCallSite = function getCallSite(top) { From 01e56240833cb71becb2c59d8f0ee61f8a0732c7 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 12 Feb 2018 23:24:54 +0100 Subject: [PATCH 06/16] doc: update buffer examples Move the print statements below a console.log call. PR-URL: https://github.com/nodejs/node/pull/18758 Reviewed-By: Benjamin Gruenbaum Reviewed-By: James M Snell Reviewed-By: Vse Mozhet Byt --- doc/api/buffer.md | 391 +++++++++++++++++++--------------------------- 1 file changed, 161 insertions(+), 230 deletions(-) diff --git a/doc/api/buffer.md b/doc/api/buffer.md index 8925f6d895572e..da46fa7c2e4341 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -161,11 +161,10 @@ Example: ```js const buf = Buffer.from('hello world', 'ascii'); -// Prints: 68656c6c6f20776f726c64 console.log(buf.toString('hex')); - -// Prints: aGVsbG8gd29ybGQ= +// Prints: 68656c6c6f20776f726c64 console.log(buf.toString('base64')); +// Prints: aGVsbG8gd29ybGQ= ``` The character encodings currently supported by Node.js include: @@ -239,23 +238,20 @@ arr[1] = 4000; // Copies the contents of `arr` const buf1 = Buffer.from(arr); - // Shares memory with `arr` const buf2 = Buffer.from(arr.buffer); -// Prints: console.log(buf1); - -// Prints: +// Prints: console.log(buf2); +// Prints: arr[1] = 6000; -// Prints: console.log(buf1); - -// Prints: +// Prints: console.log(buf2); +// Prints: ``` Note that when creating a `Buffer` using a [`TypedArray`]'s `.buffer`, it is @@ -268,8 +264,8 @@ Example: const arr = new Uint16Array(20); const buf = Buffer.from(arr.buffer, 0, 16); -// Prints: 16 console.log(buf.length); +// Prints: 16 ``` The `Buffer.from()` and [`TypedArray.from()`] have different signatures and @@ -384,14 +380,14 @@ arr[1] = 4000; // Shares memory with `arr` const buf = new Buffer(arr.buffer); -// Prints: console.log(buf); +// Prints: // Changing the original Uint16Array changes the Buffer also arr[1] = 6000; -// Prints: console.log(buf); +// Prints: ``` ### new Buffer(buffer) @@ -420,11 +416,10 @@ const buf2 = new Buffer(buf1); buf1[0] = 0x61; -// Prints: auffer console.log(buf1.toString()); - -// Prints: buffer +// Prints: auffer console.log(buf2.toString()); +// Prints: buffer ``` ### new Buffer(size) @@ -462,8 +457,8 @@ Example: ```js const buf = new Buffer(10); -// Prints: console.log(buf); +// Prints: ``` ### new Buffer(string[, encoding]) @@ -489,17 +484,14 @@ provided, the `encoding` parameter identifies the character encoding of `string` ```js const buf1 = new Buffer('this is a tést'); - -// Prints: this is a tést -console.log(buf1.toString()); - -// Prints: this is a tC)st -console.log(buf1.toString('ascii')); - const buf2 = new Buffer('7468697320697320612074c3a97374', 'hex'); +console.log(buf1.toString()); // Prints: this is a tést console.log(buf2.toString()); +// Prints: this is a tést +console.log(buf1.toString('ascii')); +// Prints: this is a tC)st ``` ### Class Method: Buffer.alloc(size[, fill[, encoding]]) @@ -526,8 +518,8 @@ Example: ```js const buf = Buffer.alloc(5); -// Prints: console.log(buf); +// Prints: ``` Allocates a new `Buffer` of `size` bytes. If the `size` is larger than @@ -542,8 +534,8 @@ Example: ```js const buf = Buffer.alloc(5, 'a'); -// Prints: console.log(buf); +// Prints: ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be @@ -554,8 +546,8 @@ Example: ```js const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); -// Prints: console.log(buf); +// Prints: ``` Calling [`Buffer.alloc()`] can be significantly slower than the alternative @@ -589,13 +581,13 @@ Example: ```js const buf = Buffer.allocUnsafe(10); -// Prints: (contents may vary): console.log(buf); +// Prints: (contents may vary): buf.fill(0); -// Prints: console.log(buf); +// Prints: ``` A `TypeError` will be thrown if `size` is not a number. @@ -698,9 +690,9 @@ Example: ```js const str = '\u00bd + \u00bc = \u00be'; -// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes console.log(`${str}: ${str.length} characters, ` + `${Buffer.byteLength(str, 'utf8')} bytes`); +// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes ``` When `string` is a `Buffer`/[`DataView`]/[`TypedArray`]/[`ArrayBuffer`]/ @@ -730,9 +722,9 @@ const buf1 = Buffer.from('1234'); const buf2 = Buffer.from('0123'); const arr = [buf1, buf2]; +console.log(arr.sort(Buffer.compare)); // Prints: [ , ] // (This result is equal to: [buf2, buf1]) -console.log(arr.sort(Buffer.compare)); ``` ### Class Method: Buffer.concat(list[, totalLength]) @@ -772,16 +764,15 @@ const buf2 = Buffer.alloc(14); const buf3 = Buffer.alloc(18); const totalLength = buf1.length + buf2.length + buf3.length; -// Prints: 42 console.log(totalLength); +// Prints: 42 const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); -// Prints: console.log(bufA); - -// Prints: 42 +// Prints: console.log(bufA.length); +// Prints: 42 ``` ### Class Method: Buffer.from(array) @@ -829,14 +820,14 @@ arr[1] = 4000; // Shares memory with `arr` const buf = Buffer.from(arr.buffer); -// Prints: console.log(buf); +// Prints: // Changing the original Uint16Array changes the Buffer also arr[1] = 6000; -// Prints: console.log(buf); +// Prints: ``` The optional `byteOffset` and `length` arguments specify a memory range within @@ -848,8 +839,8 @@ Example: const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); -// Prints: 2 console.log(buf.length); +// Prints: 2 ``` A `TypeError` will be thrown if `arrayBuffer` is not an [`ArrayBuffer`] or a @@ -872,11 +863,10 @@ const buf2 = Buffer.from(buf1); buf1[0] = 0x61; -// Prints: auffer console.log(buf1.toString()); - -// Prints: buffer +// Prints: auffer console.log(buf2.toString()); +// Prints: buffer ``` A `TypeError` will be thrown if `buffer` is not a `Buffer`. @@ -894,17 +884,14 @@ provided, the `encoding` parameter identifies the character encoding of `string` ```js const buf1 = Buffer.from('this is a tést'); - -// Prints: this is a tést -console.log(buf1.toString()); - -// Prints: this is a tC)st -console.log(buf1.toString('ascii')); - const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf1.toString()); // Prints: this is a tést console.log(buf2.toString()); +// Prints: this is a tést +console.log(buf1.toString('ascii')); +// Prints: this is a tC)st ``` A `TypeError` will be thrown if `string` is not a string. @@ -926,7 +913,7 @@ For objects whose `valueOf()` function returns a value not strictly equal to ```js const buf = Buffer.from(new String('this is a test')); -// +// Prints: ``` For objects that support `Symbol.toPrimitive`, returns @@ -940,7 +927,7 @@ class Foo { } const buf = Buffer.from(new Foo(), 'utf8'); -// +// Prints: ``` ### Class Method: Buffer.isBuffer(obj) @@ -998,8 +985,8 @@ for (let i = 0; i < str.length; i++) { buf[i] = str.charCodeAt(i); } -// Prints: Node.js console.log(buf.toString('ascii')); +// Prints: Node.js ``` ### buf.buffer @@ -1051,24 +1038,19 @@ const buf1 = Buffer.from('ABC'); const buf2 = Buffer.from('BCD'); const buf3 = Buffer.from('ABCD'); -// Prints: 0 console.log(buf1.compare(buf1)); - -// Prints: -1 +// Prints: 0 console.log(buf1.compare(buf2)); - // Prints: -1 console.log(buf1.compare(buf3)); - -// Prints: 1 +// Prints: -1 console.log(buf2.compare(buf1)); - // Prints: 1 console.log(buf2.compare(buf3)); - +// Prints: 1 +console.log([buf1, buf2, buf3].sort(Buffer.compare)); // Prints: [ , , ] // (This result is equal to: [buf1, buf3, buf2]) -console.log([buf1, buf2, buf3].sort(Buffer.compare)); ``` The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd` @@ -1079,14 +1061,12 @@ and `buf` respectively. const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); -// Prints: 0 console.log(buf1.compare(buf2, 5, 9, 0, 4)); - -// Prints: -1 +// Prints: 0 console.log(buf1.compare(buf2, 0, 6, 4)); - -// Prints: 1 +// Prints: -1 console.log(buf1.compare(buf2, 5, 6, 5)); +// Prints: 1 ``` A `RangeError` will be thrown if: `targetStart < 0`, `sourceStart < 0`, @@ -1123,8 +1103,8 @@ for (let i = 0; i < 26; i++) { buf1.copy(buf2, 8, 16, 20); -// Prints: !!!!!!!!qrst!!!!!!!!!!!!! console.log(buf2.toString('ascii', 0, 25)); +// Prints: !!!!!!!!qrst!!!!!!!!!!!!! ``` Example: Create a single `Buffer` and copy data from one region to an @@ -1140,8 +1120,8 @@ for (let i = 0; i < 26; i++) { buf.copy(buf, 0, 4, 10); -// Prints: efghijghijklmnopqrstuvwxyz console.log(buf.toString()); +// Prints: efghijghijklmnopqrstuvwxyz ``` ### buf.entries() @@ -1159,6 +1139,9 @@ Example: Log the entire contents of a `Buffer` ```js const buf = Buffer.from('buffer'); +for (const pair of buf.entries()) { + console.log(pair); +} // Prints: // [0, 98] // [1, 117] @@ -1166,9 +1149,6 @@ const buf = Buffer.from('buffer'); // [3, 102] // [4, 101] // [5, 114] -for (const pair of buf.entries()) { - console.log(pair); -} ``` ### buf.equals(otherBuffer) @@ -1191,11 +1171,10 @@ const buf1 = Buffer.from('ABC'); const buf2 = Buffer.from('414243', 'hex'); const buf3 = Buffer.from('ABCD'); -// Prints: true console.log(buf1.equals(buf2)); - -// Prints: false +// Prints: true console.log(buf1.equals(buf3)); +// Prints: false ``` ### buf.fill(value[, offset[, end]][, encoding]) @@ -1223,8 +1202,8 @@ Example: Fill a `Buffer` with the ASCII character `'h'` ```js const b = Buffer.allocUnsafe(50).fill('h'); -// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh console.log(b.toString()); +// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh ``` `value` is coerced to a `uint32` value if it is not a String or Integer. @@ -1235,8 +1214,8 @@ then only the first bytes of that character that fit into `buf` are written. Example: Fill a `Buffer` with a two-byte character ```js -// Prints: console.log(Buffer.allocUnsafe(3).fill('\u0222')); +// Prints: ``` If `value` contains invalid characters, it is truncated; if no valid @@ -1244,12 +1223,13 @@ fill data remains, no filling is performed: ```js const buf = Buffer.allocUnsafe(5); -// Prints: + console.log(buf.fill('a')); -// Prints: +// Prints: console.log(buf.fill('aazz', 'hex')); // Prints: console.log(buf.fill('zz', 'hex')); +// Throws an exception. ``` ### buf.includes(value[, byteOffset][, encoding]) @@ -1268,27 +1248,20 @@ Equivalent to [`buf.indexOf() !== -1`][`buf.indexOf()`]. ```js const buf = Buffer.from('this is a buffer'); -// Prints: true console.log(buf.includes('this')); - // Prints: true console.log(buf.includes('is')); - // Prints: true console.log(buf.includes(Buffer.from('a buffer'))); - // Prints: true -// (97 is the decimal ASCII value for 'a') console.log(buf.includes(97)); - -// Prints: false +// Prints: true (97 is the decimal ASCII value for 'a') console.log(buf.includes(Buffer.from('a buffer example'))); - -// Prints: true -console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); - // Prints: false +console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); +// Prints: true console.log(buf.includes('this', 4)); +// Prints: false ``` ### buf.indexOf(value[, byteOffset][, encoding]) @@ -1323,32 +1296,25 @@ If `value` is: ```js const buf = Buffer.from('this is a buffer'); -// Prints: 0 console.log(buf.indexOf('this')); - -// Prints: 2 +// Prints: 0 console.log(buf.indexOf('is')); - -// Prints: 8 +// Prints: 2 console.log(buf.indexOf(Buffer.from('a buffer'))); - // Prints: 8 -// (97 is the decimal ASCII value for 'a') console.log(buf.indexOf(97)); - -// Prints: -1 +// Prints: 8 (97 is the decimal ASCII value for 'a') console.log(buf.indexOf(Buffer.from('a buffer example'))); - -// Prints: 8 +// Prints: -1 console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); +// Prints: 8 const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); -// Prints: 4 console.log(utf16Buffer.indexOf('\u03a3', 0, 'ucs2')); - -// Prints: 6 +// Prints: 4 console.log(utf16Buffer.indexOf('\u03a3', -4, 'ucs2')); +// Prints: 6 ``` If `value` is not a string, number, or `Buffer`, this method will throw a @@ -1393,6 +1359,9 @@ Example: ```js const buf = Buffer.from('buffer'); +for (const key of buf.keys()) { + console.log(key); +} // Prints: // 0 // 1 @@ -1400,9 +1369,6 @@ const buf = Buffer.from('buffer'); // 3 // 4 // 5 -for (const key of buf.keys()) { - console.log(key); -} ``` ### buf.lastIndexOf(value[, byteOffset][, encoding]) @@ -1428,35 +1394,27 @@ instead of front to back. ```js const buf = Buffer.from('this buffer is a buffer'); -// Prints: 0 console.log(buf.lastIndexOf('this')); - -// Prints: 17 +// Prints: 0 console.log(buf.lastIndexOf('buffer')); - // Prints: 17 console.log(buf.lastIndexOf(Buffer.from('buffer'))); - -// Prints: 15 -// (97 is the decimal ASCII value for 'a') +// Prints: 17 console.log(buf.lastIndexOf(97)); - -// Prints: -1 +// Prints: 15 (97 is the decimal ASCII value for 'a') console.log(buf.lastIndexOf(Buffer.from('yolo'))); - -// Prints: 5 -console.log(buf.lastIndexOf('buffer', 5)); - // Prints: -1 +console.log(buf.lastIndexOf('buffer', 5)); +// Prints: 5 console.log(buf.lastIndexOf('buffer', 4)); +// Prints: -1 const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); -// Prints: 6 console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'ucs2')); - -// Prints: 4 +// Prints: 6 console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'ucs2')); +// Prints: 4 ``` If `value` is not a string, number, or `Buffer`, this method will throw a @@ -1503,13 +1461,13 @@ Example: Create a `Buffer` and write a shorter ASCII string to it ```js const buf = Buffer.alloc(1234); -// Prints: 1234 console.log(buf.length); +// Prints: 1234 buf.write('some string', 0, 'ascii'); -// Prints: 1234 console.log(buf.length); +// Prints: 1234 ``` While the `length` property is not immutable, changing the value of `length` @@ -1522,13 +1480,13 @@ let buf = Buffer.allocUnsafe(10); buf.write('abcdefghj', 0, 'ascii'); -// Prints: 10 console.log(buf.length); +// Prints: 10 buf = buf.slice(0, 5); -// Prints: 5 console.log(buf.length); +// Prints: 5 ``` ### buf.parent @@ -1560,18 +1518,15 @@ the resulting behavior is undefined. ```js const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); -// Prints: 8.20788039913184e-304 console.log(buf.readDoubleBE()); - -// Prints: 5.447603722011605e-270 +// Prints: 8.20788039913184e-304 console.log(buf.readDoubleLE()); - -// Throws an exception: RangeError: Index out of range +// Prints: 5.447603722011605e-270 console.log(buf.readDoubleLE(1)); - +// Throws an exception: RangeError: Index out of range +console.log(buf.readDoubleLE(1, true)); // Warning: reads passed end of buffer! // This will result in a segmentation fault! Don't do this! -console.log(buf.readDoubleLE(1, true)); ``` ### buf.readFloatBE(offset[, noAssert]) @@ -1594,18 +1549,15 @@ the resulting behavior is undefined. ```js const buf = Buffer.from([1, 2, 3, 4]); -// Prints: 2.387939260590663e-38 console.log(buf.readFloatBE()); - -// Prints: 1.539989614439558e-36 +// Prints: 2.387939260590663e-38 console.log(buf.readFloatLE()); - -// Throws an exception: RangeError: Index out of range +// Prints: 1.539989614439558e-36 console.log(buf.readFloatLE(1)); - +// Throws an exception: RangeError: Index out of range +console.log(buf.readFloatLE(1, true)); // Warning: reads passed end of buffer! // This will result in a segmentation fault! Don't do this! -console.log(buf.readFloatLE(1, true)); ``` ### buf.readInt8(offset[, noAssert]) @@ -1627,14 +1579,12 @@ Integers read from a `Buffer` are interpreted as two's complement signed values. ```js const buf = Buffer.from([-1, 5]); -// Prints: -1 console.log(buf.readInt8(0)); - -// Prints: 5 +// Prints: -1 console.log(buf.readInt8(1)); - -// Throws an exception: RangeError: Index out of range +// Prints: 5 console.log(buf.readInt8(2)); +// Throws an exception: RangeError: Index out of range ``` ### buf.readInt16BE(offset[, noAssert]) @@ -1659,14 +1609,12 @@ Integers read from a `Buffer` are interpreted as two's complement signed values. ```js const buf = Buffer.from([0, 5]); -// Prints: 5 console.log(buf.readInt16BE()); - -// Prints: 1280 +// Prints: 5 console.log(buf.readInt16LE()); - -// Throws an exception: RangeError: Index out of range +// Prints: 1280 console.log(buf.readInt16LE(1)); +// Throws an exception: RangeError: Index out of range ``` ### buf.readInt32BE(offset[, noAssert]) @@ -1691,14 +1639,12 @@ Integers read from a `Buffer` are interpreted as two's complement signed values. ```js const buf = Buffer.from([0, 0, 0, 5]); -// Prints: 5 console.log(buf.readInt32BE()); - -// Prints: 83886080 +// Prints: 5 console.log(buf.readInt32LE()); - -// Throws an exception: RangeError: Index out of range +// Prints: 83886080 console.log(buf.readInt32LE(1)); +// Throws an exception: RangeError: Index out of range ``` ### buf.readIntBE(offset, byteLength[, noAssert]) @@ -1722,14 +1668,12 @@ the resulting behavior is undefined. ```js const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); -// Prints: -546f87a9cbee console.log(buf.readIntLE(0, 6).toString(16)); - -// Prints: 1234567890ab +// Prints: -546f87a9cbee console.log(buf.readIntBE(0, 6).toString(16)); - -// Throws an exception: RangeError: Index out of range +// Prints: 1234567890ab console.log(buf.readIntBE(1, 6).toString(16)); +// Throws: RangeError [ERR_INDEX_OUT_OF_RANGE]: Index out of range ``` ### buf.readUInt8(offset[, noAssert]) @@ -1749,14 +1693,12 @@ the resulting behavior is undefined. ```js const buf = Buffer.from([1, -2]); -// Prints: 1 console.log(buf.readUInt8(0)); - -// Prints: 254 +// Prints: 1 console.log(buf.readUInt8(1)); - -// Throws an exception: RangeError: Index out of range +// Prints: 254 console.log(buf.readUInt8(2)); +// Throws an exception: RangeError: Index out of range ``` ### buf.readUInt16BE(offset[, noAssert]) @@ -1779,20 +1721,16 @@ the resulting behavior is undefined. ```js const buf = Buffer.from([0x12, 0x34, 0x56]); -// Prints: 1234 console.log(buf.readUInt16BE(0).toString(16)); - -// Prints: 3412 +// Prints: 1234 console.log(buf.readUInt16LE(0).toString(16)); - -// Prints: 3456 +// Prints: 3412 console.log(buf.readUInt16BE(1).toString(16)); - -// Prints: 5634 +// Prints: 3456 console.log(buf.readUInt16LE(1).toString(16)); - -// Throws an exception: RangeError: Index out of range +// Prints: 5634 console.log(buf.readUInt16LE(2).toString(16)); +// Throws an exception: RangeError: Index out of range ``` ### buf.readUInt32BE(offset[, noAssert]) @@ -1815,14 +1753,12 @@ the resulting behavior is undefined. ```js const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); -// Prints: 12345678 console.log(buf.readUInt32BE(0).toString(16)); - -// Prints: 78563412 +// Prints: 12345678 console.log(buf.readUInt32LE(0).toString(16)); - -// Throws an exception: RangeError: Index out of range +// Prints: 78563412 console.log(buf.readUInt32LE(1).toString(16)); +// Throws an exception: RangeError: Index out of range ``` ### buf.readUIntBE(offset, byteLength[, noAssert]) @@ -1846,14 +1782,12 @@ the resulting behavior is undefined. ```js const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); -// Prints: 1234567890ab console.log(buf.readUIntBE(0, 6).toString(16)); - -// Prints: ab9078563412 +// Prints: 1234567890ab console.log(buf.readUIntLE(0, 6).toString(16)); - -// Throws an exception: RangeError: Index out of range +// Prints: ab9078563412 console.log(buf.readUIntBE(1, 6).toString(16)); +// Throws an exception: RangeError: Index out of range ``` ### buf.slice([start[, end]]) @@ -1897,13 +1831,13 @@ for (let i = 0; i < 26; i++) { const buf2 = buf1.slice(0, 3); -// Prints: abc console.log(buf2.toString('ascii', 0, buf2.length)); +// Prints: abc buf1[0] = 33; -// Prints: !bc console.log(buf2.toString('ascii', 0, buf2.length)); +// Prints: !bc ``` Specifying negative indexes causes the slice to be generated relative to the @@ -1912,17 +1846,17 @@ end of `buf` rather than the beginning. ```js const buf = Buffer.from('buffer'); +console.log(buf.slice(-6, -1).toString()); // Prints: buffe // (Equivalent to buf.slice(0, 5)) -console.log(buf.slice(-6, -1).toString()); +console.log(buf.slice(-6, -2).toString()); // Prints: buff // (Equivalent to buf.slice(0, 4)) -console.log(buf.slice(-6, -2).toString()); +console.log(buf.slice(-5, -2).toString()); // Prints: uff // (Equivalent to buf.slice(1, 4)) -console.log(buf.slice(-5, -2).toString()); ``` ### buf.swap16() @@ -1938,18 +1872,18 @@ Interprets `buf` as an array of unsigned 16-bit integers and swaps the byte-orde ```js const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); -// Prints: console.log(buf1); +// Prints: buf1.swap16(); -// Prints: console.log(buf1); +// Prints: const buf2 = Buffer.from([0x1, 0x2, 0x3]); -// Throws an exception: RangeError: Buffer size must be a multiple of 16-bits buf2.swap16(); +// Throws an exception: RangeError: Buffer size must be a multiple of 16-bits ``` ### buf.swap32() @@ -1965,18 +1899,18 @@ Interprets `buf` as an array of unsigned 32-bit integers and swaps the byte-orde ```js const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); -// Prints: console.log(buf1); +// Prints: buf1.swap32(); -// Prints: console.log(buf1); +// Prints: const buf2 = Buffer.from([0x1, 0x2, 0x3]); -// Throws an exception: RangeError: Buffer size must be a multiple of 32-bits buf2.swap32(); +// Throws an exception: RangeError: Buffer size must be a multiple of 32-bits ``` ### buf.swap64() @@ -1992,18 +1926,18 @@ Throws a `RangeError` if [`buf.length`] is not a multiple of 8. ```js const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); -// Prints: console.log(buf1); +// Prints: buf1.swap64(); -// Prints: console.log(buf1); +// Prints: const buf2 = Buffer.from([0x1, 0x2, 0x3]); -// Throws an exception: RangeError: Buffer size must be a multiple of 64-bits buf2.swap64(); +// Throws an exception: RangeError: Buffer size must be a multiple of 64-bits ``` Note that JavaScript cannot encode 64-bit integers. This method is intended @@ -2025,8 +1959,8 @@ Example: const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); const json = JSON.stringify(buf); -// Prints: {"type":"Buffer","data":[1,2,3,4,5]} console.log(json); +// Prints: {"type":"Buffer","data":[1,2,3,4,5]} const copy = JSON.parse(json, (key, value) => { return value && value.type === 'Buffer' ? @@ -2034,8 +1968,8 @@ const copy = JSON.parse(json, (key, value) => { value; }); -// Prints: console.log(copy); +// Prints: ``` ### buf.toString([encoding[, start[, end]]]) @@ -2063,22 +1997,19 @@ for (let i = 0; i < 26; i++) { buf1[i] = i + 97; } -// Prints: abcdefghijklmnopqrstuvwxyz console.log(buf1.toString('ascii')); - -// Prints: abcde +// Prints: abcdefghijklmnopqrstuvwxyz console.log(buf1.toString('ascii', 0, 5)); +// Prints: abcde const buf2 = Buffer.from('tést'); -// Prints: 74c3a97374 console.log(buf2.toString('hex')); - -// Prints: té +// Prints: 74c3a97374 console.log(buf2.toString('utf8', 0, 3)); - // Prints: té console.log(buf2.toString(undefined, 0, 3)); +// Prints: té ``` ### buf.values() @@ -2094,6 +2025,9 @@ called automatically when a `Buffer` is used in a `for..of` statement. ```js const buf = Buffer.from('buffer'); +for (const value of buf.values()) { + console.log(value); +} // Prints: // 98 // 117 @@ -2101,10 +2035,10 @@ const buf = Buffer.from('buffer'); // 102 // 101 // 114 -for (const value of buf.values()) { + +for (const value of buf) { console.log(value); } - // Prints: // 98 // 117 @@ -2112,9 +2046,6 @@ for (const value of buf.values()) { // 102 // 101 // 114 -for (const value of buf) { - console.log(value); -} ``` ### buf.write(string[, offset[, length]][, encoding]) @@ -2140,8 +2071,8 @@ const buf = Buffer.allocUnsafe(256); const len = buf.write('\u00bd + \u00bc = \u00be', 0); -// Prints: 12 bytes: ½ + ¼ = ¾ console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); +// Prints: 12 bytes: ½ + ¼ = ¾ ``` ### buf.writeDoubleBE(value, offset[, noAssert]) @@ -2168,13 +2099,13 @@ const buf = Buffer.allocUnsafe(8); buf.writeDoubleBE(0xdeadbeefcafebabe, 0); -// Prints: console.log(buf); +// Prints: buf.writeDoubleLE(0xdeadbeefcafebabe, 0); -// Prints: console.log(buf); +// Prints: ``` ### buf.writeFloatBE(value, offset[, noAssert]) @@ -2201,13 +2132,13 @@ const buf = Buffer.allocUnsafe(4); buf.writeFloatBE(0xcafebabe, 0); -// Prints: console.log(buf); +// Prints: buf.writeFloatLE(0xcafebabe, 0); -// Prints: console.log(buf); +// Prints: ``` ### buf.writeInt8(value, offset[, noAssert]) @@ -2235,8 +2166,8 @@ const buf = Buffer.allocUnsafe(2); buf.writeInt8(2, 0); buf.writeInt8(-2, 1); -// Prints: console.log(buf); +// Prints: ``` ### buf.writeInt16BE(value, offset[, noAssert]) @@ -2266,8 +2197,8 @@ const buf = Buffer.allocUnsafe(4); buf.writeInt16BE(0x0102, 0); buf.writeInt16LE(0x0304, 2); -// Prints: console.log(buf); +// Prints: ``` ### buf.writeInt32BE(value, offset[, noAssert]) @@ -2297,8 +2228,8 @@ const buf = Buffer.allocUnsafe(8); buf.writeInt32BE(0x01020304, 0); buf.writeInt32LE(0x05060708, 4); -// Prints: console.log(buf); +// Prints: ``` ### buf.writeIntBE(value, offset, byteLength[, noAssert]) @@ -2326,13 +2257,13 @@ const buf = Buffer.allocUnsafe(6); buf.writeIntBE(0x1234567890ab, 0, 6); -// Prints: console.log(buf); +// Prints: buf.writeIntLE(0x1234567890ab, 0, 6); -// Prints: console.log(buf); +// Prints: ``` ### buf.writeUInt8(value, offset[, noAssert]) @@ -2360,8 +2291,8 @@ buf.writeUInt8(0x4, 1); buf.writeUInt8(0x23, 2); buf.writeUInt8(0x42, 3); -// Prints: console.log(buf); +// Prints: ``` ### buf.writeUInt16BE(value, offset[, noAssert]) @@ -2389,14 +2320,14 @@ const buf = Buffer.allocUnsafe(4); buf.writeUInt16BE(0xdead, 0); buf.writeUInt16BE(0xbeef, 2); -// Prints: console.log(buf); +// Prints: buf.writeUInt16LE(0xdead, 0); buf.writeUInt16LE(0xbeef, 2); -// Prints: console.log(buf); +// Prints: ``` ### buf.writeUInt32BE(value, offset[, noAssert]) @@ -2423,13 +2354,13 @@ const buf = Buffer.allocUnsafe(4); buf.writeUInt32BE(0xfeedface, 0); -// Prints: console.log(buf); +// Prints: buf.writeUInt32LE(0xfeedface, 0); -// Prints: console.log(buf); +// Prints: ``` ### buf.writeUIntBE(value, offset, byteLength[, noAssert]) @@ -2457,13 +2388,13 @@ const buf = Buffer.allocUnsafe(6); buf.writeUIntBE(0x1234567890ab, 0, 6); -// Prints: console.log(buf); +// Prints: buf.writeUIntLE(0x1234567890ab, 0, 6); -// Prints: console.log(buf); +// Prints: ``` ## buffer.INSPECT_MAX_BYTES @@ -2591,13 +2522,13 @@ const { SlowBuffer } = require('buffer'); const buf = new SlowBuffer(5); -// Prints: (contents may vary): console.log(buf); +// Prints: (contents may vary): buf.fill(0); -// Prints: console.log(buf); +// Prints: ``` ## Buffer Constants From 433497e2258c452904eb50a104e9eb30c6c2891f Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Sat, 17 Feb 2018 03:45:07 +0100 Subject: [PATCH 07/16] tools: enable eslint no-undef-init rule MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This also fixes the three entries that did not pass. PR-URL: https://github.com/nodejs/node/pull/18831 Reviewed-By: Luigi Pinca Reviewed-By: Matheus Marchini Reviewed-By: Anna Henningsen Reviewed-By: Michaël Zasso Reviewed-By: Anatoli Papirovski Reviewed-By: Colin Ihrig --- test/parallel/test-fs-utimes.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/parallel/test-fs-utimes.js b/test/parallel/test-fs-utimes.js index 3dc0bb59def6a2..738fc7576a8b5e 100644 --- a/test/parallel/test-fs-utimes.js +++ b/test/parallel/test-fs-utimes.js @@ -88,7 +88,7 @@ function testIt(atime, mtime, callback) { expect_errno('futimesSync', fd, ex, 'ENOSYS'); } - let err = undefined; + let err; try { fs.utimesSync('foobarbaz', atime, mtime); } catch (ex) { From dcf01b552460a482d828e06712e3d6faa4d5d77a Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Sat, 17 Feb 2018 03:46:15 +0100 Subject: [PATCH 08/16] tools: enable eslint strict key-spacing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/18831 Reviewed-By: Luigi Pinca Reviewed-By: Matheus Marchini Reviewed-By: Anna Henningsen Reviewed-By: Michaël Zasso Reviewed-By: Anatoli Papirovski Reviewed-By: Colin Ihrig --- benchmark/http/_chunky_http_client.js | 4 ++-- test/parallel/test-eslint-require-buffer.js | 8 ++++---- test/parallel/test-https-agent-servername.js | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/benchmark/http/_chunky_http_client.js b/benchmark/http/_chunky_http_client.js index a90535e489f4c9..7728a5d06c60aa 100644 --- a/benchmark/http/_chunky_http_client.js +++ b/benchmark/http/_chunky_http_client.js @@ -5,8 +5,8 @@ const common = require('../common.js'); const net = require('net'); const bench = common.createBenchmark(main, { - len: [1, 4, 8, 16, 32, 64, 128], - n: [5, 50, 500, 2000], + len: [1, 4, 8, 16, 32, 64, 128], + n: [5, 50, 500, 2000], type: ['send'], }); diff --git a/test/parallel/test-eslint-require-buffer.js b/test/parallel/test-eslint-require-buffer.js index ca2c44cb322515..bdc794dd594240 100644 --- a/test/parallel/test-eslint-require-buffer.js +++ b/test/parallel/test-eslint-require-buffer.js @@ -36,14 +36,14 @@ ruleTester.run('require-buffer', rule, { output: useStrict + bufferModule + useBuffer, }, { - code: mockComment + useBuffer, + code: mockComment + useBuffer, errors: [{ message }], - output: mockComment + bufferModule + useBuffer, + output: mockComment + bufferModule + useBuffer, }, { - code: mockComment + useStrict + useBuffer, + code: mockComment + useStrict + useBuffer, errors: [{ message }], - output: mockComment + useStrict + bufferModule + useBuffer, + output: mockComment + useStrict + bufferModule + useBuffer, }, ] }); diff --git a/test/parallel/test-https-agent-servername.js b/test/parallel/test-https-agent-servername.js index 985fbb3ce3f76e..df14d113994f89 100644 --- a/test/parallel/test-https-agent-servername.js +++ b/test/parallel/test-https-agent-servername.js @@ -10,7 +10,7 @@ const fixtures = require('../common/fixtures'); const options = { key: fixtures.readKey('agent1-key.pem'), cert: fixtures.readKey('agent1-cert.pem'), - ca: fixtures.readKey('ca1-cert.pem') + ca: fixtures.readKey('ca1-cert.pem') }; From 6a262d16221609c4e1a13380a3e832c262d9bb4f Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Sat, 17 Feb 2018 03:51:11 +0100 Subject: [PATCH 09/16] tools: enable eslint one-var rule MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/18831 Reviewed-By: Luigi Pinca Reviewed-By: Matheus Marchini Reviewed-By: Anna Henningsen Reviewed-By: Michaël Zasso Reviewed-By: Anatoli Papirovski Reviewed-By: Colin Ihrig --- benchmark/tls/tls-connect.js | 6 +-- test/parallel/test-cluster-worker-kill.js | 45 +++++++++++------------ 2 files changed, 25 insertions(+), 26 deletions(-) diff --git a/benchmark/tls/tls-connect.js b/benchmark/tls/tls-connect.js index da0f5e08d5e6db..524d7468d000a1 100644 --- a/benchmark/tls/tls-connect.js +++ b/benchmark/tls/tls-connect.js @@ -1,7 +1,7 @@ 'use strict'; -var fs = require('fs'), - path = require('path'), - tls = require('tls'); +const fs = require('fs'); +const path = require('path'); +const tls = require('tls'); const common = require('../common.js'); const bench = common.createBenchmark(main, { diff --git a/test/parallel/test-cluster-worker-kill.js b/test/parallel/test-cluster-worker-kill.js index 38e2deb1555c2d..bb2d3495d95a4d 100644 --- a/test/parallel/test-cluster-worker-kill.js +++ b/test/parallel/test-cluster-worker-kill.js @@ -40,29 +40,28 @@ if (cluster.isWorker) { } else if (cluster.isMaster) { - const KILL_SIGNAL = 'SIGKILL', - expected_results = { - cluster_emitDisconnect: [1, "the cluster did not emit 'disconnect'"], - cluster_emitExit: [1, "the cluster did not emit 'exit'"], - cluster_exitCode: [null, 'the cluster exited w/ incorrect exitCode'], - cluster_signalCode: [KILL_SIGNAL, - 'the cluster exited w/ incorrect signalCode'], - worker_emitDisconnect: [1, "the worker did not emit 'disconnect'"], - worker_emitExit: [1, "the worker did not emit 'exit'"], - worker_state: ['disconnected', 'the worker state is incorrect'], - worker_exitedAfter: [false, - 'the .exitedAfterDisconnect flag is incorrect'], - worker_died: [true, 'the worker is still running'], - worker_exitCode: [null, 'the worker exited w/ incorrect exitCode'], - worker_signalCode: [KILL_SIGNAL, - 'the worker exited w/ incorrect signalCode'] - }, - results = { - cluster_emitDisconnect: 0, - cluster_emitExit: 0, - worker_emitDisconnect: 0, - worker_emitExit: 0 - }; + const KILL_SIGNAL = 'SIGKILL'; + const expected_results = { + cluster_emitDisconnect: [1, "the cluster did not emit 'disconnect'"], + cluster_emitExit: [1, "the cluster did not emit 'exit'"], + cluster_exitCode: [null, 'the cluster exited w/ incorrect exitCode'], + cluster_signalCode: [KILL_SIGNAL, + 'the cluster exited w/ incorrect signalCode'], + worker_emitDisconnect: [1, "the worker did not emit 'disconnect'"], + worker_emitExit: [1, "the worker did not emit 'exit'"], + worker_state: ['disconnected', 'the worker state is incorrect'], + worker_exitedAfter: [false, 'the .exitedAfterDisconnect flag is incorrect'], + worker_died: [true, 'the worker is still running'], + worker_exitCode: [null, 'the worker exited w/ incorrect exitCode'], + worker_signalCode: [KILL_SIGNAL, + 'the worker exited w/ incorrect signalCode'] + }; + const results = { + cluster_emitDisconnect: 0, + cluster_emitExit: 0, + worker_emitDisconnect: 0, + worker_emitExit: 0 + }; // start worker From c2a3b9b4277cdf67fec72dddc8a206c8d2b37774 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Sat, 17 Feb 2018 03:58:50 +0100 Subject: [PATCH 10/16] doc: enable eslint prefer-template rule MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/18831 Reviewed-By: Luigi Pinca Reviewed-By: Matheus Marchini Reviewed-By: Anna Henningsen Reviewed-By: Michaël Zasso Reviewed-By: Anatoli Papirovski Reviewed-By: Colin Ihrig --- doc/.eslintrc.yaml | 1 + doc/api/esm.md | 4 ++-- doc/api/stream.md | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/doc/.eslintrc.yaml b/doc/.eslintrc.yaml index c8c1612e3a100b..7b38afec10276a 100644 --- a/doc/.eslintrc.yaml +++ b/doc/.eslintrc.yaml @@ -12,6 +12,7 @@ rules: no-var: error prefer-const: error prefer-rest-params: error + prefer-template: error # Stylistic Issues no-multiple-empty-lines: [error, {max: 1, maxEOF: 0, maxBOF: 0}] diff --git a/doc/api/esm.md b/doc/api/esm.md index e6c8525dbc02d4..4f658bc6802ad9 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -114,7 +114,7 @@ given module specifier and parent file URL: ```js const baseURL = new URL('file://'); -baseURL.pathname = process.cwd() + '/'; +baseURL.pathname = `${process.cwd()}/`; export async function resolve(specifier, parentModuleURL = baseURL, @@ -158,7 +158,7 @@ const builtins = Module.builtinModules; const JS_EXTENSIONS = new Set(['.js', '.mjs']); const baseURL = new URL('file://'); -baseURL.pathname = process.cwd() + '/'; +baseURL.pathname = `${process.cwd()}/`; export function resolve(specifier, parentModuleURL = baseURL, defaultResolve) { if (builtins.includes(specifier)) { diff --git a/doc/api/stream.md b/doc/api/stream.md index a92e11e71a2402..99c159dfefe86b 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -1801,7 +1801,7 @@ class Counter extends Readable { if (i > this._max) this.push(null); else { - const str = '' + i; + const str = String(i); const buf = Buffer.from(str, 'ascii'); this.push(buf); } From cc63116880cd7f4d39bdc527a9b9f3073f983af0 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 19 Feb 2018 01:49:30 +0100 Subject: [PATCH 11/16] errors: implement new error handling This implements a function based system. Instead of passing in the error code as first argument, the error code itself is a error class. It already contains the correct error type, so while adding a new error no one has to think about the error type anymore. In case a single error code has more than one error type, the error class has properties for the non default error types. Those can be used as fallback. This prevents typos, makes the implementation easier and it is less verbose when writing the code for a new error. The implementation itself does not interfere with the old implementation. So the old and the new system can co-exist and it is possible to slowly migrate the old ones to the new system. PR-URL: https://github.com/nodejs/node/pull/18857 Reviewed-By: Anna Henningsen Reviewed-By: Gus Caplan Reviewed-By: James M Snell Reviewed-By: Joyee Cheung --- lib/internal/errors.js | 56 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 50 insertions(+), 6 deletions(-) diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 9cc731e99fb3af..50d1cd3fb53b2c 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -12,6 +12,7 @@ const kCode = Symbol('code'); const messages = new Map(); +const codes = {}; var green = ''; var red = ''; @@ -194,6 +195,54 @@ function createErrDiff(actual, expected, operator) { return `${msg}${skipped ? skippedMsg : ''}\n${res}${other}${end}`; } +function makeNodeErrorWithCode(Base, key) { + return class NodeError extends Base { + constructor(...args) { + super(message(key, args)); + } + + get name() { + return `${super.name} [${key}]`; + } + + set name(value) { + defineProperty(this, 'name', { + configurable: true, + enumerable: true, + value, + writable: true + }); + } + + get code() { + return key; + } + + set code(value) { + defineProperty(this, 'code', { + configurable: true, + enumerable: true, + value, + writable: true + }); + } + }; +} + +// Utility function for registering the error codes. Only used here. Exported +// *only* to allow for testing. +function E(sym, val, def, ...otherClasses) { + messages.set(sym, val); + if (def === undefined) return; + def = makeNodeErrorWithCode(def, sym); + if (otherClasses.length !== 0) { + otherClasses.forEach((clazz) => { + def[clazz.name] = makeNodeErrorWithCode(clazz, sym); + }); + } + codes[sym] = def; +} + class AssertionError extends Error { constructor(options) { if (typeof options !== 'object' || options === null) { @@ -296,12 +345,6 @@ function message(key, args) { return String(fmt.apply(null, args)); } -// Utility function for registering the error codes. Only used here. Exported -// *only* to allow for testing. -function E(sym, val) { - messages.set(sym, typeof val === 'function' ? val : String(val)); -} - /** * This used to be util._errnoException(). * @@ -412,6 +455,7 @@ module.exports = exports = { RangeError: makeNodeError(RangeError), URIError: makeNodeError(URIError), AssertionError, + codes, E // This is exported only to facilitate testing. }; From c491b28adaad0534b760dbeb427e77e26e5a4d0f Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 19 Feb 2018 01:50:56 +0100 Subject: [PATCH 12/16] errors: update all internal errors This updates all internal errors to the new error type. While doing so it removes unused errors. A few errors currently seem to have the wrong type. To identify them later, comments were added next to the error type. PR-URL: https://github.com/nodejs/node/pull/18857 Reviewed-By: Anna Henningsen Reviewed-By: Gus Caplan Reviewed-By: James M Snell Reviewed-By: Joyee Cheung --- doc/api/errors.md | 55 ---- lib/internal/errors.js | 383 +++++++++++++------------- test/parallel/test-internal-errors.js | 13 - 3 files changed, 199 insertions(+), 252 deletions(-) diff --git a/doc/api/errors.md b/doc/api/errors.md index 95700d0f6707bf..0f60cdcc913f6c 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -735,12 +735,6 @@ falsy value. An attempt was made to add more headers after the headers had already been sent. - -### ERR_HTTP_INVALID_CHAR - -An invalid character was found in an HTTP response status message (reason -phrase). - ### ERR_HTTP_INVALID_STATUS_CODE @@ -752,11 +746,6 @@ Status code was outside the regular status code range (100-999). The `Trailer` header was set even though the transfer encoding does not support that. - -### ERR_HTTP2_ALREADY_SHUTDOWN - -Occurs with multiple attempts to shutdown an HTTP/2 session. - ### ERR_HTTP2_ALTSVC_INVALID_ORIGIN @@ -785,22 +774,12 @@ forbidden. For HTTP/2 requests using the `CONNECT` method, the `:scheme` pseudo-header is forbidden. - -### ERR_HTTP2_FRAME_ERROR - -A failure occurred sending an individual frame on the HTTP/2 session. - ### ERR_HTTP2_GOAWAY_SESSION New HTTP/2 Streams may not be opened after the `Http2Session` has received a `GOAWAY` frame from the connected peer. - -### ERR_HTTP2_HEADER_REQUIRED - -A required header was missing in an HTTP/2 message. - ### ERR_HTTP2_HEADER_SINGLE_VALUE @@ -812,22 +791,11 @@ have only a single value. An additional headers was specified after an HTTP/2 response was initiated. - -### ERR_HTTP2_HEADERS_OBJECT - -An HTTP/2 Headers Object was expected. - ### ERR_HTTP2_HEADERS_SENT An attempt was made to send multiple response headers. - -### ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND - -HTTP/2 Informational headers must only be sent *prior* to calling the -`Http2Stream.prototype.respond()` method. - ### ERR_HTTP2_INFO_STATUS_NOT_ALLOWED @@ -1218,14 +1186,6 @@ strict compliance with the API specification (which in some cases may accept `func(undefined)` and `func()` are treated identically, and the [`ERR_INVALID_ARG_TYPE`][] error code may be used instead. - -### ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK - -> Stability: 1 - Experimental - -An [ES6 module][] loader hook specified `format: 'dynamic` but did not provide a -`dynamicInstantiate` hook. - ### ERR_MISSING_MODULE @@ -1254,11 +1214,6 @@ would be possible by calling a callback more than once. While using `N-API`, a constructor passed was not a function. - -### ERR_NAPI_CONS_PROTOTYPE_OBJECT - -While using `N-API`, `Constructor.prototype` was not an object. - ### ERR_NAPI_INVALID_DATAVIEW_ARGS @@ -1300,11 +1255,6 @@ A Node.js API was called in an unsupported manner, such as An input argument value was outside an acceptable range. - -### ERR_PARSE_HISTORY_DATA - -The `REPL` module was unable parse data from the REPL history file. - ### ERR_REQUIRE_ESM @@ -1442,11 +1392,6 @@ recommended to use 2048 bits or larger for stronger security. A TLS/SSL handshake timed out. In this case, the server must also abort the connection. - -### ERR_TLS_RENEGOTIATION_FAILED - -A TLS renegotiation request has failed in a non-specific way. - ### ERR_TLS_REQUIRED_SERVER_NAME diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 50d1cd3fb53b2c..c349afe52ac050 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -472,124 +472,127 @@ module.exports = exports = { // Any error code added here should also be added to the documentation // // Note: Please try to keep these in alphabetical order -E('ERR_ARG_NOT_ITERABLE', '%s must be iterable'); -E('ERR_ASSERTION', '%s'); -E('ERR_ASYNC_CALLBACK', '%s must be a function'); -E('ERR_ASYNC_TYPE', 'Invalid name for async "type": %s'); -E('ERR_BUFFER_OUT_OF_BOUNDS', bufferOutOfBounds); +// +// Note: Node.js specific errors must begin with the prefix ERR_ + +E('ERR_ARG_NOT_ITERABLE', '%s must be iterable', TypeError); +E('ERR_ASSERTION', '%s', AssertionError); +E('ERR_ASYNC_CALLBACK', '%s must be a function', TypeError); +E('ERR_ASYNC_TYPE', 'Invalid name for async "type": %s', TypeError); +E('ERR_BUFFER_OUT_OF_BOUNDS', bufferOutOfBounds, RangeError); E('ERR_BUFFER_TOO_LARGE', - `Cannot create a Buffer larger than 0x${kMaxLength.toString(16)} bytes`); -E('ERR_CHILD_CLOSED_BEFORE_REPLY', 'Child closed before reply received'); + `Cannot create a Buffer larger than 0x${kMaxLength.toString(16)} bytes`, + RangeError); +E('ERR_CHILD_CLOSED_BEFORE_REPLY', + 'Child closed before reply received', Error); E('ERR_CONSOLE_WRITABLE_STREAM', - 'Console expects a writable stream instance for %s'); -E('ERR_CPU_USAGE', 'Unable to obtain cpu usage %s'); + 'Console expects a writable stream instance for %s', TypeError); +E('ERR_CPU_USAGE', 'Unable to obtain cpu usage %s', Error); E('ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED', - 'Custom engines not supported by this OpenSSL'); -E('ERR_CRYPTO_ECDH_INVALID_FORMAT', 'Invalid ECDH format: %s'); -E('ERR_CRYPTO_ENGINE_UNKNOWN', 'Engine "%s" was not found'); + 'Custom engines not supported by this OpenSSL', Error); +E('ERR_CRYPTO_ECDH_INVALID_FORMAT', 'Invalid ECDH format: %s', TypeError); +E('ERR_CRYPTO_ENGINE_UNKNOWN', 'Engine "%s" was not found', Error); E('ERR_CRYPTO_FIPS_FORCED', - 'Cannot set FIPS mode, it was forced with --force-fips at startup.'); -E('ERR_CRYPTO_FIPS_UNAVAILABLE', 'Cannot set FIPS mode in a non-FIPS build.'); -E('ERR_CRYPTO_HASH_DIGEST_NO_UTF16', 'hash.digest() does not support UTF-16'); -E('ERR_CRYPTO_HASH_FINALIZED', 'Digest already called'); -E('ERR_CRYPTO_HASH_UPDATE_FAILED', 'Hash update failed'); -E('ERR_CRYPTO_INVALID_DIGEST', 'Invalid digest: %s'); -E('ERR_CRYPTO_SIGN_KEY_REQUIRED', 'No key provided to sign'); + 'Cannot set FIPS mode, it was forced with --force-fips at startup.', Error); +E('ERR_CRYPTO_FIPS_UNAVAILABLE', 'Cannot set FIPS mode in a non-FIPS build.', + Error); +E('ERR_CRYPTO_HASH_DIGEST_NO_UTF16', 'hash.digest() does not support UTF-16', + Error); +E('ERR_CRYPTO_HASH_FINALIZED', 'Digest already called', Error); +E('ERR_CRYPTO_HASH_UPDATE_FAILED', 'Hash update failed', Error); +E('ERR_CRYPTO_INVALID_DIGEST', 'Invalid digest: %s', TypeError); +// Switch to TypeError. The current implementation does not seem right. +E('ERR_CRYPTO_SIGN_KEY_REQUIRED', 'No key provided to sign', Error); E('ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH', - 'Input buffers must have the same length'); -E('ERR_DNS_SET_SERVERS_FAILED', 'c-ares failed to set servers: "%s" [%s]'); + 'Input buffers must have the same length', RangeError); +E('ERR_DNS_SET_SERVERS_FAILED', 'c-ares failed to set servers: "%s" [%s]', + Error); E('ERR_DOMAIN_CALLBACK_NOT_AVAILABLE', 'A callback was registered through ' + - 'process.setUncaughtExceptionCaptureCallback(), which is mutually ' + - 'exclusive with using the `domain` module'); + 'process.setUncaughtExceptionCaptureCallback(), which is mutually ' + + 'exclusive with using the `domain` module', + Error); E('ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE', 'The `domain` module is in use, which is mutually exclusive with calling ' + - 'process.setUncaughtExceptionCaptureCallback()'); + 'process.setUncaughtExceptionCaptureCallback()', + Error); E('ERR_ENCODING_INVALID_ENCODED_DATA', - 'The encoded data was not valid for encoding %s'); -E('ERR_ENCODING_NOT_SUPPORTED', 'The "%s" encoding is not supported'); -E('ERR_FALSY_VALUE_REJECTION', 'Promise was rejected with falsy value'); -E('ERR_HTTP2_ALREADY_SHUTDOWN', - 'Http2Session is already shutdown or destroyed'); + 'The encoded data was not valid for encoding %s', TypeError); +E('ERR_ENCODING_NOT_SUPPORTED', 'The "%s" encoding is not supported', + RangeError); // One entry is currently falsy implemented as "Error" +E('ERR_FALSY_VALUE_REJECTION', 'Promise was rejected with falsy value', Error); E('ERR_HTTP2_ALTSVC_INVALID_ORIGIN', - 'HTTP/2 ALTSVC frames require a valid origin'); + 'HTTP/2 ALTSVC frames require a valid origin', TypeError); E('ERR_HTTP2_ALTSVC_LENGTH', - 'HTTP/2 ALTSVC frames are limited to 16382 bytes'); + 'HTTP/2 ALTSVC frames are limited to 16382 bytes', TypeError); E('ERR_HTTP2_CONNECT_AUTHORITY', - ':authority header is required for CONNECT requests'); + ':authority header is required for CONNECT requests', Error); E('ERR_HTTP2_CONNECT_PATH', - 'The :path header is forbidden for CONNECT requests'); + 'The :path header is forbidden for CONNECT requests', Error); E('ERR_HTTP2_CONNECT_SCHEME', - 'The :scheme header is forbidden for CONNECT requests'); -E('ERR_HTTP2_FRAME_ERROR', - (type, code, id) => { - let msg = `Error sending frame type ${type}`; - if (id !== undefined) - msg += ` for stream ${id}`; - msg += ` with code ${code}`; - return msg; - }); + 'The :scheme header is forbidden for CONNECT requests', Error); E('ERR_HTTP2_GOAWAY_SESSION', - 'New streams cannot be created after receiving a GOAWAY'); + 'New streams cannot be created after receiving a GOAWAY', Error); E('ERR_HTTP2_HEADERS_AFTER_RESPOND', - 'Cannot specify additional headers after response initiated'); -E('ERR_HTTP2_HEADERS_OBJECT', 'Headers must be an object'); -E('ERR_HTTP2_HEADERS_SENT', 'Response has already been initiated.'); -E('ERR_HTTP2_HEADER_REQUIRED', 'The %s header is required'); + 'Cannot specify additional headers after response initiated', Error); +E('ERR_HTTP2_HEADERS_SENT', 'Response has already been initiated.', Error); E('ERR_HTTP2_HEADER_SINGLE_VALUE', - 'Header field "%s" must have only a single value'); -E('ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND', - 'Cannot send informational headers after the HTTP message has been sent'); + 'Header field "%s" must have only a single value', Error); E('ERR_HTTP2_INFO_STATUS_NOT_ALLOWED', - 'Informational status codes cannot be used'); + 'Informational status codes cannot be used', RangeError); E('ERR_HTTP2_INVALID_CONNECTION_HEADERS', - 'HTTP/1 Connection specific headers are forbidden: "%s"'); -E('ERR_HTTP2_INVALID_HEADER_VALUE', 'Invalid value "%s" for header "%s"'); + 'HTTP/1 Connection specific headers are forbidden: "%s"', Error); +E('ERR_HTTP2_INVALID_HEADER_VALUE', + 'Invalid value "%s" for header "%s"', TypeError); E('ERR_HTTP2_INVALID_INFO_STATUS', - 'Invalid informational status code: %s'); + 'Invalid informational status code: %s', RangeError); E('ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH', - 'Packed settings length must be a multiple of six'); + 'Packed settings length must be a multiple of six', RangeError); E('ERR_HTTP2_INVALID_PSEUDOHEADER', - '"%s" is an invalid pseudoheader or is used incorrectly'); -E('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed'); + '"%s" is an invalid pseudoheader or is used incorrectly', Error); +E('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed', Error); E('ERR_HTTP2_INVALID_SETTING_VALUE', - 'Invalid value for setting "%s": %s'); -E('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed'); + 'Invalid value for setting "%s": %s', TypeError, RangeError); +E('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed', Error); E('ERR_HTTP2_MAX_PENDING_SETTINGS_ACK', - 'Maximum number of pending settings acknowledgements (%s)'); + 'Maximum number of pending settings acknowledgements (%s)', Error); E('ERR_HTTP2_NO_SOCKET_MANIPULATION', - 'HTTP/2 sockets should not be directly manipulated (e.g. read and written)'); + 'HTTP/2 sockets should not be directly manipulated (e.g. read and written)', + Error); E('ERR_HTTP2_OUT_OF_STREAMS', - 'No stream ID is available because maximum stream ID has been reached'); + 'No stream ID is available because maximum stream ID has been reached', + Error); E('ERR_HTTP2_PAYLOAD_FORBIDDEN', - 'Responses with %s status must not have a payload'); -E('ERR_HTTP2_PING_CANCEL', 'HTTP2 ping cancelled'); -E('ERR_HTTP2_PING_LENGTH', 'HTTP2 ping payload must be 8 bytes'); -E('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', 'Cannot set HTTP/2 pseudo-headers'); -E('ERR_HTTP2_PUSH_DISABLED', 'HTTP/2 client has disabled push streams'); -E('ERR_HTTP2_SEND_FILE', 'Only regular files can be sent'); -E('ERR_HTTP2_SESSION_ERROR', 'Session closed with error code %s'); + 'Responses with %s status must not have a payload', Error); +E('ERR_HTTP2_PING_CANCEL', 'HTTP2 ping cancelled', Error); +E('ERR_HTTP2_PING_LENGTH', 'HTTP2 ping payload must be 8 bytes', RangeError); +E('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', + 'Cannot set HTTP/2 pseudo-headers', Error); +E('ERR_HTTP2_PUSH_DISABLED', 'HTTP/2 client has disabled push streams', Error); +E('ERR_HTTP2_SEND_FILE', 'Only regular files can be sent', Error); +E('ERR_HTTP2_SESSION_ERROR', 'Session closed with error code %s', Error); E('ERR_HTTP2_SOCKET_BOUND', - 'The socket is already bound to an Http2Session'); + 'The socket is already bound to an Http2Session', Error); E('ERR_HTTP2_STATUS_101', - 'HTTP status code 101 (Switching Protocols) is forbidden in HTTP/2'); -E('ERR_HTTP2_STATUS_INVALID', 'Invalid status code: %s'); -E('ERR_HTTP2_STREAM_CANCEL', 'The pending stream has been canceled'); -E('ERR_HTTP2_STREAM_ERROR', 'Stream closed with error code %s'); -E('ERR_HTTP2_STREAM_SELF_DEPENDENCY', 'A stream cannot depend on itself'); -E('ERR_HTTP2_UNSUPPORTED_PROTOCOL', 'protocol "%s" is unsupported.'); + 'HTTP status code 101 (Switching Protocols) is forbidden in HTTP/2', Error); +E('ERR_HTTP2_STATUS_INVALID', 'Invalid status code: %s', RangeError); +E('ERR_HTTP2_STREAM_CANCEL', 'The pending stream has been canceled', Error); +E('ERR_HTTP2_STREAM_ERROR', 'Stream closed with error code %s', Error); +E('ERR_HTTP2_STREAM_SELF_DEPENDENCY', + 'A stream cannot depend on itself', Error); +E('ERR_HTTP2_UNSUPPORTED_PROTOCOL', 'protocol "%s" is unsupported.', Error); E('ERR_HTTP_HEADERS_SENT', - 'Cannot %s headers after they are sent to the client'); -E('ERR_HTTP_INVALID_CHAR', 'Invalid character in statusMessage.'); -E('ERR_HTTP_INVALID_STATUS_CODE', 'Invalid status code: %s'); + 'Cannot %s headers after they are sent to the client', Error); +E('ERR_HTTP_INVALID_STATUS_CODE', 'Invalid status code: %s', RangeError); E('ERR_HTTP_TRAILER_INVALID', - 'Trailers are invalid with this transfer encoding'); -E('ERR_INDEX_OUT_OF_RANGE', 'Index out of range'); -E('ERR_INSPECTOR_ALREADY_CONNECTED', 'The inspector is already connected'); -E('ERR_INSPECTOR_CLOSED', 'Session was closed'); -E('ERR_INSPECTOR_NOT_AVAILABLE', 'Inspector is not available'); -E('ERR_INSPECTOR_NOT_CONNECTED', 'Session is not connected'); -E('ERR_INVALID_ARG_TYPE', invalidArgType); + 'Trailers are invalid with this transfer encoding', Error); +E('ERR_INDEX_OUT_OF_RANGE', 'Index out of range', RangeError); +E('ERR_INSPECTOR_ALREADY_CONNECTED', + 'The inspector is already connected', Error); +E('ERR_INSPECTOR_CLOSED', 'Session was closed', Error); +E('ERR_INSPECTOR_NOT_AVAILABLE', 'Inspector is not available', Error); +E('ERR_INSPECTOR_NOT_CONNECTED', 'Session is not connected', Error); +E('ERR_INVALID_ARG_TYPE', invalidArgType, TypeError); E('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => { const util = lazyUtil(); let inspected = util.inspect(value); @@ -597,136 +600,148 @@ E('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => { inspected = inspected.slice(0, 128) + '...'; } return `The argument '${name}' ${reason}. Received ${inspected}`; -}), +}, TypeError, RangeError); // Some are currently falsy implemented as "Error" E('ERR_INVALID_ARRAY_LENGTH', (name, len, actual) => { internalAssert(typeof actual === 'number', 'actual must be a number'); return `The array "${name}" (length ${actual}) must be of length ${len}.`; - }); -E('ERR_INVALID_ASYNC_ID', 'Invalid %s value: %s'); -E('ERR_INVALID_BUFFER_SIZE', 'Buffer size must be a multiple of %s'); -E('ERR_INVALID_CALLBACK', 'Callback must be a function'); -E('ERR_INVALID_CHAR', invalidChar); + }, TypeError); +E('ERR_INVALID_ASYNC_ID', 'Invalid %s value: %s', RangeError); +E('ERR_INVALID_BUFFER_SIZE', + 'Buffer size must be a multiple of %s', RangeError); +E('ERR_INVALID_CALLBACK', 'Callback must be a function', TypeError); +E('ERR_INVALID_CHAR', invalidChar, TypeError); //Check falsy "Error" entries. E('ERR_INVALID_CURSOR_POS', - 'Cannot set cursor row without setting its column'); -E('ERR_INVALID_DOMAIN_NAME', 'Unable to determine the domain name'); -E('ERR_INVALID_FD', '"fd" must be a positive integer: %s'); -E('ERR_INVALID_FD_TYPE', 'Unsupported fd type: %s'); + 'Cannot set cursor row without setting its column', Error); +E('ERR_INVALID_DOMAIN_NAME', 'Unable to determine the domain name', Error); +E('ERR_INVALID_FD', + '"fd" must be a positive integer: %s', RangeError); +E('ERR_INVALID_FD_TYPE', 'Unsupported fd type: %s', TypeError); E('ERR_INVALID_FILE_URL_HOST', - 'File URL host must be "localhost" or empty on %s'); -E('ERR_INVALID_FILE_URL_PATH', 'File URL path %s'); -E('ERR_INVALID_HANDLE_TYPE', 'This handle type cannot be sent'); -E('ERR_INVALID_HTTP_TOKEN', '%s must be a valid HTTP token ["%s"]'); -E('ERR_INVALID_IP_ADDRESS', 'Invalid IP address: %s'); + 'File URL host must be "localhost" or empty on %s', TypeError); +E('ERR_INVALID_FILE_URL_PATH', 'File URL path %s', TypeError); +E('ERR_INVALID_HANDLE_TYPE', 'This handle type cannot be sent', TypeError); +E('ERR_INVALID_HTTP_TOKEN', '%s must be a valid HTTP token ["%s"]', TypeError); +E('ERR_INVALID_IP_ADDRESS', 'Invalid IP address: %s', TypeError, Error); E('ERR_INVALID_OPT_VALUE', (name, value) => - `The value "${String(value)}" is invalid for option "${name}"`); + `The value "${String(value)}" is invalid for option "${name}"`, + TypeError, + RangeError); E('ERR_INVALID_OPT_VALUE_ENCODING', - 'The value "%s" is invalid for option "encoding"'); -E('ERR_INVALID_PERFORMANCE_MARK', 'The "%s" performance mark has not been set'); -E('ERR_INVALID_PROTOCOL', 'Protocol "%s" not supported. Expected "%s"'); + 'The value "%s" is invalid for option "encoding"', TypeError); +E('ERR_INVALID_PERFORMANCE_MARK', + 'The "%s" performance mark has not been set', Error); +E('ERR_INVALID_PROTOCOL', 'Protocol "%s" not supported. Expected "%s"', Error); E('ERR_INVALID_REPL_EVAL_CONFIG', - 'Cannot specify both "breakEvalOnSigint" and "eval" for REPL'); + 'Cannot specify both "breakEvalOnSigint" and "eval" for REPL', Error); E('ERR_INVALID_SYNC_FORK_INPUT', - 'Asynchronous forks do not support Buffer, Uint8Array or string input: %s'); -E('ERR_INVALID_THIS', 'Value of "this" must be of type %s'); -E('ERR_INVALID_TUPLE', '%s must be an iterable %s tuple'); -E('ERR_INVALID_URI', 'URI malformed'); -E('ERR_INVALID_URL', 'Invalid URL: %s'); + 'Asynchronous forks do not support Buffer, Uint8Array or string input: %s', + TypeError); +E('ERR_INVALID_THIS', 'Value of "this" must be of type %s', TypeError); +E('ERR_INVALID_TUPLE', '%s must be an iterable %s tuple', TypeError); +E('ERR_INVALID_URI', 'URI malformed', URIError); +E('ERR_INVALID_URL', 'Invalid URL: %s', TypeError); E('ERR_INVALID_URL_SCHEME', - (expected) => `The URL must be ${oneOf(expected, 'scheme')}`); -E('ERR_IPC_CHANNEL_CLOSED', 'Channel closed'); -E('ERR_IPC_DISCONNECTED', 'IPC channel is already disconnected'); -E('ERR_IPC_ONE_PIPE', 'Child process can have only one IPC pipe'); -E('ERR_IPC_SYNC_FORK', 'IPC cannot be used with synchronous forks'); -E('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented'); -E('ERR_MISSING_ARGS', missingArgs); -E('ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK', - 'The ES Module loader may not return a format of \'dynamic\' when no ' + - 'dynamicInstantiate function was provided'); -E('ERR_MISSING_MODULE', 'Cannot find module %s'); -E('ERR_MODULE_RESOLUTION_LEGACY', '%s not found by import in %s.' + - ' Legacy behavior in require() would have found it at %s'); -E('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -E('ERR_NAPI_CONS_FUNCTION', 'Constructor must be a function'); -E('ERR_NAPI_CONS_PROTOTYPE_OBJECT', 'Constructor.prototype must be an object'); + (expected) => `The URL must be ${oneOf(expected, 'scheme')}`, TypeError); +E('ERR_IPC_CHANNEL_CLOSED', 'Channel closed', Error); +E('ERR_IPC_DISCONNECTED', 'IPC channel is already disconnected', Error); +E('ERR_IPC_ONE_PIPE', 'Child process can have only one IPC pipe', Error); +E('ERR_IPC_SYNC_FORK', 'IPC cannot be used with synchronous forks', Error); +E('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error); +E('ERR_MISSING_ARGS', missingArgs, TypeError); +E('ERR_MISSING_MODULE', 'Cannot find module %s', Error); +E('ERR_MODULE_RESOLUTION_LEGACY', + '%s not found by import in %s.' + + ' Legacy behavior in require() would have found it at %s', + Error); +E('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error); +E('ERR_NAPI_CONS_FUNCTION', 'Constructor must be a function', TypeError); E('ERR_NAPI_INVALID_DATAVIEW_ARGS', 'byte_offset + byte_length should be less than or eqaul to the size in ' + - 'bytes of the array passed in'); -E('ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT', 'start offset of %s should be a ' + - 'multiple of %s'); -E('ERR_NAPI_INVALID_TYPEDARRAY_LENGTH', 'Invalid typed array length'); -E('ERR_NO_CRYPTO', 'Node.js is not compiled with OpenSSL crypto support'); -E('ERR_NO_ICU', '%s is not supported on Node.js compiled without ICU'); -E('ERR_NO_LONGER_SUPPORTED', '%s is no longer supported'); -E('ERR_OUT_OF_RANGE', 'The "%s" argument is out of range'); -E('ERR_PARSE_HISTORY_DATA', 'Could not parse history data in %s'); -E('ERR_REQUIRE_ESM', 'Must use import to load ES Module: %s'); + 'bytes of the array passed in', + RangeError); +E('ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT', + 'start offset of %s should be a multiple of %s', RangeError); +E('ERR_NAPI_INVALID_TYPEDARRAY_LENGTH', + 'Invalid typed array length', RangeError); +E('ERR_NO_CRYPTO', + 'Node.js is not compiled with OpenSSL crypto support', Error); +E('ERR_NO_ICU', + '%s is not supported on Node.js compiled without ICU', TypeError); +E('ERR_NO_LONGER_SUPPORTED', '%s is no longer supported', Error); +E('ERR_OUT_OF_RANGE', 'The "%s" argument is out of range', RangeError); +E('ERR_REQUIRE_ESM', 'Must use import to load ES Module: %s', Error); E('ERR_SERVER_ALREADY_LISTEN', - 'Listen method has been called more than once without closing.'); -E('ERR_SOCKET_ALREADY_BOUND', 'Socket is already bound'); -E('ERR_SOCKET_BAD_BUFFER_SIZE', 'Buffer size must be a positive integer'); -E('ERR_SOCKET_BAD_PORT', 'Port should be > 0 and < 65536. Received %s.'); + 'Listen method has been called more than once without closing.', Error); +E('ERR_SOCKET_ALREADY_BOUND', 'Socket is already bound', Error); +E('ERR_SOCKET_BAD_BUFFER_SIZE', + 'Buffer size must be a positive integer', TypeError); +E('ERR_SOCKET_BAD_PORT', + 'Port should be > 0 and < 65536. Received %s.', RangeError); E('ERR_SOCKET_BAD_TYPE', - 'Bad socket type specified. Valid types are: udp4, udp6'); -E('ERR_SOCKET_BUFFER_SIZE', 'Could not get or set buffer size: %s'); -E('ERR_SOCKET_CANNOT_SEND', 'Unable to send data'); -E('ERR_SOCKET_CLOSED', 'Socket is closed'); -E('ERR_SOCKET_DGRAM_NOT_RUNNING', 'Not running'); -E('ERR_STDERR_CLOSE', 'process.stderr cannot be closed'); -E('ERR_STDOUT_CLOSE', 'process.stdout cannot be closed'); -E('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -E('ERR_STREAM_NULL_VALUES', 'May not write null values to stream'); -E('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -E('ERR_STREAM_READ_NOT_IMPLEMENTED', '_read() is not implemented'); -E('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); -E('ERR_STREAM_WRAP', 'Stream has StringDecoder set or is in objectMode'); -E('ERR_STREAM_WRITE_AFTER_END', 'write after end'); + 'Bad socket type specified. Valid types are: udp4, udp6', TypeError); +E('ERR_SOCKET_BUFFER_SIZE', 'Could not get or set buffer size: %s', Error); +E('ERR_SOCKET_CANNOT_SEND', 'Unable to send data', Error); +E('ERR_SOCKET_CLOSED', 'Socket is closed', Error); +E('ERR_SOCKET_DGRAM_NOT_RUNNING', 'Not running', Error); +E('ERR_STDERR_CLOSE', 'process.stderr cannot be closed', Error); +E('ERR_STDOUT_CLOSE', 'process.stdout cannot be closed', Error); +E('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error); +E('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +E('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error); +E('ERR_STREAM_READ_NOT_IMPLEMENTED', '_read() is not implemented', Error); +E('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', + 'stream.unshift() after end event', Error); +E('ERR_STREAM_WRAP', 'Stream has StringDecoder set or is in objectMode', Error); +E('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error); E('ERR_TLS_CERT_ALTNAME_INVALID', - 'Hostname/IP does not match certificate\'s altnames: %s'); -E('ERR_TLS_DH_PARAM_SIZE', 'DH parameter size %s is less than 2048'); -E('ERR_TLS_HANDSHAKE_TIMEOUT', 'TLS handshake timeout'); -E('ERR_TLS_RENEGOTIATION_FAILED', 'Failed to renegotiate'); + 'Hostname/IP does not match certificate\'s altnames: %s', Error); +E('ERR_TLS_DH_PARAM_SIZE', 'DH parameter size %s is less than 2048', Error); +E('ERR_TLS_HANDSHAKE_TIMEOUT', 'TLS handshake timeout', Error); E('ERR_TLS_REQUIRED_SERVER_NAME', - '"servername" is required parameter for Server.addContext'); -E('ERR_TLS_SESSION_ATTACK', 'TLS session renegotiation attack detected'); + '"servername" is required parameter for Server.addContext', Error); +E('ERR_TLS_SESSION_ATTACK', 'TLS session renegotiation attack detected', Error); E('ERR_TRANSFORM_ALREADY_TRANSFORMING', - 'Calling transform done when still transforming'); + 'Calling transform done when still transforming', Error); E('ERR_TRANSFORM_WITH_LENGTH_0', - 'Calling transform done when writableState.length != 0'); + 'Calling transform done when writableState.length != 0', Error); E('ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET', '`process.setupUncaughtExceptionCapture()` was called while a capture ' + - 'callback was already active'); -E('ERR_UNESCAPED_CHARACTERS', '%s contains unescaped characters'); + 'callback was already active', + Error); +E('ERR_UNESCAPED_CHARACTERS', '%s contains unescaped characters', TypeError); E('ERR_UNHANDLED_ERROR', (err) => { const msg = 'Unhandled error.'; if (err === undefined) return msg; return `${msg} (${err})`; - }); -E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s'); -E('ERR_UNKNOWN_FILE_EXTENSION', 'Unknown file extension: %s'); -E('ERR_UNKNOWN_MODULE_FORMAT', 'Unknown module format: %s'); -E('ERR_UNKNOWN_SIGNAL', 'Unknown signal: %s'); -E('ERR_UNKNOWN_STDIN_TYPE', 'Unknown stdin file type'); -E('ERR_UNKNOWN_STREAM_TYPE', 'Unknown stream file type'); -E('ERR_V8BREAKITERATOR', 'Full ICU data not installed. ' + - 'See https://github.com/nodejs/node/wiki/Intl'); + }, Error); +E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError); +E('ERR_UNKNOWN_FILE_EXTENSION', 'Unknown file extension: %s', Error); +E('ERR_UNKNOWN_MODULE_FORMAT', 'Unknown module format: %s', RangeError); +E('ERR_UNKNOWN_SIGNAL', 'Unknown signal: %s', TypeError); +E('ERR_UNKNOWN_STDIN_TYPE', 'Unknown stdin file type', Error); +E('ERR_UNKNOWN_STREAM_TYPE', 'Unknown stream file type', Error); +E('ERR_V8BREAKITERATOR', + 'Full ICU data not installed. See https://github.com/nodejs/node/wiki/Intl', + Error); E('ERR_VALID_PERFORMANCE_ENTRY_TYPE', - 'At least one valid performance entry type is required'); + 'At least one valid performance entry type is required', Error); E('ERR_VALUE_OUT_OF_RANGE', (start, end, value) => { return `The value of "${start}" must be ${end}. Received "${value}"`; -}); -E('ERR_VM_MODULE_ALREADY_LINKED', 'Module has already been linked'); +}, RangeError); +E('ERR_VM_MODULE_ALREADY_LINKED', 'Module has already been linked', Error); E('ERR_VM_MODULE_DIFFERENT_CONTEXT', - 'Linked modules must use the same context'); + 'Linked modules must use the same context', Error); E('ERR_VM_MODULE_LINKING_ERRORED', - 'Linking has already failed for the provided module'); + 'Linking has already failed for the provided module', Error); E('ERR_VM_MODULE_NOT_LINKED', - 'Module must be linked before it can be instantiated'); -E('ERR_VM_MODULE_NOT_MODULE', 'Provided module is not an instance of Module'); -E('ERR_VM_MODULE_STATUS', 'Module status %s'); -E('ERR_ZLIB_BINDING_CLOSED', 'zlib binding closed'); -E('ERR_ZLIB_INITIALIZATION_FAILED', 'Initialization failed'); + 'Module must be linked before it can be instantiated', Error); +E('ERR_VM_MODULE_NOT_MODULE', + 'Provided module is not an instance of Module', Error); +E('ERR_VM_MODULE_STATUS', 'Module status %s', Error); +E('ERR_ZLIB_BINDING_CLOSED', 'zlib binding closed', Error); +E('ERR_ZLIB_INITIALIZATION_FAILED', 'Initialization failed', Error); function invalidArgType(name, expected, actual) { internalAssert(name, 'name is required'); diff --git a/test/parallel/test-internal-errors.js b/test/parallel/test-internal-errors.js index 680fedc585d161..f5876b7f568dd9 100644 --- a/test/parallel/test-internal-errors.js +++ b/test/parallel/test-internal-errors.js @@ -292,19 +292,6 @@ assert.strictEqual( errors.message('ERR_ENCODING_NOT_SUPPORTED', ['enc']), 'The "enc" encoding is not supported'); -// Test ERR_HTTP2_HEADER_REQUIRED -assert.strictEqual( - errors.message('ERR_HTTP2_HEADER_REQUIRED', ['test']), - 'The test header is required'); - -// Test ERR_HTTP2_FRAME_ERROR -assert.strictEqual( - errors.message('ERR_HTTP2_FRAME_ERROR', ['foo', 'bar', 'baz']), - 'Error sending frame type foo for stream baz with code bar'); -assert.strictEqual( - errors.message('ERR_HTTP2_FRAME_ERROR', ['foo', 'bar']), - 'Error sending frame type foo with code bar'); - // Test error messages for async_hooks assert.strictEqual( errors.message('ERR_ASYNC_CALLBACK', ['init']), From d11528426a5f2d5dba91d253a87e941733bf46ea Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 19 Feb 2018 01:51:58 +0100 Subject: [PATCH 13/16] console: port errors to new system This ports the errors to the new error system. PR-URL: https://github.com/nodejs/node/pull/18857 Reviewed-By: Anna Henningsen Reviewed-By: Gus Caplan Reviewed-By: James M Snell Reviewed-By: Joyee Cheung --- lib/console.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/console.js b/lib/console.js index ac75664e850e56..ad6276297f26f7 100644 --- a/lib/console.js +++ b/lib/console.js @@ -21,7 +21,7 @@ 'use strict'; -const errors = require('internal/errors'); +const { ERR_CONSOLE_WRITABLE_STREAM } = require('internal/errors').codes; const util = require('util'); const kCounts = Symbol('counts'); @@ -35,12 +35,12 @@ function Console(stdout, stderr, ignoreErrors = true) { return new Console(stdout, stderr, ignoreErrors); } if (!stdout || typeof stdout.write !== 'function') { - throw new errors.TypeError('ERR_CONSOLE_WRITABLE_STREAM', 'stdout'); + throw new ERR_CONSOLE_WRITABLE_STREAM('stdout'); } if (!stderr) { stderr = stdout; } else if (typeof stderr.write !== 'function') { - throw new errors.TypeError('ERR_CONSOLE_WRITABLE_STREAM', 'stderr'); + throw new ERR_CONSOLE_WRITABLE_STREAM('stderr'); } var prop = { From cabe5474dacaabc5b421e5bbb4b95a58a482b91f Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 19 Feb 2018 02:20:46 +0100 Subject: [PATCH 14/16] errors: add comments about falsy error types Some error types are not properly set. This adds comments which ones are probably falty and to what they should be set instead. PR-URL: https://github.com/nodejs/node/pull/18857 Reviewed-By: Anna Henningsen Reviewed-By: Gus Caplan Reviewed-By: James M Snell Reviewed-By: Joyee Cheung --- lib/internal/errors.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/lib/internal/errors.js b/lib/internal/errors.js index c349afe52ac050..d08b1bfad156c0 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -536,10 +536,14 @@ E('ERR_HTTP2_GOAWAY_SESSION', E('ERR_HTTP2_HEADERS_AFTER_RESPOND', 'Cannot specify additional headers after response initiated', Error); E('ERR_HTTP2_HEADERS_SENT', 'Response has already been initiated.', Error); + +// This should probably be a `TypeError`. E('ERR_HTTP2_HEADER_SINGLE_VALUE', 'Header field "%s" must have only a single value', Error); E('ERR_HTTP2_INFO_STATUS_NOT_ALLOWED', 'Informational status codes cannot be used', RangeError); + +// This should probably be a `TypeError`. E('ERR_HTTP2_INVALID_CONNECTION_HEADERS', 'HTTP/1 Connection specific headers are forbidden: "%s"', Error); E('ERR_HTTP2_INVALID_HEADER_VALUE', @@ -548,6 +552,8 @@ E('ERR_HTTP2_INVALID_INFO_STATUS', 'Invalid informational status code: %s', RangeError); E('ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH', 'Packed settings length must be a multiple of six', RangeError); + +// This should probably be a `TypeError`. E('ERR_HTTP2_INVALID_PSEUDOHEADER', '"%s" is an invalid pseudoheader or is used incorrectly', Error); E('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed', Error); @@ -566,6 +572,8 @@ E('ERR_HTTP2_PAYLOAD_FORBIDDEN', 'Responses with %s status must not have a payload', Error); E('ERR_HTTP2_PING_CANCEL', 'HTTP2 ping cancelled', Error); E('ERR_HTTP2_PING_LENGTH', 'HTTP2 ping payload must be 8 bytes', RangeError); + +// This should probably be a `TypeError`. E('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', 'Cannot set HTTP/2 pseudo-headers', Error); E('ERR_HTTP2_PUSH_DISABLED', 'HTTP/2 client has disabled push streams', Error); @@ -611,8 +619,12 @@ E('ERR_INVALID_BUFFER_SIZE', 'Buffer size must be a multiple of %s', RangeError); E('ERR_INVALID_CALLBACK', 'Callback must be a function', TypeError); E('ERR_INVALID_CHAR', invalidChar, TypeError); //Check falsy "Error" entries. + +// This should probably be a `TypeError`. E('ERR_INVALID_CURSOR_POS', 'Cannot set cursor row without setting its column', Error); + +// This should probably be a `TypeError`. E('ERR_INVALID_DOMAIN_NAME', 'Unable to determine the domain name', Error); E('ERR_INVALID_FD', '"fd" must be a positive integer: %s', RangeError); @@ -622,6 +634,7 @@ E('ERR_INVALID_FILE_URL_HOST', E('ERR_INVALID_FILE_URL_PATH', 'File URL path %s', TypeError); E('ERR_INVALID_HANDLE_TYPE', 'This handle type cannot be sent', TypeError); E('ERR_INVALID_HTTP_TOKEN', '%s must be a valid HTTP token ["%s"]', TypeError); +// The `Error` should probably be a `TypeError`. E('ERR_INVALID_IP_ADDRESS', 'Invalid IP address: %s', TypeError, Error); E('ERR_INVALID_OPT_VALUE', (name, value) => `The value "${String(value)}" is invalid for option "${name}"`, @@ -631,7 +644,11 @@ E('ERR_INVALID_OPT_VALUE_ENCODING', 'The value "%s" is invalid for option "encoding"', TypeError); E('ERR_INVALID_PERFORMANCE_MARK', 'The "%s" performance mark has not been set', Error); + +// This should probably be a `TypeError`. E('ERR_INVALID_PROTOCOL', 'Protocol "%s" not supported. Expected "%s"', Error); + +// This should probably be a `TypeError`. E('ERR_INVALID_REPL_EVAL_CONFIG', 'Cannot specify both "breakEvalOnSigint" and "eval" for REPL', Error); E('ERR_INVALID_SYNC_FORK_INPUT', @@ -703,6 +720,8 @@ E('ERR_TLS_REQUIRED_SERVER_NAME', E('ERR_TLS_SESSION_ATTACK', 'TLS session renegotiation attack detected', Error); E('ERR_TRANSFORM_ALREADY_TRANSFORMING', 'Calling transform done when still transforming', Error); + +// This should probably be a `RangeError`. E('ERR_TRANSFORM_WITH_LENGTH_0', 'Calling transform done when writableState.length != 0', Error); E('ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET', @@ -717,14 +736,20 @@ E('ERR_UNHANDLED_ERROR', return `${msg} (${err})`; }, Error); E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError); + +// This should probably be a `TypeError`. E('ERR_UNKNOWN_FILE_EXTENSION', 'Unknown file extension: %s', Error); E('ERR_UNKNOWN_MODULE_FORMAT', 'Unknown module format: %s', RangeError); E('ERR_UNKNOWN_SIGNAL', 'Unknown signal: %s', TypeError); E('ERR_UNKNOWN_STDIN_TYPE', 'Unknown stdin file type', Error); + +// This should probably be a `TypeError`. E('ERR_UNKNOWN_STREAM_TYPE', 'Unknown stream file type', Error); E('ERR_V8BREAKITERATOR', 'Full ICU data not installed. See https://github.com/nodejs/node/wiki/Intl', Error); + +// This should probably be a `TypeError`. E('ERR_VALID_PERFORMANCE_ENTRY_TYPE', 'At least one valid performance entry type is required', Error); E('ERR_VALUE_OUT_OF_RANGE', (start, end, value) => { From 976823c58d552436aafef5bcc705fcdba5d0ef2b Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Sat, 30 Dec 2017 03:20:51 +0100 Subject: [PATCH 15/16] repl: upper case comments first char MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/17919 Reviewed-By: James M Snell Reviewed-By: Tobias Nießen Reviewed-By: Luigi Pinca Reviewed-By: Weijia Wang Reviewed-By: Khaidi Chu Reviewed-By: Jon Moss Reviewed-By: Lance Ball --- lib/repl.js | 52 +++++++++++++++++++++++----------------------------- 1 file changed, 23 insertions(+), 29 deletions(-) diff --git a/lib/repl.js b/lib/repl.js index 5294bb96177e5e..f8951ba243a369 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -79,7 +79,7 @@ const kBufferedCommandSymbol = Symbol('bufferedCommand'); const kContextId = Symbol('contextId'); try { - // hack for require.resolve("./relative") to work properly. + // Hack for require.resolve("./relative") to work properly. module.filename = path.resolve('repl'); } catch (e) { // path.resolve('repl') fails when the current working directory has been @@ -89,7 +89,7 @@ try { module.filename = path.resolve(dirname, 'repl'); } -// hack for repl require to work properly with node_modules folders +// Hack for repl require to work properly with node_modules folders module.paths = Module._nodeModulePaths(module.filename); // If obj.hasOwnProperty has been overridden, then calling @@ -99,14 +99,12 @@ function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } - // Can overridden with custom print functions, such as `probe` or `eyes.js`. // This is the default "writer" value if none is passed in the REPL options. exports.writer = util.inspect; exports._builtinLibs = internalModule.builtinLibs; - function REPLServer(prompt, stream, eval_, @@ -149,7 +147,6 @@ function REPLServer(prompt, var self = this; self._domain = dom || domain.create(); - self.useGlobal = !!useGlobal; self.ignoreUndefined = !!ignoreUndefined; self.replMode = replMode || exports.REPL_MODE_SLOPPY; @@ -162,7 +159,7 @@ function REPLServer(prompt, // Context id for use with the inspector protocol. self[kContextId] = undefined; - // just for backwards compat, see github.com/joyent/node/pull/7127 + // Just for backwards compat, see github.com/joyent/node/pull/7127 self.rli = this; const savedRegExMatches = ['', '', '', '', '', '', '', '', '', '']; @@ -187,8 +184,7 @@ function REPLServer(prompt, wrappedCmd = true; } - // first, create the Script object to check the syntax - + // First, create the Script object to check the syntax if (code === '\n') return cb(null); @@ -207,13 +203,13 @@ function REPLServer(prompt, } catch (e) { debug('parse error %j', code, e); if (wrappedCmd) { + // Unwrap and try again wrappedCmd = false; - // unwrap and try again code = input; wrappedErr = e; continue; } - // preserve original error for wrapped command + // Preserve original error for wrapped command const error = wrappedErr || e; if (isRecoverableError(error, code)) err = new Recoverable(error); @@ -321,7 +317,7 @@ function REPLServer(prompt, if (!input && !output) { // legacy API, passing a 'stream'/'socket' option if (!stream) { - // use stdin and stdout as the default streams if none were given + // Use stdin and stdout as the default streams if none were given stream = process; } if (stream.stdin && stream.stdout) { @@ -371,7 +367,7 @@ function REPLServer(prompt, this.commands = Object.create(null); defineDefaultCommands(this); - // figure out which "writer" function to use + // Figure out which "writer" function to use self.writer = options.writer || exports.writer; if (options.useColors === undefined) { @@ -387,14 +383,14 @@ function REPLServer(prompt, } function filterInternalStackFrames(error, structuredStack) { - // search from the bottom of the call stack to + // Search from the bottom of the call stack to // find the first frame with a null function name if (typeof structuredStack !== 'object') return structuredStack; const idx = structuredStack.reverse().findIndex( (frame) => frame.getFunctionName() === null); - // if found, get rid of it and everything below it + // If found, get rid of it and everything below it structuredStack = structuredStack.splice(idx + 1); return structuredStack; } @@ -571,7 +567,7 @@ function REPLServer(prompt, return; } - // editor mode + // Editor mode if (key.ctrl && !key.shift) { switch (key.name) { case 'd': // End editor mode @@ -591,7 +587,7 @@ function REPLServer(prompt, case 'down': // Override next history item break; case 'tab': - // prevent double tab behavior + // Prevent double tab behavior self._previousKey = null; ttyWrite(d, key); break; @@ -861,10 +857,8 @@ function complete(line, callback) { } var completions; - - // list of completion lists, one for each inheritance "level" + // List of completion lists, one for each inheritance "level" var completionGroups = []; - var completeOn, i, group, c; // REPL commands (e.g. ".break"). @@ -1042,7 +1036,7 @@ function complete(line, callback) { } } } catch (e) { - //console.log("completion error walking prototype chain:" + e); + // console.log("completion error walking prototype chain:" + e); } } @@ -1085,7 +1079,7 @@ function complete(line, callback) { } if (completionGroups.length) { - var uniq = {}; // unique completions across all groups + var uniq = {}; // Unique completions across all groups completions = []; // Completion group 0 is the "closest" // (least far up the inheritance chain) @@ -1100,7 +1094,7 @@ function complete(line, callback) { uniq[c] = true; } } - completions.push(''); // separator btwn groups + completions.push(''); // Separator btwn groups } while (completions.length && completions[completions.length - 1] === '') { completions.pop(); @@ -1167,7 +1161,7 @@ function _memory(cmd) { self.lines = self.lines || []; self.lines.level = self.lines.level || []; - // save the line so I can do magic later + // Save the line so I can do magic later if (cmd) { // TODO should I tab the level? const len = self.lines.level.length ? self.lines.level.length - 1 : 0; @@ -1181,7 +1175,7 @@ function _memory(cmd) { // Because I can not tell the difference between a } that // closes an object literal and a } that closes a function if (cmd) { - // going down is { and ( e.g. function() { + // Going down is { and ( e.g. function() { // going up is } and ) var dw = cmd.match(/{|\(/g); var up = cmd.match(/}|\)/g); @@ -1192,8 +1186,8 @@ function _memory(cmd) { if (depth) { (function workIt() { if (depth > 0) { - // going... down. - // push the line#, depth count, and if the line is a function. + // Going... down. + // Push the line#, depth count, and if the line is a function. // Since JS only has functional scope I only need to remove // "function() {" lines, clearly this will not work for // "function() @@ -1205,16 +1199,16 @@ function _memory(cmd) { isFunction: /\bfunction\b/.test(cmd) }); } else if (depth < 0) { - // going... up. + // Going... up. var curr = self.lines.level.pop(); if (curr) { var tmp = curr.depth + depth; if (tmp < 0) { - //more to go, recurse + // More to go, recurse depth += curr.depth; workIt(); } else if (tmp > 0) { - //remove and push back + // Remove and push back curr.depth += depth; self.lines.level.push(curr); } From 6086e718035d7806c70cb769f5a2c6ab0483641d Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Sat, 30 Dec 2017 03:22:01 +0100 Subject: [PATCH 16/16] repl: refactor code for readability MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/17919 Reviewed-By: James M Snell Reviewed-By: Tobias Nießen Reviewed-By: Luigi Pinca Reviewed-By: Weijia Wang Reviewed-By: Khaidi Chu Reviewed-By: Jon Moss Reviewed-By: Lance Ball --- lib/repl.js | 83 +++++++++++++++++------------------------------------ 1 file changed, 26 insertions(+), 57 deletions(-) diff --git a/lib/repl.js b/lib/repl.js index f8951ba243a369..5779e849f06017 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -320,15 +320,10 @@ function REPLServer(prompt, // Use stdin and stdout as the default streams if none were given stream = process; } - if (stream.stdin && stream.stdout) { - // We're given custom object with 2 streams, or the `process` object - input = stream.stdin; - output = stream.stdout; - } else { - // We're given a duplex readable/writable Stream, like a `net.Socket` - input = stream; - output = stream; - } + // We're given a duplex readable/writable Stream, like a `net.Socket` + // or a custom object with 2 streams, or the `process` object + input = stream.stdin || stream; + output = stream.stdout || stream; } self.inputStream = input; @@ -663,7 +658,7 @@ REPLServer.prototype.createContext = function() { Object.defineProperty(context, 'console', { configurable: true, enumerable: true, - get: () => _console + value: _console }); var names = Object.getOwnPropertyNames(global); @@ -1035,19 +1030,16 @@ function complete(line, callback) { break; } } - } catch (e) { - // console.log("completion error walking prototype chain:" + e); - } + } catch (e) {} } if (memberGroups.length) { for (i = 0; i < memberGroups.length; i++) { - completionGroups.push(memberGroups[i].map(function(member) { - return expr + '.' + member; - })); + completionGroups.push( + memberGroups[i].map((member) => `${expr}.${member}`)); } if (filter) { - filter = expr + '.' + filter; + filter = `${expr}.${filter}`; } } @@ -1068,9 +1060,8 @@ function complete(line, callback) { if (completionGroups.length && filter) { var newCompletionGroups = []; for (i = 0; i < completionGroups.length; i++) { - group = completionGroups[i].filter(function(elem) { - return elem.indexOf(filter) === 0; - }); + group = completionGroups[i] + .filter((elem) => elem.indexOf(filter) === 0); if (group.length) { newCompletionGroups.push(group); } @@ -1400,55 +1391,33 @@ function isCodeRecoverable(code) { if (previous === '\\' && (stringLiteral || isRegExpLiteral)) { current = null; - continue; - } - - if (stringLiteral) { + } else if (stringLiteral) { if (stringLiteral === current) { stringLiteral = null; } - continue; - } else { - if (isRegExpLiteral && current === '/') { - isRegExpLiteral = false; - continue; - } - - if (isBlockComment && previous === '*' && current === '/') { - isBlockComment = false; - continue; - } - - if (isSingleComment && current === '\n') { - isSingleComment = false; - continue; - } - - if (isBlockComment || isRegExpLiteral || isSingleComment) continue; - + } else if (isRegExpLiteral && current === '/') { + isRegExpLiteral = false; + } else if (isBlockComment && previous === '*' && current === '/') { + isBlockComment = false; + } else if (isSingleComment && current === '\n') { + isSingleComment = false; + } else if (!isBlockComment && !isRegExpLiteral && !isSingleComment) { if (current === '/' && previous === '/') { isSingleComment = true; - continue; - } - - if (previous === '/') { + } else if (previous === '/') { if (current === '*') { isBlockComment = true; - } else if ( // Distinguish between a division operator and the start of a regex // by examining the non-whitespace character that precedes the / - [null, '(', '[', '{', '}', ';'].includes(prevTokenChar) - ) { + } else if ([null, '(', '[', '{', '}', ';'].includes(prevTokenChar)) { isRegExpLiteral = true; } - continue; + } else { + if (current.trim()) prevTokenChar = current; + if (current === '\'' || current === '"') { + stringLiteral = current; + } } - - if (current.trim()) prevTokenChar = current; - } - - if (current === '\'' || current === '"') { - stringLiteral = current; } }