Skip to content

Commit 9cfec4b

Browse files
vsemozhetbytMylesBorins
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. Backport-PR-URL: #14370 PR-URL: #13770 Reviewed-By: Colin Ihrig <[email protected]>
1 parent 910fa50 commit 9cfec4b

40 files changed

+195
-172
lines changed

test/common/index.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -196,8 +196,9 @@ if (exports.isWindows) {
196196
}
197197

198198
const ifaces = os.networkInterfaces();
199+
const re = /lo/;
199200
exports.hasIPv6 = Object.keys(ifaces).some(function(name) {
200-
return /lo/.test(name) && ifaces[name].some(function(info) {
201+
return re.test(name) && ifaces[name].some(function(info) {
201202
return info.family === 'IPv6';
202203
});
203204
});

test/debugger/helper-debugger-repl.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,12 @@ function startDebugger(scriptToDebug) {
3030
child.stderr.pipe(process.stderr);
3131

3232
child.on('line', function(line) {
33-
line = line.replace(/^(debug> *)+/, '');
33+
line = line.replace(/^(?:debug> *)+/, '');
3434
console.log(line);
3535
assert.ok(expected.length > 0, `Got unexpected line: ${line}`);
3636

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

4040
if (expected[0].lines.length === 0) {
4141
const callback = expected[0].callback;

test/doctool/test-doctool-html.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,11 @@ const testData = [
8080
},
8181
];
8282

83+
const spaces = /\s/g;
84+
8385
testData.forEach((item) => {
8486
// Normalize expected data by stripping whitespace
85-
const expected = item.html.replace(/\s/g, '');
87+
const expected = item.html.replace(spaces, '');
8688
const includeAnalytics = typeof item.analyticsId !== 'undefined';
8789

8890
fs.readFile(item.file, 'utf8', common.mustCall((err, input) => {
@@ -101,7 +103,7 @@ testData.forEach((item) => {
101103
common.mustCall((err, output) => {
102104
assert.ifError(err);
103105

104-
const actual = output.replace(/\s/g, '');
106+
const actual = output.replace(spaces, '');
105107
// Assert that the input stripped of all whitespace contains the
106108
// expected list
107109
assert.notStrictEqual(actual.indexOf(expected), -1);

test/inspector/test-inspector.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ function checkListResponse(err, response) {
1010
assert.strictEqual(1, response.length);
1111
assert.ok(response[0]['devtoolsFrontendUrl']);
1212
assert.ok(
13-
response[0]['webSocketDebuggerUrl']
14-
.match(/ws:\/\/127.0.0.1:\d+\/[0-9A-Fa-f]{8}-/));
13+
/ws:\/\/127.0.0.1:\d+\/[0-9A-Fa-f]{8}-/
14+
.test(response[0]['webSocketDebuggerUrl']));
1515
}
1616

1717
function checkVersion(err, response) {

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-cli-syntax.js

+5-4
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',
@@ -53,8 +56,7 @@ const syntaxArgs = [
5356
assert.strictEqual(c.stdout, '', 'stdout produced');
5457

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

5961
assert.strictEqual(c.status, 1, `code == ${c.status}`);
6062
});
@@ -76,8 +78,7 @@ const syntaxArgs = [
7678
assert.strictEqual(c.stdout, '', 'stdout produced');
7779

7880
// stderr should have a module not found error message
79-
const match = c.stderr.match(/^Error: Cannot find module/m);
80-
assert(match, 'stderr incorrect');
81+
assert(notFoundRE.test(c.stderr), 'stderr incorrect');
8182

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

test/parallel/test-crypto-authenticated.js

+18-10
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,13 @@ const TEST_CASES = [
307307
tag: 'a44a8266ee1c8eb0c8b5d4cf5ae9f19a', tampered: false },
308308
];
309309

310+
const errMessages = {
311+
auth: / auth/,
312+
state: / state/,
313+
FIPS: /not supported in FIPS mode/,
314+
length: /Invalid IV length/,
315+
};
316+
310317
const ciphers = crypto.getCiphers();
311318

312319
for (const i in TEST_CASES) {
@@ -357,14 +364,14 @@ for (const i in TEST_CASES) {
357364
assert.strictEqual(msg, test.plain);
358365
} else {
359366
// assert that final throws if input data could not be verified!
360-
assert.throws(function() { decrypt.final('ascii'); }, / auth/);
367+
assert.throws(function() { decrypt.final('ascii'); }, errMessages.auth);
361368
}
362369
}
363370

364371
if (test.password) {
365372
if (common.hasFipsCrypto) {
366373
assert.throws(() => { crypto.createCipher(test.algo, test.password); },
367-
/not supported in FIPS mode/);
374+
errMessages.FIPS);
368375
} else {
369376
const encrypt = crypto.createCipher(test.algo, test.password);
370377
if (test.aad)
@@ -383,7 +390,7 @@ for (const i in TEST_CASES) {
383390
if (test.password) {
384391
if (common.hasFipsCrypto) {
385392
assert.throws(() => { crypto.createDecipher(test.algo, test.password); },
386-
/not supported in FIPS mode/);
393+
errMessages.FIPS);
387394
} else {
388395
const decrypt = crypto.createDecipher(test.algo, test.password);
389396
decrypt.setAuthTag(Buffer.from(test.tag, 'hex'));
@@ -395,7 +402,7 @@ for (const i in TEST_CASES) {
395402
assert.strictEqual(msg, test.plain);
396403
} else {
397404
// assert that final throws if input data could not be verified!
398-
assert.throws(function() { decrypt.final('ascii'); }, / auth/);
405+
assert.throws(function() { decrypt.final('ascii'); }, errMessages.auth);
399406
}
400407
}
401408
}
@@ -406,7 +413,7 @@ for (const i in TEST_CASES) {
406413
Buffer.from(test.key, 'hex'),
407414
Buffer.from(test.iv, 'hex'));
408415
encrypt.update('blah', 'ascii');
409-
assert.throws(function() { encrypt.getAuthTag(); }, / state/);
416+
assert.throws(function() { encrypt.getAuthTag(); }, errMessages.state);
410417
}
411418

412419
{
@@ -415,15 +422,15 @@ for (const i in TEST_CASES) {
415422
Buffer.from(test.key, 'hex'),
416423
Buffer.from(test.iv, 'hex'));
417424
assert.throws(() => { encrypt.setAuthTag(Buffer.from(test.tag, 'hex')); },
418-
/ state/);
425+
errMessages.state);
419426
}
420427

421428
{
422429
// trying to read tag from decryption object:
423430
const decrypt = crypto.createDecipheriv(test.algo,
424431
Buffer.from(test.key, 'hex'),
425432
Buffer.from(test.iv, 'hex'));
426-
assert.throws(function() { decrypt.getAuthTag(); }, / state/);
433+
assert.throws(function() { decrypt.getAuthTag(); }, errMessages.state);
427434
}
428435

429436
{
@@ -434,7 +441,7 @@ for (const i in TEST_CASES) {
434441
Buffer.from(test.key, 'hex'),
435442
Buffer.alloc(0)
436443
);
437-
}, /Invalid IV length/);
444+
}, errMessages.length);
438445
}
439446
}
440447

@@ -446,6 +453,7 @@ for (const i in TEST_CASES) {
446453
'6fKjEjR3Vl30EUYC');
447454
encrypt.update('blah', 'ascii');
448455
encrypt.final();
449-
assert.throws(() => encrypt.getAuthTag(), / state/);
450-
assert.throws(() => encrypt.setAAD(Buffer.from('123', 'ascii')), / state/);
456+
assert.throws(() => encrypt.getAuthTag(), errMessages.state);
457+
assert.throws(() => encrypt.setAAD(Buffer.from('123', 'ascii')),
458+
errMessages.state);
451459
}

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
@@ -280,14 +280,15 @@ if (availableCurves.has('prime256v1') && availableCurves.has('secp256k1')) {
280280
// rejected.
281281
ecdh5.setPrivateKey(cafebabeKey, 'hex');
282282

283-
[ // Some invalid private keys for the secp256k1 curve.
284-
'0000000000000000000000000000000000000000000000000000000000000000',
285-
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141',
286-
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',
283+
// Some invalid private keys for the secp256k1 curve.
284+
const errMessage = /^Error: Private key is not valid for specified curve.$/;
285+
['0000000000000000000000000000000000000000000000000000000000000000',
286+
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141',
287+
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',
287288
].forEach((element) => {
288289
assert.throws(() => {
289290
ecdh5.setPrivateKey(element, 'hex');
290-
}, /^Error: Private key is not valid for specified curve.$/);
291+
}, errMessage);
291292
// Verify object state did not change.
292293
assert.strictEqual(ecdh5.getPrivateKey('hex'), cafebabeKey);
293294
});

test/parallel/test-crypto.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,8 @@ validateList(cryptoCiphers);
7878
const tlsCiphers = tls.getCiphers();
7979
assert(tls.getCiphers().includes('aes256-sha'));
8080
// There should be no capital letters in any element.
81-
assert(tlsCiphers.every((value) => /^[^A-Z]+$/.test(value)));
81+
const noCapitals = /^[^A-Z]+$/;
82+
assert(tlsCiphers.every((value) => noCapitals.test(value)));
8283
validateList(tlsCiphers);
8384

8485
// Assert that we have sha and sha1 but not SHA and SHA1.

test/parallel/test-error-reporting.js

+7-5
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ function errExec(script, callback) {
2121
});
2222
}
2323

24+
const syntaxErrorMessage = /SyntaxError/;
25+
2426

2527
// Simple throw error
2628
errExec('throws_error.js', common.mustCall(function(err, stdout, stderr) {
@@ -30,30 +32,30 @@ errExec('throws_error.js', common.mustCall(function(err, stdout, stderr) {
3032

3133
// Trying to JSON.parse(undefined)
3234
errExec('throws_error2.js', common.mustCall(function(err, stdout, stderr) {
33-
assert.ok(/SyntaxError/.test(stderr));
35+
assert.ok(syntaxErrorMessage.test(stderr));
3436
}));
3537

3638

3739
// Trying to JSON.parse(undefined) in nextTick
3840
errExec('throws_error3.js', common.mustCall(function(err, stdout, stderr) {
39-
assert.ok(/SyntaxError/.test(stderr));
41+
assert.ok(syntaxErrorMessage.test(stderr));
4042
}));
4143

4244

4345
// throw ILLEGAL error
4446
errExec('throws_error4.js', common.mustCall(function(err, stdout, stderr) {
4547
assert.ok(/\/\*\*/.test(stderr));
46-
assert.ok(/SyntaxError/.test(stderr));
48+
assert.ok(syntaxErrorMessage.test(stderr));
4749
}));
4850

4951
// Specific long exception line doesn't result in stack overflow
5052
errExec('throws_error5.js', common.mustCall(function(err, stdout, stderr) {
51-
assert.ok(/SyntaxError/.test(stderr));
53+
assert.ok(syntaxErrorMessage.test(stderr));
5254
}));
5355

5456
// Long exception line with length > errorBuffer doesn't result in assertion
5557
errExec('throws_error6.js', common.mustCall(function(err, stdout, stderr) {
56-
assert.ok(/SyntaxError/.test(stderr));
58+
assert.ok(syntaxErrorMessage.test(stderr));
5759
}));
5860

5961
// Object that throws in toString() doesn't print garbage

test/parallel/test-event-emitter-max-listeners.js

+4-10
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,10 @@ e.on('maxListeners', common.mustCall(function() {}));
99
// Should not corrupt the 'maxListeners' queue.
1010
e.setMaxListeners(42);
1111

12-
assert.throws(function() {
13-
e.setMaxListeners(NaN);
14-
}, /^TypeError: "n" argument must be a positive number$/);
12+
const maxError = /^TypeError: "n" argument must be a positive number$/;
1513

16-
assert.throws(function() {
17-
e.setMaxListeners(-1);
18-
}, /^TypeError: "n" argument must be a positive number$/);
19-
20-
assert.throws(function() {
21-
e.setMaxListeners('and even this');
22-
}, /^TypeError: "n" argument must be a positive number$/);
14+
assert.throws(function() { e.setMaxListeners(NaN); }, maxError);
15+
assert.throws(function() { e.setMaxListeners(-1); }, maxError);
16+
assert.throws(function() { e.setMaxListeners('and even this'); }, maxError);
2317

2418
e.emit('maxListeners');

test/parallel/test-fs-null-bytes.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ function check(async, sync) {
77
const expected = /Path must be a string without null bytes/;
88
const argsSync = Array.prototype.slice.call(arguments, 2);
99
const argsAsync = argsSync.concat((er) => {
10-
assert(er && er.message.match(expected));
10+
assert(er && expected.test(er.message));
1111
assert.strictEqual(er.code, 'ENOENT');
1212
});
1313

test/parallel/test-fs-read-stream-throw-type-error.js

+6-5
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,19 @@ assert.doesNotThrow(function() {
1616
fs.createReadStream(example, {encoding: 'utf8'});
1717
});
1818

19+
const errMessage = /"options" argument must be a string or an object/;
1920
assert.throws(function() {
2021
fs.createReadStream(example, null);
21-
}, /"options" argument must be a string or an object/);
22+
}, errMessage);
2223
assert.throws(function() {
2324
fs.createReadStream(example, 123);
24-
}, /"options" argument must be a string or an object/);
25+
}, errMessage);
2526
assert.throws(function() {
2627
fs.createReadStream(example, 0);
27-
}, /"options" argument must be a string or an object/);
28+
}, errMessage);
2829
assert.throws(function() {
2930
fs.createReadStream(example, true);
30-
}, /"options" argument must be a string or an object/);
31+
}, errMessage);
3132
assert.throws(function() {
3233
fs.createReadStream(example, false);
33-
}, /"options" argument must be a string or an object/);
34+
}, errMessage);

test/parallel/test-global-console-exists.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ process.on('warning', (warning) => {
2424

2525
process.stderr.write = (data) => {
2626
if (write_calls === 0)
27-
assert.ok(data.match(leak_warning));
27+
assert.ok(leak_warning.test(data));
2828
else
2929
common.fail('stderr.write should be called only once');
3030

test/parallel/test-http-client-unescaped-path.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ const common = require('../common');
33
const assert = require('assert');
44
const http = require('http');
55

6+
const errMessage = /contains unescaped characters/;
67
for (let i = 0; i <= 32; i += 1) {
78
const path = `bad${String.fromCharCode(i)}path`;
8-
assert.throws(() => http.get({ path }, common.mustNotCall()),
9-
/contains unescaped characters/);
9+
assert.throws(() => http.get({ path }, common.mustNotCall()), errMessage);
1010
}

test/parallel/test-http-server.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,10 @@ process.on('exit', function() {
9595
assert.strictEqual(4, requests_sent);
9696

9797
const hello = new RegExp('/hello');
98-
assert.notStrictEqual(null, hello.exec(server_response));
98+
assert.ok(hello.test(server_response));
9999

100100
const quit = new RegExp('/quit');
101-
assert.notStrictEqual(null, quit.exec(server_response));
101+
assert.ok(quit.test(server_response));
102102

103103
assert.strictEqual(true, client_got_eof);
104104
});

0 commit comments

Comments
 (0)