Skip to content

Commit 1f32d9e

Browse files
vsemozhetbytaddaleax
authored andcommitted
test: fix RegExp nits
* Remove needless RegExp flag In fixed case, `/g` flag is needless in the boolean context. * Remove needless RegExp capturing Use non-capturing grouping or remove capturing completely when: * capturing is useless per se, e.g. in test() check; * captured groups are not used afterward at all; * some of the later captured groups are not used afterward. * Use test, not match/exec in boolean context match() and exec() return a complicated object, unneeded in a boolean context. * Do not needlessly repeat RegExp creation This commit takes RegExp creation out of cycles and other repetitions. As long as the RegExp does not use /g flag and match indices, we are safe here. In tests, this fix hardly gives a significant performance gain, but it increases clarity and maintainability, reassuring some RegExps to be identical. RegExp in functions are not taken out of their functions: while these functions are called many times and their RegExps are recreated with each call, the performance gain in test cases does not seem to be worth decreasing function self-dependency. PR-URL: #13770 Reviewed-By: Colin Ihrig <[email protected]>
1 parent 1fe455f commit 1f32d9e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+301
-244
lines changed

test/common/index.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -267,8 +267,9 @@ if (exports.isWindows) {
267267
}
268268

269269
const ifaces = os.networkInterfaces();
270+
const re = /lo/;
270271
exports.hasIPv6 = Object.keys(ifaces).some(function(name) {
271-
return /lo/.test(name) && ifaces[name].some(function(info) {
272+
return re.test(name) && ifaces[name].some(function(info) {
272273
return info.family === 'IPv6';
273274
});
274275
});
@@ -433,7 +434,7 @@ function leakedGlobals() {
433434
leaked.push(val);
434435

435436
if (global.__coverage__) {
436-
return leaked.filter((varname) => !/^(cov_|__cov)/.test(varname));
437+
return leaked.filter((varname) => !/^(?:cov_|__cov)/.test(varname));
437438
} else {
438439
return leaked;
439440
}

test/debugger/helper-debugger-repl.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -51,12 +51,12 @@ function startDebugger(scriptToDebug) {
5151
child.stderr.pipe(process.stderr);
5252

5353
child.on('line', function(line) {
54-
line = line.replace(/^(debug> *)+/, '');
54+
line = line.replace(/^(?:debug> *)+/, '');
5555
console.log(line);
5656
assert.ok(expected.length > 0, `Got unexpected line: ${line}`);
5757

5858
const expectedLine = expected[0].lines.shift();
59-
assert.ok(line.match(expectedLine) !== null, `${line} != ${expectedLine}`);
59+
assert.ok(expectedLine.test(line), `${line} != ${expectedLine}`);
6060

6161
if (expected[0].lines.length === 0) {
6262
const callback = expected[0].callback;

test/doctool/test-doctool-html.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -91,9 +91,11 @@ const testData = [
9191
},
9292
];
9393

94+
const spaces = /\s/g;
95+
9496
testData.forEach((item) => {
9597
// Normalize expected data by stripping whitespace
96-
const expected = item.html.replace(/\s/g, '');
98+
const expected = item.html.replace(spaces, '');
9799
const includeAnalytics = typeof item.analyticsId !== 'undefined';
98100

99101
fs.readFile(item.file, 'utf8', common.mustCall((err, input) => {
@@ -112,7 +114,7 @@ testData.forEach((item) => {
112114
common.mustCall((err, output) => {
113115
assert.ifError(err);
114116

115-
const actual = output.replace(/\s/g, '');
117+
const actual = output.replace(spaces, '');
116118
// Assert that the input stripped of all whitespace contains the
117119
// expected list
118120
assert.notStrictEqual(actual.indexOf(expected), -1);

test/inspector/inspector-helper.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -521,11 +521,11 @@ exports.startNodeForInspectorTest = function(callback,
521521
clearTimeout(timeoutId);
522522
console.log('[err]', text);
523523
if (found) return;
524-
const match = text.match(/Debugger listening on ws:\/\/(.+):(\d+)\/(.+)/);
524+
const match = text.match(/Debugger listening on ws:\/\/.+:(\d+)\/.+/);
525525
found = true;
526526
child.stderr.removeListener('data', dataCallback);
527527
assert.ok(match, text);
528-
callback(new Harness(match[2], child));
528+
callback(new Harness(match[1], child));
529529
});
530530

531531
child.stderr.on('data', dataCallback);

test/inspector/test-inspector.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ function checkListResponse(err, response) {
1313
assert.strictEqual(1, response.length);
1414
assert.ok(response[0]['devtoolsFrontendUrl']);
1515
assert.ok(
16-
response[0]['webSocketDebuggerUrl']
17-
.match(/ws:\/\/127\.0\.0\.1:\d+\/[0-9A-Fa-f]{8}-/));
16+
/ws:\/\/127\.0\.0\.1:\d+\/[0-9A-Fa-f]{8}-/
17+
.test(response[0]['webSocketDebuggerUrl']));
1818
}
1919

2020
function checkVersion(err, response) {

test/parallel/test-assert-checktag.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@ const util = require('util');
77
// for assert.throws()
88
function re(literals, ...values) {
99
let result = literals[0];
10+
const escapeRE = /[\\^$.*+?()[\]{}|=!<>:-]/g;
1011
for (const [i, value] of values.entries()) {
1112
const str = util.inspect(value);
1213
// Need to escape special characters.
13-
result += str.replace(/[\\^$.*+?()[\]{}|=!<>:-]/g, '\\$&');
14+
result += str.replace(escapeRE, '\\$&');
1415
result += literals[i + 1];
1516
}
1617
return common.expectsError({

test/parallel/test-assert-deep.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@ const util = require('util');
77
// for assert.throws()
88
function re(literals, ...values) {
99
let result = literals[0];
10+
const escapeRE = /[\\^$.*+?()[\]{}|=!<>:-]/g;
1011
for (const [i, value] of values.entries()) {
1112
const str = util.inspect(value);
1213
// Need to escape special characters.
13-
result += str.replace(/[\\^$.*+?()[\]{}|=!<>:-]/g, '\\$&');
14+
result += str.replace(escapeRE, '\\$&');
1415
result += literals[i + 1];
1516
}
1617
return common.expectsError({

test/parallel/test-assert.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -722,13 +722,14 @@ assert.throws(() => {
722722
{
723723
// bad args to AssertionError constructor should throw TypeError
724724
const args = [1, true, false, '', null, Infinity, Symbol('test'), undefined];
725+
const re = /^The "options" argument must be of type object$/;
725726
args.forEach((input) => {
726727
assert.throws(
727728
() => new assert.AssertionError(input),
728729
common.expectsError({
729730
code: 'ERR_INVALID_ARG_TYPE',
730731
type: TypeError,
731-
message: /^The "options" argument must be of type object$/
732+
message: re
732733
}));
733734
});
734735
}

test/parallel/test-buffer-bytelength.js

+5-8
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,11 @@ const SlowBuffer = require('buffer').SlowBuffer;
77
const vm = require('vm');
88

99
// coerce values to string
10-
assert.throws(() => { Buffer.byteLength(32, 'latin1'); },
11-
/"string" must be a string, Buffer, or ArrayBuffer/);
12-
assert.throws(() => { Buffer.byteLength(NaN, 'utf8'); },
13-
/"string" must be a string, Buffer, or ArrayBuffer/);
14-
assert.throws(() => { Buffer.byteLength({}, 'latin1'); },
15-
/"string" must be a string, Buffer, or ArrayBuffer/);
16-
assert.throws(() => { Buffer.byteLength(); },
17-
/"string" must be a string, Buffer, or ArrayBuffer/);
10+
const re = /"string" must be a string, Buffer, or ArrayBuffer/;
11+
assert.throws(() => { Buffer.byteLength(32, 'latin1'); }, re);
12+
assert.throws(() => { Buffer.byteLength(NaN, 'utf8'); }, re);
13+
assert.throws(() => { Buffer.byteLength({}, 'latin1'); }, re);
14+
assert.throws(() => { Buffer.byteLength(); }, re);
1815

1916
assert.strictEqual(Buffer.byteLength('', undefined, true), -1);
2017

test/parallel/test-buffer-prototype-inspect.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,5 @@ const util = require('util');
1919

2020
{
2121
const buf = Buffer.from('x'.repeat(51));
22-
assert.ok(/^<Buffer (78 ){50}\.\.\. >$/.test(util.inspect(buf)));
22+
assert.ok(/^<Buffer (?:78 ){50}\.\.\. >$/.test(util.inspect(buf)));
2323
}

test/parallel/test-child-process-constructor.js

+8-4
Original file line numberDiff line numberDiff line change
@@ -8,44 +8,48 @@ assert.strictEqual(typeof ChildProcess, 'function');
88
{
99
// Verify that invalid options to spawn() throw.
1010
const child = new ChildProcess();
11+
const re = /^TypeError: "options" must be an object$/;
1112

1213
[undefined, null, 'foo', 0, 1, NaN, true, false].forEach((options) => {
1314
assert.throws(() => {
1415
child.spawn(options);
15-
}, /^TypeError: "options" must be an object$/);
16+
}, re);
1617
});
1718
}
1819

1920
{
2021
// Verify that spawn throws if file is not a string.
2122
const child = new ChildProcess();
23+
const re = /^TypeError: "file" must be a string$/;
2224

2325
[undefined, null, 0, 1, NaN, true, false, {}].forEach((file) => {
2426
assert.throws(() => {
2527
child.spawn({ file });
26-
}, /^TypeError: "file" must be a string$/);
28+
}, re);
2729
});
2830
}
2931

3032
{
3133
// Verify that spawn throws if envPairs is not an array or undefined.
3234
const child = new ChildProcess();
35+
const re = /^TypeError: "envPairs" must be an array$/;
3336

3437
[null, 0, 1, NaN, true, false, {}, 'foo'].forEach((envPairs) => {
3538
assert.throws(() => {
3639
child.spawn({ envPairs, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });
37-
}, /^TypeError: "envPairs" must be an array$/);
40+
}, re);
3841
});
3942
}
4043

4144
{
4245
// Verify that spawn throws if args is not an array or undefined.
4346
const child = new ChildProcess();
47+
const re = /^TypeError: "args" must be an array$/;
4448

4549
[null, 0, 1, NaN, true, false, {}, 'foo'].forEach((args) => {
4650
assert.throws(() => {
4751
child.spawn({ file: 'foo', args });
48-
}, /^TypeError: "args" must be an array$/);
52+
}, re);
4953
});
5054
}
5155

test/parallel/test-cli-syntax.js

+6-6
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ const syntaxArgs = [
1313
['--check']
1414
];
1515

16+
const syntaxErrorRE = /^SyntaxError: Unexpected identifier$/m;
17+
const notFoundRE = /^Error: Cannot find module/m;
18+
1619
// test good syntax with and without shebang
1720
[
1821
'syntax/good_syntax.js',
@@ -56,8 +59,7 @@ const syntaxArgs = [
5659
assert(c.stderr.startsWith(file), "stderr doesn't start with the filename");
5760

5861
// stderr should have a syntax error message
59-
const match = c.stderr.match(/^SyntaxError: Unexpected identifier$/m);
60-
assert(match, 'stderr incorrect');
62+
assert(syntaxErrorRE.test(c.stderr), 'stderr incorrect');
6163

6264
assert.strictEqual(c.status, 1, `code === ${c.status}`);
6365
});
@@ -79,8 +81,7 @@ const syntaxArgs = [
7981
assert.strictEqual(c.stdout, '', 'stdout produced');
8082

8183
// stderr should have a module not found error message
82-
const match = c.stderr.match(/^Error: Cannot find module/m);
83-
assert(match, 'stderr incorrect');
84+
assert(notFoundRE.test(c.stderr), 'stderr incorrect');
8485

8586
assert.strictEqual(c.status, 1, `code === ${c.status}`);
8687
});
@@ -112,8 +113,7 @@ syntaxArgs.forEach(function(args) {
112113
assert.strictEqual(c.stdout, '', 'stdout produced');
113114

114115
// stderr should have a syntax error message
115-
const match = c.stderr.match(/^SyntaxError: Unexpected identifier$/m);
116-
assert(match, 'stderr incorrect');
116+
assert(syntaxErrorRE.test(c.stderr), 'stderr incorrect');
117117

118118
assert.strictEqual(c.status, 1, `code === ${c.status}`);
119119
});

test/parallel/test-crypto-authenticated.js

+18-10
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,13 @@ const TEST_CASES = [
328328
tag: 'a44a8266ee1c8eb0c8b5d4cf5ae9f19a', tampered: false },
329329
];
330330

331+
const errMessages = {
332+
auth: / auth/,
333+
state: / state/,
334+
FIPS: /not supported in FIPS mode/,
335+
length: /Invalid IV length/,
336+
};
337+
331338
const ciphers = crypto.getCiphers();
332339

333340
for (const i in TEST_CASES) {
@@ -378,14 +385,14 @@ for (const i in TEST_CASES) {
378385
assert.strictEqual(msg, test.plain);
379386
} else {
380387
// assert that final throws if input data could not be verified!
381-
assert.throws(function() { decrypt.final('ascii'); }, / auth/);
388+
assert.throws(function() { decrypt.final('ascii'); }, errMessages.auth);
382389
}
383390
}
384391

385392
if (test.password) {
386393
if (common.hasFipsCrypto) {
387394
assert.throws(() => { crypto.createCipher(test.algo, test.password); },
388-
/not supported in FIPS mode/);
395+
errMessages.FIPS);
389396
} else {
390397
const encrypt = crypto.createCipher(test.algo, test.password);
391398
if (test.aad)
@@ -404,7 +411,7 @@ for (const i in TEST_CASES) {
404411
if (test.password) {
405412
if (common.hasFipsCrypto) {
406413
assert.throws(() => { crypto.createDecipher(test.algo, test.password); },
407-
/not supported in FIPS mode/);
414+
errMessages.FIPS);
408415
} else {
409416
const decrypt = crypto.createDecipher(test.algo, test.password);
410417
decrypt.setAuthTag(Buffer.from(test.tag, 'hex'));
@@ -416,7 +423,7 @@ for (const i in TEST_CASES) {
416423
assert.strictEqual(msg, test.plain);
417424
} else {
418425
// assert that final throws if input data could not be verified!
419-
assert.throws(function() { decrypt.final('ascii'); }, / auth/);
426+
assert.throws(function() { decrypt.final('ascii'); }, errMessages.auth);
420427
}
421428
}
422429
}
@@ -427,7 +434,7 @@ for (const i in TEST_CASES) {
427434
Buffer.from(test.key, 'hex'),
428435
Buffer.from(test.iv, 'hex'));
429436
encrypt.update('blah', 'ascii');
430-
assert.throws(function() { encrypt.getAuthTag(); }, / state/);
437+
assert.throws(function() { encrypt.getAuthTag(); }, errMessages.state);
431438
}
432439

433440
{
@@ -436,15 +443,15 @@ for (const i in TEST_CASES) {
436443
Buffer.from(test.key, 'hex'),
437444
Buffer.from(test.iv, 'hex'));
438445
assert.throws(() => { encrypt.setAuthTag(Buffer.from(test.tag, 'hex')); },
439-
/ state/);
446+
errMessages.state);
440447
}
441448

442449
{
443450
// trying to read tag from decryption object:
444451
const decrypt = crypto.createDecipheriv(test.algo,
445452
Buffer.from(test.key, 'hex'),
446453
Buffer.from(test.iv, 'hex'));
447-
assert.throws(function() { decrypt.getAuthTag(); }, / state/);
454+
assert.throws(function() { decrypt.getAuthTag(); }, errMessages.state);
448455
}
449456

450457
{
@@ -455,7 +462,7 @@ for (const i in TEST_CASES) {
455462
Buffer.from(test.key, 'hex'),
456463
Buffer.alloc(0)
457464
);
458-
}, /Invalid IV length/);
465+
}, errMessages.length);
459466
}
460467
}
461468

@@ -467,6 +474,7 @@ for (const i in TEST_CASES) {
467474
'6fKjEjR3Vl30EUYC');
468475
encrypt.update('blah', 'ascii');
469476
encrypt.final();
470-
assert.throws(() => encrypt.getAuthTag(), / state/);
471-
assert.throws(() => encrypt.setAAD(Buffer.from('123', 'ascii')), / state/);
477+
assert.throws(() => encrypt.getAuthTag(), errMessages.state);
478+
assert.throws(() => encrypt.setAAD(Buffer.from('123', 'ascii')),
479+
errMessages.state);
472480
}

test/parallel/test-crypto-cipheriv-decipheriv.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,14 @@ testCipher2(Buffer.from('0123456789abcd0123456789'), Buffer.from('12345678'));
6666
// Zero-sized IV should be accepted in ECB mode.
6767
crypto.createCipheriv('aes-128-ecb', Buffer.alloc(16), Buffer.alloc(0));
6868

69+
const errMessage = /Invalid IV length/;
70+
6971
// But non-empty IVs should be rejected.
7072
for (let n = 1; n < 256; n += 1) {
7173
assert.throws(
7274
() => crypto.createCipheriv('aes-128-ecb', Buffer.alloc(16),
7375
Buffer.alloc(n)),
74-
/Invalid IV length/);
76+
errMessage);
7577
}
7678

7779
// Correctly sized IV should be accepted in CBC mode.
@@ -83,14 +85,14 @@ for (let n = 0; n < 256; n += 1) {
8385
assert.throws(
8486
() => crypto.createCipheriv('aes-128-cbc', Buffer.alloc(16),
8587
Buffer.alloc(n)),
86-
/Invalid IV length/);
88+
errMessage);
8789
}
8890

8991
// Zero-sized IV should be rejected in GCM mode.
9092
assert.throws(
9193
() => crypto.createCipheriv('aes-128-gcm', Buffer.alloc(16),
9294
Buffer.alloc(0)),
93-
/Invalid IV length/);
95+
errMessage);
9496

9597
// But all other IV lengths should be accepted.
9698
for (let n = 1; n < 256; n += 1) {

test/parallel/test-crypto-dh.js

+6-5
Original file line numberDiff line numberDiff line change
@@ -295,14 +295,15 @@ if (availableCurves.has('prime256v1') && availableCurves.has('secp256k1')) {
295295
// rejected.
296296
ecdh5.setPrivateKey(cafebabeKey, 'hex');
297297

298-
[ // Some invalid private keys for the secp256k1 curve.
299-
'0000000000000000000000000000000000000000000000000000000000000000',
300-
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141',
301-
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',
298+
// Some invalid private keys for the secp256k1 curve.
299+
const errMessage = /^Error: Private key is not valid for specified curve\.$/;
300+
['0000000000000000000000000000000000000000000000000000000000000000',
301+
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141',
302+
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',
302303
].forEach((element) => {
303304
assert.throws(() => {
304305
ecdh5.setPrivateKey(element, 'hex');
305-
}, /^Error: Private key is not valid for specified curve\.$/);
306+
}, errMessage);
306307
// Verify object state did not change.
307308
assert.strictEqual(ecdh5.getPrivateKey('hex'), cafebabeKey);
308309
});

0 commit comments

Comments
 (0)