Chrome DevTools for coding agents
test: refactor temp files and dir (#2818)
Nikolay Vitkov08b5e59e6f02
diff --git a/eslint.config.js b/eslint.config.jsindex 64eb25c7..53ceb613 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -164,6 +164,7 @@ export default defineConfig([// With the Node.js test runner, `describe` and `it` are technically// promises, but we don't need to await them.'@typescript-eslint/no-floating-promises': 'off',+ '@local/enforce-using': 'error',},},]);diff --git a/scripts/eslint_rules/enforce-using-rule.js b/scripts/eslint_rules/enforce-using-rule.jsnew file mode 100644index 00000000..734ddd6b--- /dev/null+++ b/scripts/eslint_rules/enforce-using-rule.js@@ -0,0 +1,98 @@+/**+ * @license+ * Copyright 2026 Google LLC+ * SPDX-License-Identifier: Apache-2.0+ */++const DISPOSABLE_HELPERS = new Set(['createTempDir', 'createTempFile']);+const FORBIDDEN_TEMP_CALLS = new Set(['mkdtemp', 'mkdtempSync']);++function getCalleeName(callee) {+ if (callee.type === 'Identifier') {+ return callee.name;+ }+ if (+ callee.type === 'MemberExpression' &&+ callee.property.type === 'Identifier'+ ) {+ return callee.property.name;+ }+ return null;+}++export default {+ name: 'enforce-using',+ meta: {+ type: 'problem',+ fixable: 'code',+ docs: {+ description:+ 'Enforce `using` declarations for temporary file/directory helpers and disallow raw mkdtemp calls in tests.',+ },+ schema: [],+ messages: {+ requireUsing:+ 'Use a `using` declaration with `{{name}}` so temporary resources are automatically disposed.',+ noMkdtemp:+ 'Do not use `{{name}}` directly in tests. Use `using dir = createTempDir(...)` from tests/utils.ts instead.',+ },+ },+ defaultOptions: [],+ create(context) {+ return {+ CallExpression(node) {+ const calleeName = getCalleeName(node.callee);+ if (!calleeName) {+ return;+ }++ if (FORBIDDEN_TEMP_CALLS.has(calleeName)) {+ context.report({+ node,+ messageId: 'noMkdtemp',+ data: {name: calleeName},+ });+ return;+ }++ if (DISPOSABLE_HELPERS.has(calleeName)) {+ const expr =+ node.parent?.type === 'AwaitExpression' ? node.parent : node;+ const declarator = expr.parent;+ const declaration = declarator?.parent;++ const isUsing =+ declarator?.type === 'VariableDeclarator' &&+ declarator.init === expr &&+ declaration?.type === 'VariableDeclaration' &&+ (declaration.kind === 'using' ||+ declaration.kind === 'await using');++ if (!isUsing) {+ context.report({+ node,+ messageId: 'requireUsing',+ data: {name: calleeName},+ fix(fixer) {+ if (+ declarator?.type === 'VariableDeclarator' &&+ declaration?.type === 'VariableDeclaration' &&+ declaration.declarations.length === 1 &&+ (declaration.kind === 'const' || declaration.kind === 'let')+ ) {+ const sourceCode =+ context.sourceCode || context.getSourceCode();+ const kindToken = sourceCode.getFirstToken(declaration);+ if (kindToken) {+ return fixer.replaceText(kindToken, 'using');+ }+ }+ return null;+ },+ });+ }+ }+ },+ };+ },+};diff --git a/scripts/eslint_rules/local-plugin.js b/scripts/eslint_rules/local-plugin.jsindex 481caf48..c2514915 100644--- a/scripts/eslint_rules/local-plugin.js+++ b/scripts/eslint_rules/local-plugin.js@@ -5,6 +5,7 @@*/import checkLicenseRule from './check-license-rule.js';+import enforceUsingRule from './enforce-using-rule.js';import enforceZodSchemaRule from './enforce-zod-schema-rule.js';import requireParsedArgumentsRule from './require-parsed-arguments-rule.js';import noDirectThirdPartyImportsRule from './no-direct-third-party-imports-rule.js';@@ -12,6 +13,7 @@ import noDirectThirdPartyImportsRule from './no-direct-third-party-imports-rule.export default {rules: {'check-license': checkLicenseRule,+ 'enforce-using': enforceUsingRule,'no-direct-third-party-imports': noDirectThirdPartyImportsRule,'enforce-zod-schema': enforceZodSchemaRule,'require-parsed-arguments': requireParsedArgumentsRule,diff --git a/tests/McpContext.test.ts b/tests/McpContext.test.tsindex bf8d8cfa..bc377c97 100644--- a/tests/McpContext.test.ts+++ b/tests/McpContext.test.ts@@ -25,6 +25,8 @@ import {resolveCanonicalPath} from '../src/utils/files.js';import {serverHooks} from './server.js';import {assertNoServiceWorkerReported,+ createTempDir,+ createTempFile,getMockRequest,html,withBrowser,@@ -504,52 +506,39 @@ describe('McpContext', () => {});it('validatePath allows paths within roots', async () => {+ using workspace = createTempDir('workspace-test-', os.homedir());await withMcpContext(async (_response, context) => {- const workspacePath = path.resolve(os.homedir(), 'workspace-test');- await fs.mkdir(workspacePath, {recursive: true});- try {- const roots = [- {uri: pathToFileURL(workspacePath).href, name: 'workspace'},- ];- context.setRoots(roots);- // Valid path within root- const targetPath = path.join(workspacePath, 'test.txt');- const resolved = await context.validatePath(targetPath);- assert.strictEqual(resolved, await resolveCanonicalPath(targetPath));- const resolvedWorkspace = await context.validatePath(workspacePath);- assert.strictEqual(- resolvedWorkspace,- await resolveCanonicalPath(workspacePath),- );+ const roots = [+ {uri: pathToFileURL(workspace.path).href, name: 'workspace'},+ ];+ context.setRoots(roots);+ // Valid path within root+ const targetPath = path.join(workspace.path, 'test.txt');+ const resolved = await context.validatePath(targetPath);+ assert.strictEqual(resolved, await resolveCanonicalPath(targetPath));+ const resolvedWorkspace = await context.validatePath(workspace.path);+ assert.strictEqual(+ resolvedWorkspace,+ await resolveCanonicalPath(workspace.path),+ );- // Invalid path outside root and outside temp dir- const outsidePath = path.resolve(os.homedir(), 'outside-test.txt');- await assert.rejects(- context.validatePath(outsidePath),- /Access denied/,- );- } finally {- await fs.rm(workspacePath, {recursive: true, force: true});- }+ // Invalid path outside root and outside temp dir+ const outsidePath = path.resolve(os.homedir(), 'outside-test.txt');+ await assert.rejects(context.validatePath(outsidePath), /Access denied/);});});it('validatePath allows non-existent nested paths within roots', async () => {+ using workspace = createTempDir('workspace-test-nested-', os.homedir());await withMcpContext(async (_response, context) => {- const workspacePath = path.resolve(os.homedir(), 'workspace-test-nested');- await fs.mkdir(workspacePath, {recursive: true});- try {- const roots = [- {uri: pathToFileURL(workspacePath).href, name: 'workspace'},- ];- context.setRoots(roots);- // Valid path within root with non-existent intermediate directories- const targetPath = path.join(workspacePath, 'dir1', 'dir2', 'test.txt');- const resolved = await context.validatePath(targetPath);- assert.strictEqual(resolved, await resolveCanonicalPath(targetPath));- } finally {- await fs.rm(workspacePath, {recursive: true, force: true});- }+ const roots = [+ {uri: pathToFileURL(workspace.path).href, name: 'workspace'},+ ];+ context.setRoots(roots);+ // Valid path within root with non-existent intermediate directories+ const targetPath = path.join(workspace.path, 'dir1', 'dir2', 'test.txt');+ const resolved = await context.validatePath(targetPath);+ assert.strictEqual(resolved, await resolveCanonicalPath(targetPath));});});@@ -619,118 +608,97 @@ describe('McpContext', () => {}it('validatePath resolves symlinks and returns the canonical path', async () => {+ using tmpDir = createTempDir('validate-symlink-test-');await withMcpContext(async (_response, context) => {- const tmpDir = await fs.mkdtemp(- path.join(os.tmpdir(), 'validate-symlink-test-'),- );- try {- const targetDir = path.join(tmpDir, 'target');- await fs.mkdir(targetDir);- const targetFile = path.join(targetDir, 'file.txt');- await fs.writeFile(targetFile, 'hello');-- const symlinkDir = path.join(tmpDir, 'symlink_dir');- await fs.symlink(targetDir, symlinkDir, 'dir');-- const canonicalTarget = await fs.realpath(targetDir);- context.setRoots([- {uri: pathToFileURL(canonicalTarget).href, name: 'target'},- ]);-- const filePathWithSymlink = path.join(symlinkDir, 'file.txt');- const resolved = await context.validatePath(filePathWithSymlink);- assert.strictEqual(resolved, path.join(canonicalTarget, 'file.txt'));- } finally {- await fs.rm(tmpDir, {recursive: true, force: true});- }+ const targetDir = path.join(tmpDir.path, 'target');+ await fs.mkdir(targetDir);+ const targetFile = path.join(targetDir, 'file.txt');+ await fs.writeFile(targetFile, 'hello');++ const symlinkDir = path.join(tmpDir.path, 'symlink_dir');+ await fs.symlink(targetDir, symlinkDir, 'dir');++ const canonicalTarget = await fs.realpath(targetDir);+ context.setRoots([+ {uri: pathToFileURL(canonicalTarget).href, name: 'target'},+ ]);++ const filePathWithSymlink = path.join(symlinkDir, 'file.txt');+ const resolved = await context.validatePath(filePathWithSymlink);+ assert.strictEqual(resolved, path.join(canonicalTarget, 'file.txt'));});});it('saveFile allows writing to a symlinked file if it resolves to an allowed path', async () => {+ using tmpDir = createTempDir('mcp-symlink-test-');await withMcpContext(async (_response, context) => {- const tmpDir = await fs.mkdtemp(- path.join(os.tmpdir(), 'mcp-symlink-test-'),- );- try {- context.setRoots([{uri: pathToFileURL(tmpDir).href, name: 'temp'}]);+ context.setRoots([+ {uri: pathToFileURL(tmpDir.path).href, name: 'temp'},+ ]);- const targetPath = path.join(tmpDir, 'target.txt');- await fs.writeFile(targetPath, 'original content', 'utf-8');+ const targetPath = path.join(tmpDir.path, 'target.txt');+ await fs.writeFile(targetPath, 'original content', 'utf-8');- const symlinkPath = path.join(tmpDir, 'symlink.txt');- await fs.symlink(targetPath, symlinkPath);+ const symlinkPath = path.join(tmpDir.path, 'symlink.txt');+ await fs.symlink(targetPath, symlinkPath);- const data = new TextEncoder().encode('content');- await context.saveFile(data, symlinkPath, '.txt');- await context.saveFile(data, targetPath, '.txt');+ const data = new TextEncoder().encode('content');+ await context.saveFile(data, symlinkPath, '.txt');+ await context.saveFile(data, targetPath, '.txt');- const content = await fs.readFile(targetPath, 'utf-8');- assert.strictEqual(content, 'content');- } finally {- await fs.rm(tmpDir, {recursive: true, force: true});- }+ const content = await fs.readFile(targetPath, 'utf-8');+ assert.strictEqual(content, 'content');});});it('saveFile refuses to write through a dangling symlink to a non-existent file', async () => {+ using tmpDir = createTempDir('mcp-symlink-test-');+ using outsideDir = createTempDir('mcp-outside-test-');await withMcpContext(async (_response, context) => {- const tmpDir = await fs.mkdtemp(- path.join(os.tmpdir(), 'mcp-symlink-test-'),- );- const outsideDir = await fs.mkdtemp(- path.join(os.tmpdir(), 'mcp-outside-test-'),- );- try {- context.setRoots([{uri: pathToFileURL(tmpDir).href, name: 'temp'}]);+ context.setRoots([+ {uri: pathToFileURL(tmpDir.path).href, name: 'temp'},+ ]);- const outsideTarget = path.join(outsideDir, 'target.txt');- const symlinkPath = path.join(tmpDir, 'symlink.txt');- await fs.symlink(outsideTarget, symlinkPath);+ const outsideTarget = path.join(outsideDir.path, 'target.txt');+ const symlinkPath = path.join(tmpDir.path, 'symlink.txt');+ await fs.symlink(outsideTarget, symlinkPath);- const data = new TextEncoder().encode('malicious content');- await assert.rejects(- context.saveFile(data, symlinkPath, '.txt'),- /Could not write/,- );+ const data = new TextEncoder().encode('malicious content');+ await assert.rejects(+ context.saveFile(data, symlinkPath, '.txt'),+ /Could not write/,+ );- await assert.rejects(fs.stat(outsideTarget));- } finally {- await fs.rm(tmpDir, {recursive: true, force: true});- await fs.rm(outsideDir, {recursive: true, force: true});- }+ await assert.rejects(fs.stat(outsideTarget));});});it('saveFile allows writing to a file within an allowed symlinked directory', async () => {+ using tmpDir = createTempDir('mcp-symlink-test-');await withMcpContext(async (_response, context) => {- const tmpDir = await fs.mkdtemp(- path.join(os.tmpdir(), 'mcp-symlink-test-'),- );- try {- context.setRoots([{uri: pathToFileURL(tmpDir).href, name: 'temp'}]);+ context.setRoots([+ {uri: pathToFileURL(tmpDir.path).href, name: 'temp'},+ ]);- const realDir = path.join(tmpDir, 'real_dir');- await fs.mkdir(realDir, {recursive: true});+ const realDir = path.join(tmpDir.path, 'real_dir');+ await fs.mkdir(realDir, {recursive: true});- const symlinkedDir = path.join(tmpDir, 'symlinked_dir');- await fs.symlink(realDir, symlinkedDir);+ const symlinkedDir = path.join(tmpDir.path, 'symlinked_dir');+ await fs.symlink(realDir, symlinkedDir);- const targetFilePath = path.join(symlinkedDir, 'test.txt');- const data = new TextEncoder().encode('allowed content');+ const targetFilePath = path.join(symlinkedDir, 'test.txt');+ const data = new TextEncoder().encode('allowed content');- const result = await context.saveFile(data, targetFilePath, '.txt');- assert.strictEqual(- result.filename,- await resolveCanonicalPath(targetFilePath),- );- const content = await fs.readFile(- path.join(realDir, 'test.txt'),- 'utf-8',- );- assert.strictEqual(content, 'allowed content');- } finally {- await fs.rm(tmpDir, {recursive: true, force: true});- }+ const result = await context.saveFile(data, targetFilePath, '.txt');+ assert.strictEqual(+ result.filename,+ await resolveCanonicalPath(targetFilePath),+ );+ const content = await fs.readFile(+ path.join(realDir, 'test.txt'),+ 'utf-8',+ );+ assert.strictEqual(content, 'allowed content');});});});@@ -738,41 +706,34 @@ describe('McpContext', () => {describe('loadResource', () => {describe('file protocol', () => {it('calls validatePath', async () => {+ using testFile = createTempFile(+ 'test content',+ 'load-resource-test.txt',+ );await withMcpContext(async (_response, context) => {const validatePathSpy = sinon.spy(context, 'validatePath');- const testFilePath = path.join(os.tmpdir(), 'load-resource-test.txt');- await fs.writeFile(testFilePath, 'test content');- try {- const url = pathToFileURL(testFilePath).href;- const content = await context.loadResource(url);- assert.strictEqual(content, 'test content');- sinon.assert.calledWith(validatePathSpy, testFilePath);- } finally {- await fs.rm(testFilePath, {force: true});- }+ const url = pathToFileURL(testFile.path).href;+ const content = await context.loadResource(url);+ assert.strictEqual(content, 'test content');+ sinon.assert.calledWith(validatePathSpy, testFile.path);});});it('is not blocked by allowlist', async () => {- const testFilePath = path.join(- os.tmpdir(),+ using testFile = createTempFile(+ 'test content','load-resource-test-allow.txt',);- await fs.writeFile(testFilePath, 'test content');- try {- await withMcpContext(- async (_response, context) => {- const url = pathToFileURL(testFilePath).href;- const content = await context.loadResource(url);- assert.strictEqual(content, 'test content');- },- {- allowedUrlPattern: ['https://example.com/allowed*'],- },- );- } finally {- await fs.rm(testFilePath, {force: true});- }+ await withMcpContext(+ async (_response, context) => {+ const url = pathToFileURL(testFile.path).href;+ const content = await context.loadResource(url);+ assert.strictEqual(content, 'test content');+ },+ {+ allowedUrlPattern: ['https://example.com/allowed*'],+ },+ );});});diff --git a/tests/McpResponse.test.ts b/tests/McpResponse.test.tsindex cae515e5..cf8b1447 100644--- a/tests/McpResponse.test.ts+++ b/tests/McpResponse.test.ts@@ -5,8 +5,7 @@*/import assert from 'node:assert';-import {readFile, rm} from 'node:fs/promises';-import {tmpdir} from 'node:os';+import {readFile} from 'node:fs/promises';import {join} from 'node:path';import {describe, it} from 'node:test';@@ -50,6 +49,7 @@ import {createMockParsedArguments,} from './mocks.js';import {+ createTempDir,getImageContent,getMockAggregatedIssue,getMockRequest,@@ -171,25 +171,22 @@ describe('McpResponse', () => {});it('saves snapshot to file and returns structured content', async t => {- const filePath = join(tmpdir(), 'test-snapshot.txt');- try {- await withMcpContext(async (response, context) => {- const page = context.getSelectedMcpPage().pptrPage;- await page.setContent(html`<aside>test</aside>`);- response.includeSnapshot({- verbose: true,- filePath,- });- const {content, structuredContent} = await response.handle(context);- assert.equal(content[0].type, 'text');- t.assert.snapshot(stabilizeResponseOutput(getTextContent(content[0])));- t.assert.snapshot(stabilizeStructuredContent(structuredContent));+ using tmpDir = createTempDir();+ const filePath = join(tmpDir.path, 'test-snapshot.txt');+ await withMcpContext(async (response, context) => {+ const page = context.getSelectedMcpPage().pptrPage;+ await page.setContent(html`<aside>test</aside>`);+ response.includeSnapshot({+ verbose: true,+ filePath,});- const content = await readFile(filePath, 'utf-8');- t.assert.snapshot(stabilizeResponseOutput(content));- } finally {- await rm(filePath, {force: true});- }+ const {content, structuredContent} = await response.handle(context);+ assert.equal(content[0].type, 'text');+ t.assert.snapshot(stabilizeResponseOutput(getTextContent(content[0])));+ t.assert.snapshot(stabilizeStructuredContent(structuredContent));+ });+ const content = await readFile(filePath, 'utf-8');+ t.assert.snapshot(stabilizeResponseOutput(content));});it('preserves mapping ids across multiple snapshots', async () => {diff --git a/tests/cli.test.ts b/tests/cli.test.tsindex 7a589930..55bad6f7 100644--- a/tests/cli.test.ts+++ b/tests/cli.test.ts@@ -6,9 +6,6 @@import assert from 'node:assert';import {describe, it} from 'node:test';-import fs from 'node:fs';-import os from 'node:os';-import path from 'node:path';import {buildCommand} from '../src/config/cli-commands.js';import {commands} from '../src/config/cli-options.js';@@ -18,27 +15,14 @@ import {parser,} from '../src/config/mcp-options.js';+import {createTempFile} from './utils.js';+function parseArguments(argv: string[], env: NodeJS.ProcessEnv = {}) {return parser('0.0.0', ['node', 'main.js', ...argv], env).exitProcess(false).parseSync();}-function createTempFile(content: string, fileName: string) {- const filePath = path.join(os.tmpdir(), fileName);- fs.writeFileSync(filePath, content);- return {- path: filePath,- [Symbol.dispose]() {- try {- fs.unlinkSync(filePath);- } catch {- // ignore- }- },- };-}-describe('cli args parsing', () => {const defaultArgs = {categoryInput: true,diff --git a/tests/daemon/utils.test.ts b/tests/daemon/utils.test.tsindex 79ade0ed..48a505bb 100644--- a/tests/daemon/utils.test.ts+++ b/tests/daemon/utils.test.ts@@ -25,6 +25,7 @@ import {IS_WINDOWS,} from '../../src/daemon/utils.js';import type {YargsOptions} from '../../src/third_party/index.js';+import {createTempDir} from '../utils.js';const APP_NAME = 'chrome-devtools-mcp';const SESSION_ID = 'aabbccdd-1122-3344-5566-77889900aabb';@@ -274,14 +275,9 @@ describe('getPidFilePath', () => {describe('daemon pid handling', () => {let savedXdgRuntimeDir: string | undefined;- let tempDir: string;beforeEach(() => {savedXdgRuntimeDir = process.env['XDG_RUNTIME_DIR'];- // Point XDG_RUNTIME_DIR at a temp dir so the pid file paths used by- // getDaemonPid/isDaemonRunning are isolated from any real daemon.- tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cdm-daemon-utils-test-'));- process.env['XDG_RUNTIME_DIR'] = tempDir;});afterEach(() => {@@ -290,7 +286,6 @@ describe('daemon pid handling', () => {} else {process.env['XDG_RUNTIME_DIR'] = savedXdgRuntimeDir;}- fs.rmSync(tempDir, {recursive: true, force: true});});function writePidFile(sessionId: string, contents: string): void {@@ -301,20 +296,28 @@ describe('daemon pid handling', () => {describe('getDaemonPid', () => {it('returns null when no pid file exists', () => {+ using tempDir = createTempDir('cdm-daemon-utils-test-');+ process.env['XDG_RUNTIME_DIR'] = tempDir.path;assert.strictEqual(getDaemonPid(SESSION_ID), null);});it('reads the pid from the pid file, ignoring whitespace', () => {+ using tempDir = createTempDir('cdm-daemon-utils-test-');+ process.env['XDG_RUNTIME_DIR'] = tempDir.path;writePidFile(SESSION_ID, '12345\n');assert.strictEqual(getDaemonPid(SESSION_ID), 12345);});it('is scoped per session id', () => {+ using tempDir = createTempDir('cdm-daemon-utils-test-');+ process.env['XDG_RUNTIME_DIR'] = tempDir.path;writePidFile(SESSION_ID, '12345\n');assert.strictEqual(getDaemonPid('00000000-0000'), null);});it('returns null for empty or non-numeric pid files', () => {+ using tempDir = createTempDir('cdm-daemon-utils-test-');+ process.env['XDG_RUNTIME_DIR'] = tempDir.path;writePidFile(SESSION_ID, '');assert.strictEqual(getDaemonPid(SESSION_ID), null);writePidFile(SESSION_ID, 'not-a-pid');@@ -322,6 +325,8 @@ describe('daemon pid handling', () => {});it('parses the leading integer of malformed contents', () => {+ using tempDir = createTempDir('cdm-daemon-utils-test-');+ process.env['XDG_RUNTIME_DIR'] = tempDir.path;// Documents current parseInt-based behavior.writePidFile(SESSION_ID, '123abc');assert.strictEqual(getDaemonPid(SESSION_ID), 123);@@ -330,15 +335,21 @@ describe('daemon pid handling', () => {describe('isDaemonRunning', () => {it('returns false when no pid file exists', () => {+ using tempDir = createTempDir('cdm-daemon-utils-test-');+ process.env['XDG_RUNTIME_DIR'] = tempDir.path;assert.strictEqual(isDaemonRunning(SESSION_ID), false);});it('returns true when the pid file points to a live process', () => {+ using tempDir = createTempDir('cdm-daemon-utils-test-');+ process.env['XDG_RUNTIME_DIR'] = tempDir.path;writePidFile(SESSION_ID, `${process.pid}\n`);assert.strictEqual(isDaemonRunning(SESSION_ID), true);});it('returns false when the pid file points to a dead process', async () => {+ using tempDir = createTempDir('cdm-daemon-utils-test-');+ process.env['XDG_RUNTIME_DIR'] = tempDir.path;const child = spawn(process.execPath, ['--version'], {stdio: 'ignore'});await once(child, 'exit');assert.ok(child.pid);@@ -350,6 +361,8 @@ describe('daemon pid handling', () => {});it('returns false when the pid file contains 0', () => {+ using tempDir = createTempDir('cdm-daemon-utils-test-');+ process.env['XDG_RUNTIME_DIR'] = tempDir.path;// Important: signaling pid 0 would target the whole process group, so// isDaemonRunning must not treat it as a live daemon.writePidFile(SESSION_ID, '0');@@ -357,6 +370,8 @@ describe('daemon pid handling', () => {});it('returns false for non-numeric pid files', () => {+ using tempDir = createTempDir('cdm-daemon-utils-test-');+ process.env['XDG_RUNTIME_DIR'] = tempDir.path;writePidFile(SESSION_ID, 'garbage');assert.strictEqual(isDaemonRunning(SESSION_ID), false);});diff --git a/tests/e2e/chrome-devtools-start-stop.test.ts b/tests/e2e/chrome-devtools-start-stop.test.tsindex fa3dc616..755c6b5e 100644--- a/tests/e2e/chrome-devtools-start-stop.test.ts+++ b/tests/e2e/chrome-devtools-start-stop.test.ts@@ -6,14 +6,13 @@import assert from 'node:assert';import crypto from 'node:crypto';-import fs from 'node:fs';-import os from 'node:os';import path from 'node:path';import {describe, it, afterEach, beforeEach} from 'node:test';import {assertDaemonIsNotRunning,assertDaemonIsRunning,+ createTempDir,runCli,} from '../utils.js';@@ -54,14 +53,10 @@ describe('chrome-devtools', () => {});it('can start the daemon with userDataDir', async () => {- const userDataDir = path.join(- os.tmpdir(),- `chrome-devtools-test-${crypto.randomUUID()}`,- );- fs.mkdirSync(userDataDir, {recursive: true});+ using userDataDir = createTempDir('chrome-devtools-test-');const startResult = await runCli(- ['start', '--userDataDir', userDataDir],+ ['start', '--userDataDir', userDataDir.path],sessionId,);assert.strictEqual(@@ -96,30 +91,24 @@ describe('chrome-devtools', () => {});it('can start the daemon with a workspace', async () => {- const workspace = fs.mkdtempSync(- path.join(os.tmpdir(), 'chrome-devtools-workspace-'),+ using workspace = createTempDir('chrome-devtools-workspace-');++ const startResult = await runCli(+ ['start', '--workspace', workspace.path],+ sessionId,+ );+ assert.strictEqual(+ startResult.status,+ 0,+ `start command failed: ${startResult.stderr}`,);- try {- const startResult = await runCli(- ['start', '--workspace', workspace],- sessionId,- );- assert.strictEqual(- startResult.status,- 0,- `start command failed: ${startResult.stderr}`,- );-- const statusResult = await runCli(['status'], sessionId);- assert.strictEqual(statusResult.status, 0);- assert.ok(- statusResult.stdout.includes('--filesystem-root=') &&- statusResult.stdout.includes(path.basename(workspace)),- `workspace was not forwarded: ${statusResult.stdout}`,- );- } finally {- fs.rmSync(workspace, {recursive: true, force: true});- }+ const statusResult = await runCli(['status'], sessionId);+ assert.strictEqual(statusResult.status, 0);+ assert.ok(+ statusResult.stdout.includes('--filesystem-root=') &&+ statusResult.stdout.includes(path.basename(workspace.path)),+ `workspace was not forwarded: ${statusResult.stdout}`,+ );});});diff --git a/tests/formatters/NetworkFormatter.test.ts b/tests/formatters/NetworkFormatter.test.tsindex 9c9da3b6..5bb82c7d 100644--- a/tests/formatters/NetworkFormatter.test.ts+++ b/tests/formatters/NetworkFormatter.test.ts@@ -5,26 +5,15 @@*/import assert from 'node:assert';-import {mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';-import {tmpdir} from 'node:os';+import {readFile, writeFile} from 'node:fs/promises';import {join} from 'node:path';-import {afterEach, beforeEach, describe, it} from 'node:test';+import {describe, it} from 'node:test';import {NetworkFormatter} from '../../src/formatters/NetworkFormatter.js';import type {HTTPRequest} from '../../src/third_party/index.js';-import {getMockRequest, getMockResponse} from '../utils.js';+import {createTempDir, getMockRequest, getMockResponse} from '../utils.js';describe('NetworkFormatter', () => {- let tmpDir: string;-- beforeEach(async () => {- tmpDir = await mkdtemp(join(tmpdir(), 'network-formatter-test-'));- });-- afterEach(async () => {- await rm(tmpDir, {recursive: true, force: true});- });-describe('toString', () => {it('works', async () => {const request = getMockRequest();@@ -253,8 +242,9 @@ describe('NetworkFormatter', () => {fetchPostData: async () => undefined,} as unknown as HTTPRequest;- const reqPath = join(tmpDir, 'test_req_' + Date.now());- const resPath = join(tmpDir, 'test_res_' + Date.now());+ using tmpDir = createTempDir('network-formatter-test-');+ const reqPath = join(tmpDir.path, 'test_req_' + Date.now());+ const resPath = join(tmpDir.path, 'test_res_' + Date.now());const formatter = await NetworkFormatter.from(request, {fetchData: true,@@ -297,8 +287,9 @@ describe('NetworkFormatter', () => {fetchPostData: async () => undefined,} as unknown as HTTPRequest;- const reqPath = join(tmpDir, 'test_req_large_' + Date.now());- const resPath = join(tmpDir, 'test_res_large_' + Date.now());+ using tmpDir = createTempDir('network-formatter-test-');+ const reqPath = join(tmpDir.path, 'test_req_large_' + Date.now());+ const resPath = join(tmpDir.path, 'test_res_large_' + Date.now());await NetworkFormatter.from(request, {fetchData: true,@@ -400,8 +391,9 @@ describe('NetworkFormatter', () => {fetchPostData: async () => undefined,} as unknown as HTTPRequest;- const reqPath = join(tmpDir, 'req.txt');- const resPath = join(tmpDir, 'res.txt');+ using tmpDir = createTempDir('network-formatter-test-');+ const reqPath = join(tmpDir.path, 'req.txt');+ const resPath = join(tmpDir.path, 'res.txt');const formatter = await NetworkFormatter.from(request, {fetchData: true,@@ -440,8 +432,9 @@ describe('NetworkFormatter', () => {},} as unknown as HTTPRequest;- const reqPath = join(tmpDir, 'req_missing.txt');- const resPath = join(tmpDir, 'res_missing.txt');+ using tmpDir = createTempDir('network-formatter-test-');+ const reqPath = join(tmpDir.path, 'req_missing.txt');+ const resPath = join(tmpDir.path, 'res_missing.txt');const formatter = await NetworkFormatter.from(request, {fetchData: true,@@ -587,8 +580,9 @@ describe('NetworkFormatter', () => {fetchPostData: async () => undefined,} as unknown as HTTPRequest;- const reqPath = join(tmpDir, 'req_json.txt');- const resPath = join(tmpDir, 'res_json.txt');+ using tmpDir = createTempDir('network-formatter-test-');+ const reqPath = join(tmpDir.path, 'req_json.txt');+ const resPath = join(tmpDir.path, 'res_json.txt');const formatter = await NetworkFormatter.from(request, {fetchData: true,diff --git a/tests/index.test.ts b/tests/index.test.tsindex f6be6669..65de5e67 100644--- a/tests/index.test.ts+++ b/tests/index.test.ts@@ -24,6 +24,8 @@ import {import type {ToolCategory} from '../src/tools/categories.js';import type {ToolDefinition} from '../src/tools/ToolDefinition.js';+import {createTempDir} from './utils.js';+describe('e2e', () => {async function withClient(cb: (client: Client) => Promise<void>,@@ -265,48 +267,39 @@ describe('e2e', () => {});it('combines configured filesystem roots with client roots', async () => {- const configuredRoot = await fs.promises.mkdtemp(- path.join(os.homedir(), '.configured-root-'),- );- const clientRoot = await fs.promises.mkdtemp(- path.join(os.homedir(), '.client-root-'),- );+ using configuredRoot = createTempDir('.configured-root-', os.homedir());+ using clientRoot = createTempDir('.client-root-', os.homedir());- try {- await withClient(- async client => {- client.setRequestHandler('roots/list', () => {- return {- roots: [- {uri: pathToFileURL(clientRoot).href, name: 'client-root'},- ],- };- });+ await withClient(+ async client => {+ client.setRequestHandler('roots/list', () => {+ return {+ roots: [+ {uri: pathToFileURL(clientRoot.path).href, name: 'client-root'},+ ],+ };+ });- for (const outputPath of [- path.join(configuredRoot, 'configured.png'),- path.join(clientRoot, 'client.png'),- ]) {- const result = await client.callTool({- name: 'take_screenshot',- arguments: {pageId: 1, filePath: outputPath},- });- assert.strictEqual(result.isError, undefined);- const content = result.content as TextContent[];- assert.match(content[0].text, /Saved screenshot to/);- }- },- [`--filesystem-root=${configuredRoot}`],- {- capabilities: {- roots: {listChanged: true},- },+ for (const outputPath of [+ path.join(configuredRoot.path, 'configured.png'),+ path.join(clientRoot.path, 'client.png'),+ ]) {+ const result = await client.callTool({+ name: 'take_screenshot',+ arguments: {pageId: 1, filePath: outputPath},+ });+ assert.strictEqual(result.isError, undefined);+ const content = result.content as TextContent[];+ assert.match(content[0].text, /Saved screenshot to/);+ }+ },+ [`--filesystem-root=${configuredRoot.path}`],+ {+ capabilities: {+ roots: {listChanged: true},},- );- } finally {- await fs.promises.rm(configuredRoot, {recursive: true, force: true});- await fs.promises.rm(clientRoot, {recursive: true, force: true});- }+ },+ );});it('denies file access if roots list is empty', async () => {@@ -338,6 +331,7 @@ describe('e2e', () => {});it('allows file access if roots capability is missing', async () => {+ using tempDir = createTempDir();await withClient(async client => {// Use os.tmpdir() rather than a hardcoded /tmp path.@@ -348,7 +342,7 @@ describe('e2e', () => {name: 'take_screenshot',arguments: {pageId: 1,- filePath: path.join(os.tmpdir(), 'test.png'),+ filePath: path.join(tempDir.path, 'test.png'),},});@@ -405,47 +399,43 @@ describe('e2e', () => {});it('still applies roots from a client slower than the bound', async () => {- const workspace = await fs.promises.mkdtemp(- path.join(os.homedir(), '.roots-slow-client-'),- );- try {- await withClient(- async client => {- // Answers after the bound the blocking call uses, so the roots only- // arrive via the background listing- client.setRequestHandler('roots/list', async () => {- await new Promise(resolve => setTimeout(resolve, 8_000));- return {- roots: [{uri: pathToFileURL(workspace).href, name: 'workspace'}],- };- });-- await client.callTool({name: 'list_pages', arguments: {}});- await new Promise(resolve => setTimeout(resolve, 5_000));+ using workspace = createTempDir('.roots-slow-client-', os.homedir());+ await withClient(+ async client => {+ // Answers after the bound the blocking call uses, so the roots only+ // arrive via the background listing+ client.setRequestHandler('roots/list', async () => {+ await new Promise(resolve => setTimeout(resolve, 8_000));+ return {+ roots: [+ {uri: pathToFileURL(workspace.path).href, name: 'workspace'},+ ],+ };+ });- const result = await client.callTool({- name: 'take_screenshot',- arguments: {- pageId: 1,- filePath: path.join(workspace, 'shot.png'),- },- });+ await client.callTool({name: 'list_pages', arguments: {}});+ await new Promise(resolve => setTimeout(resolve, 5_000));- // Asserted before isError so a denial reports the path it rejected- const content = result.content as TextContent[];- assert.match(content[0].text, /Saved screenshot to/);- assert.strictEqual(result.isError, undefined);- },- [],- {- capabilities: {- roots: {listChanged: true},+ const result = await client.callTool({+ name: 'take_screenshot',+ arguments: {+ pageId: 1,+ filePath: path.join(workspace.path, 'shot.png'),},+ });++ // Asserted before isError so a denial reports the path it rejected+ const content = result.content as TextContent[];+ assert.match(content[0].text, /Saved screenshot to/);+ assert.strictEqual(result.isError, undefined);+ },+ [],+ {+ capabilities: {+ roots: {listChanged: true},},- );- } finally {- await fs.promises.rm(workspace, {recursive: true, force: true});- }+ },+ );});describe('Dialogs', () => {diff --git a/tests/roots.test.ts b/tests/roots.test.tsindex 582fc603..005710a1 100644--- a/tests/roots.test.ts+++ b/tests/roots.test.ts@@ -5,7 +5,6 @@*/import assert from 'node:assert';-import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';import {describe, it} from 'node:test';@@ -13,7 +12,7 @@ import {pathToFileURL} from 'node:url';import {resolveCanonicalPath} from '../src/utils/files.js';-import {withMcpContext} from './utils.js';+import {createTempDir, withMcpContext} from './utils.js';describe('McpContext Roots', () => {it('should allow access to os.tmpdir() even if roots are empty', async () => {@@ -44,123 +43,99 @@ describe('McpContext Roots', () => {});it('should allow access to os.tmpdir() when other roots are set', async () => {+ using otherRoot = createTempDir('other_workspace_root_for_test-');await withMcpContext(async (_response, context) => {- const otherRoot = path.resolve(- os.tmpdir(),- 'other_workspace_root_for_test',- );- await fs.mkdir(otherRoot, {recursive: true});- try {- context.setRoots([{uri: pathToFileURL(otherRoot).href, name: 'other'}]);+ context.setRoots([+ {uri: pathToFileURL(otherRoot.path).href, name: 'other'},+ ]);- const tmpPath = path.join(os.tmpdir(), 'test-file.txt');- const resolvedTmp = await context.validatePath(tmpPath);- assert.strictEqual(resolvedTmp, await resolveCanonicalPath(tmpPath));+ const tmpPath = path.join(os.tmpdir(), 'test-file.txt');+ const resolvedTmp = await context.validatePath(tmpPath);+ assert.strictEqual(resolvedTmp, await resolveCanonicalPath(tmpPath));- // Other root should also be allowed.- const otherFile = path.join(otherRoot, 'file.txt');- const resolvedOther = await context.validatePath(otherFile);- assert.strictEqual(- resolvedOther,- await resolveCanonicalPath(otherFile),- );+ // Other root should also be allowed.+ const otherFile = path.join(otherRoot.path, 'file.txt');+ const resolvedOther = await context.validatePath(otherFile);+ assert.strictEqual(resolvedOther, await resolveCanonicalPath(otherFile));- // Outside should still be denied. Use a path that is definitely not a root or temp dir.- const outsidePath = path.resolve(- os.homedir(),- 'a_very_unlikely_path_name_12345',- );- await assert.rejects(- context.validatePath(outsidePath),- /Access denied/,- );- } finally {- await fs.rm(otherRoot, {recursive: true, force: true});- }+ // Outside should still be denied. Use a path that is definitely not a root or temp dir.+ const outsidePath = path.resolve(+ os.homedir(),+ 'a_very_unlikely_path_name_12345',+ );+ await assert.rejects(context.validatePath(outsidePath), /Access denied/);});});it('should enforce extensions and validate the output path', async () => {+ using workspace = createTempDir('workspace-root-');await withMcpContext(async (_response, context) => {- const workspacePath = await fs.mkdtemp(- path.join(os.tmpdir(), 'workspace-root-'),- );- try {- context.setRoots([- {uri: pathToFileURL(workspacePath).href, name: 'workspace'},- ]);-- const testCases: Array<{- filePath: string;- extension: '.json' | '.txt' | '.png' | '.zip';- expected: string;- }> = [- {- filePath: 'result',- extension: '.json',- expected: 'result.json',- },- {- filePath: 'result.jpg',- extension: '.txt',- expected: 'result.txt',- },- {- filePath: 'nested/result.jpg',- extension: '.png',- expected: 'nested/result.png',- },- {- filePath: '.bashrc',- extension: '.txt',- expected: '.bashrc.txt',- },- {- filePath: 'file.tar.gz',- extension: '.zip',- expected: 'file.tar.zip',- },- ];-- for (const testCase of testCases) {- const resolvedPath = await context.ensureExtension(- path.join(workspacePath, testCase.filePath),- testCase.extension,- );-- assert.strictEqual(- resolvedPath,- await resolveCanonicalPath(- path.join(workspacePath, testCase.expected),- ),- );- }- } finally {- await fs.rm(workspacePath, {recursive: true, force: true});+ context.setRoots([+ {uri: pathToFileURL(workspace.path).href, name: 'workspace'},+ ]);++ const testCases: Array<{+ filePath: string;+ extension: '.json' | '.txt' | '.png' | '.zip';+ expected: string;+ }> = [+ {+ filePath: 'result',+ extension: '.json',+ expected: 'result.json',+ },+ {+ filePath: 'result.jpg',+ extension: '.txt',+ expected: 'result.txt',+ },+ {+ filePath: 'nested/result.jpg',+ extension: '.png',+ expected: 'nested/result.png',+ },+ {+ filePath: '.bashrc',+ extension: '.txt',+ expected: '.bashrc.txt',+ },+ {+ filePath: 'file.tar.gz',+ extension: '.zip',+ expected: 'file.tar.zip',+ },+ ];++ for (const testCase of testCases) {+ const resolvedPath = await context.ensureExtension(+ path.join(workspace.path, testCase.filePath),+ testCase.extension,+ );++ assert.strictEqual(+ resolvedPath,+ await resolveCanonicalPath(+ path.join(workspace.path, testCase.expected),+ ),+ );}});});it('should deny extension-enforced paths outside roots', async () => {+ using workspace = createTempDir('workspace-root-');await withMcpContext(async (_response, context) => {- const workspacePath = await fs.mkdtemp(- path.join(os.tmpdir(), 'workspace-root-'),+ context.setRoots([+ {uri: pathToFileURL(workspace.path).href, name: 'workspace'},+ ]);++ await assert.rejects(+ context.ensureExtension(+ path.join(os.homedir(), 'outside-root-result'),+ '.json',+ ),+ /Access denied/,);- try {- context.setRoots([- {uri: pathToFileURL(workspacePath).href, name: 'workspace'},- ]);-- await assert.rejects(- context.ensureExtension(- path.join(os.homedir(), 'outside-root-result'),- '.json',- ),- /Access denied/,- );- } finally {- await fs.rm(workspacePath, {recursive: true, force: true});- }});});});diff --git a/tests/telemetry/persistence.test.ts b/tests/telemetry/persistence.test.tsindex a0fe62a6..c6007e07 100644--- a/tests/telemetry/persistence.test.ts+++ b/tests/telemetry/persistence.test.ts@@ -5,9 +5,7 @@*/import assert from 'node:assert';-import crypto from 'node:crypto';import fs from 'node:fs/promises';-import os from 'node:os';import path from 'node:path';import {describe, it, afterEach, beforeEach} from 'node:test';@@ -17,23 +15,21 @@ import {ClearcutLogger} from '../../src/telemetry/ClearcutLogger.js';import {ErrorCode} from '../../src/telemetry/errors.js';import * as persistence from '../../src/telemetry/persistence.js';import {WatchdogClient} from '../../src/telemetry/WatchdogClient.js';+import {createTempDir} from '../utils.js';describe('FilePersistence', () => {- let tmpDir: string;let logServerErrorStub: sinon.SinonStub;beforeEach(async () => {- tmpDir = path.join(- await fs.realpath(os.tmpdir()),- `telemetry-test-${crypto.randomUUID()}`,- );- await fs.mkdir(tmpDir, {recursive: true});-ClearcutLogger.resetForTesting();const mockWatchdog = sinon.createStubInstance(WatchdogClient);+ const mockPersistence = sinon.createStubInstance(+ persistence.FilePersistence,+ );+ mockPersistence.loadState.resolves({});const logger = ClearcutLogger.initialize({appVersion: '1.0.0',- persistence: new persistence.FilePersistence(tmpDir),+ persistence: mockPersistence,watchdogClient: mockWatchdog,});logServerErrorStub = sinon.stub(logger, 'logServerError');@@ -42,22 +38,23 @@ describe('FilePersistence', () => {afterEach(async () => {sinon.restore();ClearcutLogger.resetForTesting();- await fs.rm(tmpDir, {recursive: true, force: true});});describe('loadState', () => {it('returns default state and does NOT log telemetry if file does not exist (ENOENT)', async () => {- const filePersistence = new persistence.FilePersistence(tmpDir);+ using tmpDir = createTempDir('telemetry-test-');+ const filePersistence = new persistence.FilePersistence(tmpDir.path);const state = await filePersistence.loadState();assert.deepStrictEqual(state, {});sinon.assert.notCalled(logServerErrorStub);});it('returns default state and LOGS telemetry if load fails due to corruption', async () => {- const filePath = path.join(tmpDir, 'telemetry_state.json');+ using tmpDir = createTempDir('telemetry-test-');+ const filePath = path.join(tmpDir.path, 'telemetry_state.json');await fs.writeFile(filePath, 'not-valid-json', 'utf-8');- const filePersistence = new persistence.FilePersistence(tmpDir);+ const filePersistence = new persistence.FilePersistence(tmpDir.path);const state = await filePersistence.loadState();assert.deepStrictEqual(state, {});@@ -67,14 +64,15 @@ describe('FilePersistence', () => {});it('returns default state and LOGS telemetry if load fails during read stage', async () => {- const filePath = path.join(tmpDir, 'telemetry_state.json');+ using tmpDir = createTempDir('telemetry-test-');+ const filePath = path.join(tmpDir.path, 'telemetry_state.json');await fs.writeFile(filePath, '{"valid": "json"}', 'utf-8');const readFileStub = sinon.stub(fs, 'readFile').rejects(new Error('Synthetic read error'));- const filePersistence = new persistence.FilePersistence(tmpDir);+ const filePersistence = new persistence.FilePersistence(tmpDir.path);const state = await filePersistence.loadState();assert.deepStrictEqual(state, {});@@ -86,10 +84,11 @@ describe('FilePersistence', () => {});it('returns default state and LOGS telemetry if state file is empty', async () => {- const filePath = path.join(tmpDir, 'telemetry_state.json');+ using tmpDir = createTempDir('telemetry-test-');+ const filePath = path.join(tmpDir.path, 'telemetry_state.json');await fs.writeFile(filePath, '', 'utf-8');- const filePersistence = new persistence.FilePersistence(tmpDir);+ const filePersistence = new persistence.FilePersistence(tmpDir.path);const state = await filePersistence.loadState();assert.deepStrictEqual(state, {});@@ -99,14 +98,15 @@ describe('FilePersistence', () => {});it('returns default state if lastActive is invalid date string', async () => {- const filePath = path.join(tmpDir, 'telemetry_state.json');+ using tmpDir = createTempDir('telemetry-test-');+ const filePath = path.join(tmpDir.path, 'telemetry_state.json');await fs.writeFile(filePath,JSON.stringify({lastActive: 'invalid-date'}),'utf-8',);- const filePersistence = new persistence.FilePersistence(tmpDir);+ const filePersistence = new persistence.FilePersistence(tmpDir.path);const state = await filePersistence.loadState();assert.deepStrictEqual(state, {});@@ -114,7 +114,8 @@ describe('FilePersistence', () => {});it('returns default state if lastToolCall is invalid date string', async () => {- const filePath = path.join(tmpDir, 'telemetry_state.json');+ using tmpDir = createTempDir('telemetry-test-');+ const filePath = path.join(tmpDir.path, 'telemetry_state.json');await fs.writeFile(filePath,JSON.stringify({@@ -124,7 +125,7 @@ describe('FilePersistence', () => {'utf-8',);- const filePersistence = new persistence.FilePersistence(tmpDir);+ const filePersistence = new persistence.FilePersistence(tmpDir.path);const state = await filePersistence.loadState();assert.deepStrictEqual(state, {});@@ -132,16 +133,17 @@ describe('FilePersistence', () => {});it('returns stored state if file exists', async () => {+ using tmpDir = createTempDir('telemetry-test-');const expectedState = {lastActive: '2023-01-01T00:00:00.000Z',lastToolCall: '2023-01-01T12:00:00.000Z',};await fs.writeFile(- path.join(tmpDir, 'telemetry_state.json'),+ path.join(tmpDir.path, 'telemetry_state.json'),JSON.stringify(expectedState),);- const filePersistence = new persistence.FilePersistence(tmpDir);+ const filePersistence = new persistence.FilePersistence(tmpDir.path);const state = await filePersistence.loadState();assert.deepStrictEqual(state, expectedState);});@@ -149,15 +151,16 @@ describe('FilePersistence', () => {describe('saveState', () => {it('saves state to file', async () => {+ using tmpDir = createTempDir('telemetry-test-');const state = {lastActive: '2023-01-01T00:00:00.000Z',lastToolCall: '2023-01-01T12:00:00.000Z',};- const filePersistence = new persistence.FilePersistence(tmpDir);+ const filePersistence = new persistence.FilePersistence(tmpDir.path);await filePersistence.saveState(state);const content = await fs.readFile(- path.join(tmpDir, 'telemetry_state.json'),+ path.join(tmpDir.path, 'telemetry_state.json'),'utf-8',);assert.deepStrictEqual(JSON.parse(content), state);@@ -165,8 +168,9 @@ describe('FilePersistence', () => {});it('logs telemetry when failing to save to file', async () => {+ using tmpDir = createTempDir('telemetry-test-');// Force error by replacing directory with a file, causing mkdir to fail.- const dirPath = path.join(tmpDir, 'blocked_dir');+ const dirPath = path.join(tmpDir.path, 'blocked_dir');await fs.writeFile(dirPath, 'i-am-a-file');const filePersistence = new persistence.FilePersistence(dirPath);diff --git a/tests/tools/input.test.ts b/tests/tools/input.test.tsindex 34e0b775..171196fb 100644--- a/tests/tools/input.test.ts+++ b/tests/tools/input.test.ts@@ -5,8 +5,6 @@*/import assert from 'node:assert';-import fs from 'node:fs/promises';-import path from 'node:path';import {afterEach, describe, it} from 'node:test';import sinon from 'sinon';@@ -30,7 +28,12 @@ import {createMockElementHandle,} from '../mocks.js';import {serverHooks} from '../server.js';-import {html, withMcpContext, getTextContent} from '../utils.js';+import {+ createTempFile,+ html,+ withMcpContext,+ getTextContent,+} from '../utils.js';describe('input', () => {const server = serverHooks();@@ -1481,8 +1484,7 @@ describe('input', () => {describe('uploadFile', () => {it('uploads a file to a file input', async () => {- const testFilePath = path.join(process.cwd(), 'test.txt');- await fs.writeFile(testFilePath, 'test file content');+ using testFile = createTempFile('test file content', 'test.txt');await withMcpContext(async (response, context, args) => {const page = context.getSelectedMcpPage().pptrPage;@@ -1501,7 +1503,7 @@ describe('input', () => {{params: {uid: '1_2',- filePaths: [testFilePath],+ filePaths: [testFile.path],},page: context.getSelectedMcpPage(),},@@ -1511,18 +1513,14 @@ describe('input', () => {assert.ok(response.includeSnapshot);assert.strictEqual(response.responseLines[0],- `File uploaded from ${testFilePath}.`,+ `File uploaded from ${testFile.path}.`,);});-- await fs.unlink(testFilePath);});it('uploads multiple files to a file input', async () => {- const firstFilePath = path.join(process.cwd(), 'first.txt');- const secondFilePath = path.join(process.cwd(), 'second.txt');- await fs.writeFile(firstFilePath, 'first file content');- await fs.writeFile(secondFilePath, 'second file content');+ using firstFile = createTempFile('first file content', 'first.txt');+ using secondFile = createTempFile('second file content', 'second.txt');await withMcpContext(async (response, context, args) => {const page = context.getSelectedMcpPage().pptrPage;@@ -1542,7 +1540,7 @@ describe('input', () => {{params: {uid: '1_2',- filePaths: [firstFilePath, secondFilePath],+ filePaths: [firstFile.path, secondFile.path],},page: context.getSelectedMcpPage(),},@@ -1551,7 +1549,7 @@ describe('input', () => {);assert.strictEqual(response.responseLines[0],- `File uploaded from ${firstFilePath}, ${secondFilePath}.`,+ `File uploaded from ${firstFile.path}, ${secondFile.path}.`,);const uploadedFileNames = await page.$eval('#file-input', el => {const input = el as HTMLInputElement;@@ -1559,14 +1557,10 @@ describe('input', () => {});assert.deepStrictEqual(uploadedFileNames, ['first.txt', 'second.txt']);});-- await fs.unlink(firstFilePath);- await fs.unlink(secondFilePath);});it('uploads a file when clicking an element opens a file uploader', async () => {- const testFilePath = path.join(process.cwd(), 'test.txt');- await fs.writeFile(testFilePath, 'test file content');+ using testFile = createTempFile('test file content', 'test.txt');await withMcpContext(async (response, context, args) => {const page = context.getSelectedMcpPage().pptrPage;@@ -1592,7 +1586,7 @@ describe('input', () => {{params: {uid: '1_1',- filePaths: [testFilePath],+ filePaths: [testFile.path],},page: context.getSelectedMcpPage(),},@@ -1602,21 +1596,18 @@ describe('input', () => {assert.ok(response.includeSnapshot);assert.strictEqual(response.responseLines[0],- `File uploaded from ${testFilePath}.`,+ `File uploaded from ${testFile.path}.`,);const uploadedFileName = await page.$eval('#file-input', el => {const input = el as HTMLInputElement;return input.files?.[0]?.name;});assert.strictEqual(uploadedFileName, 'test.txt');-- await fs.unlink(testFilePath);});});it('throws an error if the element is not a file input and does not open a file chooser', async () => {- const testFilePath = path.join(process.cwd(), 'test.txt');- await fs.writeFile(testFilePath, 'test file content');+ using testFile = createTempFile('test file content', 'test.txt');await withMcpContext(async (response, context, args) => {const page = context.getSelectedMcpPage().pptrPage;@@ -1630,7 +1621,7 @@ describe('input', () => {{params: {uid: '1_1',- filePaths: [testFilePath],+ filePaths: [testFile.path],},page: context.getSelectedMcpPage(),},@@ -1645,8 +1636,6 @@ describe('input', () => {assert.strictEqual(response.responseLines.length, 0);assert.strictEqual(response.snapshotParams, undefined);-- await fs.unlink(testFilePath);});});});diff --git a/tests/tools/lighthouse.test.ts b/tests/tools/lighthouse.test.tsindex a5d76391..3bc9d3c1 100644--- a/tests/tools/lighthouse.test.ts+++ b/tests/tools/lighthouse.test.ts@@ -6,8 +6,6 @@import assert from 'node:assert/strict';import fs from 'node:fs/promises';-import os from 'node:os';-import path from 'node:path';import {afterEach, describe, it} from 'node:test';import sinon from 'sinon';@@ -17,7 +15,7 @@ import {lighthouseAudit} from '../../src/tools/lighthouse.js';import {resolveCanonicalPath} from '../../src/utils/files.js';import {createHandlerMocks, createMockRunnerResult} from '../mocks.js';import {serverHooks} from '../server.js';-import {html, withMcpContext} from '../utils.js';+import {createTempDir, html, withMcpContext} from '../utils.js';describe('lighthouse', () => {afterEach(() => {@@ -217,43 +215,35 @@ describe('lighthouse', () => {it('runs Lighthouse with custom output dir', async () => {server.addHtmlRoute('/test-mobile', html`<div>Test Mobile</div>`);- const tmpDir = os.tmpdir();- const folderPath = path.join(- tmpDir,- `temp-folder-${crypto.randomUUID()}`,- );+ using folder = createTempDir('temp-folder-');- try {- await withMcpContext(async (response, context, args) => {- const page = context.getSelectedMcpPage().pptrPage;- await page.goto(server.getRoute('/test-mobile'));+ await withMcpContext(async (response, context, args) => {+ const page = context.getSelectedMcpPage().pptrPage;+ await page.goto(server.getRoute('/test-mobile'));- await lighthouseAudit(args).handler(- {- params: {- mode: 'snapshot',- device: 'mobile',- outputDirPath: folderPath,- },- page: context.getSelectedMcpPage(),+ await lighthouseAudit(args).handler(+ {+ params: {+ mode: 'snapshot',+ device: 'mobile',+ outputDirPath: folder.path,},- response,- context,- );-- const data = response.attachedLighthouseResult;- assert.ok(data);- assert.equal(data.summary.mode, 'snapshot');- assert.equal(data.summary.device, 'mobile');- assert.ok(data.reports.length === 2);- const canonicalFolderPath = await resolveCanonicalPath(folderPath);- for (const report of data.reports) {- assert.ok(report.startsWith(canonicalFolderPath));- }- });- } finally {- await fs.rm(folderPath, {recursive: true, force: true});- }+ page: context.getSelectedMcpPage(),+ },+ response,+ context,+ );++ const data = response.attachedLighthouseResult;+ assert.ok(data);+ assert.equal(data.summary.mode, 'snapshot');+ assert.equal(data.summary.device, 'mobile');+ assert.ok(data.reports.length === 2);+ const canonicalFolderPath = await resolveCanonicalPath(folder.path);+ for (const report of data.reports) {+ assert.ok(report.startsWith(canonicalFolderPath));+ }+ });});});});diff --git a/tests/tools/memory.test.ts b/tests/tools/memory.test.tsindex b556170c..8a2cf787 100644--- a/tests/tools/memory.test.ts+++ b/tests/tools/memory.test.ts@@ -6,8 +6,6 @@import assert from 'node:assert';import {existsSync} from 'node:fs';-import {rm} from 'node:fs/promises';-import {tmpdir} from 'node:os';import {join} from 'node:path';import {describe, it, afterEach} from 'node:test';@@ -45,7 +43,7 @@ import {createMockRetainedByContextSummary,createMockRetainingPaths,} from '../mocks.js';-import {withMcpContext} from '../utils.js';+import {createTempDir, withMcpContext} from '../utils.js';describe('memory', () => {afterEach(() => {@@ -54,23 +52,20 @@ describe('memory', () => {describe('take_heapsnapshot', () => {it('with default options', async () => {+ using tmpDir = createTempDir();await withMcpContext(async (response, context, args) => {- const filePath = join(tmpdir(), 'test-screenshot.heapsnapshot');- try {- await takeHeapSnapshot(args).handler(- {params: {filePath}, page: context.getSelectedMcpPage()},- response,- context,- );- const canonicalFilePath = await resolveCanonicalPath(filePath);- assert.equal(- response.responseLines.at(0),- `Heap snapshot saved to ${canonicalFilePath}`,- );- assert.ok(existsSync(filePath));- } finally {- await rm(filePath, {force: true});- }+ const filePath = join(tmpDir.path, 'test-screenshot.heapsnapshot');+ await takeHeapSnapshot(args).handler(+ {params: {filePath}, page: context.getSelectedMcpPage()},+ response,+ context,+ );+ const canonicalFilePath = await resolveCanonicalPath(filePath);+ assert.equal(+ response.responseLines.at(0),+ `Heap snapshot saved to ${canonicalFilePath}`,+ );+ assert.ok(existsSync(filePath));});});diff --git a/tests/tools/screenshot.test.ts b/tests/tools/screenshot.test.tsindex 587bec5e..23ba8d81 100644--- a/tests/tools/screenshot.test.ts+++ b/tests/tools/screenshot.test.ts@@ -5,8 +5,7 @@*/import assert from 'node:assert';-import {rm, stat, mkdir, chmod, writeFile} from 'node:fs/promises';-import {tmpdir} from 'node:os';+import {stat, chmod, writeFile} from 'node:fs/promises';import {join} from 'node:path';import {describe, it, afterEach} from 'node:test';@@ -17,7 +16,7 @@ import {TextSnapshot} from '../../src/TextSnapshot.js';import {screenshot} from '../../src/tools/screenshot.js';import {resolveCanonicalPath} from '../../src/utils/files.js';import {screenshots} from '../snapshot.js';-import {html, withMcpContext} from '../utils.js';+import {createTempDir, html, withMcpContext} from '../utils.js';const screenshotTool = screenshot({} as ParsedArguments);@@ -255,45 +254,43 @@ describe('screenshot', () => {});it('with filePath', async () => {+ using tmpDir = createTempDir();await withMcpContext(async (response, context) => {- const filePath = join(tmpdir(), 'test-screenshot.png');- try {- const fixture = screenshots.basic;- const page = context.getSelectedMcpPage().pptrPage;- await page.setContent(fixture.html);- await screenshotTool.handler(- {- params: {format: 'png', filePath},- page: context.getSelectedMcpPage(),- },- response,- context,- );+ const filePath = join(tmpDir.path, 'test-screenshot.png');+ const fixture = screenshots.basic;+ const page = context.getSelectedMcpPage().pptrPage;+ await page.setContent(fixture.html);+ await screenshotTool.handler(+ {+ params: {format: 'png', filePath},+ page: context.getSelectedMcpPage(),+ },+ response,+ context,+ );- assert.equal(response.images.length, 0);- assert.equal(- response.responseLines.at(0),- "Took a screenshot of the current page's viewport.",- );- const canonicalFilePath = await resolveCanonicalPath(filePath);- assert.equal(- response.responseLines.at(1),- `Saved screenshot to ${canonicalFilePath}.`,- );+ assert.equal(response.images.length, 0);+ assert.equal(+ response.responseLines.at(0),+ "Took a screenshot of the current page's viewport.",+ );+ const canonicalFilePath = await resolveCanonicalPath(filePath);+ assert.equal(+ response.responseLines.at(1),+ `Saved screenshot to ${canonicalFilePath}.`,+ );- const stats = await stat(filePath);- assert.ok(stats.isFile());- assert.ok(stats.size > 0);- } finally {- await rm(filePath, {force: true});- }+ const stats = await stat(filePath);+ assert.ok(stats.isFile());+ assert.ok(stats.size > 0);});});it('with unwritable filePath', async () => {if (process.platform === 'win32') {+ using tmpDir = createTempDir();const filePath = join(- tmpdir(),+ tmpDir.path,'readonly-file-for-screenshot-test.png',);// Create the file and make it read-only.@@ -319,13 +316,11 @@ describe('screenshot', () => {} finally {// Make the file writable again so it can be deleted.await chmod(filePath, 0o600);- await rm(filePath, {force: true});}} else {- const dir = join(tmpdir(), 'readonly-dir-for-screenshot-test');- await mkdir(dir, {recursive: true});- await chmod(dir, 0o500);- const filePath = join(dir, 'test-screenshot.png');+ using dir = createTempDir('readonly-dir-for-screenshot-test-');+ await chmod(dir.path, 0o500);+ const filePath = join(dir.path, 'test-screenshot.png');try {await withMcpContext(async (response, context) => {@@ -344,8 +339,7 @@ describe('screenshot', () => {);});} finally {- await chmod(dir, 0o700);- await rm(dir, {recursive: true, force: true});+ await chmod(dir.path, 0o700);}}});diff --git a/tests/tools/script.test.ts b/tests/tools/script.test.tsindex 536ea6e6..a641f41c 100644--- a/tests/tools/script.test.ts+++ b/tests/tools/script.test.ts@@ -7,6 +7,7 @@import assert from 'node:assert';import path from 'node:path';import {describe, it} from 'node:test';+import {readFile} from 'node:fs/promises';import sinon from 'sinon';@@ -19,6 +20,7 @@ import {WaitForHelper} from '../../src/utils/WaitForHelper.js';import {serverHooks} from '../server.js';import {assertNoServiceWorkerReported,+ createTempDir,extractExtensionId,html,withMcpContext,@@ -310,33 +312,30 @@ describe('script', () => {});});it('saves output to file when filePath is provided', async () => {- const {rm, readFile} = await import('node:fs/promises');- const {tmpdir} = await import('node:os');- const {join} = await import('node:path');- const filePath = join(tmpdir(), 'test-evaluate-script-output.json');- try {- await withMcpContext(async (response, context, args) => {- await evaluateScript(args).handler(- {- params: {- function: String(() => ({hello: 'world'})),- filePath,- },+ using tmpDir = createTempDir();+ const filePath = path.join(+ tmpDir.path,+ 'test-evaluate-script-output.json',+ );+ await withMcpContext(async (response, context, args) => {+ await evaluateScript(args).handler(+ {+ params: {+ function: String(() => ({hello: 'world'})),+ filePath,},- response,- context,- );- assert.strictEqual(response.responseLines.length, 1);- assert.ok(- response.responseLines[0]?.includes('Output saved to'),- `Expected "Output saved to" but got: ${response.responseLines[0]}`,- );- });- const content = await readFile(filePath, 'utf-8');- assert.deepStrictEqual(JSON.parse(content), {hello: 'world'});- } finally {- await rm(filePath, {force: true});- }+ },+ response,+ context,+ );+ assert.strictEqual(response.responseLines.length, 1);+ assert.ok(+ response.responseLines[0]?.includes('Output saved to'),+ `Expected "Output saved to" but got: ${response.responseLines[0]}`,+ );+ });+ const content = await readFile(filePath, 'utf-8');+ assert.deepStrictEqual(JSON.parse(content), {hello: 'world'});});it('evaluates inside extension service worker', async () => {await withMcpContext(diff --git a/tests/utils.ts b/tests/utils.tsindex 21a0bd9c..8af66b8e 100644--- a/tests/utils.ts+++ b/tests/utils.ts@@ -6,6 +6,8 @@import assert from 'node:assert';import {spawn, type ChildProcess} from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';import path from 'node:path';import type {Browser} from 'puppeteer';@@ -479,3 +481,42 @@ export async function waitExecutionFor(throw new Error(`Timeout of ${timeout} reached.`);}++export function createTempDir(+ prefix = 'chrome-devtools-test-',+ baseDir = os.tmpdir(),+) {+ const dirPath = fs.mkdtempSync(path.join(baseDir, prefix));+ return {+ path: dirPath,+ [Symbol.dispose]() {+ try {+ fs.rmSync(dirPath, {recursive: true, force: true});+ } catch {+ // ignore+ }+ },+ };+}++export function createTempFile(+ content: string,+ fileName: string,+ baseDir = os.tmpdir(),+) {+ const dirPath = fs.mkdtempSync(+ path.join(baseDir, 'chrome-devtools-test-file-'),+ );+ const filePath = path.join(dirPath, fileName);+ fs.writeFileSync(filePath, content);+ return {+ path: filePath,+ [Symbol.dispose]() {+ try {+ fs.rmSync(dirPath, {recursive: true, force: true});+ } catch {+ // ignore+ }+ },+ };+}diff --git a/tests/utils/files.test.ts b/tests/utils/files.test.tsindex 342d42c5..41d17012 100644--- a/tests/utils/files.test.ts+++ b/tests/utils/files.test.ts@@ -8,9 +8,10 @@ import assert from 'node:assert';import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';-import {afterEach, beforeEach, describe, it} from 'node:test';+import {describe, it} from 'node:test';import {resolveCanonicalPath} from '../../src/utils/files.js';+import {createTempDir} from '../utils.js';async function createSymlinkOrSkip(t: it.TestContext,@@ -36,22 +37,10 @@ async function createSymlinkOrSkip(}describe('resolveCanonicalPath', () => {- let tmpDir: string;- let canonicalTmpDir: string;-- beforeEach(async () => {- tmpDir = await fs.mkdtemp(- path.join(os.tmpdir(), 'resolve-canonical-test-'),- );- canonicalTmpDir = await fs.realpath(tmpDir);- });-- afterEach(async () => {- await fs.rm(tmpDir, {recursive: true, force: true});- });-it('should resolve an existing standard file path', async () => {- const filePath = path.join(tmpDir, 'test.txt');+ using tmpDir = createTempDir('resolve-canonical-test-');+ const canonicalTmpDir = await fs.realpath(tmpDir.path);+ const filePath = path.join(tmpDir.path, 'test.txt');await fs.writeFile(filePath, 'hello');const resolved = await resolveCanonicalPath(filePath);@@ -59,7 +48,9 @@ describe('resolveCanonicalPath', () => {});it('should resolve a non-existent file whose parent directory exists', async () => {- const filePath = path.join(tmpDir, 'non-existent.txt');+ using tmpDir = createTempDir('resolve-canonical-test-');+ const canonicalTmpDir = await fs.realpath(tmpDir.path);+ const filePath = path.join(tmpDir.path, 'non-existent.txt');const resolved = await resolveCanonicalPath(filePath);assert.strictEqual(@@ -69,8 +60,10 @@ describe('resolveCanonicalPath', () => {});it('should resolve a non-existent deeply nested file whose parent directories do not exist', async () => {+ using tmpDir = createTempDir('resolve-canonical-test-');+ const canonicalTmpDir = await fs.realpath(tmpDir.path);const filePath = path.join(- tmpDir,+ tmpDir.path,'nested1','nested2','non-existent.txt',@@ -84,12 +77,13 @@ describe('resolveCanonicalPath', () => {});it('should resolve existing files with symlinks in path', async t => {- const targetDir = path.join(tmpDir, 'target');+ using tmpDir = createTempDir('resolve-canonical-test-');+ const targetDir = path.join(tmpDir.path, 'target');await fs.mkdir(targetDir);const targetFile = path.join(targetDir, 'file.txt');await fs.writeFile(targetFile, 'hello');- const symlinkDir = path.join(tmpDir, 'symlink_dir');+ const symlinkDir = path.join(tmpDir.path, 'symlink_dir');const created = await createSymlinkOrSkip(t, targetDir, symlinkDir, 'dir');if (!created) {return;@@ -103,10 +97,11 @@ describe('resolveCanonicalPath', () => {});it('should resolve non-existent files with symlinks in path', async t => {- const targetDir = path.join(tmpDir, 'target');+ using tmpDir = createTempDir('resolve-canonical-test-');+ const targetDir = path.join(tmpDir.path, 'target');await fs.mkdir(targetDir);- const symlinkDir = path.join(tmpDir, 'symlink_dir');+ const symlinkDir = path.join(tmpDir.path, 'symlink_dir');const created = await createSymlinkOrSkip(t, targetDir, symlinkDir, 'dir');if (!created) {return;@@ -123,8 +118,10 @@ describe('resolveCanonicalPath', () => {});it('should resolve dangling symlink at the end of path', async t => {- const nonExistentTarget = path.join(tmpDir, 'non-existent-target.txt');- const danglingSymlink = path.join(tmpDir, 'dangling-symlink.txt');+ using tmpDir = createTempDir('resolve-canonical-test-');+ const canonicalTmpDir = await fs.realpath(tmpDir.path);+ const nonExistentTarget = path.join(tmpDir.path, 'non-existent-target.txt');+ const danglingSymlink = path.join(tmpDir.path, 'dangling-symlink.txt');const created = await createSymlinkOrSkip(t,nonExistentTarget,@@ -142,8 +139,10 @@ describe('resolveCanonicalPath', () => {});it('should resolve path with a dangling symlink directory in the middle', async t => {- const nonExistentTargetDir = path.join(tmpDir, 'non-existent-dir');- const danglingSymlinkDir = path.join(tmpDir, 'dangling-dir');+ using tmpDir = createTempDir('resolve-canonical-test-');+ const canonicalTmpDir = await fs.realpath(tmpDir.path);+ const nonExistentTargetDir = path.join(tmpDir.path, 'non-existent-dir');+ const danglingSymlinkDir = path.join(tmpDir.path, 'dangling-dir');const created = await createSymlinkOrSkip(t,nonExistentTargetDir,