Skip to content

Commit 8dc2bdd

Browse files
authored
test: use RegExp.escape to improve test reliability
PR-URL: #60803 Reviewed-By: LiviaMedeiros <[email protected]> Reviewed-By: Benjamin Gruenbaum <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Colin Ihrig <[email protected]>
1 parent d255fc7 commit 8dc2bdd

13 files changed

+26
-27
lines changed

test/common/assertSnapshot.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ function replaceTestDuration(str) {
109109

110110
const root = path.resolve(__dirname, '..', '..');
111111
const color = '(\\[\\d+m)';
112-
const stackTraceBasePath = new RegExp(`${color}\\(${root.replaceAll(/[\\^$*+?.()|[\]{}]/g, '\\$&')}/?${color}(.*)${color}\\)`, 'g');
112+
const stackTraceBasePath = new RegExp(`${color}\\(${RegExp.escape(root)}/?${color}(.*)${color}\\)`, 'g');
113113

114114
function replaceSpecDuration(str) {
115115
return str

test/parallel/test-crypto-argon2.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ for (const [algorithm, overrides, expected] of good) {
112112
for (const [algorithm, overrides, param] of bad) {
113113
const expected = {
114114
code: 'ERR_OUT_OF_RANGE',
115-
message: new RegExp(`The value of "${param}" is out of range`),
115+
message: new RegExp(`The value of "${RegExp.escape(param)}" is out of range`),
116116
};
117117
const parameters = { ...defaults, ...overrides };
118118
assert.throws(() => crypto.argon2(algorithm, parameters, () => {}), expected);
@@ -122,7 +122,7 @@ for (const [algorithm, overrides, param] of bad) {
122122
for (const key of Object.keys(defaults)) {
123123
const expected = {
124124
code: 'ERR_INVALID_ARG_TYPE',
125-
message: new RegExp(`"parameters\\.${key}"`),
125+
message: new RegExp(`"parameters\\.${RegExp.escape(key)}"`),
126126
};
127127
const parameters = { ...defaults };
128128
delete parameters[key];

test/parallel/test-crypto-x509.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ oans248kpal88CGqsN2so/wZKxVnpiXlPHMdiNL7hRSUqlHkUi07FrP2Htg8kjI=
296296
'OCSP - URI': ['http://ocsp.nodejs.org/'],
297297
'CA Issuers - URI': ['http://ca.nodejs.org/ca.cert']
298298
}),
299-
modulusPattern: new RegExp(`^${modulusOSSL}$`, 'i'),
299+
modulusPattern: new RegExp(`^${RegExp.escape(modulusOSSL)}$`, 'i'),
300300
bits: 2048,
301301
exponent: '0x10001',
302302
valid_from: 'Sep 3 21:40:37 2022 GMT',

test/parallel/test-module-loading-globalpaths.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ if (process.argv[2] === 'child') {
5454
child_process.execFileSync(testExecPath, [ __filename, 'child' ],
5555
{ encoding: 'utf8', env: env });
5656
},
57-
new RegExp(`Cannot find module '${pkgName}'`));
57+
new RegExp(`Cannot find module '${RegExp.escape(pkgName)}'`));
5858

5959
// Test module in $HOME/.node_modules.
6060
const modHomeDir = path.join(testFixturesDir, 'home-pkg-in-node_modules');

test/parallel/test-permission-warning-flags.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,6 @@ for (const flag of warnFlags) {
2121
]
2222
);
2323

24-
assert.match(stderr.toString(), new RegExp(`SecurityWarning: The flag ${flag} must be used with extreme caution`));
24+
assert.match(stderr.toString(), new RegExp(`SecurityWarning: The flag ${RegExp.escape(flag)} must be used with extreme caution`));
2525
assert.strictEqual(status, 0);
2626
}

test/parallel/test-process-env-allowed-flags-are-documented.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ const cliMd = path.join(rootDir, 'doc', 'api', 'cli.md');
1212
const cliText = fs.readFileSync(cliMd, { encoding: 'utf8' });
1313

