summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorVse Mozhet Byt <vsemozhetbyt@gmail.com>2017-06-18 16:22:32 +0300
committerMyles Borins <mylesborins@google.com>2017-07-30 23:11:11 -0500
commit9cfec4ba0fd8d3841fcca3b10f1f056c50327c52 (patch)
treea253a0313931da4ca3089305c5a51a6445327749
parent910fa50e0ebade03fc0f0c5809c2b5a275679df5 (diff)
downloadnode-new-9cfec4ba0fd8d3841fcca3b10f1f056c50327c52.tar.gz
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: https://github.com/nodejs/node/pull/14370 PR-URL: https://github.com/nodejs/node/pull/13770 Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
-rw-r--r--test/common/index.js3
-rw-r--r--test/debugger/helper-debugger-repl.js4
-rw-r--r--test/doctool/test-doctool-html.js6
-rw-r--r--test/inspector/test-inspector.js4
-rw-r--r--test/parallel/test-buffer-prototype-inspect.js2
-rw-r--r--test/parallel/test-cli-syntax.js9
-rw-r--r--test/parallel/test-crypto-authenticated.js28
-rw-r--r--test/parallel/test-crypto-cipheriv-decipheriv.js8
-rw-r--r--test/parallel/test-crypto-dh.js11
-rw-r--r--test/parallel/test-crypto.js3
-rw-r--r--test/parallel/test-error-reporting.js12
-rw-r--r--test/parallel/test-event-emitter-max-listeners.js14
-rw-r--r--test/parallel/test-fs-null-bytes.js2
-rw-r--r--test/parallel/test-fs-read-stream-throw-type-error.js11
-rw-r--r--test/parallel/test-global-console-exists.js2
-rw-r--r--test/parallel/test-http-client-unescaped-path.js4
-rw-r--r--test/parallel/test-http-server.js4
-rw-r--r--test/parallel/test-path.js11
-rw-r--r--test/parallel/test-process-chdir.js7
-rw-r--r--test/parallel/test-process-emitwarning.js2
-rw-r--r--test/parallel/test-process-setuid-setgid.js4
-rw-r--r--test/parallel/test-repl.js4
-rw-r--r--test/parallel/test-require-json.js6
-rw-r--r--test/parallel/test-stream-readable-invalid-chunk.js7
-rw-r--r--test/parallel/test-string-decoder.js3
-rw-r--r--test/parallel/test-timers-throw-when-cb-not-function.js56
-rw-r--r--test/parallel/test-tls-client-mindhsize.js7
-rw-r--r--test/parallel/test-tls-env-bad-extra-ca.js5
-rw-r--r--test/parallel/test-tls-no-sslv23.js16
-rw-r--r--test/parallel/test-tls-passphrase.js18
-rw-r--r--test/parallel/test-tls-server-failed-handshake-emits-clienterror.js6
-rw-r--r--test/parallel/test-tls-socket-failed-handshake-emits-error.js6
-rw-r--r--test/parallel/test-util-inspect.js3
-rw-r--r--test/parallel/test-util-internal.js35
-rw-r--r--test/parallel/test-util-log.js2
-rw-r--r--test/parallel/test-zlib-truncated.js6
-rw-r--r--test/pummel/test-net-pingpong.js2
-rw-r--r--test/sequential/test-module-loading.js8
-rw-r--r--test/sequential/test-process-warnings.js8
-rw-r--r--test/sequential/test-regress-GH-784.js18
40 files changed, 195 insertions, 172 deletions
diff --git a/test/common/index.js b/test/common/index.js
index a4f61e9ccc..455d50fe6c 100644
--- a/test/common/index.js
+++ b/test/common/index.js
@@ -196,8 +196,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';
});
});
diff --git a/test/debugger/helper-debugger-repl.js b/test/debugger/helper-debugger-repl.js
index 4c1bf68594..ca2dd37e83 100644
--- a/test/debugger/helper-debugger-repl.js
+++ b/test/debugger/helper-debugger-repl.js
@@ -30,12 +30,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 58ec2bc731..b28d34b57e 100644
--- a/test/doctool/test-doctool-html.js
+++ b/test/doctool/test-doctool-html.js
@@ -80,9 +80,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) => {
@@ -101,7 +103,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/test-inspector.js b/test/inspector/test-inspector.js
index f4de8bbc28..59d6d4cf71 100644
--- a/test/inspector/test-inspector.js
+++ b/test/inspector/test-inspector.js
@@ -10,8 +10,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-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(/^<Buffer (78 ){50}\.\.\. >$/.test(util.inspect(buf)));
+ assert.ok(/^<Buffer (?:78 ){50}\.\.\. >$/.test(util.inspect(buf)));
}
diff --git a/test/parallel/test-cli-syntax.js b/test/parallel/test-cli-syntax.js
index 1986c117ab..6426a5803c 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',
@@ -53,8 +56,7 @@ const syntaxArgs = [
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}`);
});
@@ -76,8 +78,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}`);
});
diff --git a/test/parallel/test-crypto-authenticated.js b/test/parallel/test-crypto-authenticated.js
index 5caaf121a5..b92d6d681d 100644
--- a/test/parallel/test-crypto-authenticated.js
+++ b/test/parallel/test-crypto-authenticated.js
@@ -307,6 +307,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) {
@@ -357,14 +364,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)
@@ -383,7 +390,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'));
@@ -395,7 +402,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);
}
}
}
@@ -406,7 +413,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);
}
{
@@ -415,7 +422,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);
}
{
@@ -423,7 +430,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);
}
{
@@ -434,7 +441,7 @@ for (const i in TEST_CASES) {
Buffer.from(test.key, 'hex'),
Buffer.alloc(0)
);
- }, /Invalid IV length/);
+ }, errMessages.length);
}
}
@@ -446,6 +453,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 6f22dbe71a..7c1fad34bf 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 9e1226efaf..ccc30353af 100644
--- a/test/parallel/test-crypto-dh.js
+++ b/test/parallel/test-crypto-dh.js
@@ -280,14 +280,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.js b/test/parallel/test-crypto.js
index 4a08463ca3..a923694f3d 100644
--- a/test/parallel/test-crypto.js
+++ b/test/parallel/test-crypto.js
@@ -78,7 +78,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-error-reporting.js b/test/parallel/test-error-reporting.js
index 965d7fbf77..73799cda48 100644
--- a/test/parallel/test-error-reporting.js
+++ b/test/parallel/test-error-reporting.js
@@ -21,6 +21,8 @@ function errExec(script, callback) {
});
}
+const syntaxErrorMessage = /SyntaxError/;
+
// Simple throw error
errExec('throws_error.js', common.mustCall(function(err, stdout, stderr) {
@@ -30,30 +32,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 0ace154aa0..2946c48f8f 100644
--- a/test/parallel/test-event-emitter-max-listeners.js
+++ b/test/parallel/test-event-emitter-max-listeners.js
@@ -9,16 +9,10 @@ e.on('maxListeners', common.mustCall(function() {}));
// Should not corrupt the 'maxListeners' queue.
e.setMaxListeners(42);
-assert.throws(function() {
- e.setMaxListeners(NaN);
-}, /^TypeError: "n" argument must be a positive number$/);
+const maxError = /^TypeError: "n" argument must be a positive number$/;
-assert.throws(function() {
- e.setMaxListeners(-1);
-}, /^TypeError: "n" argument must be a positive number$/);
-
-assert.throws(function() {
- e.setMaxListeners('and even this');
-}, /^TypeError: "n" argument must be a positive number$/);
+assert.throws(function() { e.setMaxListeners(NaN); }, maxError);
+assert.throws(function() { e.setMaxListeners(-1); }, maxError);
+assert.throws(function() { e.setMaxListeners('and even this'); }, maxError);
e.emit('maxListeners');
diff --git a/test/parallel/test-fs-null-bytes.js b/test/parallel/test-fs-null-bytes.js
index 24d5514eec..aa9935df29 100644
--- a/test/parallel/test-fs-null-bytes.js
+++ b/test/parallel/test-fs-null-bytes.js
@@ -7,7 +7,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 81f924d355..0eb2de6aca 100644
--- a/test/parallel/test-fs-read-stream-throw-type-error.js
+++ b/test/parallel/test-fs-read-stream-throw-type-error.js
@@ -16,18 +16,19 @@ assert.doesNotThrow(function() {
fs.createReadStream(example, {encoding: 'utf8'});
});
+const errMessage = /"options" argument must be a string or an object/;
assert.throws(function() {
fs.createReadStream(example, null);
-}, /"options" argument must be a string or an object/);
+}, errMessage);
assert.throws(function() {
fs.createReadStream(example, 123);
-}, /"options" argument must be a string or an object/);
+}, errMessage);
assert.throws(function() {
fs.createReadStream(example, 0);
-}, /"options" argument must be a string or an object/);
+}, errMessage);
assert.throws(function() {
fs.createReadStream(example, true);
-}, /"options" argument must be a string or an object/);
+}, errMessage);
assert.throws(function() {
fs.createReadStream(example, false);
-}, /"options" argument 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 d4a7c21222..fe77d42630 100644
--- a/test/parallel/test-global-console-exists.js
+++ b/test/parallel/test-global-console-exists.js
@@ -24,7 +24,7 @@ process.on('warning', (warning) => {
process.stderr.write = (data) => {
if (write_calls === 0)
- assert.ok(data.match(leak_warning));
+ assert.ok(leak_warning.test(data));
else
common.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 eb04a42d37..ce4db0c7cd 100644
--- a/test/parallel/test-http-client-unescaped-path.js
+++ b/test/parallel/test-http-client-unescaped-path.js
@@ -3,8 +3,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-server.js b/test/parallel/test-http-server.js
index 90c2709ebd..1bf6194874 100644
--- a/test/parallel/test-http-server.js
+++ b/test/parallel/test-http-server.js
@@ -95,10 +95,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-path.js b/test/parallel/test-path.js
index 9541cdcbb8..46f36e36e7 100644
--- a/test/parallel/test-path.js
+++ b/test/parallel/test-path.js
@@ -7,6 +7,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');
@@ -167,7 +170,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';
@@ -324,7 +327,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';
@@ -430,9 +433,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 651bdbd1ab..6d24865d3c 100644
--- a/test/parallel/test-process-emitwarning.js
+++ b/test/parallel/test-process-emitwarning.js
@@ -8,7 +8,7 @@ const util = require('util');
process.on('warning', common.mustCall((warning) => {
assert(warning);
- assert(/^(Warning|CustomWarning)/.test(warning.name));
+ assert(/^(?:Warning|CustomWarning)/.test(warning.name));
assert(warning.message, 'A Warning');
}, 7));
diff --git a/test/parallel/test-process-setuid-setgid.js b/test/parallel/test-process-setuid-setgid.js
index b60eb91366..33cb718eae 100644
--- a/test/parallel/test-process-setuid-setgid.js
+++ b/test/parallel/test-process-setuid-setgid.js
@@ -26,12 +26,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-repl.js b/test/parallel/test-repl.js
index 2b2cf1a199..2fc888de67 100644
--- a/test/parallel/test-repl.js
+++ b/test/parallel/test-repl.js
@@ -75,7 +75,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 = '';
@@ -358,7 +358,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 f2c74dc57d..1d0b10f84c 100644
--- a/test/parallel/test-require-json.js
+++ b/test/parallel/test-require-json.js
@@ -6,7 +6,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-stream-readable-invalid-chunk.js b/test/parallel/test-stream-readable-invalid-chunk.js
index d845b6114c..62cd103b02 100644
--- a/test/parallel/test-stream-readable-invalid-chunk.js
+++ b/test/parallel/test-stream-readable-invalid-chunk.js
@@ -7,6 +7,7 @@ const readable = new stream.Readable({
read: () => {}
});
-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 3879f2021b..b9fa47da52 100644
--- a/test/parallel/test-string-decoder.js
+++ b/test/parallel/test-string-decoder.js
@@ -127,6 +127,7 @@ function test(encoding, input, expected, singleSequence) {
} else {
sequences = [singleSequence];
}
+ const hexNumberRE = /.{2}/g;
sequences.forEach((sequence) => {
const decoder = new StringDecoder(encoding);
let output = '';
@@ -139,7 +140,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..f68134d760 100644
--- a/test/parallel/test-tls-client-mindhsize.js
+++ b/test/parallel/test-tls-client-mindhsize.js
@@ -78,13 +78,14 @@ 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/);
+ assert.throws(() => tls.connect({ minDHSize }), 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 4630fe236d..f2f6f5ccda 100644
--- a/test/parallel/test-tls-passphrase.js
+++ b/test/parallel/test-tls-passphrase.js
@@ -204,6 +204,8 @@ server.listen(0, common.mustCall(function() {
}, common.mustCall(function() {}));
})).unref();
+const errMessagePassword = /bad password read/;
+
// Missing passphrase
assert.throws(function() {
tls.connect({
@@ -212,7 +214,7 @@ assert.throws(function() {
cert: cert,
rejectUnauthorized: false
});
-}, /bad password read/);
+}, errMessagePassword);
assert.throws(function() {
tls.connect({
@@ -221,7 +223,7 @@ assert.throws(function() {
cert: cert,
rejectUnauthorized: false
});
-}, /bad password read/);
+}, errMessagePassword);
assert.throws(function() {
tls.connect({
@@ -230,7 +232,9 @@ assert.throws(function() {
cert: cert,
rejectUnauthorized: false
});
-}, /bad password read/);
+}, errMessagePassword);
+
+const errMessageDecrypt = /bad decrypt/;
// Invalid passphrase
assert.throws(function() {
@@ -241,7 +245,7 @@ assert.throws(function() {
cert: cert,
rejectUnauthorized: false
});
-}, /bad decrypt/);
+}, errMessageDecrypt);
assert.throws(function() {
tls.connect({
@@ -251,7 +255,7 @@ assert.throws(function() {
cert: cert,
rejectUnauthorized: false
});
-}, /bad decrypt/);
+}, errMessageDecrypt);
assert.throws(function() {
tls.connect({
@@ -261,7 +265,7 @@ assert.throws(function() {
cert: cert,
rejectUnauthorized: false
});
-}, /bad decrypt/);
+}, errMessageDecrypt);
assert.throws(function() {
tls.connect({
@@ -271,4 +275,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-util-inspect.js b/test/parallel/test-util-inspect.js
index 177d46f5f6..e3a65c895a 100644
--- a/test/parallel/test-util-inspect.js
+++ b/test/parallel/test-util-inspect.js
@@ -746,9 +746,10 @@ assert.strictEqual(util.inspect(keys), 'SetIterator { 1, 3 }');
function checkAlignment(container) {
const lines = util.inspect(container).split('\n');
+ const numRE = /\d/;
let pos;
lines.forEach(function(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 386e9a739c..49c74966a3 100644
--- a/test/parallel/test-util-internal.js
+++ b/test/parallel/test-util-internal.js
@@ -19,24 +19,27 @@ function setHiddenValue(obj, name, 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({}), /name must be a string/);
-assert.throws(getHiddenValue({}, null), /name must be a string/);
-assert.throws(getHiddenValue({}, []), /name must be a string/);
+const errMessageObj = /obj must be an object/;
+const errMessageStr = /name must be a string/;
+
+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({}), errMessageStr);
+assert.throws(getHiddenValue({}, null), errMessageStr);
+assert.throws(getHiddenValue({}, []), errMessageStr);
assert.deepStrictEqual(internalUtil.getHiddenValue({}, 'foo'), 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({}), /name must be a string/);
-assert.throws(setHiddenValue({}, null), /name must be a string/);
-assert.throws(setHiddenValue({}, []), /name must be a string/);
+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({}), errMessageStr);
+assert.throws(setHiddenValue({}, null), errMessageStr);
+assert.throws(setHiddenValue({}, []), errMessageStr);
const obj = {};
assert.strictEqual(internalUtil.setHiddenValue(obj, 'foo', 'bar'), true);
assert.strictEqual(internalUtil.getHiddenValue(obj, 'foo'), 'bar');
diff --git a/test/parallel/test-util-log.js b/test/parallel/test-util-log.js
index 3604b42820..38ae710a27 100644
--- a/test/parallel/test-util-log.js
+++ b/test/parallel/test-util-log.js
@@ -26,10 +26,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 517b63886f..22171a8f9c 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.Z_SYNC_FLUSH };
diff --git a/test/pummel/test-net-pingpong.js b/test/pummel/test-net-pingpong.js
index 1441c85ab6..35a836b4c8 100644
--- a/test/pummel/test-net-pingpong.js
+++ b/test/pummel/test-net-pingpong.js
@@ -31,7 +31,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 f12b766c98..8fd681cc65 100644
--- a/test/sequential/test-module-loading.js
+++ b/test/sequential/test-module-loading.js
@@ -4,6 +4,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.
@@ -158,7 +160,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);
@@ -166,7 +168,7 @@ assert.strictEqual(require(`${loadOrder}file6`).file6, 'file6/index.js', msg);
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);
assert.strictEqual(require(`${loadOrder}file9`).file9, 'file9/index.reg2', msg);
@@ -194,7 +196,7 @@ assert.deepStrictEqual(json, {
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 9eaa45bd38..558601c539 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\.<anonymous>\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 6278a7f446..f567b9bc52 100644
--- a/test/sequential/test-regress-GH-784.js
+++ b/test/sequential/test-regress-GH-784.js
@@ -49,28 +49,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;