Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
feat(tracing): add resourcesDir option to Tracing.startHar (#40488)
Dmitry Gozmanb3714205d4d7
diff --git a/docs/src/api/class-tracing.md b/docs/src/api/class-tracing.mdindex 50501c3bce..1af0427bfd 100644--- a/docs/src/api/class-tracing.md+++ b/docs/src/api/class-tracing.md@@ -372,6 +372,14 @@ When set to `minimal`, only record information necessary for routing from HAR. TA glob or regex pattern to filter requests that are stored in the HAR. Defaults to none.+### option: Tracing.startHar.resourcesDir+* since: v1.60+* langs: js+- `resourcesDir` <[path]>++Only used together with `content: 'attach'`. When set, response bodies are placed in this directory instead of next to+the HAR file. Not compatible with a `.zip` HAR file.+## async method: Tracing.group* since: v1.49- returns: <[Disposable]>diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.tsindex c612d45530..527243cd56 100644--- a/packages/playwright-client/types/types.d.ts+++ b/packages/playwright-client/types/types.d.ts@@ -22191,6 +22191,12 @@ export interface Tracing {*/mode?: "full"|"minimal";+ /**+ * Only used together with `content: 'attach'`. When set, response bodies are placed in this directory instead of next+ * to the HAR file. Not compatible with a `.zip` HAR file.+ */+ resourcesDir?: string;+/*** A glob or regex pattern to filter requests that are stored in the HAR. Defaults to none.*/diff --git a/packages/playwright-core/src/client/tracing.ts b/packages/playwright-core/src/client/tracing.tsindex 4d7d50f32e..5d771656b2 100644--- a/packages/playwright-core/src/client/tracing.ts+++ b/packages/playwright-core/src/client/tracing.ts@@ -31,7 +31,7 @@ export class Tracing extends ChannelOwner<channels.TracingChannel> implements apprivate _stacksId: string | undefined;private _isTracing = false;private _harId: string | undefined;- private _harRecorders = new Map<string, { path: string, content: 'embed' | 'attach' | 'omit' | undefined }>();+ private _harRecorders = new Map<string, { path: string, resourcesDir?: string }>();static from(channel: channels.TracingChannel): Tracing {return (channel as any)._object;@@ -96,15 +96,18 @@ export class Tracing extends ChannelOwner<channels.TracingChannel> implements ap});}- async startHar(path: string, options: { content?: 'embed' | 'attach' | 'omit', mode?: 'full' | 'minimal', urlFilter?: string | RegExp } = {}) {+ async startHar(path: string, options: { content?: 'embed' | 'attach' | 'omit', mode?: 'full' | 'minimal', urlFilter?: string | RegExp, resourcesDir?: string } = {}) {await this._wrapApiCall(async () => {if (this._harId)throw new Error('HAR recording has already been started');+ if (options.resourcesDir && path.endsWith('.zip'))+ throw new Error('resourcesDir option is not compatible with a .zip har file');const defaultContent = path.endsWith('.zip') ? 'attach' : 'embed';this._harId = await this._recordIntoHAR(path, null, {url: options.urlFilter,updateContent: options.content ?? defaultContent,updateMode: options.mode ?? 'full',+ resourcesDir: options.resourcesDir,});});return new DisposableStub(() => this.stopHar());@@ -120,19 +123,21 @@ export class Tracing extends ChannelOwner<channels.TracingChannel> implements ap});}- async _recordIntoHAR(har: string, page: Page | null, options: { url?: string | RegExp, updateContent?: 'attach' | 'embed' | 'omit', updateMode?: 'minimal' | 'full' } = {}): Promise<string> {+ async _recordIntoHAR(har: string, page: Page | null, options: { url?: string | RegExp, updateContent?: 'attach' | 'embed' | 'omit', updateMode?: 'minimal' | 'full', resourcesDir?: string } = {}): Promise<string> {+ const isZip = har.endsWith('.zip');const { harId } = await this._channel.harStart({page: page?._channel,options: {- zip: har.endsWith('.zip'),content: options.updateContent ?? 'attach',urlGlob: isString(options.url) ? options.url : undefined,urlRegexSource: isRegExp(options.url) ? options.url.source : undefined,urlRegexFlags: isRegExp(options.url) ? options.url.flags : undefined,mode: options.updateMode ?? 'minimal',+ harPath: isZip ? undefined : har,+ resourcesDir: options.resourcesDir,},});- this._harRecorders.set(harId, { path: har, content: options.updateContent ?? 'attach' });+ this._harRecorders.set(harId, { path: har, resourcesDir: options.resourcesDir });return harId;}@@ -141,19 +146,34 @@ export class Tracing extends ChannelOwner<channels.TracingChannel> implements apif (!harParams)return;this._harRecorders.delete(harId);- const har = await this._channel.harExport({ harId });- const artifact = Artifact.from(har.artifact);- const isCompressed = harParams.content === 'attach' || harParams.path.endsWith('.zip');- const needCompressed = harParams.path.endsWith('.zip');- if (isCompressed && !needCompressed) {+ const isLocal = !this._connection.isRemote();+ const isZip = harParams.path.endsWith('.zip');++ if (isLocal) {+ const { entries } = await this._channel.harExport({ harId, mode: 'entries' });+ if (!isZip) {+ // Server wrote HAR and resources to the user's chosen paths.+ return;+ }const localUtils = this._connection.localUtils();if (!localUtils)- throw new Error('Uncompressed har is not supported in thin clients');- await artifact.saveAs(harParams.path + '.tmp');- await localUtils.harUnzip({ zipFile: harParams.path + '.tmp', harFile: harParams.path });- } else {+ throw new Error('Cannot save zipped HAR in thin clients');+ await localUtils.zip({ zipFile: harParams.path, entries: entries!, mode: 'write', includeSources: false, additionalSources: [] });+ return;+ }++ const { artifact: artifactChannel } = await this._channel.harExport({ harId, mode: 'archive' });+ const artifact = Artifact.from(artifactChannel!);+ if (isZip) {await artifact.saveAs(harParams.path);+ await artifact.delete();+ return;}+ const localUtils = this._connection.localUtils();+ if (!localUtils)+ throw new Error('Uncompressed har is not supported in thin clients');+ await artifact.saveAs(harParams.path + '.tmp');+ await localUtils.harUnzip({ zipFile: harParams.path + '.tmp', harFile: harParams.path, resourcesDir: harParams.resourcesDir });await artifact.delete();}diff --git a/packages/playwright-core/src/protocol/validator.ts b/packages/playwright-core/src/protocol/validator.tsindex c44a77298c..d0f5d2b4ea 100644--- a/packages/playwright-core/src/protocol/validator.ts+++ b/packages/playwright-core/src/protocol/validator.ts@@ -178,12 +178,13 @@ scheme.SerializedError = tObject({value: tOptional(tType('SerializedValue')),});scheme.RecordHarOptions = tObject({- zip: tOptional(tBoolean),content: tOptional(tEnum(['embed', 'attach', 'omit'])),mode: tOptional(tEnum(['full', 'minimal'])),urlGlob: tOptional(tString),urlRegexSource: tOptional(tString),urlRegexFlags: tOptional(tString),+ harPath: tOptional(tString),+ resourcesDir: tOptional(tString),});scheme.FormField = tObject({name: tString,@@ -312,6 +313,7 @@ scheme.LocalUtilsHarCloseResult = tOptional(tObject({}));scheme.LocalUtilsHarUnzipParams = tObject({zipFile: tString,harFile: tString,+ resourcesDir: tOptional(tString),});scheme.LocalUtilsHarUnzipResult = tOptional(tObject({}));scheme.LocalUtilsConnectParams = tObject({@@ -2656,9 +2658,11 @@ scheme.TracingHarStartResult = tObject({});scheme.TracingHarExportParams = tObject({harId: tOptional(tString),+ mode: tEnum(['archive', 'entries']),});scheme.TracingHarExportResult = tObject({- artifact: tChannel(['Artifact']),+ artifact: tOptional(tChannel(['Artifact'])),+ entries: tOptional(tArray(tType('NameValue'))),});scheme.ArtifactInitializer = tObject({absolutePath: tString,diff --git a/packages/playwright-core/src/server/dispatchers/tracingDispatcher.ts b/packages/playwright-core/src/server/dispatchers/tracingDispatcher.tsindex 7569e11fb4..f52c02f48a 100644--- a/packages/playwright-core/src/server/dispatchers/tracingDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/tracingDispatcher.ts@@ -71,10 +71,11 @@ export class TracingDispatcher extends Dispatcher<Tracing, channels.TracingChann}async harExport(params: channels.TracingHarExportParams, progress: Progress): Promise<channels.TracingHarExportResult> {- const artifact = await this._object.harExport(progress, params.harId);- if (!artifact)- throw new Error('No HAR artifact. Ensure record.harPath is set.');- return { artifact: ArtifactDispatcher.from(this, artifact) };+ const { artifact, entries } = await this._object.harExport(progress, params.harId, params.mode);+ return {+ artifact: artifact ? ArtifactDispatcher.from(this, artifact) : undefined,+ entries,+ };}override _onDispose() {diff --git a/packages/playwright-core/src/server/har/harRecorder.ts b/packages/playwright-core/src/server/har/harRecorder.tsindex 57be2659ab..3367c1acdb 100644--- a/packages/playwright-core/src/server/har/harRecorder.ts+++ b/packages/playwright-core/src/server/har/harRecorder.ts@@ -14,36 +14,42 @@* limitations under the License.*/-import fs from 'fs';import path from 'path';-import * as yazl from 'yazl';-import { ManualPromise } from '@isomorphic/manualPromise';+import { SerializedFS } from '@utils/serializedFS';import { Artifact } from '../artifact';import { HarTracer } from './harTracer';import type { APIRequestContext } from '../fetch';import type { BrowserContext } from '../browserContext';import type { HarTracerDelegate } from './harTracer';-import type { ZipFile } from 'yazl';import type { Page } from '../page';+import type { NameValue } from '@isomorphic/types';import type * as channels from '@protocol/channels';import type * as har from '@trace/har';-import type EventEmitter from 'events';export class HarRecorder implements HarTracerDelegate {- private _artifact: Artifact;+ private _context: BrowserContext | APIRequestContext;+ private _fs = new SerializedFS();+ private _harFilePath: string;+ private _resourcesDir: string;private _isFlushed: boolean = false;private _tracer: HarTracer;private _entries: har.Entry[] = [];- private _zipFile: ZipFile | null = null;- private _writtenZipEntries = new Set<string>();-- constructor(context: BrowserContext | APIRequestContext, harFilePath: string, page: Page | null, options: channels.RecordHarOptions) {- this._artifact = new Artifact(context, harFilePath);+ private _writtenContentEntries = new Set<string>();++ constructor(context: BrowserContext | APIRequestContext, fallbackDir: string, harId: string, page: Page | null, options: channels.RecordHarOptions) {+ this._context = context;+ const isServer = !!context.attribution.playwright.options.isServer;+ this._harFilePath = !isServer && options.harPath ? options.harPath : path.join(fallbackDir, `${harId}.har`);+ if (!isServer && options.resourcesDir)+ this._resourcesDir = options.resourcesDir;+ else if (!isServer && options.harPath)+ this._resourcesDir = path.dirname(options.harPath);+ else+ this._resourcesDir = path.join(fallbackDir, `${harId}-resources`);const urlFilterRe = options.urlRegexSource !== undefined && options.urlRegexFlags !== undefined ? new RegExp(options.urlRegexSource, options.urlRegexFlags) : undefined;- const expectsZip = !!options.zip;- const content = options.content || (expectsZip ? 'attach' : 'embed');+ const content = options.content || 'embed';this._tracer = new HarTracer(context, page, this, {content,slimMode: options.mode === 'minimal',@@ -52,7 +58,6 @@ export class HarRecorder implements HarTracerDelegate {waitForContentOnStop: true,urlFilter: urlFilterRe ?? options.urlGlob,});- this._zipFile = content === 'attach' || expectsZip ? new yazl.ZipFile() : null;this._tracer.start({ omitScripts: false });}@@ -64,13 +69,15 @@ export class HarRecorder implements HarTracerDelegate {}onContentBlob(sha1: string, buffer: Buffer) {- if (!this._zipFile || this._writtenZipEntries.has(sha1))+ if (this._writtenContentEntries.has(sha1))return;- this._writtenZipEntries.add(sha1);- this._zipFile!.addBuffer(buffer, sha1);+ if (!this._writtenContentEntries.size)+ this._fs.mkdir(this._resourcesDir);+ this._writtenContentEntries.add(sha1);+ this._fs.writeFile(path.join(this._resourcesDir, sha1), buffer, true /* skipIfExists */);}- async flush() {+ private async _flush() {if (this._isFlushed)return;this._isFlushed = true;@@ -79,28 +86,33 @@ export class HarRecorder implements HarTracerDelegate {const log = this._tracer.stop();log.entries = this._entries;- const harFileContent = jsonStringify({ log });-- await fs.promises.mkdir(path.dirname(this._artifact.localPath()), { recursive: true });-- if (this._zipFile) {- const result = new ManualPromise<void>();- (this._zipFile as unknown as EventEmitter).on('error', error => result.reject(error));- this._zipFile.addBuffer(Buffer.from(harFileContent, 'utf-8'), 'har.har');- this._zipFile.end();- this._zipFile.outputStream.pipe(fs.createWriteStream(this._artifact.localPath())).on('close', () => {- result.resolve();- });- await result;- } else {- await fs.promises.writeFile(this._artifact.localPath(), harFileContent);- }+ this._fs.mkdir(path.dirname(this._harFilePath));+ this._fs.writeFile(this._harFilePath, jsonStringify({ log }));+ }++ async flush() {+ await this._flush();+ const error = await this._fs.syncAndGetError();+ if (error)+ throw error;}- async export(): Promise<Artifact> {- await this.flush();- this._artifact.reportFinished();- return this._artifact;+ async export(mode: 'archive' | 'entries'): Promise<{ entries?: NameValue[], artifact?: Artifact }> {+ await this._flush();+ const entries: NameValue[] = [{ name: 'har.har', value: this._harFilePath }];+ for (const sha1 of this._writtenContentEntries)+ entries.push({ name: sha1, value: path.join(this._resourcesDir, sha1) });+ const zipPath = this._harFilePath + '.zip';+ if (mode === 'archive')+ this._fs.zip(entries, zipPath);+ const error = await this._fs.syncAndGetError();+ if (error)+ throw error;+ if (mode === 'entries')+ return { entries };+ const artifact = new Artifact(this._context, zipPath);+ artifact.reportFinished();+ return { artifact };}}diff --git a/packages/playwright-core/src/server/localUtils.ts b/packages/playwright-core/src/server/localUtils.tsindex 661287f1c9..781e21379d 100644--- a/packages/playwright-core/src/server/localUtils.ts+++ b/packages/playwright-core/src/server/localUtils.ts@@ -174,15 +174,21 @@ export function harClose(harBackends: Map<string, HarBackend>, params: channels.}export async function harUnzip(progress: Progress, params: channels.LocalUtilsHarUnzipParams): Promise<void> {- const dir = path.dirname(params.zipFile);+ const resourcesDir = params.resourcesDir ?? path.dirname(params.zipFile);const zipFile = new ZipFile(params.zipFile);+ let resourcesDirCreated = false;try {for (const entry of await progress.race(zipFile.entries())) {const buffer = await progress.race(zipFile.read(entry));- if (entry === 'har.har')+ if (entry === 'har.har') {await progress.race(fs.promises.writeFile(params.harFile, buffer));- else- await progress.race(fs.promises.writeFile(path.join(dir, entry), buffer));+ } else {+ if (!resourcesDirCreated) {+ await progress.race(fs.promises.mkdir(resourcesDir, { recursive: true }));+ resourcesDirCreated = true;+ }+ await progress.race(fs.promises.writeFile(path.join(resourcesDir, entry), buffer));+ }}await progress.race(fs.promises.unlink(params.zipFile));} finally {diff --git a/packages/playwright-core/src/server/trace/recorder/tracing.ts b/packages/playwright-core/src/server/trace/recorder/tracing.tsindex 80addbab78..f6f30684a7 100644--- a/packages/playwright-core/src/server/trace/recorder/tracing.ts+++ b/packages/playwright-core/src/server/trace/recorder/tracing.ts@@ -359,16 +359,15 @@ export class Tracing extends SdkObject implements InstrumentationListener, SnapsharStart(page: Page | null, options: RecordHarOptions): string {const harId = createGuid();const artifactsDir = this._context instanceof BrowserContext ? this._context._browser.options.artifactsDir : this._createTracesDirIfNeeded();- const harFilePath = path.join(artifactsDir, `${harId}.har`);- this.harRecorders.set(harId, new HarRecorder(this._context, harFilePath, page, options));+ this.harRecorders.set(harId, new HarRecorder(this._context, artifactsDir, harId, page, options));return harId;}- async harExport(progress: Progress, harId: string | undefined): Promise<Artifact> {+ async harExport(progress: Progress, harId: string | undefined, mode: 'archive' | 'entries'): Promise<{ artifact?: Artifact, entries?: NameValue[] }> {const recorder = this.harRecorders.get(harId || '')!;- const artifact = await progress.race(recorder.export());+ const result = await progress.race(recorder.export(mode));this.harRecorders.delete(harId || '');- return artifact;+ return result;}private _closeAllGroups() {diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.tsindex c612d45530..527243cd56 100644--- a/packages/playwright-core/types/types.d.ts+++ b/packages/playwright-core/types/types.d.ts@@ -22191,6 +22191,12 @@ export interface Tracing {*/mode?: "full"|"minimal";+ /**+ * Only used together with `content: 'attach'`. When set, response bodies are placed in this directory instead of next+ * to the HAR file. Not compatible with a `.zip` HAR file.+ */+ resourcesDir?: string;+/*** A glob or regex pattern to filter requests that are stored in the HAR. Defaults to none.*/diff --git a/packages/protocol/src/channels.d.ts b/packages/protocol/src/channels.d.tsindex 3d7bcdf94f..9847c692d5 100644--- a/packages/protocol/src/channels.d.ts+++ b/packages/protocol/src/channels.d.ts@@ -310,12 +310,13 @@ export type SerializedError = {};export type RecordHarOptions = {- zip?: boolean,content?: 'embed' | 'attach' | 'omit',mode?: 'full' | 'minimal',urlGlob?: string,urlRegexSource?: string,urlRegexFlags?: string,+ harPath?: string,+ resourcesDir?: string,};export type FormField = {@@ -521,9 +522,10 @@ export type LocalUtilsHarCloseResult = void;export type LocalUtilsHarUnzipParams = {zipFile: string,harFile: string,+ resourcesDir?: string,};export type LocalUtilsHarUnzipOptions = {-+ resourcesDir?: string,};export type LocalUtilsHarUnzipResult = void;export type LocalUtilsConnectParams = {@@ -4604,12 +4606,14 @@ export type TracingHarStartResult = {};export type TracingHarExportParams = {harId?: string,+ mode: 'archive' | 'entries',};export type TracingHarExportOptions = {harId?: string,};export type TracingHarExportResult = {- artifact: ArtifactChannel,+ artifact?: ArtifactChannel,+ entries?: NameValue[],};export interface TracingEvents {diff --git a/packages/protocol/src/protocol.yml b/packages/protocol/src/protocol.ymlindex fbb20b6100..26145d4799 100644--- a/packages/protocol/src/protocol.yml+++ b/packages/protocol/src/protocol.yml@@ -310,7 +310,6 @@ SerializedError:RecordHarOptions:type: objectproperties:- zip: boolean?content:type: enum?literals:@@ -325,6 +324,8 @@ RecordHarOptions:urlGlob: string?urlRegexSource: string?urlRegexFlags: string?+ harPath: string?+ resourcesDir: string?FormField:@@ -726,6 +727,7 @@ LocalUtils:parameters:zipFile: stringharFile: string+ resourcesDir: string?connect:internal: true@@ -4099,8 +4101,18 @@ Tracing:internal: trueparameters:harId: string?+ mode:+ type: enum+ literals:+ - archive+ - entriesreturns:- artifact: Artifact+ # Present when mode is 'archive'.+ artifact: Artifact?+ # Present when mode is 'entries'.+ entries:+ type: array?+ items: NameValueArtifact:diff --git a/tests/library/har.spec.ts b/tests/library/har.spec.tsindex c7de2865d3..6deab064cf 100644--- a/tests/library/har.spec.ts+++ b/tests/library/har.spec.ts@@ -17,6 +17,7 @@import { browserTest as it, expect } from '../config/browserTest';import fs from 'fs';+import path from 'path';import type { BrowserContext, BrowserContextOptions } from 'playwright-core';import type { AddressInfo } from 'net';import type { Log } from '../../packages/trace/src/har';@@ -944,4 +945,31 @@ it.describe('tracing.startHar', () => {const log = JSON.parse(resources.get('har.har')!.toString()).log as Log;expect(log.entries.some(e => e.request.url === server.PREFIX + '/simple.json')).toBe(true);});++ it('should record a HAR with resourcesDir', async ({ contextFactory, server }, testInfo) => {+ const context = await contextFactory();+ const harPath = testInfo.outputPath('tracing.har');+ const resourcesDir = testInfo.outputPath('har-resources');+ await context.tracing.startHar(harPath, { content: 'attach', resourcesDir });+ const page = await context.newPage();+ await page.goto(server.PREFIX + '/one-style.html');+ await context.tracing.stopHar();+ await context.close();++ const log = JSON.parse(fs.readFileSync(harPath).toString()).log as Log;+ const styleEntry = log.entries.find(e => e.request.url.endsWith('/one-style.css'))!;+ const sha1 = (styleEntry.response.content as any)._file as string;+ expect(sha1).toBeTruthy();+ const resourcePath = path.join(resourcesDir, sha1);+ expect(fs.existsSync(resourcePath)).toBe(true);+ expect(fs.readFileSync(resourcePath).toString()).toContain('pink');+ });++ it('should reject resourcesDir together with a .zip har file', async ({ contextFactory }, testInfo) => {+ const context = await contextFactory();+ const harPath = testInfo.outputPath('tracing.har.zip');+ const resourcesDir = testInfo.outputPath('har-resources');+ await expect(context.tracing.startHar(harPath, { content: 'attach', resourcesDir })).rejects.toThrow(/resourcesDir option is not compatible with a \.zip har file/);+ await context.close();+ });});