Skip to content

Commit b5991f5

Browse files
aduh95RafaelGSS
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 Reviewed-By: Moshe Atlow <moshe@atlow.co.il> Reviewed-By: Michaël Zasso <targos@protonmail.com>
1 parent 62e23f8 commit b5991f5

10 files changed

+33
-31
lines changed

test/es-module/test-cjs-legacyMainResolve-permission.js

+10-10
Original file line numberDiff line numberDiff line change
@@ -49,21 +49,21 @@ describe('legacyMainResolve', () => {
4949
5050
const packageJsonUrl = pathToFileURL(
5151
path.resolve(
52-
'${fixtextureFolderEscaped}',
52+
${JSON.stringify(fixtextureFolderEscaped)},
5353
'package.json'
5454
)
5555
);
5656
5757
const packageConfig = { main: '${mainOrFolder}' };
5858
const base = path.resolve(
59-
'${fixtextureFolderEscaped}'
59+
${JSON.stringify(fixtextureFolderEscaped)},
6060
);
6161
6262
assert.throws(() => legacyMainResolve(packageJsonUrl, packageConfig, base), {
6363
code: 'ERR_ACCESS_DENIED',
6464
resource: path.resolve(
65-
'${fixtextureFolderEscaped}',
66-
'${mainOrFolder}'
65+
${JSON.stringify(fixtextureFolderEscaped)},
66+
${JSON.stringify(mainOrFolder)},
6767
)
6868
});
6969
`,
@@ -103,23 +103,23 @@ describe('legacyMainResolve', () => {
103103
104104
const packageJsonUrl = pathToFileURL(
105105
path.resolve(
106-
'${fixtextureFolderEscaped}',
107-
'${folder}',
106+
${JSON.stringify(fixtextureFolderEscaped)},
107+
${JSON.stringify(folder)},
108108
'package.json'
109109
)
110110
);
111111
112112
const packageConfig = { main: undefined };
113113
const base = path.resolve(
114-
'${fixtextureFolderEscaped}'
114+
${JSON.stringify(fixtextureFolderEscaped)},
115115
);
116116
117117
assert.throws(() => legacyMainResolve(packageJsonUrl, packageConfig, base), {
118118
code: 'ERR_ACCESS_DENIED',
119119
resource: path.resolve(
120-
'${fixtextureFolderEscaped}',
121-
'${folder}',
122-
'${expectedFile}'
120+
${JSON.stringify(fixtextureFolderEscaped)},
121+
${JSON.stringify(folder)},
122+
${JSON.stringify(expectedFile)},
123123
)
124124
});
125125
`,

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

+4-4
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

+5-5
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

+2-1
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

+1-1
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

+1-1
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

+1-1
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

+1-1
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

+1-1
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

+7-6
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 });
@@ -276,7 +277,7 @@ console.log(values.random);
276277

277278
it('should not load --import modules in main process', async () => {
278279
const file = createTmpFile();
279-
const imported = `file://${createTmpFile('setImmediate(() => process.exit(0));')}`;
280+
const imported = pathToFileURL(createTmpFile('setImmediate(() => process.exit(0));'));
280281
const args = ['--import', imported, file];
281282
const { stderr, stdout } = await runWriteSucceed({ file, watchedFile: file, args });
282283

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

325326
await failWriteSucceed({ file: dependant, watchedFile: dependency });
326327
});

0 commit comments

Comments
 (0)