diff --git a/test/common/index.js b/test/common/index.js index 765e7c8aa1..7f00820123 100644 --- a/test/common/index.js +++ b/test/common/index.js @@ -267,8 +267,9 @@ if (exports.isWindows) { } const ifaces = os.networkInterfaces(); +const re = /lo/; exports.hasIPv6 = Object.keys(ifaces).some(function(name) { - return /lo/.test(name) && ifaces[name].some(function(info) { + return re.test(name) && ifaces[name].some(function(info) { return info.family === 'IPv6'; }); }); @@ -433,7 +434,7 @@ function leakedGlobals() { leaked.push(val); if (global.__coverage__) { - return leaked.filter((varname) => !/^(cov_|__cov)/.test(varname)); + return leaked.filter((varname) => !/^(?:cov_|__cov)/.test(varname)); } else { return leaked; } diff --git a/test/debugger/helper-debugger-repl.js b/test/debugger/helper-debugger-repl.js index 234a401023..f11d4d9498 100644 --- a/test/debugger/helper-debugger-repl.js +++ b/test/debugger/helper-debugger-repl.js @@ -51,12 +51,12 @@ function startDebugger(scriptToDebug) { child.stderr.pipe(process.stderr); child.on('line', function(line) { - line = line.replace(/^(debug> *)+/, ''); + line = line.replace(/^(?:debug> *)+/, ''); console.log(line); assert.ok(expected.length > 0, `Got unexpected line: ${line}`); const expectedLine = expected[0].lines.shift(); - assert.ok(line.match(expectedLine) !== null, `${line} != ${expectedLine}`); + assert.ok(expectedLine.test(line), `${line} != ${expectedLine}`); if (expected[0].lines.length === 0) { const callback = expected[0].callback; diff --git a/test/doctool/test-doctool-html.js b/test/doctool/test-doctool-html.js index ba3e793e8a..8f78663cbe 100644 --- a/test/doctool/test-doctool-html.js +++ b/test/doctool/test-doctool-html.js @@ -91,9 +91,11 @@ const testData = [ }, ]; +const spaces = /\s/g; + testData.forEach((item) => { // Normalize expected data by stripping whitespace - const expected = item.html.replace(/\s/g, ''); + const expected = item.html.replace(spaces, ''); const includeAnalytics = typeof item.analyticsId !== 'undefined'; fs.readFile(item.file, 'utf8', common.mustCall((err, input) => { @@ -112,7 +114,7 @@ testData.forEach((item) => { common.mustCall((err, output) => { assert.ifError(err); - const actual = output.replace(/\s/g, ''); + const actual = output.replace(spaces, ''); // Assert that the input stripped of all whitespace contains the // expected list assert.notStrictEqual(actual.indexOf(expected), -1); diff --git a/test/inspector/inspector-helper.js b/test/inspector/inspector-helper.js index faf932f495..bc60974364 100644 --- a/test/inspector/inspector-helper.js +++ b/test/inspector/inspector-helper.js @@ -521,11 +521,11 @@ exports.startNodeForInspectorTest = function(callback, clearTimeout(timeoutId); console.log('[err]', text); if (found) return; - const match = text.match(/Debugger listening on ws:\/\/(.+):(\d+)\/(.+)/); + const match = text.match(/Debugger listening on ws:\/\/.+:(\d+)\/.+/); found = true; child.stderr.removeListener('data', dataCallback); assert.ok(match, text); - callback(new Harness(match[2], child)); + callback(new Harness(match[1], child)); }); child.stderr.on('data', dataCallback); diff --git a/test/inspector/test-inspector.js b/test/inspector/test-inspector.js index 19eb3601f0..313fba9bd9 100644 --- a/test/inspector/test-inspector.js +++ b/test/inspector/test-inspector.js @@ -13,8 +13,8 @@ function checkListResponse(err, response) { assert.strictEqual(1, response.length); assert.ok(response[0]['devtoolsFrontendUrl']); assert.ok( - response[0]['webSocketDebuggerUrl'] - .match(/ws:\/\/127\.0\.0\.1:\d+\/[0-9A-Fa-f]{8}-/)); + /ws:\/\/127\.0\.0\.1:\d+\/[0-9A-Fa-f]{8}-/ + .test(response[0]['webSocketDebuggerUrl'])); } function checkVersion(err, response) { diff --git a/test/parallel/test-assert-checktag.js b/test/parallel/test-assert-checktag.js index 027af93560..c4823243e7 100644 --- a/test/parallel/test-assert-checktag.js +++ b/test/parallel/test-assert-checktag.js @@ -7,10 +7,11 @@ const util = require('util'); // for assert.throws() function re(literals, ...values) { let result = literals[0]; + const escapeRE = /[\\^$.*+?()[\]{}|=!<>:-]/g; for (const [i, value] of values.entries()) { const str = util.inspect(value); // Need to escape special characters. - result += str.replace(/[\\^$.*+?()[\]{}|=!<>:-]/g, '\\$&'); + result += str.replace(escapeRE, '\\$&'); result += literals[i + 1]; } return common.expectsError({ diff --git a/test/parallel/test-assert-deep.js b/test/parallel/test-assert-deep.js index fecb5c89db..9f1c8dadf9 100644 --- a/test/parallel/test-assert-deep.js +++ b/test/parallel/test-assert-deep.js @@ -7,10 +7,11 @@ const util = require('util'); // for assert.throws() function re(literals, ...values) { let result = literals[0]; + const escapeRE = /[\\^$.*+?()[\]{}|=!<>:-]/g; for (const [i, value] of values.entries()) { const str = util.inspect(value); // Need to escape special characters. - result += str.replace(/[\\^$.*+?()[\]{}|=!<>:-]/g, '\\$&'); + result += str.replace(escapeRE, '\\$&'); result += literals[i + 1]; } return common.expectsError({ diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 7b492374f0..561ce6d79b 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -722,13 +722,14 @@ assert.throws(() => { { // 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) => { assert.throws( () => new assert.AssertionError(input), common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', type: TypeError, - message: /^The "options" argument must be of type object$/ + message: re })); }); } diff --git a/test/parallel/test-buffer-bytelength.js b/test/parallel/test-buffer-bytelength.js index 09e59743e4..8077cc7d5e 100644 --- a/test/parallel/test-buffer-bytelength.js +++ b/test/parallel/test-buffer-bytelength.js @@ -7,14 +7,11 @@ const SlowBuffer = require('buffer').SlowBuffer; const vm = require('vm'); // coerce values to string -assert.throws(() => { Buffer.byteLength(32, 'latin1'); }, - /"string" must be a string, Buffer, or ArrayBuffer/); -assert.throws(() => { Buffer.byteLength(NaN, 'utf8'); }, - /"string" must be a string, Buffer, or ArrayBuffer/); -assert.throws(() => { Buffer.byteLength({}, 'latin1'); }, - /"string" must be a string, Buffer, or ArrayBuffer/); -assert.throws(() => { Buffer.byteLength(); }, - /"string" must be a string, Buffer, or ArrayBuffer/); +const re = /"string" must be a string, Buffer, or ArrayBuffer/; +assert.throws(() => { Buffer.byteLength(32, 'latin1'); }, re); +assert.throws(() => { Buffer.byteLength(NaN, 'utf8'); }, re); +assert.throws(() => { Buffer.byteLength({}, 'latin1'); }, re); +assert.throws(() => { Buffer.byteLength(); }, re); assert.strictEqual(Buffer.byteLength('', undefined, true), -1); diff --git a/test/parallel/test-buffer-prototype-inspect.js b/test/parallel/test-buffer-prototype-inspect.js index 5f65a9bb28..9e6c66dc3d 100644 --- a/test/parallel/test-buffer-prototype-inspect.js +++ b/test/parallel/test-buffer-prototype-inspect.js @@ -19,5 +19,5 @@ const util = require('util'); { const buf = Buffer.from('x'.repeat(51)); - assert.ok(/^$/.test(util.inspect(buf))); + assert.ok(/^$/.test(util.inspect(buf))); } diff --git a/test/parallel/test-child-process-constructor.js b/test/parallel/test-child-process-constructor.js index c495f1895d..8e62f5cc23 100644 --- a/test/parallel/test-child-process-constructor.js +++ b/test/parallel/test-child-process-constructor.js @@ -8,44 +8,48 @@ assert.strictEqual(typeof ChildProcess, 'function'); { // Verify that invalid options to spawn() throw. const child = new ChildProcess(); + const re = /^TypeError: "options" must be an object$/; [undefined, null, 'foo', 0, 1, NaN, true, false].forEach((options) => { assert.throws(() => { child.spawn(options); - }, /^TypeError: "options" must be an object$/); + }, re); }); } { // Verify that spawn throws if file is not a string. const child = new ChildProcess(); + const re = /^TypeError: "file" must be a string$/; [undefined, null, 0, 1, NaN, true, false, {}].forEach((file) => { assert.throws(() => { child.spawn({ file }); - }, /^TypeError: "file" must be a string$/); + }, re); }); } { // Verify that spawn throws if envPairs is not an array or undefined. const child = new ChildProcess(); + const re = /^TypeError: "envPairs" must be an array$/; [null, 0, 1, NaN, true, false, {}, 'foo'].forEach((envPairs) => { assert.throws(() => { child.spawn({ envPairs, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] }); - }, /^TypeError: "envPairs" must be an array$/); + }, re); }); } { // Verify that spawn throws if args is not an array or undefined. const child = new ChildProcess(); + const re = /^TypeError: "args" must be an array$/; [null, 0, 1, NaN, true, false, {}, 'foo'].forEach((args) => { assert.throws(() => { child.spawn({ file: 'foo', args }); - }, /^TypeError: "args" must be an array$/); + }, re); }); } diff --git a/test/parallel/test-cli-syntax.js b/test/parallel/test-cli-syntax.js index eda45701a5..867f05256d 100644 --- a/test/parallel/test-cli-syntax.js +++ b/test/parallel/test-cli-syntax.js @@ -13,6 +13,9 @@ const syntaxArgs = [ ['--check'] ]; +const syntaxErrorRE = /^SyntaxError: Unexpected identifier$/m; +const notFoundRE = /^Error: Cannot find module/m; + // test good syntax with and without shebang [ 'syntax/good_syntax.js', @@ -56,8 +59,7 @@ const syntaxArgs = [ assert(c.stderr.startsWith(file), "stderr doesn't start with the filename"); // stderr should have a syntax error message - const match = c.stderr.match(/^SyntaxError: Unexpected identifier$/m); - assert(match, 'stderr incorrect'); + assert(syntaxErrorRE.test(c.stderr), 'stderr incorrect'); assert.strictEqual(c.status, 1, `code === ${c.status}`); }); @@ -79,8 +81,7 @@ const syntaxArgs = [ assert.strictEqual(c.stdout, '', 'stdout produced'); // stderr should have a module not found error message - const match = c.stderr.match(/^Error: Cannot find module/m); - assert(match, 'stderr incorrect'); + assert(notFoundRE.test(c.stderr), 'stderr incorrect'); assert.strictEqual(c.status, 1, `code === ${c.status}`); }); @@ -112,8 +113,7 @@ syntaxArgs.forEach(function(args) { assert.strictEqual(c.stdout, '', 'stdout produced'); // stderr should have a syntax error message - const match = c.stderr.match(/^SyntaxError: Unexpected identifier$/m); - assert(match, 'stderr incorrect'); + assert(syntaxErrorRE.test(c.stderr), 'stderr incorrect'); assert.strictEqual(c.status, 1, `code === ${c.status}`); }); diff --git a/test/parallel/test-crypto-authenticated.js b/test/parallel/test-crypto-authenticated.js index c1d70efa5f..2d5370ba3e 100644 --- a/test/parallel/test-crypto-authenticated.js +++ b/test/parallel/test-crypto-authenticated.js @@ -328,6 +328,13 @@ const TEST_CASES = [ tag: 'a44a8266ee1c8eb0c8b5d4cf5ae9f19a', tampered: false }, ]; +const errMessages = { + auth: / auth/, + state: / state/, + FIPS: /not supported in FIPS mode/, + length: /Invalid IV length/, +}; + const ciphers = crypto.getCiphers(); for (const i in TEST_CASES) { @@ -378,14 +385,14 @@ for (const i in TEST_CASES) { assert.strictEqual(msg, test.plain); } else { // assert that final throws if input data could not be verified! - assert.throws(function() { decrypt.final('ascii'); }, / auth/); + assert.throws(function() { decrypt.final('ascii'); }, errMessages.auth); } } if (test.password) { if (common.hasFipsCrypto) { assert.throws(() => { crypto.createCipher(test.algo, test.password); }, - /not supported in FIPS mode/); + errMessages.FIPS); } else { const encrypt = crypto.createCipher(test.algo, test.password); if (test.aad) @@ -404,7 +411,7 @@ for (const i in TEST_CASES) { if (test.password) { if (common.hasFipsCrypto) { assert.throws(() => { crypto.createDecipher(test.algo, test.password); }, - /not supported in FIPS mode/); + errMessages.FIPS); } else { const decrypt = crypto.createDecipher(test.algo, test.password); decrypt.setAuthTag(Buffer.from(test.tag, 'hex')); @@ -416,7 +423,7 @@ for (const i in TEST_CASES) { assert.strictEqual(msg, test.plain); } else { // assert that final throws if input data could not be verified! - assert.throws(function() { decrypt.final('ascii'); }, / auth/); + assert.throws(function() { decrypt.final('ascii'); }, errMessages.auth); } } } @@ -427,7 +434,7 @@ for (const i in TEST_CASES) { Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); encrypt.update('blah', 'ascii'); - assert.throws(function() { encrypt.getAuthTag(); }, / state/); + assert.throws(function() { encrypt.getAuthTag(); }, errMessages.state); } { @@ -436,7 +443,7 @@ for (const i in TEST_CASES) { Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); assert.throws(() => { encrypt.setAuthTag(Buffer.from(test.tag, 'hex')); }, - / state/); + errMessages.state); } { @@ -444,7 +451,7 @@ for (const i in TEST_CASES) { const decrypt = crypto.createDecipheriv(test.algo, Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); - assert.throws(function() { decrypt.getAuthTag(); }, / state/); + assert.throws(function() { decrypt.getAuthTag(); }, errMessages.state); } { @@ -455,7 +462,7 @@ for (const i in TEST_CASES) { Buffer.from(test.key, 'hex'), Buffer.alloc(0) ); - }, /Invalid IV length/); + }, errMessages.length); } } @@ -467,6 +474,7 @@ for (const i in TEST_CASES) { '6fKjEjR3Vl30EUYC'); encrypt.update('blah', 'ascii'); encrypt.final(); - assert.throws(() => encrypt.getAuthTag(), / state/); - assert.throws(() => encrypt.setAAD(Buffer.from('123', 'ascii')), / state/); + assert.throws(() => encrypt.getAuthTag(), errMessages.state); + assert.throws(() => encrypt.setAAD(Buffer.from('123', 'ascii')), + errMessages.state); } diff --git a/test/parallel/test-crypto-cipheriv-decipheriv.js b/test/parallel/test-crypto-cipheriv-decipheriv.js index a03a25d511..31a79d8bf1 100644 --- a/test/parallel/test-crypto-cipheriv-decipheriv.js +++ b/test/parallel/test-crypto-cipheriv-decipheriv.js @@ -66,12 +66,14 @@ testCipher2(Buffer.from('0123456789abcd0123456789'), Buffer.from('12345678')); // Zero-sized IV should be accepted in ECB mode. crypto.createCipheriv('aes-128-ecb', Buffer.alloc(16), Buffer.alloc(0)); +const errMessage = /Invalid IV length/; + // But non-empty IVs should be rejected. for (let n = 1; n < 256; n += 1) { assert.throws( () => crypto.createCipheriv('aes-128-ecb', Buffer.alloc(16), Buffer.alloc(n)), - /Invalid IV length/); + errMessage); } // Correctly sized IV should be accepted in CBC mode. @@ -83,14 +85,14 @@ for (let n = 0; n < 256; n += 1) { assert.throws( () => crypto.createCipheriv('aes-128-cbc', Buffer.alloc(16), Buffer.alloc(n)), - /Invalid IV length/); + errMessage); } // Zero-sized IV should be rejected in GCM mode. assert.throws( () => crypto.createCipheriv('aes-128-gcm', Buffer.alloc(16), Buffer.alloc(0)), - /Invalid IV length/); + errMessage); // But all other IV lengths should be accepted. for (let n = 1; n < 256; n += 1) { diff --git a/test/parallel/test-crypto-dh.js b/test/parallel/test-crypto-dh.js index 285f35b830..91a066d1bd 100644 --- a/test/parallel/test-crypto-dh.js +++ b/test/parallel/test-crypto-dh.js @@ -295,14 +295,15 @@ if (availableCurves.has('prime256v1') && availableCurves.has('secp256k1')) { // rejected. ecdh5.setPrivateKey(cafebabeKey, 'hex'); - [ // Some invalid private keys for the secp256k1 curve. - '0000000000000000000000000000000000000000000000000000000000000000', - 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141', - 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', + // Some invalid private keys for the secp256k1 curve. + const errMessage = /^Error: Private key is not valid for specified curve\.$/; + ['0000000000000000000000000000000000000000000000000000000000000000', + 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141', + 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', ].forEach((element) => { assert.throws(() => { ecdh5.setPrivateKey(element, 'hex'); - }, /^Error: Private key is not valid for specified curve\.$/); + }, errMessage); // Verify object state did not change. assert.strictEqual(ecdh5.getPrivateKey('hex'), cafebabeKey); }); diff --git a/test/parallel/test-crypto-random.js b/test/parallel/test-crypto-random.js index fd9e71bb08..c60e3b2681 100644 --- a/test/parallel/test-crypto-random.js +++ b/test/parallel/test-crypto-random.js @@ -140,6 +140,14 @@ const expectedErrorRegexp = /^TypeError: size must be a number >= 0$/; Buffer.alloc(10), new Uint8Array(new Array(10).fill(0)) ]; + const errMessages = { + offsetNotNumber: /offset must be a number/, + offsetOutOfRange: /offset out of range/, + offsetNotUInt32: /offset must be a uint32/, + sizeNotNumber: /size must be a number/, + sizeNotUInt32: /size must be a uint32/, + bufferTooSmall: /buffer too small/, + }; for (const buf of bufs) { const len = Buffer.byteLength(buf); @@ -147,108 +155,108 @@ const expectedErrorRegexp = /^TypeError: size must be a number >= 0$/; assert.throws(() => { crypto.randomFillSync(buf, 'test'); - }, /offset must be a number/); + }, errMessages.offsetNotNumber); assert.throws(() => { crypto.randomFillSync(buf, NaN); - }, /offset must be a number/); + }, errMessages.offsetNotNumber); assert.throws(() => { crypto.randomFill(buf, 'test', common.mustNotCall()); - }, /offset must be a number/); + }, errMessages.offsetNotNumber); assert.throws(() => { crypto.randomFill(buf, NaN, common.mustNotCall()); - }, /offset must be a number/); + }, errMessages.offsetNotNumber); const max = require('buffer').kMaxLength + 1; assert.throws(() => { crypto.randomFillSync(buf, 11); - }, /offset out of range/); + }, errMessages.offsetOutOfRange); assert.throws(() => { crypto.randomFillSync(buf, max); - }, /offset out of range/); + }, errMessages.offsetOutOfRange); assert.throws(() => { crypto.randomFill(buf, 11, common.mustNotCall()); - }, /offset out of range/); + }, errMessages.offsetOutOfRange); assert.throws(() => { crypto.randomFill(buf, max, common.mustNotCall()); - }, /offset out of range/); + }, errMessages.offsetOutOfRange); assert.throws(() => { crypto.randomFillSync(buf, 0, 'test'); - }, /size must be a number/); + }, errMessages.sizeNotNumber); assert.throws(() => { crypto.randomFillSync(buf, 0, NaN); - }, /size must be a number/); + }, errMessages.sizeNotNumber); assert.throws(() => { crypto.randomFill(buf, 0, 'test', common.mustNotCall()); - }, /size must be a number/); + }, errMessages.sizeNotNumber); assert.throws(() => { crypto.randomFill(buf, 0, NaN, common.mustNotCall()); - }, /size must be a number/); + }, errMessages.sizeNotNumber); { const size = (-1 >>> 0) + 1; assert.throws(() => { crypto.randomFillSync(buf, 0, -10); - }, /size must be a uint32/); + }, errMessages.sizeNotUInt32); assert.throws(() => { crypto.randomFillSync(buf, 0, size); - }, /size must be a uint32/); + }, errMessages.sizeNotUInt32); assert.throws(() => { crypto.randomFill(buf, 0, -10, common.mustNotCall()); - }, /size must be a uint32/); + }, errMessages.sizeNotUInt32); assert.throws(() => { crypto.randomFill(buf, 0, size, common.mustNotCall()); - }, /size must be a uint32/); + }, errMessages.sizeNotUInt32); } assert.throws(() => { crypto.randomFillSync(buf, -10); - }, /offset must be a uint32/); + }, errMessages.offsetNotUInt32); assert.throws(() => { crypto.randomFill(buf, -10, common.mustNotCall()); - }, /offset must be a uint32/); + }, errMessages.offsetNotUInt32); assert.throws(() => { crypto.randomFillSync(buf, 1, 10); - }, /buffer too small/); + }, errMessages.bufferTooSmall); assert.throws(() => { crypto.randomFill(buf, 1, 10, common.mustNotCall()); - }, /buffer too small/); + }, errMessages.bufferTooSmall); assert.throws(() => { crypto.randomFillSync(buf, 0, 12); - }, /buffer too small/); + }, errMessages.bufferTooSmall); assert.throws(() => { crypto.randomFill(buf, 0, 12, common.mustNotCall()); - }, /buffer too small/); + }, errMessages.bufferTooSmall); { // Offset is too big const offset = (-1 >>> 0) + 1; assert.throws(() => { crypto.randomFillSync(buf, offset, 10); - }, /offset must be a uint32/); + }, errMessages.offsetNotUInt32); assert.throws(() => { crypto.randomFill(buf, offset, 10, common.mustNotCall()); - }, /offset must be a uint32/); + }, errMessages.offsetNotUInt32); } } } diff --git a/test/parallel/test-crypto-sign-verify.js b/test/parallel/test-crypto-sign-verify.js index 52daf2e6ff..2a64b6d072 100644 --- a/test/parallel/test-crypto-sign-verify.js +++ b/test/parallel/test-crypto-sign-verify.js @@ -105,6 +105,7 @@ const modSize = 1024; getEffectiveSaltLength(crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN), 0, 16, 32, 64, 128 ]; + const errMessage = /^Error:.*data too large for key size$/; signSaltLengths.forEach((signSaltLength) => { if (signSaltLength > max) { @@ -117,7 +118,7 @@ const modSize = 1024; padding: crypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: signSaltLength }); - }, /^Error:.*data too large for key size$/); + }, errMessage); } else { // Otherwise, a valid signature should be generated const s4 = crypto.createSign(algo) @@ -200,6 +201,9 @@ const modSize = 1024; // Test exceptions for invalid `padding` and `saltLength` values { + const paddingNotInteger = /^TypeError: padding must be an integer$/; + const saltLengthNotInteger = /^TypeError: saltLength must be an integer$/; + [null, undefined, NaN, 'boom', {}, [], true, false] .forEach((invalidValue) => { assert.throws(() => { @@ -209,7 +213,7 @@ const modSize = 1024; key: keyPem, padding: invalidValue }); - }, /^TypeError: padding must be an integer$/); + }, paddingNotInteger); assert.throws(() => { crypto.createSign('RSA-SHA256') @@ -219,7 +223,7 @@ const modSize = 1024; padding: crypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: invalidValue }); - }, /^TypeError: saltLength must be an integer$/); + }, saltLengthNotInteger); }); assert.throws(() => { diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js index 19fb6f2687..a7638d3cd8 100644 --- a/test/parallel/test-crypto.js +++ b/test/parallel/test-crypto.js @@ -99,7 +99,8 @@ validateList(cryptoCiphers); const tlsCiphers = tls.getCiphers(); assert(tls.getCiphers().includes('aes256-sha')); // There should be no capital letters in any element. -assert(tlsCiphers.every((value) => /^[^A-Z]+$/.test(value))); +const noCapitals = /^[^A-Z]+$/; +assert(tlsCiphers.every((value) => noCapitals.test(value))); validateList(tlsCiphers); // Assert that we have sha and sha1 but not SHA and SHA1. diff --git a/test/parallel/test-dgram-createSocket-type.js b/test/parallel/test-dgram-createSocket-type.js index e6b17251f8..125a9d0be5 100644 --- a/test/parallel/test-dgram-createSocket-type.js +++ b/test/parallel/test-dgram-createSocket-type.js @@ -19,6 +19,7 @@ const validTypes = [ { type: 'udp4' }, { type: 'udp6' } ]; +const errMessage = /^Bad socket type specified\. Valid types are: udp4, udp6$/; // Error must be thrown with invalid types invalidTypes.forEach((invalidType) => { @@ -27,7 +28,7 @@ invalidTypes.forEach((invalidType) => { }, common.expectsError({ code: 'ERR_SOCKET_BAD_TYPE', type: Error, - message: /^Bad socket type specified\. Valid types are: udp4, udp6$/ + message: errMessage })); }); diff --git a/test/parallel/test-error-reporting.js b/test/parallel/test-error-reporting.js index cdd066f959..8a96129979 100644 --- a/test/parallel/test-error-reporting.js +++ b/test/parallel/test-error-reporting.js @@ -42,6 +42,8 @@ function errExec(script, callback) { }); } +const syntaxErrorMessage = /SyntaxError/; + // Simple throw error errExec('throws_error.js', common.mustCall(function(err, stdout, stderr) { @@ -51,30 +53,30 @@ errExec('throws_error.js', common.mustCall(function(err, stdout, stderr) { // Trying to JSON.parse(undefined) errExec('throws_error2.js', common.mustCall(function(err, stdout, stderr) { - assert.ok(/SyntaxError/.test(stderr)); + assert.ok(syntaxErrorMessage.test(stderr)); })); // Trying to JSON.parse(undefined) in nextTick errExec('throws_error3.js', common.mustCall(function(err, stdout, stderr) { - assert.ok(/SyntaxError/.test(stderr)); + assert.ok(syntaxErrorMessage.test(stderr)); })); // throw ILLEGAL error errExec('throws_error4.js', common.mustCall(function(err, stdout, stderr) { assert.ok(/\/\*\*/.test(stderr)); - assert.ok(/SyntaxError/.test(stderr)); + assert.ok(syntaxErrorMessage.test(stderr)); })); // Specific long exception line doesn't result in stack overflow errExec('throws_error5.js', common.mustCall(function(err, stdout, stderr) { - assert.ok(/SyntaxError/.test(stderr)); + assert.ok(syntaxErrorMessage.test(stderr)); })); // Long exception line with length > errorBuffer doesn't result in assertion errExec('throws_error6.js', common.mustCall(function(err, stdout, stderr) { - assert.ok(/SyntaxError/.test(stderr)); + assert.ok(syntaxErrorMessage.test(stderr)); })); // Object that throws in toString() doesn't print garbage diff --git a/test/parallel/test-event-emitter-max-listeners.js b/test/parallel/test-event-emitter-max-listeners.js index 614801e397..cf8c072271 100644 --- a/test/parallel/test-event-emitter-max-listeners.js +++ b/test/parallel/test-event-emitter-max-listeners.js @@ -31,12 +31,12 @@ e.on('maxListeners', common.mustCall()); e.setMaxListeners(42); const throwsObjs = [NaN, -1, 'and even this']; +const maxError = /^TypeError: "n" argument must be a positive number$/; +const defError = /^TypeError: "defaultMaxListeners" must be a positive number$/; for (const obj of throwsObjs) { - assert.throws(() => e.setMaxListeners(obj), - /^TypeError: "n" argument must be a positive number$/); - assert.throws(() => events.defaultMaxListeners = obj, - /^TypeError: "defaultMaxListeners" must be a positive number$/); + assert.throws(() => e.setMaxListeners(obj), maxError); + assert.throws(() => events.defaultMaxListeners = obj, defError); } e.emit('maxListeners'); diff --git a/test/parallel/test-fs-null-bytes.js b/test/parallel/test-fs-null-bytes.js index e9f421a6c4..a21fe516a0 100644 --- a/test/parallel/test-fs-null-bytes.js +++ b/test/parallel/test-fs-null-bytes.js @@ -29,7 +29,7 @@ function check(async, sync) { const expected = /Path must be a string without null bytes/; const argsSync = Array.prototype.slice.call(arguments, 2); const argsAsync = argsSync.concat((er) => { - assert(er && er.message.match(expected)); + assert(er && expected.test(er.message)); assert.strictEqual(er.code, 'ENOENT'); }); 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 bc1fca3a3c..6e4f405daa 100644 --- a/test/parallel/test-fs-read-stream-throw-type-error.js +++ b/test/parallel/test-fs-read-stream-throw-type-error.js @@ -19,15 +19,16 @@ assert.doesNotThrow(function() { fs.createReadStream(example, {encoding: 'utf8'}); }); +const errMessage = /"options" must be a string or an object/; assert.throws(function() { fs.createReadStream(example, 123); -}, /"options" must be a string or an object/); +}, errMessage); assert.throws(function() { fs.createReadStream(example, 0); -}, /"options" must be a string or an object/); +}, errMessage); assert.throws(function() { fs.createReadStream(example, true); -}, /"options" must be a string or an object/); +}, errMessage); assert.throws(function() { fs.createReadStream(example, false); -}, /"options" must be a string or an object/); +}, errMessage); diff --git a/test/parallel/test-global-console-exists.js b/test/parallel/test-global-console-exists.js index 425eac077a..29b92f8481 100644 --- a/test/parallel/test-global-console-exists.js +++ b/test/parallel/test-global-console-exists.js @@ -11,7 +11,7 @@ const leakWarning = /EventEmitter memory leak detected\. 2 hello listeners/; common.hijackStderr(common.mustCall(function(data) { if (process.stderr.writeTimes === 0) { - assert.ok(data.match(leakWarning)); + assert.ok(leakWarning.test(data)); } else { assert.fail('stderr.write should be called only once'); } diff --git a/test/parallel/test-http-client-unescaped-path.js b/test/parallel/test-http-client-unescaped-path.js index d991e9f75e..11faaec41a 100644 --- a/test/parallel/test-http-client-unescaped-path.js +++ b/test/parallel/test-http-client-unescaped-path.js @@ -24,8 +24,8 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); +const errMessage = /contains unescaped characters/; for (let i = 0; i <= 32; i += 1) { const path = `bad${String.fromCharCode(i)}path`; - assert.throws(() => http.get({ path }, common.mustNotCall()), - /contains unescaped characters/); + assert.throws(() => http.get({ path }, common.mustNotCall()), errMessage); } diff --git a/test/parallel/test-http-hostname-typechecking.js b/test/parallel/test-http-hostname-typechecking.js index 5fd776db27..c3b702896d 100644 --- a/test/parallel/test-http-hostname-typechecking.js +++ b/test/parallel/test-http-hostname-typechecking.js @@ -8,14 +8,14 @@ const http = require('http'); // when passed as the value of either options.hostname or options.host const vals = [{}, [], NaN, Infinity, -Infinity, true, false, 1, 0, new Date()]; -function errCheck(name) { - return new RegExp(`^TypeError: "options\\.${name}" must either be a ` + - 'string, undefined or null$'); -} +const errHostname = + /^TypeError: "options\.hostname" must either be a string, undefined or null$/; +const errHost = + /^TypeError: "options\.host" must either be a string, undefined or null$/; vals.forEach((v) => { - assert.throws(() => http.request({hostname: v}), errCheck('hostname')); - assert.throws(() => http.request({host: v}), errCheck('host')); + assert.throws(() => http.request({hostname: v}), errHostname); + assert.throws(() => http.request({host: v}), errHost); }); // These values are OK and should not throw synchronously diff --git a/test/parallel/test-http-server.js b/test/parallel/test-http-server.js index 701d91f623..85b2be52fe 100644 --- a/test/parallel/test-http-server.js +++ b/test/parallel/test-http-server.js @@ -116,10 +116,10 @@ process.on('exit', function() { assert.strictEqual(4, requests_sent); const hello = new RegExp('/hello'); - assert.notStrictEqual(null, hello.exec(server_response)); + assert.ok(hello.test(server_response)); const quit = new RegExp('/quit'); - assert.notStrictEqual(null, quit.exec(server_response)); + assert.ok(quit.test(server_response)); assert.strictEqual(true, client_got_eof); }); diff --git a/test/parallel/test-icu-punycode.js b/test/parallel/test-icu-punycode.js index 13db2dd7ba..9488568267 100644 --- a/test/parallel/test-icu-punycode.js +++ b/test/parallel/test-icu-punycode.js @@ -24,6 +24,8 @@ const wptToASCIITests = require('../fixtures/url-toascii.js'); } { + const errMessage = /^Error: Cannot convert name to ASCII$/; + for (const [i, test] of wptToASCIITests.entries()) { if (typeof test === 'string') continue; // skip comments @@ -33,8 +35,7 @@ const wptToASCIITests = require('../fixtures/url-toascii.js'); caseComment += ` (${comment})`; if (output === null) { assert.throws(() => icu.toASCII(input), - /^Error: Cannot convert name to ASCII$/, - `ToASCII ${caseComment}`); + errMessage, `ToASCII ${caseComment}`); assert.doesNotThrow(() => icu.toASCII(input, true), `ToASCII ${caseComment} in lenient mode`); } else { diff --git a/test/parallel/test-internal-errors.js b/test/parallel/test-internal-errors.js index c97b522e4a..8e06bab349 100644 --- a/test/parallel/test-internal-errors.js +++ b/test/parallel/test-internal-errors.js @@ -5,6 +5,13 @@ const common = require('../common'); const errors = require('internal/errors'); const assert = require('assert'); +const errMessages = { + objectString: /^'object' === 'string'$/, + booleanString: /^'boolean' === 'string'$/, + numberString: /^'number' === 'string'$/, + invalidKey: /^An invalid error message key was used: TEST_FOO_KEY\.$/, +}; + errors.E('TEST_ERROR_1', 'Error for testing purposes: %s'); errors.E('TEST_ERROR_2', (a, b) => `${a} ${b}`); @@ -43,86 +50,86 @@ assert.throws( () => new errors.Error('TEST_FOO_KEY'), common.expectsError({ code: 'ERR_ASSERTION', - message: /^An invalid error message key was used: TEST_FOO_KEY\.$/ + message: errMessages.invalidKey })); // Calling it twice yields same result (using the key does not create it) assert.throws( () => new errors.Error('TEST_FOO_KEY'), common.expectsError({ code: 'ERR_ASSERTION', - message: /^An invalid error message key was used: TEST_FOO_KEY\.$/ + message: errMessages.invalidKey })); assert.throws( () => new errors.Error(1), common.expectsError({ code: 'ERR_ASSERTION', - message: /^'number' === 'string'$/ + message: errMessages.numberString })); assert.throws( () => new errors.Error({}), common.expectsError({ code: 'ERR_ASSERTION', - message: /^'object' === 'string'$/ + message: errMessages.objectString })); assert.throws( () => new errors.Error([]), common.expectsError({ code: 'ERR_ASSERTION', - message: /^'object' === 'string'$/ + message: errMessages.objectString })); assert.throws( () => new errors.Error(true), common.expectsError({ code: 'ERR_ASSERTION', - message: /^'boolean' === 'string'$/ + message: errMessages.booleanString })); assert.throws( () => new errors.TypeError(1), common.expectsError({ code: 'ERR_ASSERTION', - message: /^'number' === 'string'$/ + message: errMessages.numberString })); assert.throws( () => new errors.TypeError({}), common.expectsError({ code: 'ERR_ASSERTION', - message: /^'object' === 'string'$/ + message: errMessages.objectString })); assert.throws( () => new errors.TypeError([]), common.expectsError({ code: 'ERR_ASSERTION', - message: /^'object' === 'string'$/ + message: errMessages.objectString })); assert.throws( () => new errors.TypeError(true), common.expectsError({ code: 'ERR_ASSERTION', - message: /^'boolean' === 'string'$/ + message: errMessages.booleanString })); assert.throws( () => new errors.RangeError(1), common.expectsError({ code: 'ERR_ASSERTION', - message: /^'number' === 'string'$/ + message: errMessages.numberString })); assert.throws( () => new errors.RangeError({}), common.expectsError({ code: 'ERR_ASSERTION', - message: /^'object' === 'string'$/ + message: errMessages.objectString })); assert.throws( () => new errors.RangeError([]), common.expectsError({ code: 'ERR_ASSERTION', - message: /^'object' === 'string'$/ + message: errMessages.objectString })); assert.throws( () => new errors.RangeError(true), common.expectsError({ code: 'ERR_ASSERTION', - message: /^'boolean' === 'string'$/ + message: errMessages.booleanString })); diff --git a/test/parallel/test-net-connect-options-port.js b/test/parallel/test-net-connect-options-port.js index b3c370c8d9..1a2bd850f3 100644 --- a/test/parallel/test-net-connect-options-port.js +++ b/test/parallel/test-net-connect-options-port.js @@ -190,7 +190,7 @@ function canConnect(port) { function asyncFailToConnect(port) { const onError = () => common.mustCall(function(err) { - const regexp = /^Error: connect (E\w+)(.+)$/; + const regexp = /^Error: connect E\w+.+$/; assert(regexp.test(String(err)), String(err)); }); diff --git a/test/parallel/test-path.js b/test/parallel/test-path.js index c9729ae875..4ee3740038 100644 --- a/test/parallel/test-path.js +++ b/test/parallel/test-path.js @@ -28,6 +28,9 @@ const path = require('path'); const f = __filename; const failures = []; +const slashRE = /\//g; +const backslashRE = /\\/g; + // path.basename tests assert.strictEqual(path.basename(f), 'test-path.js'); assert.strictEqual(path.basename(f, '.js'), 'test-path'); @@ -188,7 +191,7 @@ assert.strictEqual(path.win32.dirname('foo'), '.'); let input = test[0]; let os; if (extname === path.win32.extname) { - input = input.replace(/\//g, '\\'); + input = input.replace(slashRE, '\\'); os = 'win32'; } else { os = 'posix'; @@ -345,7 +348,7 @@ joinTests.forEach((test) => { let actualAlt; let os; if (join === path.win32.join) { - actualAlt = actual.replace(/\\/g, '/'); + actualAlt = actual.replace(backslashRE, '/'); os = 'win32'; } else { os = 'posix'; @@ -451,9 +454,9 @@ resolveTests.forEach((test) => { let actualAlt; const os = resolve === path.win32.resolve ? 'win32' : 'posix'; if (resolve === path.win32.resolve && !common.isWindows) - actualAlt = actual.replace(/\\/g, '/'); + actualAlt = actual.replace(backslashRE, '/'); else if (resolve !== path.win32.resolve && common.isWindows) - actualAlt = actual.replace(/\//g, '\\'); + actualAlt = actual.replace(slashRE, '\\'); const expected = test[1]; const message = diff --git a/test/parallel/test-process-chdir.js b/test/parallel/test-process-chdir.js index b137be4611..61707706a3 100644 --- a/test/parallel/test-process-chdir.js +++ b/test/parallel/test-process-chdir.js @@ -31,9 +31,10 @@ process.chdir('..'); assert.strictEqual(process.cwd().normalize(), path.resolve(common.tmpDir).normalize()); +const errMessage = /^TypeError: Bad argument\.$/; assert.throws(function() { process.chdir({}); }, - /^TypeError: Bad argument\.$/, 'Bad argument.'); + errMessage, 'Bad argument.'); assert.throws(function() { process.chdir(); }, - /^TypeError: Bad argument\.$/, 'Bad argument.'); + errMessage, 'Bad argument.'); assert.throws(function() { process.chdir('x', 'y'); }, - /^TypeError: Bad argument\.$/, 'Bad argument.'); + errMessage, 'Bad argument.'); diff --git a/test/parallel/test-process-emitwarning.js b/test/parallel/test-process-emitwarning.js index 61ca05cfe9..d2d090eae3 100644 --- a/test/parallel/test-process-emitwarning.js +++ b/test/parallel/test-process-emitwarning.js @@ -12,7 +12,7 @@ const testType = 'CustomWarning'; process.on('warning', common.mustCall((warning) => { assert(warning); - assert(/^(Warning|CustomWarning)/.test(warning.name)); + assert(/^(?:Warning|CustomWarning)/.test(warning.name)); assert.strictEqual(warning.message, testMsg); if (warning.code) assert.strictEqual(warning.code, testCode); if (warning.detail) assert.strictEqual(warning.detail, testDetail); diff --git a/test/parallel/test-process-setuid-setgid.js b/test/parallel/test-process-setuid-setgid.js index 1feb4248d1..e0db8ee002 100644 --- a/test/parallel/test-process-setuid-setgid.js +++ b/test/parallel/test-process-setuid-setgid.js @@ -46,12 +46,12 @@ if (process.getuid() !== 0) { assert.throws( () => { process.setgid('nobody'); }, - /^Error: (EPERM, .+|setgid group id does not exist)$/ + /^Error: (?:EPERM, .+|setgid group id does not exist)$/ ); assert.throws( () => { process.setuid('nobody'); }, - /^Error: (EPERM, .+|setuid user id does not exist)$/ + /^Error: (?:EPERM, .+|setuid user id does not exist)$/ ); return; } diff --git a/test/parallel/test-process-versions.js b/test/parallel/test-process-versions.js index 4da16379d5..02eeb93cb1 100644 --- a/test/parallel/test-process-versions.js +++ b/test/parallel/test-process-versions.js @@ -21,10 +21,13 @@ const actual_keys = Object.keys(process.versions).sort(); assert.deepStrictEqual(actual_keys, expected_keys); -assert(/^\d+\.\d+\.\d+(-.*)?$/.test(process.versions.ares)); -assert(/^\d+\.\d+\.\d+(-.*)?$/.test(process.versions.http_parser)); -assert(/^\d+\.\d+\.\d+(-.*)?$/.test(process.versions.node)); -assert(/^\d+\.\d+\.\d+(-.*)?$/.test(process.versions.uv)); -assert(/^\d+\.\d+\.\d+(-.*)?$/.test(process.versions.zlib)); -assert(/^\d+\.\d+\.\d+(\.\d+)?( \(candidate\))?$/.test(process.versions.v8)); +const commonTemplate = /^\d+\.\d+\.\d+(?:-.*)?$/; + +assert(commonTemplate.test(process.versions.ares)); +assert(commonTemplate.test(process.versions.http_parser)); +assert(commonTemplate.test(process.versions.node)); +assert(commonTemplate.test(process.versions.uv)); +assert(commonTemplate.test(process.versions.zlib)); + +assert(/^\d+\.\d+\.\d+(?:\.\d+)?(?: \(candidate\))?$/.test(process.versions.v8)); assert(/^\d+$/.test(process.versions.modules)); diff --git a/test/parallel/test-repl.js b/test/parallel/test-repl.js index 86dd96d550..703300b333 100644 --- a/test/parallel/test-repl.js +++ b/test/parallel/test-repl.js @@ -95,7 +95,7 @@ function error_test() { let expect = client_unix.expect; if (expect === prompt_multiline) expect = /[.]{3} /; - assert.ok(read_buffer.match(expect)); + assert.ok(RegExp(expect).test(read_buffer)); console.error('match'); } read_buffer = ''; @@ -378,7 +378,7 @@ function error_test() { expect: /^(?!repl)/ }, // Avoid emitting stack trace { client: client_unix, send: 'a = 3.5e', - expect: /^(?!\s+at\s)/gm }, + expect: /^(?!\s+at\s)/m }, // https://github.com/nodejs/node/issues/9850 { client: client_unix, send: 'function* foo() {}; foo().next();', diff --git a/test/parallel/test-require-json.js b/test/parallel/test-require-json.js index 2ab86f0fb9..45581b186c 100644 --- a/test/parallel/test-require-json.js +++ b/test/parallel/test-require-json.js @@ -27,7 +27,7 @@ const assert = require('assert'); try { require(path.join(common.fixturesDir, 'invalid.json')); } catch (err) { - const re = /test[/\\]fixtures[/\\]invalid\.json: Unexpected string/; - const i = err.message.match(re); - assert.notStrictEqual(null, i, 'require() json error should include path'); + assert.ok( + /test[/\\]fixtures[/\\]invalid\.json: Unexpected string/.test(err.message), + 'require() json error should include path'); } diff --git a/test/parallel/test-socket-address.js b/test/parallel/test-socket-address.js index 3e05f89f08..ccffc5300b 100644 --- a/test/parallel/test-socket-address.js +++ b/test/parallel/test-socket-address.js @@ -12,6 +12,6 @@ server.listen(0, common.mustCall(function() { return -1; }; assert.throws(() => this.address(), - /^Error: address ([\w|\s-\d])+$/); + /^Error: address [\w|\s-\d]+$/); server.close(); })); diff --git a/test/parallel/test-stream-readable-invalid-chunk.js b/test/parallel/test-stream-readable-invalid-chunk.js index 3db42e18cd..990154144a 100644 --- a/test/parallel/test-stream-readable-invalid-chunk.js +++ b/test/parallel/test-stream-readable-invalid-chunk.js @@ -8,6 +8,7 @@ const readable = new stream.Readable({ read: common.noop }); -assert.throws(() => readable.push([]), /Invalid non-string\/buffer chunk/); -assert.throws(() => readable.push({}), /Invalid non-string\/buffer chunk/); -assert.throws(() => readable.push(0), /Invalid non-string\/buffer chunk/); +const errMessage = /Invalid non-string\/buffer chunk/; +assert.throws(() => readable.push([]), errMessage); +assert.throws(() => readable.push({}), errMessage); +assert.throws(() => readable.push(0), errMessage); diff --git a/test/parallel/test-string-decoder.js b/test/parallel/test-string-decoder.js index 8de0f7ba16..87ab5e8d37 100644 --- a/test/parallel/test-string-decoder.js +++ b/test/parallel/test-string-decoder.js @@ -144,6 +144,7 @@ function test(encoding, input, expected, singleSequence) { } else { sequences = [singleSequence]; } + const hexNumberRE = /.{2}/g; sequences.forEach((sequence) => { const decoder = new StringDecoder(encoding); let output = ''; @@ -155,7 +156,7 @@ function test(encoding, input, expected, singleSequence) { const message = 'Expected "' + unicodeEscape(expected) + '", ' + 'but got "' + unicodeEscape(output) + '"\n' + - 'input: ' + input.toString('hex').match(/.{2}/g) + '\n' + + 'input: ' + input.toString('hex').match(hexNumberRE) + '\n' + 'Write sequence: ' + JSON.stringify(sequence) + '\n' + 'Full Decoder State: ' + inspect(decoder); assert.fail(output, expected, message); diff --git a/test/parallel/test-timers-throw-when-cb-not-function.js b/test/parallel/test-timers-throw-when-cb-not-function.js index 2aff904f06..4e866726c1 100644 --- a/test/parallel/test-timers-throw-when-cb-not-function.js +++ b/test/parallel/test-timers-throw-when-cb-not-function.js @@ -8,18 +8,14 @@ function doSetTimeout(callback, after) { }; } -assert.throws(doSetTimeout('foo'), - /"callback" argument must be a function/); -assert.throws(doSetTimeout({foo: 'bar'}), - /"callback" argument must be a function/); -assert.throws(doSetTimeout(), - /"callback" argument must be a function/); -assert.throws(doSetTimeout(undefined, 0), - /"callback" argument must be a function/); -assert.throws(doSetTimeout(null, 0), - /"callback" argument must be a function/); -assert.throws(doSetTimeout(false, 0), - /"callback" argument must be a function/); +const errMessage = /"callback" argument must be a function/; + +assert.throws(doSetTimeout('foo'), errMessage); +assert.throws(doSetTimeout({foo: 'bar'}), errMessage); +assert.throws(doSetTimeout(), errMessage); +assert.throws(doSetTimeout(undefined, 0), errMessage); +assert.throws(doSetTimeout(null, 0), errMessage); +assert.throws(doSetTimeout(false, 0), errMessage); function doSetInterval(callback, after) { @@ -28,18 +24,12 @@ function doSetInterval(callback, after) { }; } -assert.throws(doSetInterval('foo'), - /"callback" argument must be a function/); -assert.throws(doSetInterval({foo: 'bar'}), - /"callback" argument must be a function/); -assert.throws(doSetInterval(), - /"callback" argument must be a function/); -assert.throws(doSetInterval(undefined, 0), - /"callback" argument must be a function/); -assert.throws(doSetInterval(null, 0), - /"callback" argument must be a function/); -assert.throws(doSetInterval(false, 0), - /"callback" argument must be a function/); +assert.throws(doSetInterval('foo'), errMessage); +assert.throws(doSetInterval({foo: 'bar'}), errMessage); +assert.throws(doSetInterval(), errMessage); +assert.throws(doSetInterval(undefined, 0), errMessage); +assert.throws(doSetInterval(null, 0), errMessage); +assert.throws(doSetInterval(false, 0), errMessage); function doSetImmediate(callback, after) { @@ -48,15 +38,9 @@ function doSetImmediate(callback, after) { }; } -assert.throws(doSetImmediate('foo'), - /"callback" argument must be a function/); -assert.throws(doSetImmediate({foo: 'bar'}), - /"callback" argument must be a function/); -assert.throws(doSetImmediate(), - /"callback" argument must be a function/); -assert.throws(doSetImmediate(undefined, 0), - /"callback" argument must be a function/); -assert.throws(doSetImmediate(null, 0), - /"callback" argument must be a function/); -assert.throws(doSetImmediate(false, 0), - /"callback" argument must be a function/); +assert.throws(doSetImmediate('foo'), errMessage); +assert.throws(doSetImmediate({foo: 'bar'}), errMessage); +assert.throws(doSetImmediate(), errMessage); +assert.throws(doSetImmediate(undefined, 0), errMessage); +assert.throws(doSetImmediate(null, 0), errMessage); +assert.throws(doSetImmediate(false, 0), errMessage); diff --git a/test/parallel/test-tls-client-mindhsize.js b/test/parallel/test-tls-client-mindhsize.js index f9bd0efea4..10fe196b53 100644 --- a/test/parallel/test-tls-client-mindhsize.js +++ b/test/parallel/test-tls-client-mindhsize.js @@ -78,13 +78,15 @@ testDHE1024(); assert.throws(() => test(512, true, common.mustNotCall()), /DH parameter is less than 1024 bits/); +let errMessage = /minDHSize is not a positive number/; [0, -1, -Infinity, NaN].forEach((minDHSize) => { assert.throws(() => tls.connect({ minDHSize }), - /minDHSize is not a positive number/); + errMessage); }); +errMessage = /minDHSize is not a number/; [true, false, null, undefined, {}, [], '', '1'].forEach((minDHSize) => { - assert.throws(() => tls.connect({ minDHSize }), /minDHSize is not a number/); + assert.throws(() => tls.connect({ minDHSize }), errMessage); }); process.on('exit', function() { diff --git a/test/parallel/test-tls-env-bad-extra-ca.js b/test/parallel/test-tls-env-bad-extra-ca.js index 12e4e3a4d9..57e4c1cfaf 100644 --- a/test/parallel/test-tls-env-bad-extra-ca.js +++ b/test/parallel/test-tls-env-bad-extra-ca.js @@ -33,9 +33,8 @@ fork(__filename, opts) assert.strictEqual(status, 0, 'client did not succeed in connecting'); })) .on('close', common.mustCall(function() { - assert(stderr.match( - /Warning: Ignoring extra certs from.*no-such-file-exists.* load failed:.*No such file or directory/ - ), stderr); + const re = /Warning: Ignoring extra certs from.*no-such-file-exists.* load failed:.*No such file or directory/; + assert(re.test(stderr), stderr); })) .stderr.setEncoding('utf8').on('data', function(str) { stderr += str; diff --git a/test/parallel/test-tls-no-sslv23.js b/test/parallel/test-tls-no-sslv23.js index ff1214d167..564efab26d 100644 --- a/test/parallel/test-tls-no-sslv23.js +++ b/test/parallel/test-tls-no-sslv23.js @@ -12,29 +12,33 @@ assert.throws(function() { tls.createSecureContext({ secureProtocol: 'blargh' }); }, /Unknown method/); +const errMessageSSLv2 = /SSLv2 methods disabled/; + assert.throws(function() { tls.createSecureContext({ secureProtocol: 'SSLv2_method' }); -}, /SSLv2 methods disabled/); +}, errMessageSSLv2); assert.throws(function() { tls.createSecureContext({ secureProtocol: 'SSLv2_client_method' }); -}, /SSLv2 methods disabled/); +}, errMessageSSLv2); assert.throws(function() { tls.createSecureContext({ secureProtocol: 'SSLv2_server_method' }); -}, /SSLv2 methods disabled/); +}, errMessageSSLv2); + +const errMessageSSLv3 = /SSLv3 methods disabled/; assert.throws(function() { tls.createSecureContext({ secureProtocol: 'SSLv3_method' }); -}, /SSLv3 methods disabled/); +}, errMessageSSLv3); assert.throws(function() { tls.createSecureContext({ secureProtocol: 'SSLv3_client_method' }); -}, /SSLv3 methods disabled/); +}, errMessageSSLv3); assert.throws(function() { tls.createSecureContext({ secureProtocol: 'SSLv3_server_method' }); -}, /SSLv3 methods disabled/); +}, errMessageSSLv3); // Note that SSLv2 and SSLv3 are disallowed but SSLv2_method and friends are // still accepted. They are OpenSSL's way of saying that all known protocols diff --git a/test/parallel/test-tls-passphrase.js b/test/parallel/test-tls-passphrase.js index 48777e1b05..20b5961fb4 100644 --- a/test/parallel/test-tls-passphrase.js +++ b/test/parallel/test-tls-passphrase.js @@ -225,6 +225,8 @@ server.listen(0, common.mustCall(function() { }, common.mustCall()); })).unref(); +const errMessagePassword = /bad password read/; + // Missing passphrase assert.throws(function() { tls.connect({ @@ -233,7 +235,7 @@ assert.throws(function() { cert: cert, rejectUnauthorized: false }); -}, /bad password read/); +}, errMessagePassword); assert.throws(function() { tls.connect({ @@ -242,7 +244,7 @@ assert.throws(function() { cert: cert, rejectUnauthorized: false }); -}, /bad password read/); +}, errMessagePassword); assert.throws(function() { tls.connect({ @@ -251,7 +253,9 @@ assert.throws(function() { cert: cert, rejectUnauthorized: false }); -}, /bad password read/); +}, errMessagePassword); + +const errMessageDecrypt = /bad decrypt/; // Invalid passphrase assert.throws(function() { @@ -262,7 +266,7 @@ assert.throws(function() { cert: cert, rejectUnauthorized: false }); -}, /bad decrypt/); +}, errMessageDecrypt); assert.throws(function() { tls.connect({ @@ -272,7 +276,7 @@ assert.throws(function() { cert: cert, rejectUnauthorized: false }); -}, /bad decrypt/); +}, errMessageDecrypt); assert.throws(function() { tls.connect({ @@ -282,7 +286,7 @@ assert.throws(function() { cert: cert, rejectUnauthorized: false }); -}, /bad decrypt/); +}, errMessageDecrypt); assert.throws(function() { tls.connect({ @@ -292,4 +296,4 @@ assert.throws(function() { cert: cert, rejectUnauthorized: false }); -}, /bad decrypt/); +}, errMessageDecrypt); diff --git a/test/parallel/test-tls-server-failed-handshake-emits-clienterror.js b/test/parallel/test-tls-server-failed-handshake-emits-clienterror.js index 1ff7decf3c..0290bcc629 100644 --- a/test/parallel/test-tls-server-failed-handshake-emits-clienterror.js +++ b/test/parallel/test-tls-server-failed-handshake-emits-clienterror.js @@ -21,9 +21,9 @@ const server = tls.createServer({}) }).on('tlsClientError', common.mustCall(function(e) { assert.ok(e instanceof Error, 'Instance of Error should be passed to error handler'); - assert.ok(e.message.match( - /SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol/), - 'Expecting SSL unknown protocol'); + assert.ok( + /SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol/.test(e.message), + 'Expecting SSL unknown protocol'); server.close(); })); diff --git a/test/parallel/test-tls-socket-failed-handshake-emits-error.js b/test/parallel/test-tls-socket-failed-handshake-emits-error.js index ffeb42c8eb..106a14a7df 100644 --- a/test/parallel/test-tls-socket-failed-handshake-emits-error.js +++ b/test/parallel/test-tls-socket-failed-handshake-emits-error.js @@ -21,9 +21,9 @@ const server = net.createServer(function(c) { s.on('error', common.mustCall(function(e) { assert.ok(e instanceof Error, 'Instance of Error should be passed to error handler'); - assert.ok(e.message.match( - /SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol/), - 'Expecting SSL unknown protocol'); + assert.ok( + /SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol/.test(e.message), + 'Expecting SSL unknown protocol'); })); s.on('close', function() { diff --git a/test/parallel/test-url-parse-invalid-input.js b/test/parallel/test-url-parse-invalid-input.js index a6de25e10c..a259112332 100644 --- a/test/parallel/test-url-parse-invalid-input.js +++ b/test/parallel/test-url-parse-invalid-input.js @@ -4,6 +4,7 @@ const assert = require('assert'); const url = require('url'); // https://github.com/joyent/node/issues/568 +const errMessage = /^TypeError: Parameter "url" must be a string, not (?:undefined|boolean|number|object|function|symbol)$/; [ undefined, null, @@ -16,8 +17,7 @@ const url = require('url'); () => {}, Symbol('foo') ].forEach((val) => { - assert.throws(() => { url.parse(val); }, - /^TypeError: Parameter "url" must be a string, not (undefined|boolean|number|object|function|symbol)$/); + assert.throws(() => { url.parse(val); }, errMessage); }); assert.throws(() => { url.parse('http://%E0%A4%A@fail'); }, diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 3edaac7370..2d05a55e2c 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -837,9 +837,10 @@ if (typeof Symbol !== 'undefined') { { function checkAlignment(container) { const lines = util.inspect(container).split('\n'); + const numRE = /\d/; let pos; lines.forEach((line) => { - const npos = line.search(/\d/); + const npos = line.search(numRE); if (npos !== -1) { if (pos !== undefined) { assert.strictEqual(pos, npos, 'container items not aligned'); diff --git a/test/parallel/test-util-internal.js b/test/parallel/test-util-internal.js index 5131353abb..9c016f3c3e 100644 --- a/test/parallel/test-util-internal.js +++ b/test/parallel/test-util-internal.js @@ -20,26 +20,29 @@ function setHiddenValue(obj, index, val) { }; } -assert.throws(getHiddenValue(), /obj must be an object/); -assert.throws(getHiddenValue(null, 'foo'), /obj must be an object/); -assert.throws(getHiddenValue(undefined, 'foo'), /obj must be an object/); -assert.throws(getHiddenValue('bar', 'foo'), /obj must be an object/); -assert.throws(getHiddenValue(85, 'foo'), /obj must be an object/); -assert.throws(getHiddenValue({}), /index must be an uint32/); -assert.throws(getHiddenValue({}, null), /index must be an uint32/); -assert.throws(getHiddenValue({}, []), /index must be an uint32/); +const errMessageObj = /obj must be an object/; +const errMessageIndex = /index must be an uint32/; + +assert.throws(getHiddenValue(), errMessageObj); +assert.throws(getHiddenValue(null, 'foo'), errMessageObj); +assert.throws(getHiddenValue(undefined, 'foo'), errMessageObj); +assert.throws(getHiddenValue('bar', 'foo'), errMessageObj); +assert.throws(getHiddenValue(85, 'foo'), errMessageObj); +assert.throws(getHiddenValue({}), errMessageIndex); +assert.throws(getHiddenValue({}, null), errMessageIndex); +assert.throws(getHiddenValue({}, []), errMessageIndex); assert.deepStrictEqual( binding.getHiddenValue({}, kArrowMessagePrivateSymbolIndex), undefined); -assert.throws(setHiddenValue(), /obj must be an object/); -assert.throws(setHiddenValue(null, 'foo'), /obj must be an object/); -assert.throws(setHiddenValue(undefined, 'foo'), /obj must be an object/); -assert.throws(setHiddenValue('bar', 'foo'), /obj must be an object/); -assert.throws(setHiddenValue(85, 'foo'), /obj must be an object/); -assert.throws(setHiddenValue({}), /index must be an uint32/); -assert.throws(setHiddenValue({}, null), /index must be an uint32/); -assert.throws(setHiddenValue({}, []), /index must be an uint32/); +assert.throws(setHiddenValue(), errMessageObj); +assert.throws(setHiddenValue(null, 'foo'), errMessageObj); +assert.throws(setHiddenValue(undefined, 'foo'), errMessageObj); +assert.throws(setHiddenValue('bar', 'foo'), errMessageObj); +assert.throws(setHiddenValue(85, 'foo'), errMessageObj); +assert.throws(setHiddenValue({}), errMessageIndex); +assert.throws(setHiddenValue({}, null), errMessageIndex); +assert.throws(setHiddenValue({}, []), errMessageIndex); const obj = {}; assert.strictEqual( binding.setHiddenValue(obj, kArrowMessagePrivateSymbolIndex, 'bar'), diff --git a/test/parallel/test-util-log.js b/test/parallel/test-util-log.js index 24e84e1be9..d660106e17 100644 --- a/test/parallel/test-util-log.js +++ b/test/parallel/test-util-log.js @@ -46,10 +46,10 @@ const tests = [ ]; // test util.log() +const re = /[0-9]{1,2} [A-Z][a-z]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} - (.+)$/; tests.forEach(function(test) { util.log(test.input); const result = strings.shift().trim(); - const re = (/[0-9]{1,2} [A-Z][a-z]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} - (.+)$/); const match = re.exec(result); assert.ok(match); assert.strictEqual(match[1], test.output); diff --git a/test/parallel/test-zlib-truncated.js b/test/parallel/test-zlib-truncated.js index c7b84c0d70..678bfedd41 100644 --- a/test/parallel/test-zlib-truncated.js +++ b/test/parallel/test-zlib-truncated.js @@ -15,6 +15,8 @@ const inputString = 'ΩΩLorem ipsum dolor sit amet, consectetur adipiscing eli' 'm arcu mi, sodales non suscipit id, ultrices ut massa. S' + 'ed ac sem sit amet arcu malesuada fermentum. Nunc sed. '; +const errMessage = /unexpected end of file/; + [ { comp: 'gzip', decomp: 'gunzip', decompSync: 'gunzipSync' }, { comp: 'gzip', decomp: 'unzip', decompSync: 'unzipSync' }, @@ -41,11 +43,11 @@ const inputString = 'ΩΩLorem ipsum dolor sit amet, consectetur adipiscing eli' // sync truncated input test assert.throws(function() { zlib[methods.decompSync](truncated); - }, /unexpected end of file/); + }, errMessage); // async truncated input test zlib[methods.decomp](truncated, function(err, result) { - assert(/unexpected end of file/.test(err.message)); + assert(errMessage.test(err.message)); }); const syncFlushOpt = { finishFlush: zlib.constants.Z_SYNC_FLUSH }; diff --git a/test/pummel/test-net-pingpong.js b/test/pummel/test-net-pingpong.js index d88b4f638a..4db843afd3 100644 --- a/test/pummel/test-net-pingpong.js +++ b/test/pummel/test-net-pingpong.js @@ -52,7 +52,7 @@ function pingPongTest(port, host, on_complete) { console.log(`server got: ${JSON.stringify(data)}`); assert.strictEqual('open', socket.readyState); assert.strictEqual(true, count <= N); - if (/PING/.exec(data)) { + if (/PING/.test(data)) { socket.write('PONG'); } }); diff --git a/test/sequential/test-module-loading.js b/test/sequential/test-module-loading.js index c55c03279e..8a7bfe15c4 100644 --- a/test/sequential/test-module-loading.js +++ b/test/sequential/test-module-loading.js @@ -25,6 +25,8 @@ const assert = require('assert'); const path = require('path'); const fs = require('fs'); +const backslash = /\\/g; + console.error('load test-module-loading.js'); // assert that this is the main module. @@ -195,7 +197,7 @@ try { require(`${loadOrder}file3`); } catch (e) { // Not a real .node module, but we know we require'd the right thing. - assert.ok(e.message.replace(/\\/g, '/').match(/file3\.node/)); + assert.ok(/file3\.node/.test(e.message.replace(backslash, '/'))); } assert.strictEqual(require(`${loadOrder}file4`).file4, 'file4.reg', msg); assert.strictEqual(require(`${loadOrder}file5`).file5, 'file5.reg2', msg); @@ -203,7 +205,7 @@ try { try { require(`${loadOrder}file7`); } catch (e) { - assert.ok(e.message.replace(/\\/g, '/').match(/file7\/index\.node/)); + assert.ok(/file7\/index\.node/.test(e.message.replace(backslash, '/'))); } assert.strictEqual(require(`${loadOrder}file8`).file8, 'file8/index.reg', msg); @@ -237,7 +239,7 @@ try { const children = module.children.reduce(function red(set, child) { let id = path.relative(path.dirname(__dirname), child.id); - id = id.replace(/\\/g, '/'); + id = id.replace(backslash, '/'); set[id] = child.children.reduce(red, {}); return set; }, {}); diff --git a/test/sequential/test-process-warnings.js b/test/sequential/test-process-warnings.js index 0ab8652f56..944029d8b3 100644 --- a/test/sequential/test-process-warnings.js +++ b/test/sequential/test-process-warnings.js @@ -10,24 +10,26 @@ const normal = [warnmod]; const noWarn = ['--no-warnings', warnmod]; const traceWarn = ['--trace-warnings', warnmod]; +const warningMessage = /^\(.+\)\sWarning: a bad practice warning/; + execFile(node, normal, function(er, stdout, stderr) { // Show Process Warnings assert.strictEqual(er, null); assert.strictEqual(stdout, ''); - assert(/^\(.+\)\sWarning: a bad practice warning/.test(stderr)); + assert(warningMessage.test(stderr)); }); execFile(node, noWarn, function(er, stdout, stderr) { // Hide Process Warnings assert.strictEqual(er, null); assert.strictEqual(stdout, ''); - assert(!/^\(.+\)\sWarning: a bad practice warning/.test(stderr)); + assert(!warningMessage.test(stderr)); }); execFile(node, traceWarn, function(er, stdout, stderr) { // Show Warning Trace assert.strictEqual(er, null); assert.strictEqual(stdout, ''); - assert(/^\(.+\)\sWarning: a bad practice warning/.test(stderr)); + assert(warningMessage.test(stderr)); assert(/at Object\.\s\(.+warnings\.js:3:9\)/.test(stderr)); }); diff --git a/test/sequential/test-regress-GH-784.js b/test/sequential/test-regress-GH-784.js index 7abc622dbe..127d921626 100644 --- a/test/sequential/test-regress-GH-784.js +++ b/test/sequential/test-regress-GH-784.js @@ -70,28 +70,30 @@ const responses = []; function afterPing(result) { responses.push(result); console.error(`afterPing. responses.length = ${responses.length}`); + const ECONNREFUSED_RE = /ECONNREFUSED/; + const successRE = /success/; switch (responses.length) { case 2: - assert.ok(/ECONNREFUSED/.test(responses[0])); - assert.ok(/ECONNREFUSED/.test(responses[1])); + assert.ok(ECONNREFUSED_RE.test(responses[0])); + assert.ok(ECONNREFUSED_RE.test(responses[1])); serverOn(); break; case 4: - assert.ok(/success/.test(responses[2])); - assert.ok(/success/.test(responses[3])); + assert.ok(successRE.test(responses[2])); + assert.ok(successRE.test(responses[3])); serverOff(); break; case 6: - assert.ok(/ECONNREFUSED/.test(responses[4])); - assert.ok(/ECONNREFUSED/.test(responses[5])); + assert.ok(ECONNREFUSED_RE.test(responses[4])); + assert.ok(ECONNREFUSED_RE.test(responses[5])); serverOn(); break; case 8: - assert.ok(/success/.test(responses[6])); - assert.ok(/success/.test(responses[7])); + assert.ok(successRE.test(responses[6])); + assert.ok(successRE.test(responses[7])); server.close(); // we should go to process.on('exit') from here. break;