Skip to content

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

fix(test): support test_debug for manually created contexts (#40635)

Dmitry Gozmanb08440d16f49
diff --git a/packages/playwright-electron/src/index.ts b/packages/playwright-electron/src/index.ts
index 5a2446a093..d8c9f5b881 100644
--- a/packages/playwright-electron/src/index.ts
+++ b/packages/playwright-electron/src/index.ts
@@ -21,20 +21,17 @@ import { selectors } from 'playwright/test';
export { expect, devices, defineConfig, mergeExpects, mergeTests } from 'playwright/test';
export { electron, selectors };
-import type { BrowserContext, TestType } from '../index.d.ts';
+import type { TestType } from '../index.d.ts';
-const baseTest = _utilityTest as TestType<{
- _decorateContext: (context: BrowserContext) => Promise<void>;
-}, {}>;
+const baseTest = _utilityTest as TestType<{}, {}>;
export const test = baseTest.extend({
// @ts-expect-error
appOptions: [{}, { option: true }],
- app: async ({ appOptions, testIdAttribute, _decorateContext }, use) => {
+ app: async ({ appOptions, testIdAttribute }, use) => {
selectors.setTestIdAttribute(testIdAttribute);
const app = await electron.launch(appOptions);
- await _decorateContext(app.context());
await use(app);
await app.close();
},
diff --git a/packages/playwright/src/index.ts b/packages/playwright/src/index.ts
index 5bf7710f55..b820f11690 100644
--- a/packages/playwright/src/index.ts
+++ b/packages/playwright/src/index.ts
@@ -64,7 +64,6 @@ type TestFixtures = PlaywrightTestArgs & PlaywrightTestOptions & {
_combinedContextOptions: BrowserContextOptions,
_setupContextOptions: void;
_setupArtifacts: void;
- _decorateContext: (context: BrowserContext) => Promise<void>;
_contextFactory: (options?: BrowserContextOptions) => Promise<{ context: BrowserContext, close: () => Promise<void> }>;
};
@@ -77,7 +76,7 @@ type WorkerFixtures = PlaywrightWorkerArgs & PlaywrightWorkerOptions & {
};
// Note: utility fixtures and _utilityTest are reused in electron package. Be mindful when changing them.
-type UtilityTestFixtures = Pick<TestFixtures, 'testIdAttribute' | 'request' | '_combinedContextOptions' | '_setupArtifacts' | '_decorateContext'>;
+type UtilityTestFixtures = Pick<TestFixtures, 'testIdAttribute' | 'request' | '_combinedContextOptions' | '_setupArtifacts'>;
type UtilityWorkerFixtures = Pick<WorkerFixtures, 'playwright' | 'screenshot' | 'trace'>;
const utilityFixtures: Fixtures<UtilityTestFixtures, UtilityWorkerFixtures> = {
playwright: [async ({}, use) => {
@@ -87,13 +86,6 @@ const utilityFixtures: Fixtures<UtilityTestFixtures, UtilityWorkerFixtures> = {
trace: ['off', { scope: 'worker', option: true, box: true }],
testIdAttribute: ['data-testid', { option: true, box: true }],
_combinedContextOptions: [{}, { box: true }],
- _decorateContext: [async ({}, use, testInfoPublic) => {
- const testInfo = testInfoPublic as TestInfoImpl;
- await use(async (context: BrowserContext) => {
- testInfo._onCustomMessageCallback = createCustomMessageHandler(testInfo, context);
- await runDaemonForContext(testInfo, context);
- });
- }, { box: true }],
_setupArtifacts: [async ({ playwright, screenshot, _combinedContextOptions }, use, testInfo) => {
// This fixture has a separate zero-timeout slot to ensure that artifact collection
// happens even after some fixtures or hooks time out.
@@ -180,9 +172,12 @@ const utilityFixtures: Fixtures<UtilityTestFixtures, UtilityWorkerFixtures> = {
});
await artifactsRecorder.didCreateBrowserContext(context);
- const testInfo = globals.currentTestInfo();
- if (testInfo)
- attachConnectedHeaderIfNeeded(testInfo, context.browser());
+ const currentTestInfo = globals.currentTestInfo() as TestInfoImpl | undefined;
+ if (currentTestInfo) {
+ attachConnectedHeaderIfNeeded(currentTestInfo, context.browser());
+ currentTestInfo._onCustomMessageCallback = createCustomMessageHandler(currentTestInfo, context);
+ await runDaemonForContext(currentTestInfo, context);
+ }
},
runAfterCreateRequestContext: async (context: APIRequestContextImpl) => {
await artifactsRecorder.didCreateRequestContext(context);
@@ -480,14 +475,13 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures, UtilityTestFixt
await use(reuse);
}, { scope: 'worker', title: 'context', box: true }],
- context: async ({ browser, video, _reuseContext, _contextFactory, _decorateContext }, use, testInfoPublic) => {
+ context: async ({ browser, video, _reuseContext, _contextFactory }, use, testInfoPublic) => {
const browserImpl = browser as BrowserImpl;
const testInfo = testInfoPublic as TestInfoImpl;
const show = typeof video === 'string' ? undefined : video.show;
attachConnectedHeaderIfNeeded(testInfo, browserImpl);
if (!_reuseContext) {
const { context, close } = await _contextFactory();
- await _decorateContext(context);
await installScreencastTitleUpdater(testInfo, context, show?.test);
await use(context);
await close();
@@ -495,7 +489,6 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures, UtilityTestFixt
}
const context = await browserImpl._wrapApiCall(() => browserImpl._newContextForReuse(), { internal: true });
- await _decorateContext(context);
await installScreencastTitleUpdater(testInfo, context, show?.test);
await use(context);
const closeReason = testInfo.status === 'timedOut' ? 'Test timeout of ' + testInfo.timeout + 'ms exceeded.' : 'Test ended.';
diff --git a/packages/playwright/src/mcp/test/browserBackend.ts b/packages/playwright/src/mcp/test/browserBackend.ts
index b154cd391f..001570c117 100644
--- a/packages/playwright/src/mcp/test/browserBackend.ts
+++ b/packages/playwright/src/mcp/test/browserBackend.ts
@@ -40,6 +40,11 @@ export function createCustomMessageHandler(testInfo: TestInfoImpl, context: play
const config: tools.ContextConfig = { capabilities: ['testing'] };
let tools: typeof import('playwright-core/lib/coreBundle').tools | undefined;
+ context.once('close', () => {
+ void backend?.dispose();
+ backend = undefined;
+ });
+
return async (data: BrowserMCPRequest): Promise<BrowserMCPResponse> => {
if (!tools)
({ tools } = require('playwright-core/lib/coreBundle') as typeof import('playwright-core/lib/coreBundle'));
diff --git a/tests/mcp/cli-test.spec.ts b/tests/mcp/cli-test.spec.ts
index ab4c5eebd0..7a246c7d05 100644
--- a/tests/mcp/cli-test.spec.ts
+++ b/tests/mcp/cli-test.spec.ts
@@ -72,3 +72,45 @@ test('debug test and snapshot', async ({ cliEnv, cli, childProcess }) => {
const { output: listOutput3 } = await cli('list');
expect(listOutput3).toContain('(no browsers)');
});
+
+test('debug test with custom fixture using browser.newContext', async ({ cliEnv, cli, childProcess }) => {
+ await writeFiles({
+ 'subdir/a.test.ts': `
+ import { test as base, expect } from '@playwright/test';
+ const test = base.extend<{ customPage: import('@playwright/test').Page }>({
+ customPage: async ({ browser }, use) => {
+ const context = await browser.newContext();
+ const page = await context.newPage();
+ await use(page);
+ await context.close();
+ },
+ });
+ test('example test', async ({ customPage }) => {
+ await customPage.setContent('<title>My Page</title><body><button>Submit</button></body>');
+ await expect(customPage.getByRole('button', { name: 'Submit' })).toBeVisible();
+ });
+ `,
+ });
+
+ const testProcess = childProcess({
+ command: [process.argv[0], testEntrypoint, 'test', '--debug=cli'],
+ cwd: test.info().outputPath('subdir'),
+ env: cliEnv,
+ });
+
+ await testProcess.waitForOutput('playwright-cli attach');
+
+ const match = testProcess.output.match(/attach ([a-zA-Z0-9-_]+)/);
+ const session = match[1];
+
+ const { output: attachOutput } = await cli('attach', session);
+ expect(attachOutput).toContain('### Paused');
+
+ const { output: stepOutput } = await cli(`--session=${session}`, 'step-over');
+ expect(stepOutput).toContain('### Paused');
+
+ const snapshotResult = await cli(`--session=${session}`, 'snapshot');
+ expect(snapshotResult.inlineSnapshot).toContain('button "Submit"');
+
+ await cli(`--session=${session}`, 'resume');
+});
diff --git a/tests/mcp/test-debug.spec.ts b/tests/mcp/test-debug.spec.ts
index 88463d2970..880d73f3f5 100644
--- a/tests/mcp/test-debug.spec.ts
+++ b/tests/mcp/test-debug.spec.ts
@@ -453,3 +453,34 @@ test('test_debug (no default page fixture)', async ({ startClient }) => {
},
})).toHaveTextResponse(expect.stringContaining(`Only tests that use default Playwright context or page fixture support test_debug`));
});
+
+test('test_debug (custom fixture with browser.newContext)', async ({ startClient }) => {
+ const { client, id } = await prepareDebugTest(startClient, `
+ import { test as base, expect } from '@playwright/test';
+ const test = base.extend<{ customPage: import('@playwright/test').Page }>({
+ customPage: async ({ browser }, use) => {
+ const context = await browser.newContext();
+ const page = await context.newPage();
+ await use(page);
+ await context.close();
+ },
+ });
+ test('fail', async ({ customPage }) => {
+ await customPage.setContent('<button>Submit</button>');
+ await expect(customPage.getByRole('button', { name: 'Missing' })).toBeVisible({ timeout: 1000 });
+ });
+ `);
+
+ expect(await client.callTool({
+ name: 'test_debug',
+ arguments: {
+ test: { id, title: 'fail' },
+ },
+ })).toHaveTextResponse(expect.stringContaining(`### Paused on error:`));
+
+ expect(await client.callTool({
+ name: 'browser_snapshot',
+ })).toHaveResponse({
+ inlineSnapshot: expect.stringContaining(`- button "Submit" [ref=e2]`),
+ });
+});