1414
const parseSection = (text, startMarker, endMarker) => {
15-
const regExp = new RegExp(`${startMarker}\r?\n([^]*)\r?\n${endMarker}`);
15+
const regExp = new RegExp(`${RegExp.escape(startMarker)}\r?\n([^]*)\r?\n${RegExp.escape(endMarker)}`);
1616
const match = text.match(regExp);
1717
assert(match,
1818
`Unable to locate text between '${startMarker}' and '${endMarker}'.`);

test/parallel/test-quic-internal-endpoint-options.mjs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ for (const { key, valid, invalid } of cases) {
148148
const options = {};
149149
options[key] = value;
150150
throws(() => new QuicEndpoint(options), {
151-
message: new RegExp(`${key}`),
151+
message: new RegExp(`${RegExp.escape(key)}`),
152152
}, value);
153153
}
154154
}

test/parallel/test-release-changelog.js

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ const fs = require('fs');
88
const path = require('path');
99

1010
const getDefine = (text, name) => {
11-
const regexp = new RegExp(`#define\\s+${name}\\s+(.*)`);
11+
const regexp = new RegExp(`#define\\s+${RegExp.escape(name)}\\s+(.*)`);
1212
const match = regexp.exec(text);
1313
assert.notStrictEqual(match, null);
1414
return match[1];
@@ -27,7 +27,7 @@ if (!release) {
2727
const major = getDefine(versionText, 'NODE_MAJOR_VERSION');
2828
const minor = getDefine(versionText, 'NODE_MINOR_VERSION');
2929
const patch = getDefine(versionText, 'NODE_PATCH_VERSION');
30-
const versionForRegex = `${major}\\.${minor}\\.${patch}`;
30+
const versionForRegex = RegExp.escape(`${major}.${minor}.${patch}`);
3131

3232
const lts = getDefine(versionText, 'NODE_VERSION_IS_LTS') !== '0';
3333
const codename = getDefine(versionText, 'NODE_VERSION_LTS_CODENAME').slice(1, -1);
@@ -45,7 +45,7 @@ const changelogPath = `doc/changelogs/CHANGELOG_V${major}.md`;
4545
// Check table header
4646
let tableHeader;
4747
if (lts) {
48-
tableHeader = new RegExp(`<th>LTS '${codename}'</th>`);
48+
tableHeader = new RegExp(`<th>LTS '${RegExp.escape(codename)}'</th>`);
4949
} else {
5050
tableHeader = /<th>Current<\/th>/;
5151
}
@@ -57,7 +57,7 @@ const changelogPath = `doc/changelogs/CHANGELOG_V${major}.md`;
5757
// Check title for changelog entry.
5858
let title;
5959
if (lts) {
60-
title = new RegExp(`## \\d{4}-\\d{2}-\\d{2}, Version ${versionForRegex} '${codename}' \\(LTS\\), @\\S+`);
60+
title = new RegExp(`## \\d{4}-\\d{2}-\\d{2}, Version ${versionForRegex} '${RegExp.escape(codename)}' \\(LTS\\), @\\S+`);
6161
} else {
6262
title = new RegExp(`## \\d{4}-\\d{2}-\\d{2}, Version ${versionForRegex} \\(Current\\), @\\S+`);
6363
}
@@ -70,20 +70,20 @@ const changelogPath = `doc/changelogs/CHANGELOG_V${major}.md`;
7070
// Check for the link to the appropriate CHANGELOG_V*.md file.
7171
let linkToChangelog;
7272
if (lts) {
73-
linkToChangelog = new RegExp(`\\[Node\\.js ${major}\\]\\(${changelogPath}\\) \\*\\*Long Term Support\\*\\*`);
73+
linkToChangelog = new RegExp(`\\[Node\\.js ${major}\\]\\(${RegExp.escape(changelogPath)}\\) \\*\\*Long Term Support\\*\\*`);
7474
} else {
75-
linkToChangelog = new RegExp(`\\[Node\\.js ${major}\\]\\(${changelogPath}\\) \\*\\*Current\\*\\*`);
75+
linkToChangelog = new RegExp(`\\[Node\\.js ${major}\\]\\(${RegExp.escape(changelogPath)}\\) \\*\\*Current\\*\\*`);
7676
}
7777
assert.match(mainChangelog, linkToChangelog);
7878
// Check table header.
7979
let tableHeader;
8080
if (lts) {
81-
tableHeader = new RegExp(`<th title="LTS Until \\d{4}-\\d{2}"><a href="${changelogPath}">${major}</a> \\(LTS\\)</th>`);
81+
tableHeader = new RegExp(`<th title="LTS Until \\d{4}-\\d{2}"><a href="${RegExp.escape(changelogPath)}">${major}</a> \\(LTS\\)</th>`);
8282
} else {
83-
tableHeader = new RegExp(`<th title="Current"><a href="${changelogPath}">${major}</a> \\(Current\\)</th>`);
83+
tableHeader = new RegExp(`<th title="Current"><a href="${RegExp.escape(changelogPath)}">${major}</a> \\(Current\\)</th>`);
8484
}
8585
assert.match(mainChangelog, tableHeader);
8686
// Check the table contains a link to the release in the appropriate CHANGELOG_V*.md file.
87-
const linkToVersion = new RegExp(`<b><a href="${changelogPath}#${versionForRegex}">${versionForRegex}</a></b><br/>`);
87+
const linkToVersion = new RegExp(`<b><a href="${RegExp.escape(changelogPath)}#${versionForRegex}">${versionForRegex}</a></b><br/>`);
8888
assert.match(mainChangelog, linkToVersion);
8989
}

test/parallel/test-repl-custom-eval-previews.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ describe('with previews', () => {
4545
);
4646
const lines = getSingleCommandLines(output);
4747
assert.match(lines.command, /^'Hello custom' \+ ' eval World!'/);
48-
assert.match(lines.prompt, new RegExp(`${testingReplPrompt}$`));
48+
assert.match(lines.prompt, new RegExp(`${RegExp.escape(testingReplPrompt)}$`));
4949
assert.strictEqual(lines.result, "'Hello custom eval World!'");
5050
assert.strictEqual(lines.preview, undefined);
5151
});
@@ -62,7 +62,7 @@ describe('with previews', () => {
6262
);
6363
const lines = getSingleCommandLines(output);
6464
assert.match(lines.command, /^'Hello custom' \+ ' eval World!'/);
65-
assert.match(lines.prompt, new RegExp(`${testingReplPrompt}$`));
65+
assert.match(lines.prompt, new RegExp(`${RegExp.escape(testingReplPrompt)}$`));
6666
assert.strictEqual(lines.result, "'Hello custom eval World!'");
6767
assert.match(lines.preview, /'Hello custom eval World!'/);
6868
});

test/parallel/test-util-inspect.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2912,11 +2912,10 @@ assert.strictEqual(
29122912
frame.replaceAll('/', '\\'))
29132913
).join('\n');
29142914
}
2915-
const escapedCWD = util.inspect(process.cwd()).slice(1, -1);
29162915
util.inspect(err, { colors: true }).split('\n').forEach(common.mustCallAtLeast((line, i) => {
29172916
let expected = stack[i].replace(/node_modules\/(@[^/]+\/[^/]+|[^/]+)/gi, (_, m) => {
29182917
return `node_modules/\u001b[4m${m}\u001b[24m`;
2919-
}).replaceAll(new RegExp(`(\\(?${escapedCWD}(\\\\|/))`, 'gi'), (_, m) => {
2918+
}).replaceAll(new RegExp(`(\\(?${RegExp.escape(process.cwd())}(\\\\|/))`, 'gi'), (_, m) => {
29202919
return `\x1B[90m${m}\x1B[39m`;
29212920
});
29222921
if (expected.includes(process.cwd()) && expected.endsWith(')')) {

0 commit comments

Comments
 (0)