Skip to content

Commit

Permalink
chore: add _browserTypes helpers to playwright (#34611)
Browse files Browse the repository at this point in the history
  • Loading branch information
Skn0tt authored Feb 7, 2025
1 parent 9e43306 commit 893e7bb
Show file tree
Hide file tree
Showing 13 changed files with 78 additions and 87 deletions.
2 changes: 1 addition & 1 deletion packages/playwright-core/src/client/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
26 changes: 10 additions & 16 deletions packages/playwright-core/src/client/browserType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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;
}
Expand All @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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);
}

Expand Down
19 changes: 9 additions & 10 deletions packages/playwright-core/src/client/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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[];
};

Expand All @@ -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;
}
Expand Down
19 changes: 19 additions & 0 deletions packages/playwright-core/src/client/playwright.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
Expand Down Expand Up @@ -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());
}
}
65 changes: 22 additions & 43 deletions packages/playwright/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -50,6 +51,7 @@ type TestFixtures = PlaywrightTestArgs & PlaywrightTestOptions & {
};

type WorkerFixtures = PlaywrightWorkerArgs & PlaywrightWorkerOptions & {
playwright: PlaywrightImpl;
_browserOptions: LaunchOptions;
_optionContextReuseMode: ContextReuseMode,
_optionConnectOptions: PlaywrightWorkerOptions['connectOptions'],
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -622,15 +609,15 @@ class SnapshotRecorder {

class ArtifactsRecorder {
_testInfo!: TestInfoImpl;
_playwright: Playwright;
_playwright: PlaywrightImpl;
_artifactsDir: string;
private _reusedContexts = new Set<BrowserContext>();
private _startedCollectingArtifacts: symbol;

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;
Expand All @@ -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) {
if ((context as any)[kIsReusedContext])
this._reusedContexts.add(context);
else
promises.push(this.didCreateBrowserContext(context));
}
await Promise.all(promises);
}
await Promise.all(this._playwright._allContexts().map(async context => {
if ((context as any)[kIsReusedContext])
this._reusedContexts.add(context);
else
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)));
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion tests/config/remoteServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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] = {
Expand Down
2 changes: 1 addition & 1 deletion tests/library/browsercontext-reuse.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
});
Expand Down
2 changes: 1 addition & 1 deletion tests/library/browsertype-basic.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading

0 comments on commit 893e7bb

Please sign in to comment.