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 <cjihrig@gmail.com>
1 parent 910fa50 commit 9cfec4b

40 files changed

Lines changed: 195 additions & 172 deletions

‎test/common/index.js‎

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

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

‎test/debugger/helper-debugger-repl.js‎

Lines changed: 2 additions & 2 deletions
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
constexpectedLine=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
constcallback=expected[0].callback;

‎test/doctool/test-doctool-html.js‎

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

83+
constspaces=/\s/g;
84+
8385
testData.forEach((item)=>{
8486
// Normalize expected data by stripping whitespace
85-
constexpected=item.html.replace(/\s/g,'');
87+
constexpected=item.html.replace(spaces,'');
8688
constincludeAnalytics=typeofitem.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-
constactual=output.replace(/\s/g,'');
106+
constactual=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‎

Lines changed: 2 additions & 2 deletions
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
functioncheckVersion(err,response){

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,5 @@ const util = require('util');
1919

2020
{
2121
constbuf=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‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ const syntaxArgs = [
1313
['--check']
1414
];
1515

16+
constsyntaxErrorRE=/^SyntaxError:Unexpectedidentifier$/m;
17+
constnotFoundRE=/^Error:Cannotfindmodule/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-
constmatch=c.stderr.match(/^SyntaxError:Unexpectedidentifier$/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-
constmatch=c.stderr.match(/^Error:Cannotfindmodule/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‎

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

310+
consterrMessages={
311+
auth: /auth/,
312+
state: /state/,
313+
FIPS: /notsupportedinFIPSmode/,
314+
length: /InvalidIVlength/,
315+
};
316+
310317
constciphers=crypto.getCiphers();
311318

312319
for(constiinTEST_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-
/notsupportedinFIPSmode/);
374+
errMessages.FIPS);
368375
}else{
369376
constencrypt=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-
/notsupportedinFIPSmode/);
393+
errMessages.FIPS);
387394
}else{
388395
constdecrypt=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
constdecrypt=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-
},/InvalidIVlength/);
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‎

Lines changed: 5 additions & 3 deletions
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+
consterrMessage=/InvalidIVlength/;
70+
6971
// But non-empty IVs should be rejected.
7072
for(letn=1;n<256;n+=1){
7173
assert.throws(
7274
()=>crypto.createCipheriv('aes-128-ecb',Buffer.alloc(16),
7375
Buffer.alloc(n)),
74-
/InvalidIVlength/);
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-
/InvalidIVlength/);
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-
/InvalidIVlength/);
95+
errMessage);
9496

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

‎test/parallel/test-crypto-dh.js‎

Lines changed: 6 additions & 5 deletions
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+
consterrMessage=/^Error:Privatekeyisnotvalidforspecifiedcurve.$/;
285+
['0000000000000000000000000000000000000000000000000000000000000000',
286+
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141',
287+
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',
287288
].forEach((element)=>{
288289
assert.throws(()=>{
289290
ecdh5.setPrivateKey(element,'hex');
290-
},/^Error:Privatekeyisnotvalidforspecifiedcurve.$/);
291+
},errMessage);
291292
// Verify object state did not change.
292293
assert.strictEqual(ecdh5.getPrivateKey('hex'),cafebabeKey);
293294
});

‎test/parallel/test-crypto.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,8 @@ validateList(cryptoCiphers);
7878
consttlsCiphers=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+
constnoCapitals=/^[^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.

0 commit comments

Comments
 (0)