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> { 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 contextOptions = await prepareBrowserContextParams(options);
const response = forReuse ? await this._channel.newContextForReuse(contextOptions) : await this._channel.newContext(contextOptions); const response = forReuse ? await this._channel.newContextForReuse(contextOptions) : await this._channel.newContext(contextOptions);
const context = BrowserContext.from(response.context); const context = BrowserContext.from(response.context);

View file

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

View file

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

View file

@ -22,6 +22,7 @@ import { ChannelOwner } from './channelOwner';
import { Electron } from './electron'; import { Electron } from './electron';
import { APIRequest } from './fetch'; import { APIRequest } from './fetch';
import { Selectors, SelectorsOwner } from './selectors'; import { Selectors, SelectorsOwner } from './selectors';
import type { BrowserContextOptions, LaunchOptions } from 'playwright-core';
export class Playwright extends ChannelOwner<channels.PlaywrightChannel> { export class Playwright extends ChannelOwner<channels.PlaywrightChannel> {
readonly _android: Android; readonly _android: Android;
@ -36,6 +37,12 @@ export class Playwright extends ChannelOwner<channels.PlaywrightChannel> {
readonly request: APIRequest; readonly request: APIRequest;
readonly errors: { TimeoutError: typeof TimeoutError }; readonly errors: { TimeoutError: typeof TimeoutError };
// Instrumentation.
_defaultLaunchOptions?: LaunchOptions;
_defaultContextOptions?: BrowserContextOptions;
_defaultContextTimeout?: number;
_defaultContextNavigationTimeout?: number;
constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.PlaywrightInitializer) { constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.PlaywrightInitializer) {
super(parent, type, guid, initializer); super(parent, type, guid, initializer);
this.request = new APIRequest(this); this.request = new APIRequest(this);
@ -73,4 +80,16 @@ export class Playwright extends ChannelOwner<channels.PlaywrightChannel> {
static from(channel: channels.PlaywrightChannel): Playwright { static from(channel: channels.PlaywrightChannel): Playwright {
return (channel as any)._object; 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 { rootTestType } from './common/testType';
import type { ContextReuseMode } from './common/config'; import type { ContextReuseMode } from './common/config';
import type { ApiCallData, ClientInstrumentation, ClientInstrumentationListener } from '../../playwright-core/src/client/clientInstrumentation'; 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'; import { currentTestInfo } from './common/globals';
export { expect } from './matchers/expect'; export { expect } from './matchers/expect';
export const _baseTest: TestType<{}, {}> = rootTestType.test; export const _baseTest: TestType<{}, {}> = rootTestType.test;
@ -50,6 +51,7 @@ type TestFixtures = PlaywrightTestArgs & PlaywrightTestOptions & {
}; };
type WorkerFixtures = PlaywrightWorkerArgs & PlaywrightWorkerOptions & { type WorkerFixtures = PlaywrightWorkerArgs & PlaywrightWorkerOptions & {
playwright: PlaywrightImpl;
_browserOptions: LaunchOptions; _browserOptions: LaunchOptions;
_optionContextReuseMode: ContextReuseMode, _optionContextReuseMode: ContextReuseMode,
_optionConnectOptions: PlaywrightWorkerOptions['connectOptions'], _optionConnectOptions: PlaywrightWorkerOptions['connectOptions'],
@ -78,18 +80,16 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
const options: LaunchOptions = { const options: LaunchOptions = {
handleSIGINT: false, handleSIGINT: false,
...launchOptions, ...launchOptions,
tracesDir: tracing().tracesDir(),
}; };
if (headless !== undefined) if (headless !== undefined)
options.headless = headless; options.headless = headless;
if (channel !== undefined) if (channel !== undefined)
options.channel = channel; options.channel = channel;
options.tracesDir = tracing().tracesDir();
for (const browserType of [playwright.chromium, playwright.firefox, playwright.webkit, playwright._bidiChromium, playwright._bidiFirefox]) playwright._defaultLaunchOptions = options;
(browserType as any)._defaultLaunchOptions = options;
await use(options); await use(options);
for (const browserType of [playwright.chromium, playwright.firefox, playwright.webkit, playwright._bidiChromium, playwright._bidiFirefox]) playwright._defaultLaunchOptions = undefined;
(browserType as any)._defaultLaunchOptions = undefined;
}, { scope: 'worker', auto: true, box: true }], }, { scope: 'worker', auto: true, box: true }],
browser: [async ({ playwright, browserName, _browserOptions, connectOptions, _reuseContext }, use, testInfo) => { browser: [async ({ playwright, browserName, _browserOptions, connectOptions, _reuseContext }, use, testInfo) => {
@ -232,21 +232,14 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
testInfo.snapshotSuffix = process.platform; testInfo.snapshotSuffix = process.platform;
if (debugMode()) if (debugMode())
(testInfo as TestInfoImpl)._setDebugMode(); (testInfo as TestInfoImpl)._setDebugMode();
for (const browserType of [playwright.chromium, playwright.firefox, playwright.webkit]) {
(browserType as any)._defaultContextOptions = _combinedContextOptions; playwright._defaultContextOptions = _combinedContextOptions;
(browserType as any)._defaultContextTimeout = actionTimeout || 0; playwright._defaultContextTimeout = actionTimeout || 0;
(browserType as any)._defaultContextNavigationTimeout = navigationTimeout || 0; playwright._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;
await use(); await use();
(playwright.request as any)._defaultContextOptions = undefined; playwright._defaultContextOptions = undefined;
for (const browserType of [playwright.chromium, playwright.firefox, playwright.webkit]) { playwright._defaultContextTimeout = undefined;
(browserType as any)._defaultContextOptions = undefined; playwright._defaultContextNavigationTimeout = undefined;
(browserType as any)._defaultContextTimeout = undefined;
(browserType as any)._defaultContextNavigationTimeout = undefined;
}
}, { auto: 'all-hooks-included', title: 'context configuration', box: true } as any], }, { auto: 'all-hooks-included', title: 'context configuration', box: true } as any],
_setupArtifacts: [async ({ playwright, screenshot, _pageSnapshot }, use, testInfo) => { _setupArtifacts: [async ({ playwright, screenshot, _pageSnapshot }, use, testInfo) => {
@ -453,7 +446,6 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
}); });
type ScreenshotOption = PlaywrightWorkerOptions['screenshot'] | undefined; type ScreenshotOption = PlaywrightWorkerOptions['screenshot'] | undefined;
type Playwright = PlaywrightWorkerArgs['playwright'];
type PageSnapshotOption = 'off' | 'on' | 'only-on-failure'; type PageSnapshotOption = 'off' | 'on' | 'only-on-failure';
function normalizeVideoMode(video: VideoMode | 'retry-with-video' | { mode: VideoMode } | undefined): VideoMode { function normalizeVideoMode(video: VideoMode | 'retry-with-video' | { mode: VideoMode } | undefined): VideoMode {
@ -556,12 +548,7 @@ class SnapshotRecorder {
if (!this.shouldCaptureUponFinish()) if (!this.shouldCaptureUponFinish())
return; return;
const contexts: BrowserContext[] = []; await Promise.all(this._artifactsRecorder._playwright._allPages().map(page => this._snapshotPage(page, false)));
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))));
} }
async persistTemporary() { async persistTemporary() {
@ -622,7 +609,7 @@ class SnapshotRecorder {
class ArtifactsRecorder { class ArtifactsRecorder {
_testInfo!: TestInfoImpl; _testInfo!: TestInfoImpl;
_playwright: Playwright; _playwright: PlaywrightImpl;
_artifactsDir: string; _artifactsDir: string;
private _reusedContexts = new Set<BrowserContext>(); private _reusedContexts = new Set<BrowserContext>();
private _startedCollectingArtifacts: symbol; private _startedCollectingArtifacts: symbol;
@ -630,7 +617,7 @@ class ArtifactsRecorder {
private _pageSnapshotRecorder: SnapshotRecorder; private _pageSnapshotRecorder: SnapshotRecorder;
private _screenshotRecorder: 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._playwright = playwright;
this._artifactsDir = artifactsDir; this._artifactsDir = artifactsDir;
const screenshotOptions = typeof screenshot === 'string' ? undefined : screenshot; const screenshotOptions = typeof screenshot === 'string' ? undefined : screenshot;
@ -654,17 +641,12 @@ class ArtifactsRecorder {
this._pageSnapshotRecorder.fixOrdinal(); this._pageSnapshotRecorder.fixOrdinal();
// Process existing contexts. // Process existing contexts.
for (const browserType of [this._playwright.chromium, this._playwright.firefox, this._playwright.webkit]) { await Promise.all(this._playwright._allContexts().map(async context => {
const promises: (Promise<void> | undefined)[] = [];
const existingContexts = Array.from((browserType as any)._contexts) as BrowserContext[];
for (const context of existingContexts) {
if ((context as any)[kIsReusedContext]) if ((context as any)[kIsReusedContext])
this._reusedContexts.add(context); this._reusedContexts.add(context);
else else
promises.push(this.didCreateBrowserContext(context)); await this.didCreateBrowserContext(context);
} }));
await Promise.all(promises);
}
{ {
const existingApiRequests: APIRequestContext[] = Array.from((this._playwright.request as any)._contexts as Set<APIRequestContext>); const existingApiRequests: APIRequestContext[] = Array.from((this._playwright.request as any)._contexts as Set<APIRequestContext>);
await Promise.all(existingApiRequests.map(c => this.didCreateRequestContext(c))); await Promise.all(existingApiRequests.map(c => this.didCreateRequestContext(c)));
@ -704,10 +686,7 @@ class ArtifactsRecorder {
async didFinishTest() { async didFinishTest() {
await this.didFinishTestFunction(); await this.didFinishTestFunction();
let leftoverContexts: BrowserContext[] = []; const leftoverContexts = this._playwright._allContexts().filter(context => !this._reusedContexts.has(context));
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 leftoverApiRequests: APIRequestContext[] = Array.from((this._playwright.request as any)._contexts as Set<APIRequestContext>); const leftoverApiRequests: APIRequestContext[] = Array.from((this._playwright.request as any)._contexts as Set<APIRequestContext>);
// Collect traces/screenshots for remaining contexts. // 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 = {}) { async _start(childProcess: CommonFixtures['childProcess'], browserType: BrowserType, channel: string, remoteServerOptions: RemoteServerOptions = {}) {
this._browserType = browserType; 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. // Copy options to prevent a large JSON string when launching subprocess.
// Otherwise, we get `Error: spawn ENAMETOOLONG` on Windows. // Otherwise, we get `Error: spawn ENAMETOOLONG` on Windows.
const launchOptions: Parameters<BrowserType['launchServer']>[0] = { 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> }>({ const test = browserTest.extend<{ reusedContext: () => Promise<BrowserContext> }>({
reusedContext: async ({ browserType, browser }, use) => { reusedContext: async ({ browserType, browser }, use) => {
await use(async () => { await use(async () => {
const defaultContextOptions = (browserType as any)._defaultContextOptions; const defaultContextOptions = (browserType as any)._playwright._defaultContextOptions;
const context = await (browser as any)._newContextForReuse(defaultContextOptions); const context = await (browser as any)._newContextForReuse(defaultContextOptions);
return context; 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('browserType.executablePath should work', async ({ browserType, channel, mode }) => {
test.skip(!!channel, 'We skip browser download when testing a channel'); test.skip(!!channel, 'We skip browser download when testing a channel');
test.skip(mode.startsWith('service')); 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(); const executablePath = browserType.executablePath();
expect(fs.existsSync(executablePath)).toBe(true); 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> => { await use(async (wsEndpoint, options = {}, redirectPortForTest): Promise<Browser> => {
(options as any).__testHookRedirectPortForwarding = redirectPortForTest; (options as any).__testHookRedirectPortForwarding = redirectPortForTest;
options.headers = { 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, ...options.headers,
}; };
browser = await browserType.connect(wsEndpoint, options); 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('should ignore page.pause when headed', async ({ connect, startRemoteServer, browserType, channel }) => {
test.skip(channel === 'chromium-headless-shell', 'shell is never headed'); test.skip(channel === 'chromium-headless-shell', 'shell is never headed');
const headless = (browserType as any)._defaultLaunchOptions.headless; const headless = (browserType as any)._playwright._defaultLaunchOptions.headless;
(browserType as any)._defaultLaunchOptions.headless = false; (browserType as any)._playwright._defaultLaunchOptions.headless = false;
const remoteServer = await startRemoteServer(kind); const remoteServer = await startRemoteServer(kind);
const browser = await connect(remoteServer.wsEndpoint()); const browser = await connect(remoteServer.wsEndpoint());
const browserContext = await browser.newContext(); const browserContext = await browser.newContext();
@ -182,7 +182,7 @@ for (const kind of ['launchServer', 'run-server'] as const) {
// @ts-ignore // @ts-ignore
await page.pause({ __testHookKeepTestTimeout: true }); await page.pause({ __testHookKeepTestTimeout: true });
await browser.close(); 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 }) => { 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({ const browser = await browserType.connect({
wsEndpoint: remoteServer.wsEndpoint(), wsEndpoint: remoteServer.wsEndpoint(),
headers: { 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(); 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) => { test('should filter launch options', async ({ connect, startRemoteServer, server, browserType }, testInfo) => {
const tracesDir = testInfo.outputPath('traces'); const tracesDir = testInfo.outputPath('traces');
const oldTracesDir = (browserType as any)._defaultLaunchOptions.tracesDir; const oldTracesDir = (browserType as any)._playwright._defaultTracesDir;
(browserType as any)._defaultLaunchOptions.tracesDir = tracesDir; (browserType as any)._playwright._defaultTracesDir = tracesDir;
const remoteServer = await startRemoteServer(kind); const remoteServer = await startRemoteServer(kind);
const browser = await connect(remoteServer.wsEndpoint()); const browser = await connect(remoteServer.wsEndpoint());
const page = await browser.newPage(); const page = await browser.newPage();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await browser.close(); await browser.close();
(browserType as any)._defaultLaunchOptions.tracesDir = oldTracesDir; (browserType as any)._playwright._defaultTracesDir = oldTracesDir;
expect(fs.existsSync(tracesDir)).toBe(false); expect(fs.existsSync(tracesDir)).toBe(false);
}); });

View file

@ -51,7 +51,7 @@ const test = baseTest.extend<Fixtures>({
await use(async () => { await use(async () => {
const browser = await browserType.connect(wsEndpoint, { const browser = await browserType.connect(wsEndpoint, {
headers: { 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', 'x-playwright-reuse-context': '1',
}, },
}) as BrowserWithReuse; }) as BrowserWithReuse;

View file

@ -150,7 +150,7 @@ it('should have passed URL when launching with ignoreDefaultArgs: true', async (
it.skip(mode !== 'default'); it.skip(mode !== 'default');
const userDataDir = await createUserDataDir(); 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 = { const options = {
args: browserName === 'firefox' ? [...args, '-new-tab', server.EMPTY_PAGE] : [...args, server.EMPTY_PAGE], args: browserName === 'firefox' ? [...args, '-new-tab', server.EMPTY_PAGE] : [...args, server.EMPTY_PAGE],
ignoreDefaultArgs: true, 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 }) => { 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); const response = await request.get(server.EMPTY_PAGE);
expect(response.ok()).toBeTruthy(); expect(response.ok()).toBeTruthy();
await request.dispose(); 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) => { test('should survive browser.close with auto-created traces dir', async ({ browserType }, testInfo) => {
const oldTracesDir = (browserType as any)._defaultLaunchOptions.tracesDir; const oldTracesDir = (browserType as any)._playwright._defaultTracesDir;
(browserType as any)._defaultLaunchOptions.tracesDir = undefined; (browserType as any)._playwright._defaultTracesDir = undefined;
const browser = await browserType.launch(); const browser = await browserType.launch();
const page = await browser.newPage(); const page = await browser.newPage();
await page.context().tracing.start(); await page.context().tracing.start();
@ -394,7 +394,7 @@ test('should survive browser.close with auto-created traces dir', async ({ brows
]); ]);
done.value = true; 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 }) => { test('should not stall on dialogs', async ({ page, context, server }) => {