Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

test: use commonFixtures for mcp cli tests (#38959)

Dmitry Gozmandf7b3f3c43a6
diff --git a/tests/config/commonFixtures.ts b/tests/config/commonFixtures.ts
index e28feed7b2..0c7fef0db2 100644
--- a/tests/config/commonFixtures.ts
+++ b/tests/config/commonFixtures.ts
@@ -75,7 +75,7 @@ function readAllProcessesMacOS(): { pid: number, ppid: number, pgrp: number }[]
return result;
}
-function buildProcessTreePosix(pid: number): ProcessData {
+function buildProcessTreePosix(pid: number): ProcessData | undefined {
// Certain Linux distributions might not have `ps` installed.
const allProcesses = process.platform === 'darwin' ? readAllProcessesMacOS() : readAllProcessesLinux();
const pidToProcess = new Map<number, ProcessData>();
@@ -89,7 +89,7 @@ function buildProcessTreePosix(pid: number): ProcessData {
if (parent && child)
parent.children.add(child);
}
- return pidToProcess.get(pid)!;
+ return pidToProcess.get(pid);
}
export class TestChildProcess {
@@ -167,50 +167,15 @@ export class TestChildProcess {
private _killProcessTree(signal: 'SIGINT' | 'SIGKILL') {
if (!this.process.pid || !this.process.kill(0))
return;
-
- // On Windows, we always call `taskkill` no matter signal.
- if (process.platform === 'win32') {
- try {
- execSync(`taskkill /pid ${this.process.pid} /T /F /FI "MEMUSAGE gt 0"`, { stdio: 'ignore' });
- } catch (e) {
- // the process might have already stopped
- }
- return;
- }
-
- // In case of POSIX and `SIGINT` signal, send it to the main process group only.
- if (signal === 'SIGINT') {
- try {
- process.kill(-this.process.pid, 'SIGINT');
- } catch (e) {
- // the process might have already stopped
- }
- return;
- }
-
- // In case of POSIX and `SIGKILL` signal, we should send it to all descendant process groups.
- const rootProcess = buildProcessTreePosix(this.process.pid);
- const descendantProcessGroups = (function flatten(processData: ProcessData, result: Set<number> = new Set()) {
- // Process can nullify its own process group with `setpgid`. Use its PID instead.
- result.add(processData.pgrp || processData.pid);
- processData.children.forEach(child => flatten(child, result));
- return result;
- })(rootProcess);
- for (const pgrp of descendantProcessGroups) {
- try {
- process.kill(-pgrp, 'SIGKILL');
- } catch (e) {
- // the process might have already stopped
- }
- }
+ killProcessGroup(this.process.pid, signal);
}
async cleanExit() {
const r = await this.exited;
if (r.exitCode)
- throw new Error(`Process failed with exit code ${r.exitCode}`);
+ throw new Error(`Process failed with exit code ${r.exitCode}. Output:\n${this.output}`);
if (r.signal)
- throw new Error(`Process received signal: ${r.signal}`);
+ throw new Error(`Process received signal: ${r.signal}. Output:\n${this.output}`);
}
async waitForOutput(substring: string, count = 1) {
@@ -227,6 +192,47 @@ export class TestChildProcess {
}
}
+export function killProcessGroup(pid: number, signal: 'SIGINT' | 'SIGKILL' = 'SIGKILL') {
+ // On Windows, we always call `taskkill` no matter signal.
+ if (process.platform === 'win32') {
+ try {
+ execSync(`taskkill /pid ${pid} /T /F /FI "MEMUSAGE gt 0"`, { stdio: 'ignore' });
+ } catch (e) {
+ // the process might have already stopped
+ }
+ return;
+ }
+
+ // In case of POSIX and `SIGINT` signal, send it to the main process group only.
+ if (signal === 'SIGINT') {
+ try {
+ process.kill(-pid, 'SIGINT');
+ } catch (e) {
+ // the process might have already stopped
+ }
+ return;
+ }
+
+ // In case of POSIX and `SIGKILL` signal, we should send it to all descendant process groups.
+ const rootProcess = buildProcessTreePosix(pid);
+ if (!rootProcess)
+ return;
+
+ const descendantProcessGroups = (function flatten(processData: ProcessData, result: Set<number> = new Set()) {
+ // Process can nullify its own process group with `setpgid`. Use its PID instead.
+ result.add(processData.pgrp || processData.pid);
+ processData.children.forEach(child => flatten(child, result));
+ return result;
+ })(rootProcess);
+ for (const pgrp of descendantProcessGroups) {
+ try {
+ process.kill(-pgrp, 'SIGKILL');
+ } catch (e) {
+ // the process might have already stopped
+ }
+ }
+}
+
export type CommonFixtures = {
childProcess: (params: TestChildParams) => TestChildProcess;
waitForPort: (port: number) => Promise<void>;
diff --git a/tests/mcp/cli-fixtures.ts b/tests/mcp/cli-fixtures.ts
index 1aa8889fab..0ef9b81c05 100644
--- a/tests/mcp/cli-fixtures.ts
+++ b/tests/mcp/cli-fixtures.ts
@@ -16,9 +16,11 @@
import fs from 'fs';
import path from 'path';
-import { spawn } from 'child_process';
import { test as baseTest } from './fixtures';
+import { killProcessGroup } from '../config/commonFixtures';
+
+import type { CommonFixtures } from '../config/commonFixtures';
export { expect } from './fixtures';
export const test = baseTest.extend<{
@@ -29,19 +31,16 @@ export const test = baseTest.extend<{
attachments?: { name: string, data: Buffer | null }[],
}>;
}>({
- cli: async ({ mcpBrowser, mcpHeadless }, use) => {
+ cli: async ({ mcpBrowser, mcpHeadless, childProcess }, use) => {
const sessions: { name: string, pid: number }[] = [];
await use(async (...args: string[]) => {
- return await runCli(args, { mcpBrowser, mcpHeadless }, sessions);
+ return await runCli(childProcess, args, { mcpBrowser, mcpHeadless }, sessions);
});
for (const session of sessions) {
- await runCli(['session-stop', session.name], { mcpBrowser, mcpHeadless }, []);
- try {
- process.kill(session.pid, 'SIGTERM');
- } catch (e) {
- }
+ await runCli(childProcess, ['session-stop', session.name], { mcpBrowser, mcpHeadless }, []);
+ killProcessGroup(session.pid);
}
const daemonDir = path.join(test.info().outputDir, 'daemon');
@@ -51,50 +50,45 @@ export const test = baseTest.extend<{
},
});
-async function runCli(args: string[], options: { mcpBrowser: string, mcpHeadless: boolean }, sessions: { name: string, pid: number }[]) {
- const testInfo = test.info();
- const cli = spawn(process.execPath, [require.resolve('../../packages/playwright/lib/mcp/terminal/cli.js'), ...args], {
- cwd: testInfo.outputPath(),
- stdio: 'pipe',
- env: {
- ...process.env,
- PLAYWRIGHT_DAEMON_INSTALL_DIR: testInfo.outputPath(),
- PLAYWRIGHT_DAEMON_SESSION_DIR: testInfo.outputPath('daemon'),
- PLAYWRIGHT_DAEMON_SOCKETS_DIR: path.join(testInfo.project.outputDir, 'daemon-sockets'),
- PLAYWRIGHT_MCP_BROWSER: options.mcpBrowser,
- PLAYWRIGHT_MCP_HEADLESS: String(options.mcpHeadless),
- },
- });
- let stdout = '';
- let stderr = '';
- cli.stdout.on('data', data => { stdout += data.toString(); });
- cli.stderr.on('data', data => { stderr += data.toString(); });
- await new Promise<void>((resolve, reject) => {
- cli.on('close', code => {
- if (code === 0)
- resolve();
- else
- reject(new Error(`CLI exited with code ${code}: ${stderr}`));
+async function runCli(childProcess: CommonFixtures['childProcess'], args: string[], options: { mcpBrowser: string, mcpHeadless: boolean }, sessions: { name: string, pid: number }[]) {
+ const stepTitle = `cli ${args.join(' ')}`;
+ return await test.step(stepTitle, async () => {
+ const testInfo = test.info();
+ const cli = childProcess({
+ command: [process.execPath, require.resolve('../../packages/playwright/lib/mcp/terminal/cli.js'), ...args],
+ cwd: testInfo.outputPath(),
+ env: {
+ ...process.env,
+ PLAYWRIGHT_DAEMON_INSTALL_DIR: testInfo.outputPath(),
+ PLAYWRIGHT_DAEMON_SESSION_DIR: testInfo.outputPath('daemon'),
+ PLAYWRIGHT_DAEMON_SOCKETS_DIR: path.join(testInfo.project.outputDir, 'daemon-sockets'),
+ PLAYWRIGHT_MCP_BROWSER: options.mcpBrowser,
+ PLAYWRIGHT_MCP_HEADLESS: String(options.mcpHeadless),
+ },
});
- });
- let snapshot: string | undefined;
- if (stdout.includes('### Snapshot'))
- snapshot = await loadSnapshot(stdout);
- const attachments = loadAttachments(stdout);
+ await cli.cleanExit().finally(async () => {
+ await testInfo.attach(stepTitle, { body: cli.output, contentType: 'text/plain' });
+ });
+
+ let snapshot: string | undefined;
+ if (cli.stdout.includes('### Snapshot'))
+ snapshot = await loadSnapshot(cli.stdout);
+ const attachments = loadAttachments(cli.stdout);
- const matches = stdout.includes('Daemon for') ? stdout.match(/Daemon for `(.+)` session started with pid (\d+)\./) : undefined;
- const [, sessionName, pid] = matches ?? [];
- if (sessionName && pid)
- sessions.push({ name: sessionName, pid: +pid });
- return {
- output: stdout.trim(),
- error: stderr.trim(),
- snapshot,
- attachments
- };
+ const matches = cli.stdout.includes('Daemon for') ? cli.stdout.match(/Daemon for `(.+)` session started with pid (\d+)\./) : undefined;
+ const [, sessionName, pid] = matches ?? [];
+ if (sessionName && pid)
+ sessions.push({ name: sessionName, pid: +pid });
+ return {
+ output: cli.stdout.trim(),
+ error: cli.stderr.trim(),
+ snapshot,
+ attachments
+ };
+ });
}
-export function loadAttachments(output: string) {
+function loadAttachments(output: string) {
// attachments look like md links - [Page as pdf](.playwright-cli/page-2026-01-22T23-13-56-347Z.pdf)
const match = output.match(/- \[(.+)\]\((.+)\)/g);
if (!match)
@@ -111,7 +105,7 @@ export function loadAttachments(output: string) {
});
}
-export async function loadSnapshot(output: string) {
+async function loadSnapshot(output: string) {
const lines = output.split('\n');
if (!lines.includes('### Snapshot'))
throw new Error('Snapshot file not found');
diff --git a/tests/mcp/fixtures.ts b/tests/mcp/fixtures.ts
index bb758a28e0..ee2043a691 100644
--- a/tests/mcp/fixtures.ts
+++ b/tests/mcp/fixtures.ts
@@ -26,7 +26,9 @@ import { ListRootsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { TestServer } from '../config/testserver';
import { serverFixtures } from '../config/serverFixtures';
import { parseResponse } from '../../packages/playwright/lib/mcp/browser/response';
+import { commonFixtures } from '../config/commonFixtures';
+import type { CommonFixtures, CommonWorkerFixtures } from '../config/commonFixtures';
import type { Config } from '../../packages/playwright/src/mcp/config';
import type { BrowserContext } from 'playwright';
import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
@@ -74,7 +76,9 @@ type WorkerFixtures = {
_workerServers: { server: TestServer, httpsServer: TestServer };
};
-export const serverTest = baseTest.extend<ServerFixtures, ServerWorkerOptions>(serverFixtures);
+export const serverTest = baseTest
+ .extend<CommonFixtures, CommonWorkerFixtures>(commonFixtures)
+ .extend<ServerFixtures, ServerWorkerOptions>(serverFixtures);
export const test = serverTest.extend<TestFixtures & TestOptions, WorkerFixtures>({
mcpArgs: [undefined, { option: true }],