Skip to content

Commit adb9280

Browse files
aduh95targos
authored andcommitted
test: fix some assumptions in tests
Some tests are assuming they will be run from a directory that do not contain any quote or special character in its path. That assumption is not necessary, using `JSON.stringify` or `pathToFileURL` ensures the test can be run whatever the path looks like. PR-URL: #48958 Backport-PR-URL: #50669 Reviewed-By: Moshe Atlow <[email protected]> Reviewed-By: Michaël Zasso <[email protected]>
1 parent 48c25b1 commit adb9280

9 files changed

+23
-21
lines changed

test/es-module/test-esm-dynamic-import.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
'use strict';
22
const common = require('../common');
3+
const { pathToFileURL } = require('url');
34
const assert = require('assert');
45

56
const relativePath = '../fixtures/es-modules/test-esm-ok.mjs';
6-
const absolutePath = require.resolve('../fixtures/es-modules/test-esm-ok.mjs');
7-
const targetURL = new URL('file:///');
8-
targetURL.pathname = absolutePath;
7+
const absolutePath = require.resolve(relativePath);
8+
const targetURL = pathToFileURL(absolutePath);
99

1010
function expectModuleError(result, code, message) {
1111
Promise.resolve(result).catch(common.mustCall((error) => {
@@ -41,7 +41,7 @@ function expectFsNamespace(result) {
4141
// expectOkNamespace(import(relativePath));
4242
expectOkNamespace(eval(`import("${relativePath}")`));
4343
expectOkNamespace(eval(`import("${relativePath}")`));
44-
expectOkNamespace(eval(`import("${targetURL}")`));
44+
expectOkNamespace(eval(`import(${JSON.stringify(targetURL)})`));
4545

4646
// Importing a built-in, both direct & via eval
4747
expectFsNamespace(import('fs'));

test/es-module/test-esm-loader-spawn-promisified.mjs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ describe('Loader hooks throwing errors', { concurrency: true }, () => {
2828
fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'),
2929
'--input-type=module',
3030
'--eval',
31-
`import '${fixtures.fileURL('/es-modules/file.unknown')}'`,
31+
`import ${JSON.stringify(fixtures.fileURL('/es-modules/file.unknown'))}`,
3232
]);
3333

3434
assert.match(stderr, /ERR_UNKNOWN_FILE_EXTENSION/);
@@ -142,7 +142,7 @@ describe('Loader hooks throwing errors', { concurrency: true }, () => {
142142
`import assert from 'node:assert';
143143
await Promise.allSettled([
144144
import('nonexistent/file.mjs'),
145-
import('${fixtures.fileURL('/es-modules/file.unknown')}'),
145+
import(${JSON.stringify(fixtures.fileURL('/es-modules/file.unknown'))}),
146146
import('esmHook/badReturnVal.mjs'),
147147
import('esmHook/format.false'),
148148
import('esmHook/format.true'),
@@ -170,7 +170,7 @@ describe('Loader hooks parsing modules', { concurrency: true }, () => {
170170
'--input-type=module',
171171
'--eval',
172172
`import assert from 'node:assert';
173-
await import('${fixtures.fileURL('/es-module-loaders/js-as-esm.js')}')
173+
await import(${JSON.stringify(fixtures.fileURL('/es-module-loaders/js-as-esm.js'))})
174174
.then((parsedModule) => {
175175
assert.strictEqual(typeof parsedModule, 'object');
176176
assert.strictEqual(parsedModule.namedExport, 'named-export');
@@ -191,7 +191,7 @@ describe('Loader hooks parsing modules', { concurrency: true }, () => {
191191
'--input-type=module',
192192
'--eval',
193193
`import assert from 'node:assert';
194-
await import('${fixtures.fileURL('/es-modules/file.ext')}')
194+
await import(${JSON.stringify(fixtures.fileURL('/es-modules/file.ext'))})
195195
.then((parsedModule) => {
196196
assert.strictEqual(typeof parsedModule, 'object');
197197
const { default: defaultExport } = parsedModule;
@@ -258,7 +258,7 @@ describe('Loader hooks parsing modules', { concurrency: true }, () => {
258258
'--input-type=module',
259259
'--eval',
260260
`import assert from 'node:assert';
261-
await import('${fixtures.fileURL('/es-modules/stateful.mjs')}')
261+
await import(${JSON.stringify(fixtures.fileURL('/es-modules/stateful.mjs'))})
262262
.then(({ default: count }) => {
263263
assert.strictEqual(count(), 1);
264264
});`,

test/parallel/test-fs-mkdtemp.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ const common = require('../common');
44
const assert = require('assert');
55
const fs = require('fs');
66
const path = require('path');
7+
const { pathToFileURL } = require('url');
78

89
const tmpdir = require('../common/tmpdir');
910
tmpdir.refresh();
@@ -40,7 +41,7 @@ function handler(err, folder) {
4041

4142
// Test with URL object
4243
{
43-
tmpdir.url = new URL(`file://${tmpdir.path}`);
44+
tmpdir.url = pathToFileURL(tmpdir.path);
4445
const urljoin = (base, path) => new URL(path, base);
4546

4647
const tmpFolder = fs.mkdtempSync(urljoin(tmpdir.url, 'foo.'));

test/parallel/test-internal-util-decorate-error-stack.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ checkStack(err.stack);
5858
// Verify that the stack is only decorated once for uncaught exceptions.
5959
const args = [
6060
'-e',
61-
`require('${badSyntaxPath}')`,
61+
`require(${JSON.stringify(badSyntaxPath)})`,
6262
];
6363
const result = spawnSync(process.argv[0], args, { encoding: 'utf8' });
6464
checkStack(result.stderr);

test/parallel/test-repl-require-context.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,6 @@ child.on('exit', common.mustCall(() => {
1919

2020
child.stdin.write('const isObject = (obj) => obj.constructor === Object;\n');
2121
child.stdin.write('isObject({});\n');
22-
child.stdin.write(`require('${fixture}').isObject({});\n`);
22+
child.stdin.write(`require(${JSON.stringify(fixture)}).isObject({});\n`);
2323
child.stdin.write('.exit');
2424
child.stdin.end();

test/parallel/test-stdio-pipe-stderr.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ fs.writeFileSync(fakeModulePath, '', 'utf8');
2222

2323
stream.on('open', () => {
2424
spawnSync(process.execPath, {
25-
input: `require("${fakeModulePath.replace(/\\/g, '/')}")`,
25+
input: `require(${JSON.stringify(fakeModulePath)})`,
2626
stdio: ['pipe', 'pipe', stream]
2727
});
2828
const stderr = fs.readFileSync(stderrOutputPath, 'utf8').trim();

test/parallel/test-trace-events-worker-metadata-with-name.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ const { isMainThread } = require('worker_threads');
77

88
if (isMainThread) {
99
const CODE = 'const { Worker } = require(\'worker_threads\'); ' +
10-
`new Worker('${__filename.replace(/\\/g, '/')}', { name: 'foo' })`;
10+
`new Worker(${JSON.stringify(__filename)}, { name: 'foo' })`;
1111
const FILE_NAME = 'node_trace.1.log';
1212
const tmpdir = require('../common/tmpdir');
1313
tmpdir.refresh();

test/parallel/test-trace-events-worker-metadata.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ const { isMainThread } = require('worker_threads');
77

88
if (isMainThread) {
99
const CODE = 'const { Worker } = require(\'worker_threads\'); ' +
10-
`new Worker('${__filename.replace(/\\/g, '/')}')`;
10+
`new Worker(${JSON.stringify(__filename)})`;
1111
const FILE_NAME = 'node_trace.1.log';
1212
const tmpdir = require('../common/tmpdir');
1313
tmpdir.refresh();

test/sequential/test-watch-mode.mjs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { describe, it } from 'node:test';
77
import { spawn } from 'node:child_process';
88
import { writeFileSync, readFileSync, mkdirSync } from 'node:fs';
99
import { inspect } from 'node:util';
10+
import { pathToFileURL } from 'node:url';
1011
import { createInterface } from 'node:readline';
1112

1213
if (common.isIBMi)
@@ -188,7 +189,7 @@ console.log("don't show me");`);
188189
it('should watch changes to dependencies - cjs', async () => {
189190
const dependency = createTmpFile('module.exports = {};');
190191
const file = createTmpFile(`
191-
const dependency = require('${dependency.replace(/\\/g, '/')}');
192+
const dependency = require(${JSON.stringify(dependency)});
192193
console.log(dependency);
193194
`);
194195
const { stderr, stdout } = await runWriteSucceed({ file, watchedFile: dependency });
@@ -206,7 +207,7 @@ console.log(dependency);
206207
it('should watch changes to dependencies - esm', async () => {
207208
const dependency = createTmpFile('module.exports = {};');
208209
const file = createTmpFile(`
209-
import dependency from 'file://${dependency.replace(/\\/g, '/')}';
210+
import dependency from ${JSON.stringify(pathToFileURL(dependency))};
210211
console.log(dependency);
211212
`, '.mjs');
212213
const { stderr, stdout } = await runWriteSucceed({ file, watchedFile: dependency });
@@ -278,7 +279,7 @@ console.log(values.random);
278279
skip: 'enable once --import is backported',
279280
}, async () => {
280281
const file = createTmpFile();
281-
const imported = `file://${createTmpFile('setImmediate(() => process.exit(0));')}`;
282+
const imported = pathToFileURL(createTmpFile('setImmediate(() => process.exit(0));'));
282283
const args = ['--import', imported, file];
283284
const { stderr, stdout } = await runWriteSucceed({ file, watchedFile: file, args });
284285

@@ -320,9 +321,9 @@ console.log(values.random);
320321
it('should watch changes to previously missing ESM dependency', {
321322
skip: !supportsRecursive
322323
}, async () => {
323-
const dependency = path.join(tmpdir.path, `${tmpFiles++}.mjs`);
324-
const relativeDependencyPath = `./${path.basename(dependency)}`;
325-
const dependant = createTmpFile(`import '${relativeDependencyPath}'`, '.mjs');
324+
const relativeDependencyPath = `./${tmpFiles++}.mjs`;
325+
const dependency = path.join(tmpdir.path, relativeDependencyPath);
326+
const dependant = createTmpFile(`import ${JSON.stringify(relativeDependencyPath)}`, '.mjs');
326327

327328
await failWriteSucceed({ file: dependant, watchedFile: dependency });
328329
});

0 commit comments

Comments
 (0)