chore: add _browserTypes helpers to playwright (#34611)

This commit is contained in:
Simon Knott 2025-02-07 15:43:08 +01:00 committed by GitHub
parent 9e433060fe
commit 893e7bbf3b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 78 additions and 87 deletions

View file

@ -80,7 +80,7 @@ export class Browser extends ChannelOwner<channels.BrowserChannel> implements ap
}
async _innerNewContext(options: BrowserContextOptions = {}, forReuse: boolean): Promise<BrowserContext> {
options = { ...this._browserType._defaultContextOptions, ...options };
options = { ...this._browserType._playwright._defaultContextOptions, ...options };
const contextOptions = await prepareBrowserContextParams(options);
const response = forReuse ? await this._channel.newContextForReuse(contextOptions) : await this._channel.newContext(contextOptions);
const context = BrowserContext.from(response.context);

View file

@ -18,7 +18,7 @@ import type * as channels from '@protocol/channels';
import { Browser } from './browser';
import { BrowserContext, prepareBrowserContextParams } from './browserContext';
import { ChannelOwner } from './channelOwner';
import type { LaunchOptions, LaunchServerOptions, ConnectOptions, LaunchPersistentContextOptions, BrowserContextOptions, Logger } from './types';
import type { LaunchOptions, LaunchServerOptions, ConnectOptions, LaunchPersistentContextOptions, Logger } from './types';
import { Connection } from './connection';
import { Events } from './events';
import type { ChildProcess } from 'child_process';
@ -45,12 +45,6 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> imple
_contexts = new Set<BrowserContext>();
_playwright!: Playwright;
// Instrumentation.
_defaultContextOptions?: BrowserContextOptions;
_defaultContextTimeout?: number;
_defaultContextNavigationTimeout?: number;
private _defaultLaunchOptions?: LaunchOptions;
static from(browserType: channels.BrowserTypeChannel): BrowserType {
return (browserType as any)._object;
}
@ -69,8 +63,8 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> imple
assert(!(options as any).userDataDir, 'userDataDir option is not supported in `browserType.launch`. Use `browserType.launchPersistentContext` instead');
assert(!(options as any).port, 'Cannot specify a port without launching as a server.');
const logger = options.logger || this._defaultLaunchOptions?.logger;
options = { ...this._defaultLaunchOptions, ...options };
const logger = options.logger || this._playwright._defaultLaunchOptions?.logger;
options = { ...this._playwright._defaultLaunchOptions, ...options };
const launchOptions: channels.BrowserTypeLaunchParams = {
...options,
ignoreDefaultArgs: Array.isArray(options.ignoreDefaultArgs) ? options.ignoreDefaultArgs : undefined,
@ -87,14 +81,14 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> imple
async launchServer(options: LaunchServerOptions = {}): Promise<api.BrowserServer> {
if (!this._serverLauncher)
throw new Error('Launching server is not supported');
options = { ...this._defaultLaunchOptions, ...options };
options = { ...this._playwright._defaultLaunchOptions, ...options };
return await this._serverLauncher.launchServer(options);
}
async launchPersistentContext(userDataDir: string, options: LaunchPersistentContextOptions = {}): Promise<BrowserContext> {
const logger = options.logger || this._defaultLaunchOptions?.logger;
const logger = options.logger || this._playwright._defaultLaunchOptions?.logger;
assert(!(options as any).port, 'Cannot specify a port without launching as a server.');
options = { ...this._defaultLaunchOptions, ...this._defaultContextOptions, ...options };
options = { ...this._playwright._defaultLaunchOptions, ...this._playwright._defaultContextOptions, ...options };
const contextParams = await prepareBrowserContextParams(options);
const persistentParams: channels.BrowserTypeLaunchPersistentContextParams = {
...contextParams,
@ -237,10 +231,10 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> imple
context._browserType = this;
this._contexts.add(context);
context._setOptions(contextOptions, browserOptions);
if (this._defaultContextTimeout !== undefined)
context.setDefaultTimeout(this._defaultContextTimeout);
if (this._defaultContextNavigationTimeout !== undefined)
context.setDefaultNavigationTimeout(this._defaultContextNavigationTimeout);
if (this._playwright._defaultContextTimeout !== undefined)
context.setDefaultTimeout(this._playwright._defaultContextTimeout);
if (this._playwright._defaultContextNavigationTimeout !== undefined)
context.setDefaultNavigationTimeout(this._playwright._defaultContextNavigationTimeout);
await this._instrumentation.runAfterCreateBrowserContext(context);
}

View file

@ -25,7 +25,7 @@ import { assert, headersObjectToArray, isString } from '../utils';
import { mkdirIfNeeded } from '../utils/fileUtils';
import { ChannelOwner } from './channelOwner';
import { RawHeaders } from './network';
import type { ClientCertificate, FilePayload, Headers, StorageState } from './types';
import type { ClientCertificate, FilePayload, Headers, SetStorageState, StorageState } from './types';
import type { Playwright } from './playwright';
import { Tracing } from './tracing';
import { TargetClosedError, isTargetClosedError } from './errors';
@ -47,7 +47,7 @@ export type FetchOptions = {
type NewContextOptions = Omit<channels.PlaywrightNewRequestOptions, 'extraHTTPHeaders' | 'clientCertificates' | 'storageState' | 'tracesDir'> & {
extraHTTPHeaders?: Headers,
storageState?: string | StorageState,
storageState?: string | SetStorageState,
clientCertificates?: ClientCertificate[];
};
@ -57,30 +57,29 @@ export class APIRequest implements api.APIRequest {
private _playwright: Playwright;
readonly _contexts = new Set<APIRequestContext>();
// Instrumentation.
_defaultContextOptions?: NewContextOptions & { tracesDir?: string };
constructor(playwright: Playwright) {
this._playwright = playwright;
}
async newContext(options: NewContextOptions = {}): Promise<APIRequestContext> {
options = { ...this._defaultContextOptions, ...options };
options = {
...this._playwright._defaultContextOptions,
timeout: this._playwright._defaultContextTimeout,
...options,
};
const storageState = typeof options.storageState === 'string' ?
JSON.parse(await fs.promises.readFile(options.storageState, 'utf8')) :
options.storageState;
// We do not expose tracesDir in the API, so do not allow options to accidentally override it.
const tracesDir = this._defaultContextOptions?.tracesDir;
const context = APIRequestContext.from((await this._playwright._channel.newRequest({
...options,
extraHTTPHeaders: options.extraHTTPHeaders ? headersObjectToArray(options.extraHTTPHeaders) : undefined,
storageState,
tracesDir,
tracesDir: this._playwright._defaultLaunchOptions?.tracesDir, // We do not expose tracesDir in the API, so do not allow options to accidentally override it.
clientCertificates: await toClientCertificatesProtocol(options.clientCertificates),
})).request);
this._contexts.add(context);
context._request = this;
context._tracing._tracesDir = tracesDir;
context._tracing._tracesDir = this._playwright._defaultLaunchOptions?.tracesDir;
await context._instrumentation.runAfterCreateRequestContext(context);
return context;
}

View file

@ -22,6 +22,7 @@ import { ChannelOwner } from './channelOwner';
import { Electron } from './electron';
import { APIRequest } from './fetch';
import { Selectors, SelectorsOwner } from './selectors';
import type { BrowserContextOptions, LaunchOptions } from 'playwright-core';
export class Playwright extends ChannelOwner<channels.PlaywrightChannel> {
readonly _android: Android;
@ -36,6 +37,12 @@ export class Playwright extends ChannelOwner<channels.PlaywrightChannel> {
readonly request: APIRequest;
readonly errors: { TimeoutError: typeof TimeoutError };
// Instrumentation.
_defaultLaunchOptions?: LaunchOptions;
_defaultContextOptions?: BrowserContextOptions;
_defaultContextTimeout?: number;
_defaultContextNavigationTimeout?: number;
constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.PlaywrightInitializer) {
super(parent, type, guid, initializer);
this.request = new APIRequest(this);
@ -73,4 +80,16 @@ export class Playwright extends ChannelOwner<channels.PlaywrightChannel> {
static from(channel: channels.PlaywrightChannel): Playwright {
return (channel as any)._object;
}
private _browserTypes(): BrowserType[] {
return [this.chromium, this.firefox, this.webkit, this._bidiChromium, this._bidiFirefox];
}
_allContexts() {
return this._browserTypes().flatMap(type => [...type._contexts]);
}
_allPages() {
return this._allContexts().flatMap(context => context.pages());
}
}

View file

@ -24,6 +24,7 @@ import type { TestInfoImpl, TestStepInternal } from './worker/testInfo';
import { rootTestType } from './common/testType';
import type { ContextReuseMode } from './common/config';
import type { ApiCallData, ClientInstrumentation, ClientInstrumentationListener } from '../../playwright-core/src/client/clientInstrumentation';
import type { Playwright as PlaywrightImpl } from '../../playwright-core/src/client/playwright';
import { currentTestInfo } from './common/globals';
export { expect } from './matchers/expect';
export const _baseTest: TestType<{}, {}> = rootTestType.test;
@ -50,6 +51,7 @@ type TestFixtures = PlaywrightTestArgs & PlaywrightTestOptions & {
};
type WorkerFixtures = PlaywrightWorkerArgs & PlaywrightWorkerOptions & {
playwright: PlaywrightImpl;
_browserOptions: LaunchOptions;
_optionContextReuseMode: ContextReuseMode,
_optionConnectOptions: PlaywrightWorkerOptions['connectOptions'],
@ -78,18 +80,16 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
const options: LaunchOptions = {
handleSIGINT: false,
...launchOptions,
tracesDir: tracing().tracesDir(),
};
if (headless !== undefined)
options.headless = headless;
if (channel !== undefined)
options.channel = channel;
options.tracesDir = tracing().tracesDir();
for (const browserType of [playwright.chromium, playwright.firefox, playwright.webkit, playwright._bidiChromium, playwright._bidiFirefox])
(browserType as any)._defaultLaunchOptions = options;
playwright._defaultLaunchOptions = options;
await use(options);
for (const browserType of [playwright.chromium, playwright.firefox, playwright.webkit, playwright._bidiChromium, playwright._bidiFirefox])
(browserType as any)._defaultLaunchOptions = undefined;
playwright._defaultLaunchOptions = undefined;
}, { scope: 'worker', auto: true, box: true }],
browser: [async ({ playwright, browserName, _browserOptions, connectOptions, _reuseContext }, use, testInfo) => {
@ -232,21 +232,14 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
testInfo.snapshotSuffix = process.platform;
if (debugMode())
(testInfo as TestInfoImpl)._setDebugMode();
for (const browserType of [playwright.chromium, playwright.firefox, playwright.webkit]) {
(browserType as any)._defaultContextOptions = _combinedContextOptions;
(browserType as any)._defaultContextTimeout = actionTimeout || 0;
(browserType as any)._defaultContextNavigationTimeout = navigationTimeout || 0;
}
(playwright.request as any)._defaultContextOptions = { ..._combinedContextOptions };
(playwright.request as any)._defaultContextOptions.tracesDir = tracing().tracesDir();
(playwright.request as any)._defaultContextOptions.timeout = actionTimeout || 0;
playwright._defaultContextOptions = _combinedContextOptions;
playwright._defaultContextTimeout = actionTimeout || 0;
playwright._defaultContextNavigationTimeout = navigationTimeout || 0;
await use();
(playwright.request as any)._defaultContextOptions = undefined;
for (const browserType of [playwright.chromium, playwright.firefox, playwright.webkit]) {
(browserType as any)._defaultContextOptions = undefined;
(browserType as any)._defaultContextTimeout = undefined;
(browserType as any)._defaultContextNavigationTimeout = undefined;
}
playwright._defaultContextOptions = undefined;
playwright._defaultContextTimeout = undefined;
playwright._defaultContextNavigationTimeout = undefined;
}, { auto: 'all-hooks-included', title: 'context configuration', box: true } as any],
_setupArtifacts: [async ({ playwright, screenshot, _pageSnapshot }, use, testInfo) => {
@ -453,7 +446,6 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
});
type ScreenshotOption = PlaywrightWorkerOptions['screenshot'] | undefined;
type Playwright = PlaywrightWorkerArgs['playwright'];
type PageSnapshotOption = 'off' | 'on' | 'only-on-failure';
function normalizeVideoMode(video: VideoMode | 'retry-with-video' | { mode: VideoMode } | undefined): VideoMode {
@ -556,12 +548,7 @@ class SnapshotRecorder {
if (!this.shouldCaptureUponFinish())
return;
const contexts: BrowserContext[] = [];
const playwright = this._artifactsRecorder._playwright;
for (const browserType of [playwright.chromium, playwright.firefox, playwright.webkit])
contexts.push(...(browserType as any)._contexts);
await Promise.all(contexts.flatMap(context => context.pages().map(page => this._snapshotPage(page, false))));
await Promise.all(this._artifactsRecorder._playwright._allPages().map(page => this._snapshotPage(page, false)));
}
async persistTemporary() {
@ -622,7 +609,7 @@ class SnapshotRecorder {
class ArtifactsRecorder {
_testInfo!: TestInfoImpl;
_playwright: Playwright;
_playwright: PlaywrightImpl;
_artifactsDir: string;
private _reusedContexts = new Set<BrowserContext>();
private _startedCollectingArtifacts: symbol;
@ -630,7 +617,7 @@ class ArtifactsRecorder {
private _pageSnapshotRecorder: SnapshotRecorder;
private _screenshotRecorder: SnapshotRecorder;
constructor(playwright: Playwright, artifactsDir: string, screenshot: ScreenshotOption, pageSnapshot: PageSnapshotOption) {
constructor(playwright: PlaywrightImpl, artifactsDir: string, screenshot: ScreenshotOption, pageSnapshot: PageSnapshotOption) {
this._playwright = playwright;
this._artifactsDir = artifactsDir;
const screenshotOptions = typeof screenshot === 'string' ? undefined : screenshot;
@ -654,17 +641,12 @@ class ArtifactsRecorder {
this._pageSnapshotRecorder.fixOrdinal();
// Process existing contexts.
for (const browserType of [this._playwright.chromium, this._playwright.firefox, this._playwright.webkit]) {
const promises: (Promise<void> | undefined)[] = [];
const existingContexts = Array.from((browserType as any)._contexts) as BrowserContext[];
for (const context of existingContexts) {
await Promise.all(this._playwright._allContexts().map(async context => {
if ((context as any)[kIsReusedContext])
this._reusedContexts.add(context);
else
promises.push(this.didCreateBrowserContext(context));
}
await Promise.all(promises);
}
await this.didCreateBrowserContext(context);
}));
{
const existingApiRequests: APIRequestContext[] = Array.from((this._playwright.request as any)._contexts as Set<APIRequestContext>);
await Promise.all(existingApiRequests.map(c => this.didCreateRequestContext(c)));
@ -704,10 +686,7 @@ class ArtifactsRecorder {
async didFinishTest() {
await this.didFinishTestFunction();
let leftoverContexts: BrowserContext[] = [];
for (const browserType of [this._playwright.chromium, this._playwright.firefox, this._playwright.webkit])
leftoverContexts.push(...(browserType as any)._contexts);
leftoverContexts = leftoverContexts.filter(context => !this._reusedContexts.has(context));
const leftoverContexts = this._playwright._allContexts().filter(context => !this._reusedContexts.has(context));
const leftoverApiRequests: APIRequestContext[] = Array.from((this._playwright.request as any)._contexts as Set<APIRequestContext>);
// Collect traces/screenshots for remaining contexts.

View file

@ -82,7 +82,7 @@ export class RemoteServer implements PlaywrightServer {
async _start(childProcess: CommonFixtures['childProcess'], browserType: BrowserType, channel: string, remoteServerOptions: RemoteServerOptions = {}) {
this._browserType = browserType;
const browserOptions = (browserType as any)._defaultLaunchOptions;
const browserOptions = (browserType as any)._playwright._defaultLaunchOptions;
// Copy options to prevent a large JSON string when launching subprocess.
// Otherwise, we get `Error: spawn ENAMETOOLONG` on Windows.
const launchOptions: Parameters<BrowserType['launchServer']>[0] = {

View file

@ -20,7 +20,7 @@ import type { BrowserContext, Page } from '@playwright/test';
const test = browserTest.extend<{ reusedContext: () => Promise<BrowserContext> }>({
reusedContext: async ({ browserType, browser }, use) => {
await use(async () => {
const defaultContextOptions = (browserType as any)._defaultContextOptions;
const defaultContextOptions = (browserType as any)._playwright._defaultContextOptions;
const context = await (browser as any)._newContextForReuse(defaultContextOptions);
return context;
});

View file

@ -21,7 +21,7 @@ import { playwrightTest as test, expect } from '../config/browserTest';
test('browserType.executablePath should work', async ({ browserType, channel, mode }) => {
test.skip(!!channel, 'We skip browser download when testing a channel');
test.skip(mode.startsWith('service'));
test.skip(!!(browserType as any)._defaultLaunchOptions.executablePath, 'Skip with custom executable path');
test.skip(!!(browserType as any)._playwright._defaultLaunchOptions.executablePath, 'Skip with custom executable path');
const executablePath = browserType.executablePath();
expect(fs.existsSync(executablePath)).toBe(true);

View file

@ -40,7 +40,7 @@ const test = playwrightTest.extend<ExtraFixtures>({
await use(async (wsEndpoint, options = {}, redirectPortForTest): Promise<Browser> => {
(options as any).__testHookRedirectPortForwarding = redirectPortForTest;
options.headers = {
'x-playwright-launch-options': JSON.stringify((browserType as any)._defaultLaunchOptions || {}),
'x-playwright-launch-options': JSON.stringify((browserType as any)._playwright._defaultLaunchOptions || {}),
...options.headers,
};
browser = await browserType.connect(wsEndpoint, options);
@ -173,8 +173,8 @@ for (const kind of ['launchServer', 'run-server'] as const) {
test('should ignore page.pause when headed', async ({ connect, startRemoteServer, browserType, channel }) => {
test.skip(channel === 'chromium-headless-shell', 'shell is never headed');
const headless = (browserType as any)._defaultLaunchOptions.headless;
(browserType as any)._defaultLaunchOptions.headless = false;
const headless = (browserType as any)._playwright._defaultLaunchOptions.headless;
(browserType as any)._playwright._defaultLaunchOptions.headless = false;
const remoteServer = await startRemoteServer(kind);
const browser = await connect(remoteServer.wsEndpoint());
const browserContext = await browser.newContext();
@ -182,7 +182,7 @@ for (const kind of ['launchServer', 'run-server'] as const) {
// @ts-ignore
await page.pause({ __testHookKeepTestTimeout: true });
await browser.close();
(browserType as any)._defaultLaunchOptions.headless = headless;
(browserType as any)._playwright._defaultLaunchOptions.headless = headless;
});
test('should be able to visit ipv6 through localhost', async ({ connect, startRemoteServer, ipV6ServerPort }) => {
@ -599,7 +599,7 @@ for (const kind of ['launchServer', 'run-server'] as const) {
const browser = await browserType.connect({
wsEndpoint: remoteServer.wsEndpoint(),
headers: {
'x-playwright-launch-options': JSON.stringify((browserType as any)._defaultLaunchOptions || {}),
'x-playwright-launch-options': JSON.stringify((browserType as any)._playwright._defaultLaunchOptions || {}),
},
});
const page = await browser.newPage();
@ -630,14 +630,14 @@ for (const kind of ['launchServer', 'run-server'] as const) {
test('should filter launch options', async ({ connect, startRemoteServer, server, browserType }, testInfo) => {
const tracesDir = testInfo.outputPath('traces');
const oldTracesDir = (browserType as any)._defaultLaunchOptions.tracesDir;
(browserType as any)._defaultLaunchOptions.tracesDir = tracesDir;
const oldTracesDir = (browserType as any)._playwright._defaultTracesDir;
(browserType as any)._playwright._defaultTracesDir = tracesDir;
const remoteServer = await startRemoteServer(kind);
const browser = await connect(remoteServer.wsEndpoint());
const page = await browser.newPage();
await page.goto(server.EMPTY_PAGE);
await browser.close();
(browserType as any)._defaultLaunchOptions.tracesDir = oldTracesDir;
(browserType as any)._playwright._defaultTracesDir = oldTracesDir;
expect(fs.existsSync(tracesDir)).toBe(false);
});

View file

@ -51,7 +51,7 @@ const test = baseTest.extend<Fixtures>({
await use(async () => {
const browser = await browserType.connect(wsEndpoint, {
headers: {
'x-playwright-launch-options': JSON.stringify((browserType as any)._defaultLaunchOptions),
'x-playwright-launch-options': JSON.stringify((browserType as any)._playwright._defaultLaunchOptions),
'x-playwright-reuse-context': '1',
},
}) as BrowserWithReuse;

View file

@ -150,7 +150,7 @@ it('should have passed URL when launching with ignoreDefaultArgs: true', async (
it.skip(mode !== 'default');
const userDataDir = await createUserDataDir();
const args = toImpl(browserType).defaultArgs((browserType as any)._defaultLaunchOptions, 'persistent', userDataDir, 0).filter(a => a !== 'about:blank');
const args = toImpl(browserType).defaultArgs((browserType as any)._playwright._defaultLaunchOptions, 'persistent', userDataDir, 0).filter(a => a !== 'about:blank');
const options = {
args: browserName === 'firefox' ? [...args, '-new-tab', server.EMPTY_PAGE] : [...args, server.EMPTY_PAGE],
ignoreDefaultArgs: true,

View file

@ -255,7 +255,7 @@ it('should set playwright as user-agent', async ({ playwright, server, isWindows
});
it('should be able to construct with context options', async ({ playwright, browserType, server }) => {
const request = await playwright.request.newContext((browserType as any)._defaultContextOptions);
const request = await playwright.request.newContext((browserType as any)._playwright._defaultContextOptions);
const response = await request.get(server.EMPTY_PAGE);
expect(response.ok()).toBeTruthy();
await request.dispose();

View file

@ -368,8 +368,8 @@ test('should not crash when browser closes mid-trace', async ({ browserType, ser
});
test('should survive browser.close with auto-created traces dir', async ({ browserType }, testInfo) => {
const oldTracesDir = (browserType as any)._defaultLaunchOptions.tracesDir;
(browserType as any)._defaultLaunchOptions.tracesDir = undefined;
const oldTracesDir = (browserType as any)._playwright._defaultTracesDir;
(browserType as any)._playwright._defaultTracesDir = undefined;
const browser = await browserType.launch();
const page = await browser.newPage();
await page.context().tracing.start();
@ -394,7 +394,7 @@ test('should survive browser.close with auto-created traces dir', async ({ brows
]);
done.value = true;
(browserType as any)._defaultLaunchOptions.tracesDir = oldTracesDir;
(browserType as any)._playwright._defaultTracesDir = oldTracesDir;
});
test('should not stall on dialogs', async ({ page, context, server }) => {