Skip to content

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

feat(cli): add network log (#39072)

Yury Semikhatsky4b68c65345c7
diff --git a/packages/playwright/src/mcp/browser/logFile.ts b/packages/playwright/src/mcp/browser/logFile.ts
new file mode 100644
index 0000000000..05773d8efc
--- /dev/null
+++ b/packages/playwright/src/mcp/browser/logFile.ts
@@ -0,0 +1,92 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import fs from 'fs';
+
+import { dateAsFileName } from './tools/utils';
+import { logUnhandledError } from '../log';
+
+import type { Context } from './context';
+
+export type LogChunk = {
+ type: string;
+ file: string;
+ fromLine: number;
+ toLine: number;
+ entryCount: number;
+};
+
+export class LogFile {
+ private _startTime: number;
+ private _context: Context;
+ private _filePrefix: string;
+ private _title: string;
+
+ private _file: string | undefined;
+ private _stopped: boolean = false;
+
+ private _line: number = 0;
+ private _entries: number = 0;
+ private _lastLine: number = 0;
+ private _lastEntries: number = 0;
+
+ private _writeChain: Promise<void> = Promise.resolve();
+
+ constructor(context: Context, startTime: number, filePrefix: string, title: string) {
+ this._context = context;
+ this._startTime = startTime;
+ this._filePrefix = filePrefix;
+ this._title = title;
+ }
+
+ appendLine(wallTime: number, text: () => string | Promise<string>) {
+ this._writeChain = this._writeChain.then(() => this._write(wallTime, text)).catch(logUnhandledError);
+ }
+
+ stop() {
+ this._stopped = true;
+ }
+
+ async take(): Promise<LogChunk | undefined> {
+ await this._writeChain;
+ if (!this._file || this._entries === this._lastEntries)
+ return undefined;
+ const chunk: LogChunk = {
+ type: this._title.toLowerCase(),
+ file: this._file,
+ fromLine: this._lastLine + 1,
+ toLine: this._line,
+ entryCount: this._entries - this._lastEntries,
+ };
+ this._lastLine = this._line;
+ this._lastEntries = this._entries;
+ return chunk;
+ }
+
+ private async _write(wallTime: number, text: () => string | Promise<string>) {
+ if (this._stopped)
+ return;
+ this._file ??= await this._context.outputFile(dateAsFileName(this._filePrefix, 'log', new Date(this._startTime)), { origin: 'code', title: this._title });
+ const relativeTime = Math.round(wallTime - this._startTime);
+ const renderedText = await text();
+ const logLine = `[${String(relativeTime).padStart(8, ' ')}ms] ${renderedText}\n`;
+ await fs.promises.appendFile(this._file, logLine);
+
+ const lineCount = logLine.split('\n').length - 1;
+ this._line += lineCount;
+ this._entries++;
+ }
+}
diff --git a/packages/playwright/src/mcp/browser/response.ts b/packages/playwright/src/mcp/browser/response.ts
index f1e432e573..ff5d20452c 100644
--- a/packages/playwright/src/mcp/browser/response.ts
+++ b/packages/playwright/src/mcp/browser/response.ts
@@ -22,7 +22,8 @@ import { renderModalStates, shouldIncludeMessage } from './tab';
import { dateAsFileName } from './tools/utils';
import { scaleImageToFitMessage } from './tools/screenshot';
-import type { LogChunk, TabHeader } from './tab';
+import type { TabHeader } from './tab';
+import type { LogChunk } from './logFile';
import type { CallToolResult, ImageContent, TextContent } from '@modelcontextprotocol/sdk/types.js';
import type { Context } from './context';
@@ -40,7 +41,7 @@ type ResolvedFile = {
printableLink: string;
};
-export type Section = {
+type Section = {
title: string;
content: string[];
isError?: boolean;
@@ -217,21 +218,21 @@ export class Response {
}
// Handle tab log
- const text: string[] = renderLogChunk(tabSnapshot?.logChunk, 'console', file => this._computRelativeTo(file));
+ const text: string[] = tabSnapshot?.logs?.map(log => renderLogChunk(log, log.type, file => this._computRelativeTo(file))).flat() ?? [];
if (tabSnapshot?.events.filter(event => event.type !== 'request').length) {
for (const event of tabSnapshot.events) {
- if (event.type === 'console' && !tabSnapshot.logChunk) {
+ if (event.type === 'console' && this._context.config.outputMode !== 'file') {
if (shouldIncludeMessage(this._context.config.console.level, event.message.type))
text.push(`- ${trimMiddle(event.message.toString(), 100)}`);
} else if (event.type === 'download-start') {
-
text.push(`- Downloading file ${event.download.download.suggestedFilename()} ...`);
} else if (event.type === 'download-finish') {
text.push(`- Downloaded file ${event.download.download.suggestedFilename()} to "${this._computRelativeTo(event.download.outputFile)}"`);
}
}
}
- addSection('Events', text);
+ if (text.length)
+ addSection('Events', text);
return sections;
}
}
diff --git a/packages/playwright/src/mcp/browser/tab.ts b/packages/playwright/src/mcp/browser/tab.ts
index 2c4932b0de..6e77f154b4 100644
--- a/packages/playwright/src/mcp/browser/tab.ts
+++ b/packages/playwright/src/mcp/browser/tab.ts
@@ -14,28 +14,30 @@
* limitations under the License.
*/
-import fs from 'fs';
import { EventEmitter } from 'events';
import * as playwright from 'playwright-core';
import { asLocator, ManualPromise } from 'playwright-core/lib/utils';
-import { callOnPageNoTrace, waitForCompletion, eventWaiter, dateAsFileName } from './tools/utils';
+import { callOnPageNoTrace, waitForCompletion, eventWaiter } from './tools/utils';
import { logUnhandledError } from '../log';
+import { LogFile } from './logFile';
import { ModalState } from './tools/tool';
import { handleDialog } from './tools/dialogs';
import { uploadFile } from './tools/files';
+import { isStatic, renderRequest } from './tools/network';
import { requireOrImport } from '../../transform/transform';
import type { Context } from './context';
import type { Page } from '../../../../playwright-core/src/client/page';
import type { Locator } from '../../../../playwright-core/src/client/locator';
import type { FullConfig } from './config';
+import type { LogChunk } from './logFile';
-export const TabEvents = {
+const TabEvents = {
modalState: 'modalState'
};
-export type TabEventsInterface = {
+type TabEventsInterface = {
[TabEvents.modalState]: [modalState: ModalState];
};
@@ -78,94 +80,28 @@ export type TabHeader = {
current: boolean;
};
-export type LogChunk = {
- file: string;
- fromLine: number;
- toLine: number;
- entryCount: number;
-};
-
-export type TabSnapshot = {
+type TabSnapshot = {
ariaSnapshot: string;
ariaSnapshotDiff?: string;
modalStates: ModalState[];
events: EventEntry[];
- logChunk?: LogChunk;
+ logs?: LogChunk[];
};
-class LogFile {
- private _startTime: number = Date.now();
- private _context: Context;
- private _filePrefix: string;
- private _title: string;
-
- private _file: string | undefined;
- private _stopped: boolean = false;
-
- private _line: number = 0;
- private _entries: number = 0;
- private _lastLine: number = 0;
- private _lastEntries: number = 0;
-
- private _writeChain: Promise<void> = Promise.resolve();
-
- constructor(context: Context, filePrefix: string, title: string) {
- this._context = context;
- this._filePrefix = filePrefix;
- this._title = title;
- }
-
- appendLine(wallTime: number, text: string) {
- this._writeChain = this._writeChain.then(() => this._write(wallTime, text)).catch(logUnhandledError);
- }
-
- stop() {
- this._stopped = true;
- }
-
- async take(): Promise<LogChunk | undefined> {
- await this._writeChain;
- if (!this._file || this._entries === this._lastEntries)
- return undefined;
- const chunk: LogChunk = {
- file: this._file,
- fromLine: this._lastLine + 1,
- toLine: this._line,
- entryCount: this._entries - this._lastEntries,
- };
- this._lastLine = this._line;
- this._lastEntries = this._entries;
- return chunk;
- }
-
- private async _write(wallTime: number, text: string) {
- if (this._stopped)
- return;
- this._file ??= await this._context.outputFile(dateAsFileName(this._filePrefix, 'log', new Date(this._startTime)), { origin: 'code', title: this._title });
- const relativeTime = wallTime - this._startTime;
-
- const logLine = `[${String(relativeTime).padStart(8, ' ')}ms] ${text}\n`;
- await fs.promises.appendFile(this._file, logLine);
-
- const lineCount = logLine.split('\n').length - 1;
- this._line += lineCount;
- this._entries++;
- }
-}
-
export class Tab extends EventEmitter<TabEventsInterface> {
readonly context: Context;
readonly page: Page;
private _lastHeader: TabHeader = { title: 'about:blank', url: 'about:blank', current: false };
private _consoleMessages: ConsoleMessage[] = [];
private _downloads: Download[] = [];
- private _requests: Set<playwright.Request> = new Set();
+ private _requests: playwright.Request[] = [];
private _onPageClose: (tab: Tab) => void;
private _modalStates: ModalState[] = [];
private _initializedPromise: Promise<void>;
private _needsFullSnapshot = false;
private _recentEventEntries: EventEntry[] = [];
- private _consoleLog: LogFile | undefined;
+
+ private _logs!: Record<'console-error' | 'console-warning' | 'console-info' | 'console-debug' | 'network-full' | 'network-dynamic', LogFile>;
constructor(context: Context, page: playwright.Page, onPageClose: (tab: Tab) => void) {
super();
@@ -175,6 +111,8 @@ export class Tab extends EventEmitter<TabEventsInterface> {
page.on('console', event => this._handleConsoleMessage(messageToConsoleMessage(event)));
page.on('pageerror', error => this._handleConsoleMessage(pageErrorToConsoleMessage(error)));
page.on('request', request => this._handleRequest(request));
+ page.on('response', response => this._handleResponse(response));
+ page.on('requestfailed', request => this._handleRequestFailed(request));
page.on('close', () => this._onClose());
page.on('filechooser', chooser => {
this.setModalState({
@@ -191,7 +129,7 @@ export class Tab extends EventEmitter<TabEventsInterface> {
page.setDefaultNavigationTimeout(this.context.config.timeouts.navigation);
page.setDefaultTimeout(this.context.config.timeouts.action);
(page as any)[tabSymbol] = this;
- this._resetConsoleLogFile();
+ this._resetLogs();
this._initializedPromise = this._initialize();
}
@@ -214,8 +152,8 @@ export class Tab extends EventEmitter<TabEventsInterface> {
for (const message of await Tab.collectConsoleMessages(this.page))
this._handleConsoleMessage(message);
const requests = await this.page.requests().catch(() => []);
- for (const request of requests)
- this._requests.add(request);
+ for (const request of requests.filter(r => r.existingResponse() || r.failure()))
+ this._requests.push(request);
for (const initPage of this.context.config.browser.initPage || []) {
try {
const { default: func } = await requireOrImport(initPage);
@@ -264,28 +202,63 @@ export class Tab extends EventEmitter<TabEventsInterface> {
private _clearCollectedArtifacts() {
this._consoleMessages.length = 0;
this._downloads.length = 0;
- this._requests.clear();
+ this._requests.length = 0;
this._recentEventEntries.length = 0;
- this._resetConsoleLogFile();
+ this._resetLogs();
}
- private _resetConsoleLogFile() {
- if (this.context.config.outputMode !== 'file')
- return;
- this._consoleLog?.stop();
- this._consoleLog = new LogFile(this.context, 'console', 'Console');
+ private _resetLogs() {
+ const wallTime = Date.now();
+ for (const log of Object.values(this._logs ?? {}))
+ log.stop();
+ this._logs = {
+ 'console-error': new LogFile(this.context, wallTime, 'console-error', 'Console'),
+ 'console-warning': new LogFile(this.context, wallTime, 'console-warning', 'Console'),
+ 'console-info': new LogFile(this.context, wallTime, 'console-info', 'Console'),
+ 'console-debug': new LogFile(this.context, wallTime, 'console-debug', 'Console'),
+ 'network-full': new LogFile(this.context, wallTime, 'network-full', 'Network'),
+ 'network-dynamic': new LogFile(this.context, wallTime, 'network-dynamic', 'Network'),
+ };
}
private _handleRequest(request: playwright.Request) {
- this._requests.add(request);
- this._addLogEntry({ type: 'request', wallTime: Date.now(), request });
+ this._requests.push(request);
+ // TODO: request start time is not available for fetch() before the
+ // response is received, so we use Date.now() as a fallback.
+ const wallTime = request.timing().startTime || Date.now();
+ this._addLogEntry({ type: 'request', wallTime, request });
+ const render = async () => await renderRequest(request);
+ this._logs['network-full'].appendLine(wallTime, render);
+ if (!isStatic(request))
+ this._logs['network-dynamic'].appendLine(wallTime, render);
+ }
+
+ private _handleResponse(response: playwright.Response) {
+ const timing = response.request().timing();
+ const wallTime = timing.responseStart + timing.startTime;
+ this._addLogEntry({ type: 'request', wallTime, request: response.request() });
+ const render = async () => await renderRequest(response.request());
+ this._logs['network-full'].appendLine(wallTime, render);
+ if (!isStatic(response.request()) || response.status() >= 400)
+ this._logs['network-dynamic'].appendLine(wallTime, render);
+ }
+
+ private _handleRequestFailed(request: playwright.Request) {
+ this._requests.push(request);
+ const timing = request.timing();
+ const wallTime = timing.responseEnd + timing.startTime;
+ this._addLogEntry({ type: 'request', wallTime, request });
+ const render = async () => await renderRequest(request);
+ this._logs['network-full'].appendLine(wallTime, render);
+ this._logs['network-dynamic'].appendLine(wallTime, render);
}
private _handleConsoleMessage(message: ConsoleMessage) {
this._consoleMessages.push(message);
const wallTime = Date.now();
this._addLogEntry({ type: 'console', wallTime, message });
- this._consoleLog?.appendLine(wallTime, message.toString());
+ const level = consoleLevelForMessageType(message.type);
+ this._logs[`console-${level}`].appendLine(wallTime, () => message.toString());
}
private _addLogEntry(entry: EventEntry) {
@@ -357,14 +330,14 @@ export class Tab extends EventEmitter<TabEventsInterface> {
this._consoleMessages.length = 0;
}
- async requests(): Promise<Set<playwright.Request>> {
+ async requests(): Promise<playwright.Request[]> {
await this._initializedPromise;
return this._requests;
}
async clearRequests() {
await this._initializedPromise;
- this._requests.clear();
+ this._requests.length = 0;
}
async captureSnapshot(): Promise<TabSnapshot> {
@@ -380,7 +353,7 @@ export class Tab extends EventEmitter<TabEventsInterface> {
};
});
if (tabSnapshot) {
- tabSnapshot.logChunk = await this._consoleLog?.take();
+ tabSnapshot.logs = (await Promise.all(Object.values(this._logs).map(log => log.take()))).filter(l => !!l);
tabSnapshot.events = this._recentEventEntries;
this._recentEventEntries = [];
}
diff --git a/packages/playwright/src/mcp/browser/tools/network.ts b/packages/playwright/src/mcp/browser/tools/network.ts
index a22562ea2c..c1c1c80bdd 100644
--- a/packages/playwright/src/mcp/browser/tools/network.ts
+++ b/packages/playwright/src/mcp/browser/tools/network.ts
@@ -37,9 +37,9 @@ const requests = defineTabTool({
const requests = await tab.requests();
const text: string[] = [];
for (const request of requests) {
- const rendered = await renderRequest(request, params.includeStatic);
- if (rendered)
- text.push(rendered);
+ if (!params.includeStatic && isStatic(request) && isSuccessfulResponse(request))
+ continue;
+ text.push(await renderRequest(request));
}
await response.addResult('Network', text.join('\n'), { prefix: 'network', ext: 'log', suggestedFilename: params.filename });
},
@@ -60,18 +60,26 @@ const networkClear = defineTabTool({
},
});
-async function renderRequest(request: playwright.Request, includeStatic: boolean): Promise<string | undefined> {
+function isSuccessfulResponse(request: playwright.Request): boolean {
+ if (request.failure())
+ return false;
const response = request.existingResponse();
- const isStaticRequest = ['document', 'stylesheet', 'image', 'media', 'font', 'script', 'manifest'].includes(request.resourceType());
- const isSuccessfulRequest = !response || response.status() < 400;
+ return !!response && response.status() < 400;
+}
+
+export function isStatic(request: playwright.Request): boolean {
+ return ['document', 'stylesheet', 'image', 'media', 'font', 'script', 'manifest'].includes(request.resourceType());
+}
- if (isStaticRequest && isSuccessfulRequest && !includeStatic)
- return undefined;
+export async function renderRequest(request: playwright.Request): Promise<string> {
+ const response = request.existingResponse();
const result: string[] = [];
result.push(`[${request.method().toUpperCase()}] ${request.url()}`);
if (response)
result.push(`=> [${response.status()}] ${response.statusText()}`);
+ else if (request.failure())
+ result.push(`=> [FAILED] ${request.failure()?.errorText ?? 'Unknown error'}`);
return result.join(' ');
}
diff --git a/tests/mcp/console.spec.ts b/tests/mcp/console.spec.ts
index 810778651a..f0d27d4129 100644
--- a/tests/mcp/console.spec.ts
+++ b/tests/mcp/console.spec.ts
@@ -206,7 +206,8 @@ test('console log file is created on snapshot', async ({ startClient, server },
<html>
<script>
console.log("Hello from console");
- console.error("Error message");
+ console.error("Error message1");
+ console.error("Error message2");
</script>
</html>
`, 'text/html');
@@ -217,16 +218,27 @@ test('console log file is created on snapshot', async ({ startClient, server },
}));
// Check events section mentions the log file with line range
- expect(response.events).toMatch(/\d+ new console entr(y|ies) in ".+\.log#L\d+(-L\d+)?"/);
+ expect(response.events).toMatch(/1 new console entry in "output\/console-info.+\.log#L\d+(-L\d+)?"/);
+ expect(response.events).toMatch(/2 new console entries in "output\/console-error.+\.log#L\d+(-L\d+)?"/);
- // Verify log file exists and contains the messages
+ // Verify log files exist and contain the messages
const files = await fs.promises.readdir(outputDir);
- const logFile = files.find(f => f.startsWith('console-') && f.endsWith('.log'));
- expect(logFile).toBeTruthy();
+ const logFiles = files.filter(f => f.startsWith('console-') && f.endsWith('.log'));
+ expect(logFiles.length).toBe(2);
+
+ async function readLog(level: string) {
+ const file = logFiles.find(f => f.startsWith(`console-${level}-`));
+ if (!file)
+ return '<no log file>';
+ return fs.promises.readFile(path.join(outputDir, file), 'utf-8');
+ }
+
+ const infoLog = await readLog('info');
+ expect(infoLog).toContain('Hello from console');
- const logContent = await fs.promises.readFile(path.join(outputDir, logFile!), 'utf-8');
- expect(logContent).toContain('Hello from console');
- expect(logContent).toContain('Error message');
+ const errorLog = await readLog('error');
+ expect(errorLog).toContain('Error message1');
+ expect(errorLog).toContain('Error message2');
});
test('console log file shows correct entry count', async ({ startClient, server }, testInfo) => {
@@ -389,22 +401,35 @@ test('console log file stores message type and content', async ({ startClient, s
});
const files = await fs.promises.readdir(outputDir);
- const logFile = files.find(f => f.startsWith('console-') && f.endsWith('.log'));
- expect(logFile).toBeTruthy();
+ const logFiles = files.filter(f => f.startsWith('console-') && f.endsWith('.log'));
+ expect(logFiles.length).toBe(4);
- const logContent = await fs.promises.readFile(path.join(outputDir, logFile!), 'utf-8');
+ async function readLog(level: string) {
+ const file = logFiles.find(f => f.startsWith(`console-${level}-`));
+ if (!file)
+ return '<no log file>';
+ return fs.promises.readFile(path.join(outputDir, file), 'utf-8');
+ }
// Check that message types are stored
- expect(logContent).toContain('[LOG] Log message');
- expect(logContent).toContain('[WARNING] Warning message');
- expect(logContent).toContain('[ERROR] Error message');
- expect(logContent).toContain('[INFO] Info message');
- expect(logContent).toContain('[DEBUG] Debug message');
+ const infoContent = await readLog('info');
+ expect(infoContent).toContain('[LOG] Log message');
+ expect(infoContent).toContain('[INFO] Info message');
+
+ const warningContent = await readLog('warning');
+ expect(warningContent).toContain('[WARNING] Warning message');
+
+ const errorContent = await readLog('error');
+ expect(errorContent).toContain('[ERROR] Error message');
+
+ const debugContent = await readLog('debug');
+ expect(debugContent).toContain('[DEBUG] Debug message');
// Check that source location is stored
- expect(logContent).toMatch(/@ http:\/\/localhost:\d+\/:5/); // console.log line
- expect(logContent).toMatch(/@ http:\/\/localhost:\d+\/:6/); // console.warn line
- expect(logContent).toMatch(/@ http:\/\/localhost:\d+\/:7/); // console.error line
+ expect(infoContent).toMatch(/@ http:\/\/localhost:\d+\/:\d/); // console.log line
+ expect(warningContent).toMatch(/@ http:\/\/localhost:\d+\/:\d/); // console.warn line
+ expect(errorContent).toMatch(/@ http:\/\/localhost:\d+\/:\d/); // console.error line
+ expect(debugContent).toMatch(/@ http:\/\/localhost:\d+\/:\d/); // console.debug line
});
test('console log is updated without taking snapshots', async ({ startClient, server }, testInfo) => {
diff --git a/tests/mcp/network.spec.ts b/tests/mcp/network.spec.ts
index 9bfdbe337b..4bd7d3b12a 100644
--- a/tests/mcp/network.spec.ts
+++ b/tests/mcp/network.spec.ts
@@ -14,8 +14,19 @@
* limitations under the License.
*/
+import fs from 'fs/promises';
+
import { test, expect, parseResponse } from './fixtures';
+function parseLogEvents(events: string) {
+ const dynamicMatch = /\d+ new network entr(y|ies) in "(output[\\/]network-dynamic-.+\.log)#L\d+(-L\d+)?"/.exec(events);
+ const fullMatch = /\d+ new network entr(y|ies) in "(output[\\/]network-full-.+\.log)#L\d+(-L\d+)?"/.exec(events);
+ return {
+ dynamicLogFile: dynamicMatch?.[2],
+ fullLogFile: fullMatch?.[2],
+ };
+}
+
test('browser_network_requests', async ({ client, server }) => {
server.setContent('/', `
<button onclick="fetch('/json')">Click me</button>
@@ -60,3 +71,201 @@ test('browser_network_requests', async ({ client, server }) => {
expect(response.result).toContain(`[GET] ${`${server.PREFIX}/image.png`} => [404]`);
}
});
+
+test('network log file is returned on snapshot', async ({ startClient, server }, testInfo) => {
+ const outputDir = testInfo.outputPath('output');
+ const { client } = await startClient({
+ config: { outputDir, outputMode: 'file' },
+ });
+
+ server.setContent('/empty.html', `
+ <html>
+ <head>
+ <link rel="stylesheet" href="/one-style.css">
+ </head>
+ <body>
+ <img src="/image.png" />
+ <script src="/script.js"></script>
+ </body>
+ </html>
+ `, 'text/html');
+
+ const response = parseResponse(await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: server.EMPTY_PAGE },
+ }));
+
+ expect(response.events).toMatch(/\d+ new network entr(y|ies) in "output\/network-full-.+\.log#L\d+(-L\d+)?"/);
+
+ // Verify network log file exist
+ const files = await fs.readdir(outputDir);
+ const networkLogFiles = files.filter(f => f.startsWith('network-full-') && f.endsWith('.log'));
+ expect(networkLogFiles.length).toBe(1);
+
+ const { fullLogFile } = parseLogEvents(response.events);
+ expect(fullLogFile).toBeTruthy();
+ // Verify the log contains both requests
+ const logContent = await fs.readFile(testInfo.outputPath(fullLogFile), 'utf-8');
+ expect(logContent).toMatch(new RegExp([
+ /\[GET\].*empty\.html => \[200\] OK/,
+ /\/image\.png => \[404\] Not Found/,
+ /\/one-style\.css => \[200\] OK/,
+ /\/script\.js => \[404\] Not Found/,
+ ].map(r => `(?=[\\s\\S]*${r.source})`).join(''))
+ );
+});
+
+test('network log file separates requests and assets', async ({ startClient, server }, testInfo) => {
+ const outputDir = testInfo.outputPath('output');
+ const { client } = await startClient({
+ config: { outputDir, outputMode: 'file' },
+ });
+
+ server.setContent('/empty.html', `
+ <html>
+ <body>
+ <img src="/image.png" />
+ </body>
+ </html>
+ `, 'text/html');
+
+ server.setContent('/api/data', JSON.stringify({ data: 'test' }), 'application/json');
+
+ await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: server.EMPTY_PAGE },
+ });
+
+ const response = parseResponse(await client.callTool({
+ name: 'browser_evaluate',
+ arguments: { function: '() => fetch("/api/data")' },
+ }));
+ expect(response.events).toMatch(/\d+ new network entr(y|ies) in "output\/network-dynamic-.+\.log#L\d+(-L\d+)?"/);
+
+ // Check that both network-dynamic and network-full log files exist
+ const { dynamicLogFile, fullLogFile } = parseLogEvents(response.events);
+ expect(dynamicLogFile).toBeTruthy();
+ expect(fullLogFile).toBeTruthy();
+
+ // API request should be in network-dynamic log
+ const dynamicContent = await fs.readFile(testInfo.outputPath(dynamicLogFile), 'utf-8');
+ expect(dynamicContent).toMatch(new RegExp([
+ /\/api\/data => \[200\] OK/,
+ /\/image\.png => \[404\] Not Found/,
+ ].map(r => `(?=[\\s\\S]*${r.source})`).join('')));
+ // main resource
+ expect(dynamicContent).not.toContain(`[GET] ${server.EMPTY_PAGE}`);
+
+ // network-full should contain all requests
+ const fullContent = await fs.readFile(testInfo.outputPath(fullLogFile), 'utf-8');
+ expect(fullContent).toMatch(new RegExp([
+ /\[GET\].*empty\.html => \[200\] OK/,
+ /\/image\.png => \[404\] Not Found/,
+ /\/api\/data => \[200\] OK/,
+ ].map(r => `(?=[\\s\\S]*${r.source})`).join('')));
+});
+
+test('network log file stores method and status', async ({ startClient, server }, testInfo) => {
+ const outputDir = testInfo.outputPath('output');
+ const { client } = await startClient({
+ config: { outputDir, outputMode: 'file' },
+ });
+
+ server.setContent('/api/get', JSON.stringify({ method: 'get' }), 'application/json');
+ server.setContent('/api/post', JSON.stringify({ method: 'post' }), 'application/json');
+
+ await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: server.EMPTY_PAGE },
+ });
+
+ const response = parseResponse(await client.callTool({
+ name: 'browser_evaluate',
+ arguments: { function: `async () => {
+ await fetch('/api/get');
+ await fetch('/api/post', { method: 'POST' });
+ }`
+ },
+ }));
+ expect(response.events).toMatch(/\d+ new network entr(y|ies) in "output\/network-dynamic-.+\.log#L\d+(-L\d+)?"/);
+
+ const { dynamicLogFile, fullLogFile } = parseLogEvents(response.events);
+ expect(dynamicLogFile).toBeTruthy();
+ expect(fullLogFile).toBeTruthy();
+
+ const logContent = await fs.readFile(testInfo.outputPath(dynamicLogFile), 'utf-8');
+ expect(logContent).toMatch(new RegExp([
+ /\[GET\].*\/api\/get.*=>\s*\[200\]/,
+ /\[POST\].*\/api\/post.*=>\s*\[200\]/,
+ ].map(r => `(?=[\\s\\S]*${r.source})`).join('')));
+
+ const fullContent = await fs.readFile(testInfo.outputPath(fullLogFile), 'utf-8');
+ expect(fullContent).toMatch(new RegExp([
+ /\[GET\].*\/api\/get.*=>\s*\[200\]/,
+ /\[POST\].*\/api\/post.*=>\s*\[200\]/,
+ ].map(r => `(?=[\\s\\S]*${r.source})`).join('')));
+});
+
+test('new network log file after navigation', async ({ startClient, server }, testInfo) => {
+ const outputDir = testInfo.outputPath('output');
+ const { client } = await startClient({
+ config: { outputDir, outputMode: 'file' },
+ });
+
+ server.setContent('/page1', `
+ <html>
+ <head>
+ <link rel="stylesheet" href="/one-style.css">
+ </head>
+ </html>
+ `, 'text/html');
+
+ server.setContent('/page2', `
+ <html>
+ <head>
+ <link rel="stylesheet" href="/one-style.css">
+ </head>
+ <body>
+ <img src="/image.png" />
+ </body>
+ </html>
+ `, 'text/html');
+
+ // Navigate to first page
+ const response1 = parseResponse(await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: server.PREFIX + '/page1' },
+ }));
+
+ {
+ // Should have one network-full log file
+ const { fullLogFile } = parseLogEvents(response1.events);
+ expect(fullLogFile).toBeTruthy();
+
+ const logContent = await fs.readFile(testInfo.outputPath(fullLogFile), 'utf-8');
+ expect(logContent).toContain('/one-style.css');
+ }
+
+ // Navigate to second page
+ const response2 = parseResponse(await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: server.PREFIX + '/page2' },
+ }));
+
+ expect(response2.events).toMatch(/\d+ new network entries in "output\/network-full-.+\.log#L\d+(-L\d+)?"/);
+ const { fullLogFile: secondLogFile } = parseLogEvents(response2.events);
+
+ {
+ // Should have 2 network-full log files (one per navigation)
+ const files = await fs.readdir(outputDir);
+ const networkLogs = files.filter(f => f.startsWith('network-full-') && f.endsWith('.log'));
+ expect(networkLogs.length).toBe(2);
+
+ expect(secondLogFile).toBeTruthy();
+ const logContent = await fs.readFile(testInfo.outputPath(secondLogFile), 'utf-8');
+ expect(logContent).toMatch(new RegExp([
+ /\/one-style\.css => \[200\] OK/,
+ /\/image\.png => \[404\] Not Found/,
+ ].map(r => `(?=[\\s\\S]*${r.source})`).join('')));
+ }
+});
diff --git a/tests/mcp/roots.spec.ts b/tests/mcp/roots.spec.ts
index e386428157..0a5a44eac3 100644
--- a/tests/mcp/roots.spec.ts
+++ b/tests/mcp/roots.spec.ts
@@ -64,8 +64,8 @@ test('check that trace is saved in workspace', async ({ startClient, server }, t
code: expect.stringContaining(`page.goto('http://localhost`),
});
- const [file] = await fs.promises.readdir(path.join(rootPath, '.playwright-mcp'));
- expect(file).toContain('traces');
+ const files = await fs.promises.readdir(path.join(rootPath, '.playwright-mcp'));
+ expect(files).toContain('traces');
});
test('should list all tools when listRoots is slow', async ({ startClient }) => {
diff --git a/tests/mcp/session-log.spec.ts b/tests/mcp/session-log.spec.ts
index d080d5b045..b854d59bf8 100644
--- a/tests/mcp/session-log.spec.ts
+++ b/tests/mcp/session-log.spec.ts
@@ -48,40 +48,41 @@ test('session log should record tool calls', async ({ startClient, server, mcpBr
const output = stderr().split('\n').filter(line => line.startsWith('Session: '))[0];
const sessionFolder = output.substring('Session: '.length);
- await expect.poll(() => readSessionLog(sessionFolder)).toBe(`
+ await expect.poll(() => readSessionLog(sessionFolder)).toMatch(new RegExp(`
### Tool call: browser_navigate
- Args
-\`\`\`json
-{
+\\\`\\\`\\\`json
+\\{
"url": "http://localhost:${server.PORT}"
-}
-\`\`\`
+\\}
+\\\`\\\`\\\`
- Result
-\`\`\`json
-{
- "code": "await page.goto('http://localhost:${server.PORT}');",
- "page": "- Page URL: http://localhost:${server.PORT}/\\n- Page Title: Title",
- "snapshot": "\`\`\`yaml\\n- button \\"Submit\\" [ref=e2]\\n\`\`\`"
-}
-\`\`\`
+\\\`\\\`\\\`json
+\\{
+ "code": "await page.goto\\('http://localhost:${server.PORT}'\\);",
+ "page": "- Page URL: http://localhost:${server.PORT}/\\\\n- Page Title: Title",
+ "snapshot": "\\\`\\\`\\\`yaml\\\\n- button \\\\"Submit\\\\" \\[ref=e2\\]\\\\n\\\`\\\`\\\`",
+ "events": "- \\d+ new network entr(?:y|ies) in \\\\"output/network-full-.+\\.log#L\\d+(?:-L\\d+)?\\\\""
+\\}
+\\\`\\\`\\\`
### Tool call: browser_click
- Args
-\`\`\`json
-{
+\\\`\\\`\\\`json
+\\{
"element": "Submit button",
"ref": "e2"
-}
-\`\`\`
+\\}
+\\\`\\\`\\\`
- Result
-\`\`\`json
-{
- "code": "await page.getByRole('button', { name: 'Submit' }).click();",
- "page": "- Page URL: http://localhost:${server.PORT}/\\n- Page Title: Title",
- "snapshot": "\`\`\`yaml\\n- <changed> button \\"Submit\\" [active] [ref=e2]\\n\`\`\`"
-}
-\`\`\`
-`);
+\\\`\\\`\\\`json
+\\{
+ "code": "await page.getByRole\\('button', \\{ name: 'Submit' \\}\\).click\\(\\);",
+ "page": "- Page URL: http://localhost:${server.PORT}/\\\\n- Page Title: Title",
+ "snapshot": "\\\`\\\`\\\`yaml\\\\n- <changed> button \\\\"Submit\\\\" \\[active\\] \\[ref=e2\\]\\\\n\\\`\\\`\\\`"
+\\}
+\\\`\\\`\\\`
+`.trim()));
});
async function readSessionLog(sessionFolder: string): Promise<string> {
diff --git a/tests/mcp/tracing.spec.ts b/tests/mcp/tracing.spec.ts
index 7b63b19993..0d1862d0be 100644
--- a/tests/mcp/tracing.spec.ts
+++ b/tests/mcp/tracing.spec.ts
@@ -32,8 +32,8 @@ test('check that trace is saved with --save-trace', async ({ startClient, server
code: expect.stringContaining(`page.goto('http://localhost`),
});
- const [file] = await fs.promises.readdir(outputDir);
- expect(file).toContain('traces');
+ const files = await fs.promises.readdir(outputDir);
+ expect(files).toContain('traces');
});
test('check that trace is saved with browser_start_tracing', async ({ startClient, server }, testInfo) => {