Skip to content

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

feat(trace): split API requests into a separate network stream (#42073)

Devin Rousso1e83c243f986
diff --git a/docs/src/api/class-apirequestcontext.md b/docs/src/api/class-apirequestcontext.md
index 28399a0b03..65ce2c1020 100644
--- a/docs/src/api/class-apirequestcontext.md
+++ b/docs/src/api/class-apirequestcontext.md
@@ -918,3 +918,5 @@ Set to `true` to include IndexedDB in the storage state snapshot.
## property: APIRequestContext.tracing
* since: v1.60
- type: <[Tracing]>
+
+Tracing recorder for requests made through this API request context.
diff --git a/docs/src/api/class-tracing.md b/docs/src/api/class-tracing.md
index d28ce386ae..e181129ccf 100644
--- a/docs/src/api/class-tracing.md
+++ b/docs/src/api/class-tracing.md
@@ -320,7 +320,7 @@ To specify the final trace zip file name, you need to pass `path` option to
Start recording a HAR (HTTP Archive) of network activity in this context. The HAR file is written to disk when [`method: Tracing.stopHar`] is called, or when the returned [Disposable] is disposed.
-Only one HAR recording can be active at a time per [BrowserContext].
+Only one HAR recording can be active at a time per [Tracing] instance.
**Usage**
diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.ts
index 1b92b5acb8..da0a75d1bf 100644
--- a/packages/playwright-client/types/types.d.ts
+++ b/packages/playwright-client/types/types.d.ts
@@ -20479,6 +20479,9 @@ export interface APIRequestContext {
}>;
}>;
+ /**
+ * Tracing recorder for requests made through this API request context.
+ */
tracing: Tracing;
[Symbol.asyncDispose](): Promise<void>;
@@ -23771,8 +23774,8 @@ export interface Tracing {
* [tracing.stopHar()](https://playwright.dev/docs/api/class-tracing#tracing-stop-har) is called, or when the returned
* [Disposable](https://playwright.dev/docs/api/class-disposable) is disposed.
*
- * Only one HAR recording can be active at a time per
- * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext).
+ * Only one HAR recording can be active at a time per [Tracing](https://playwright.dev/docs/api/class-tracing)
+ * instance.
*
* **Usage**
*
diff --git a/packages/playwright-core/src/client/browser.ts b/packages/playwright-core/src/client/browser.ts
index 368e518bb9..4a9736ebde 100644
--- a/packages/playwright-core/src/client/browser.ts
+++ b/packages/playwright-core/src/client/browser.ts
@@ -118,6 +118,7 @@ export class Browser extends ChannelOwner<channels.BrowserChannel> implements ap
private _setupBrowserContext(context: BrowserContext) {
context._logger = this._logger;
context.tracing._tracesDir = this._options.tracesDir;
+ context.request.tracing._tracesDir = this._options.tracesDir;
this._browserType._contexts.add(context);
this._browserType._playwright.selectors._contextsForSelectors.add(context);
context.setDefaultTimeout(this._browserType._playwright._defaultContextTimeout);
diff --git a/packages/playwright-core/src/client/browserContext.ts b/packages/playwright-core/src/client/browserContext.ts
index c54f131d4f..3cd2f2df64 100644
--- a/packages/playwright-core/src/client/browserContext.ts
+++ b/packages/playwright-core/src/client/browserContext.ts
@@ -513,6 +513,7 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>
this._browser?._browserType._playwright.selectors._contextsForSelectors.delete(this);
this._disposeHarRouters();
this.tracing._resetStackCounter();
+ this.request.tracing._resetStackCounter();
this.emit(Events.BrowserContext.Close, this);
}
diff --git a/packages/playwright-core/src/client/electron.ts b/packages/playwright-core/src/client/electron.ts
index 927c8a4b9d..ffbba3bb25 100644
--- a/packages/playwright-core/src/client/electron.ts
+++ b/packages/playwright-core/src/client/electron.ts
@@ -69,6 +69,7 @@ export class Electron extends ChannelOwner<channels.ElectronChannel> implements
app.once(Events.ElectronApplication.Close, () => this._playwright.selectors._contextsForSelectors.delete(app._context));
await app._context._initializeHarFromOptions(options.recordHar);
app._context.tracing._tracesDir = options.tracesDir;
+ app._context.request.tracing._tracesDir = options.tracesDir;
return app;
}
}
diff --git a/packages/playwright-core/src/server/browserContext.ts b/packages/playwright-core/src/server/browserContext.ts
index 91ee14bcc6..2dc2b84222 100644
--- a/packages/playwright-core/src/server/browserContext.ts
+++ b/packages/playwright-core/src/server/browserContext.ts
@@ -222,6 +222,7 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk
async resetForReuse(progress: Progress, params: channels.BrowserNewContextForReuseParams | null) {
await this.tracing.resetForReuse(progress);
+ await this.fetchRequest.tracing().resetForReuse(progress);
if (params) {
for (const key of paramsThatAllowContextReuse)
@@ -269,6 +270,7 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk
this._closedStatus = 'closed';
this._clientCertificatesProxy?.close().catch(() => {});
this.tracing.abort();
+ this.fetchRequest.tracing().abort();
this._closePromiseFulfill!(new Error('Context closed'));
this.emit(BrowserContext.Events.Close);
}
@@ -558,7 +560,10 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk
this.emit(BrowserContext.Events.BeforeClose);
this._closedStatus = 'closing';
- await progress.race(this.tracing.flush());
+ await progress.race(Promise.all([
+ this.tracing.flush(),
+ this.fetchRequest.tracing().flush(),
+ ]));
await progress.race(Promise.all(this.pages().map(page => page.screencast.handlePageOrContextClose())));
if (this._customCloseHandler) {
diff --git a/packages/playwright-core/src/server/fetch.ts b/packages/playwright-core/src/server/fetch.ts
index d49f1619e6..27a520fea4 100644
--- a/packages/playwright-core/src/server/fetch.ts
+++ b/packages/playwright-core/src/server/fetch.ts
@@ -125,6 +125,7 @@ export abstract class APIRequestContext extends SdkObject {
constructor(parent: SdkObject) {
super(parent, 'request-context');
+ this.attribution.context = this;
APIRequestContext.allInstances.add(this);
}
@@ -676,19 +677,22 @@ class SafeEmptyStreamTransform extends Transform {
export class BrowserContextAPIRequestContext extends APIRequestContext {
private readonly _context: BrowserContext;
+ private readonly _tracing: Tracing;
constructor(context: BrowserContext) {
super(context);
this._context = context;
+ this._tracing = new Tracing(this, context._browser.options.tracesDir);
context.once(BrowserContext.Events.Close, () => this._disposeImpl());
}
override tracing() {
- return this._context.tracing;
+ return this._tracing;
}
override async dispose(options: { reason?: string }) {
this._closeReason = options.reason;
+ await this._tracing.flush();
this.fetchResponses.clear();
}
@@ -727,7 +731,6 @@ export class GlobalAPIRequestContext extends APIRequestContext {
constructor(playwright: Playwright, options: channels.PlaywrightNewRequestOptions) {
super(playwright);
- this.attribution.context = this;
if (options.storageState) {
this._origins = options.storageState.origins?.map(origin => ({ indexedDB: [], ...origin }));
this._cookieStore.addCookies(options.storageState.cookies || []);
diff --git a/packages/playwright-core/src/server/har/harTracer.ts b/packages/playwright-core/src/server/har/harTracer.ts
index 4817c94112..cae4a886c6 100644
--- a/packages/playwright-core/src/server/har/harTracer.ts
+++ b/packages/playwright-core/src/server/har/harTracer.ts
@@ -105,11 +105,7 @@ export class HarTracer {
return;
this._options.omitScripts = options.omitScripts;
this._started = true;
- const apiRequest = this._context instanceof APIRequestContext ? this._context : this._context.fetchRequest;
- this._eventListeners = [
- eventsHelper.addEventListener(apiRequest, APIRequestContext.Events.Request, (event: APIRequestEvent) => this._onAPIRequest(event)),
- eventsHelper.addEventListener(apiRequest, APIRequestContext.Events.RequestFinished, (event: APIRequestFinishedEvent) => this._onAPIRequestFinished(event)),
- ];
+ this._eventListeners = [];
if (this._context instanceof BrowserContext) {
this._eventListeners.push(
eventsHelper.addEventListener(this._context, BrowserContext.Events.Page, (page: Page) => this._createPageEntryIfNeeded(page)),
@@ -125,6 +121,12 @@ export class HarTracer {
for (const page of this._context.pages())
this._createPageEntryIfNeeded(page);
}
+ if (this._context instanceof APIRequestContext) {
+ this._eventListeners.push(
+ eventsHelper.addEventListener(this._context, APIRequestContext.Events.Request, (event: APIRequestEvent) => this._onAPIRequest(event)),
+ eventsHelper.addEventListener(this._context, APIRequestContext.Events.RequestFinished, (event: APIRequestFinishedEvent) => this._onAPIRequestFinished(event)),
+ );
+ }
}
private _shouldIncludeEntryWithUrl(urlString: string) {
diff --git a/packages/playwright-core/src/server/trace/recorder/tracing.ts b/packages/playwright-core/src/server/trace/recorder/tracing.ts
index 3531681496..3c55d8b3c5 100644
--- a/packages/playwright-core/src/server/trace/recorder/tracing.ts
+++ b/packages/playwright-core/src/server/trace/recorder/tracing.ts
@@ -450,7 +450,7 @@ export class Tracing extends SdkObject implements InstrumentationListener, Snaps
if (error) {
// This check is here because closing the browser removes the tracesDir and tracing
// cannot access removed files. Clients are ready for the missing artifact.
- if (!isAbortError(error) && this._context instanceof BrowserContext && !this._context._browser.isConnected())
+ if (!isAbortError(error) && this._context.attribution.browser && !this._context.attribution.browser.isConnected())
return {};
throw error;
}
diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.ts
index 1b92b5acb8..da0a75d1bf 100644
--- a/packages/playwright-core/types/types.d.ts
+++ b/packages/playwright-core/types/types.d.ts
@@ -20479,6 +20479,9 @@ export interface APIRequestContext {
}>;
}>;
+ /**
+ * Tracing recorder for requests made through this API request context.
+ */
tracing: Tracing;
[Symbol.asyncDispose](): Promise<void>;
@@ -23771,8 +23774,8 @@ export interface Tracing {
* [tracing.stopHar()](https://playwright.dev/docs/api/class-tracing#tracing-stop-har) is called, or when the returned
* [Disposable](https://playwright.dev/docs/api/class-disposable) is disposed.
*
- * Only one HAR recording can be active at a time per
- * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext).
+ * Only one HAR recording can be active at a time per [Tracing](https://playwright.dev/docs/api/class-tracing)
+ * instance.
*
* **Usage**
*
diff --git a/packages/playwright/src/index.ts b/packages/playwright/src/index.ts
index fd4ac59061..a7b6455a3a 100644
--- a/packages/playwright/src/index.ts
+++ b/packages/playwright/src/index.ts
@@ -761,6 +761,7 @@ class ArtifactsRecorder {
async didCreateBrowserContext(context: BrowserContextImpl) {
await this._startTraceChunkOnContextCreation(context, context.tracing);
+ await this._startTraceChunkOnContextCreation(context.request, context.request.tracing);
}
async willCloseBrowserContext(context: BrowserContextImpl) {
@@ -812,6 +813,7 @@ class ArtifactsRecorder {
// Collect traces/screenshots for remaining contexts.
await Promise.all(leftoverContexts.map(async context => {
+ await this._stopTracing(context.request, context.request.tracing);
await this._stopTracing(context, context.tracing);
}).concat(leftoverApiRequests.map(async context => {
await this._stopTracing(context, context.tracing);
diff --git a/tests/library/channels.spec.ts b/tests/library/channels.spec.ts
index 04875b7095..0276d1bd88 100644
--- a/tests/library/channels.spec.ts
+++ b/tests/library/channels.spec.ts
@@ -76,7 +76,9 @@ it('should scope context handles', async ({ browserType, server, expectScopeStat
] },
] },
{ _guid: 'debugger', objects: [] },
- { _guid: 'request-context', objects: [] },
+ { _guid: 'request-context', objects: [
+ { _guid: 'tracing', objects: [] },
+ ] },
{ _guid: 'tracing', objects: [] }
] },
] },
@@ -164,7 +166,9 @@ it('should scope browser handles', async ({ browserType, expectScopeState }) =>
_guid: 'browser', objects: [
{ _guid: 'browser-context', objects: [
{ _guid: 'debugger', objects: [] },
- { _guid: 'request-context', objects: [] },
+ { _guid: 'request-context', objects: [
+ { _guid: 'tracing', objects: [] },
+ ] },
{ _guid: 'tracing', objects: [] },
] },
]
@@ -208,7 +212,9 @@ it('should not generate dispatchers for subresources w/o listeners', async ({ pa
]
},
{ _guid: 'debugger', objects: [] },
- { _guid: 'request-context', objects: [] },
+ { _guid: 'request-context', objects: [
+ { _guid: 'tracing', objects: [] },
+ ] },
{ _guid: 'tracing', objects: [] }
] },
]
@@ -308,7 +314,12 @@ it('exposeFunction should not leak', async ({ page, expectScopeState, server })
},
{
'_guid': 'request-context',
- 'objects': [],
+ 'objects': [
+ {
+ '_guid': 'tracing',
+ 'objects': [],
+ },
+ ],
},
{
'_guid': 'tracing',
diff --git a/tests/library/har.spec.ts b/tests/library/har.spec.ts
index 143a3186b1..f78aab9955 100644
--- a/tests/library/har.spec.ts
+++ b/tests/library/har.spec.ts
@@ -640,10 +640,14 @@ it('should have security details', async ({ contextFactory, httpsServer, browser
it.fail(browserName === 'webkit' && platform === 'win32' && channel !== 'webkit-wsl');
it.skip(isFrozenWebkit);
- const { page, getLog } = await pageWithHar(contextFactory, testInfo);
+ const { page, context, getLog } = await pageWithHar(contextFactory, testInfo);
+ const apiHarPath = testInfo.outputPath('api.har');
+ await context.request.tracing.startHar(apiHarPath);
await page.goto(httpsServer.EMPTY_PAGE);
await page.request.get(httpsServer.EMPTY_PAGE);
+ await context.request.tracing.stopHar();
const log = await getLog();
+ expect(log.entries).toHaveLength(1);
const { serverIPAddress, _serverPort: port, _securityDetails: securityDetails } = log.entries[0];
expect(serverIPAddress).toMatch(/^127\.0\.0\.1|\[::1\]/);
expect(port).toBe(httpsServer.PORT);
@@ -652,7 +656,9 @@ it('should have security details', async ({ contextFactory, httpsServer, browser
else
expect(securityDetails).toEqual({ issuer: 'playwright-test', protocol: 'TLS 1.3', subjectName: 'playwright-test', validFrom: 1691708270, validTo: 2007068270 });
- expect(log.entries[1]._securityDetails).toEqual({ issuer: 'playwright-test', protocol: 'TLSv1.3', subjectName: 'playwright-test', validFrom: 1691708270, validTo: 2007068270 });
+ const apiLog = JSON.parse(fs.readFileSync(apiHarPath).toString()).log as Log;
+ expect(apiLog.entries).toHaveLength(1);
+ expect(apiLog.entries[0]._securityDetails).toEqual({ issuer: 'playwright-test', protocol: 'TLSv1.3', subjectName: 'playwright-test', validFrom: 1691708270, validTo: 2007068270 });
});
it('should have connection details for redirects', async ({ contextFactory, server, browserName, mode }, testInfo) => {
@@ -811,64 +817,25 @@ it('should have different hars for concurrent contexts', async ({ contextFactory
}
});
-it('should include API request', async ({ contextFactory, server }, testInfo) => {
+it('should exclude API request', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
- const url = server.PREFIX + '/simple.json';
- const response = await page.request.post(url, {
- headers: { cookie: 'a=b; c=d' },
- data: { foo: 'bar' }
- });
- const responseBody = await response.body();
+ await page.goto(server.EMPTY_PAGE);
+ await page.request.get(server.PREFIX + '/simple.json');
const log = await getLog();
- expect(log.entries.length).toBe(1);
- const entry = log.entries[0];
- expect(entry.request.url).toBe(url);
- expect(entry.request.method).toBe('POST');
- expect(entry.request.httpVersion).toBe('HTTP/1.1');
- expect(entry.request.cookies).toEqual([
- {
- 'name': 'a',
- 'value': 'b'
- },
- {
- 'name': 'c',
- 'value': 'd'
- }
- ]);
- expect(entry.request.headers.length).toBeGreaterThan(1);
- expect(entry.request.headers.find(h => h.name.toLowerCase() === 'user-agent')).toBeTruthy();
- expect(entry.request.headers.find(h => h.name.toLowerCase() === 'content-type')?.value).toBe('application/json');
- expect(entry.request.headers.find(h => h.name.toLowerCase() === 'content-length')?.value).toBe('13');
- expect(entry.request.bodySize).toBe(13);
-
- expect(entry.response.status).toBe(200);
- expect(entry.response.headers.find(h => h.name.toLowerCase() === 'content-type')?.value).toContain('application/json');
- expect(entry.response.content.size).toBe(15);
- expect(entry.response.content.text).toBe(responseBody.toString());
- expect(entry.response.bodySize).toBe(15);
-
- expect(entry.time).toBeGreaterThan(0);
- expect(entry.timings).toEqual(expect.objectContaining({
- blocked: -1,
- connect: expect.any(Number),
- dns: expect.any(Number),
- receive: expect.any(Number),
- send: expect.any(Number),
- ssl: expect.any(Number),
- wait: expect.any(Number),
- }));
-
- expect(entry.serverIPAddress).toBeDefined();
- expect(entry._serverPort).toEqual(server.PORT);
+ expect(log.entries.map(entry => entry.request.url)).toEqual([server.EMPTY_PAGE]);
});
it('should correctly record API request cookies with equals sign in value', async ({ contextFactory, server }, testInfo) => {
- const { page, getLog } = await pageWithHar(contextFactory, testInfo);
+ const context = await contextFactory();
+ const harPath = testInfo.outputPath('request.har');
+ await context.request.tracing.startHar(harPath);
const url = server.PREFIX + '/simple.json';
- await page.request.get(url, {
+ await context.request.get(url, {
headers: { cookie: 'token=abc=xyz; other=val' },
});
- const log = await getLog();
+ await context.request.tracing.stopHar();
+ await context.close();
+ const log = JSON.parse(fs.readFileSync(harPath).toString()).log as Log;
expect(log.entries[0].request.cookies).toEqual([
{ name: 'token', value: 'abc=xyz' },
{ name: 'other', value: 'val' },
@@ -876,13 +843,17 @@ it('should correctly record API request cookies with equals sign in value', asyn
});
it('should respect minimal mode for API Requests', async ({ contextFactory, server }, testInfo) => {
- const { page, getLog } = await pageWithHar(contextFactory, testInfo, { mode: 'minimal' });
+ const context = await contextFactory();
+ const harPath = testInfo.outputPath('request.har');
+ await context.request.tracing.startHar(harPath, { mode: 'minimal' });
const url = server.PREFIX + '/simple.json';
- await page.request.post(url, {
+ await context.request.post(url, {
headers: { cookie: 'a=b; c=d' },
data: { foo: 'bar' }
});
- const { entries } = await getLog();
+ await context.request.tracing.stopHar();
+ await context.close();
+ const { entries } = JSON.parse(fs.readFileSync(harPath).toString()).log as Log;
expect(entries).toHaveLength(1);
const [entry] = entries;
expect(entry.timings).toEqual({ receive: -1, send: -1, wait: -1 });
@@ -895,12 +866,16 @@ it('should respect minimal mode for API Requests', async ({ contextFactory, serv
it('should include redirects from API request', async ({ contextFactory, server }, testInfo) => {
server.setRedirect('/redirect-me', '/simple.json');
- const { page, getLog } = await pageWithHar(contextFactory, testInfo);
- await page.request.post(server.PREFIX + '/redirect-me', {
+ const context = await contextFactory();
+ const harPath = testInfo.outputPath('request.har');
+ await context.request.tracing.startHar(harPath);
+ await context.request.post(server.PREFIX + '/redirect-me', {
headers: { cookie: 'a=b; c=d' },
data: { foo: 'bar' }
});
- const log = await getLog();
+ await context.request.tracing.stopHar();
+ await context.close();
+ const log = JSON.parse(fs.readFileSync(harPath).toString()).log as Log;
expect(log.entries.length).toBe(2);
const [redirect, json] = log.entries;
expect(redirect.request.url).toBe(server.PREFIX + '/redirect-me');
@@ -971,7 +946,8 @@ it('should support HAR larger than 512MB', async ({ contextFactory, server, brow
it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/36707' });
const harPath = testInfo.outputPath('test.har');
- const context = await contextFactory({ recordHar: { path: harPath } });
+ const context = await contextFactory();
+ await context.request.tracing.startHar(harPath);
// 30 x 20MB textual responses push the HAR JSON past V8's ~512MB max
// string length. Each body still fits in a single string; only the
@@ -983,6 +959,7 @@ it('should support HAR larger than 512MB', async ({ contextFactory, server, brow
});
for (let i = 0; i < 30; i++)
await context.request.get(`${server.PREFIX}/large`);
+ await context.request.tracing.stopHar();
await context.close();
const stats = fs.statSync(harPath);
@@ -1073,6 +1050,64 @@ it.describe('tracing.startHar', () => {
expect(log.entries[0].request.bodySize).toBe(-1);
});
+ it('should record a HAR for a context APIRequestContext', async ({ contextFactory, server }, testInfo) => {
+ const context = await contextFactory();
+ const harPath = testInfo.outputPath('request.har');
+ await context.request.tracing.startHar(harPath);
+ const page = await context.newPage();
+ await page.goto(server.EMPTY_PAGE);
+ const url = server.PREFIX + '/simple.json';
+ const response = await context.request.post(url, {
+ headers: { cookie: 'a=b; c=d' },
+ data: { foo: 'bar' }
+ });
+ const responseBody = await response.body();
+ await context.request.tracing.stopHar();
+ await context.close();
+
+ const log = JSON.parse(fs.readFileSync(harPath).toString()).log as Log;
+ expect(log.entries).toHaveLength(1);
+ const entry = log.entries[0];
+ expect(entry.request.url).toBe(url);
+ expect(entry.request.method).toBe('POST');
+ expect(entry.request.httpVersion).toBe('HTTP/1.1');
+ expect(entry.request.cookies).toEqual([
+ {
+ 'name': 'a',
+ 'value': 'b'
+ },
+ {
+ 'name': 'c',
+ 'value': 'd'
+ }
+ ]);
+ expect(entry.request.headers.length).toBeGreaterThan(1);
+ expect(entry.request.headers.find(h => h.name.toLowerCase() === 'user-agent')).toBeTruthy();
+ expect(entry.request.headers.find(h => h.name.toLowerCase() === 'content-type')?.value).toBe('application/json');
+ expect(entry.request.headers.find(h => h.name.toLowerCase() === 'content-length')?.value).toBe('13');
+ expect(entry.request.bodySize).toBe(13);
+
+ expect(entry.response.status).toBe(200);
+ expect(entry.response.headers.find(h => h.name.toLowerCase() === 'content-type')?.value).toContain('application/json');
+ expect(entry.response.content.size).toBe(15);
+ expect(entry.response.content.text).toBe(responseBody.toString());
+ expect(entry.response.bodySize).toBe(15);
+
+ expect(entry.time).toBeGreaterThan(0);
+ expect(entry.timings).toEqual(expect.objectContaining({
+ blocked: -1,
+ connect: expect.any(Number),
+ dns: expect.any(Number),
+ receive: expect.any(Number),
+ send: expect.any(Number),
+ ssl: expect.any(Number),
+ wait: expect.any(Number),
+ }));
+
+ expect(entry.serverIPAddress).toBeDefined();
+ expect(entry._serverPort).toEqual(server.PORT);
+ });
+
it('should include pages', async ({ contextFactory, server }, testInfo) => {
const context = await contextFactory();
const harPath = testInfo.outputPath('tracing.har');
diff --git a/tests/library/tracing.spec.ts b/tests/library/tracing.spec.ts
index 85466e461f..2d6ea300ee 100644
--- a/tests/library/tracing.spec.ts
+++ b/tests/library/tracing.spec.ts
@@ -207,16 +207,31 @@ test('should exclude internal pages', async ({ browserName, context, page, serve
expect(pageIds.size).toBe(1);
});
-test('should include context API requests', async ({ context, page, server }, testInfo) => {
+test('should record context API request trace independently', async ({ context, page, server }, testInfo) => {
+ const browserTracePath = testInfo.outputPath('browser-trace.zip');
+ const apiTracePath = testInfo.outputPath('api-trace.zip');
+ const apiURL = server.PREFIX + '/simple.json';
+ expect(context.request.tracing).not.toBe(context.tracing);
+
await context.tracing.start({ snapshots: true });
- await page.request.post(server.PREFIX + '/simple.json', { data: { foo: 'bar' } });
- await context.tracing.stop({ path: testInfo.outputPath('trace.zip') });
- const { events, actions } = await parseTraceRaw(testInfo.outputPath('trace.zip'));
- expect(actions).toContain('POST "/simple.json"');
- const harEntry = events.find(e => e.type === 'resource-snapshot');
- expect(harEntry).toBeTruthy();
- expect(harEntry.snapshot.request.url).toBe(server.PREFIX + '/simple.json');
- expect(harEntry.snapshot.response.status).toBe(200);
+ await context.request.tracing.start({ snapshots: true });
+ await page.goto(server.PREFIX + '/one-style.html');
+ await page.request.post(apiURL, { data: { foo: 'bar' } });
+ await context.tracing.stop({ path: browserTracePath });
+ await context.request.tracing.stop({ path: apiTracePath });
+
+ const browserTrace = await parseTraceRaw(browserTracePath);
+ expect(browserTrace.actions).toContain('Navigate to "/one-style.html"');
+ expect(browserTrace.actions).not.toContain('POST "/simple.json"');
+ expect(browserTrace.events.some(event => event.type === 'resource-snapshot' && event.snapshot._apiRequest)).toBe(false);
+ expect(browserTrace.events.some(event => event.type === 'resource-snapshot' && event.snapshot.request.url.endsWith('/one-style.html'))).toBe(true);
+
+ const apiTrace = await parseTraceRaw(apiTracePath);
+ expect(apiTrace.actions).toContain('POST "/simple.json"');
+ expect(apiTrace.actions).not.toContain('Navigate to "/one-style.html"');
+ const apiAction = apiTrace.actionObjects.find(action => action.class === 'APIRequestContext' && action.method === 'fetch')!;
+ expect(relativeStack(apiAction, apiTrace.stacks)).toEqual(['tracing.spec.ts']);
+ expect(apiTrace.events.filter(event => event.type === 'resource-snapshot').map(event => event.snapshot.request.url)).toEqual([apiURL]);
});
test('should collect two traces', async ({ context, page, server }, testInfo) => {
diff --git a/tests/playwright-test/playwright.connect.spec.ts b/tests/playwright-test/playwright.connect.spec.ts
index 71aa32b0cc..b31e15edfd 100644
--- a/tests/playwright-test/playwright.connect.spec.ts
+++ b/tests/playwright-test/playwright.connect.spec.ts
@@ -210,9 +210,9 @@ test('should record trace', async ({ runInlineTest }) => {
expect(result.passed).toBe(1);
expect(result.failed).toBe(1);
- // A single tracing artifact should be created. We see it in the logs twice:
+ // One tracing artifact should be created for each tracing stream. We see each in the logs twice:
// as a regular message and wrapped inside a jsonPipe.
- expect(countTimes(result.output, `"type":"Artifact","initializer"`)).toBe(2);
+ expect(countTimes(result.output, `"type":"Artifact","initializer"`)).toBe(4);
expect(fs.existsSync(test.info().outputPath('test-results', 'a-pass', 'trace.zip'))).toBe(false);
diff --git a/tests/playwright-test/playwright.trace.spec.ts b/tests/playwright-test/playwright.trace.spec.ts
index 810be371d8..cf057e6bb8 100644
--- a/tests/playwright-test/playwright.trace.spec.ts
+++ b/tests/playwright-test/playwright.trace.spec.ts
@@ -188,9 +188,11 @@ test('should not mixup network files between contexts', async ({ runInlineTest,
test.beforeAll(async ({ browser }) => {
page1 = await browser.newPage();
await page1.goto("${server.EMPTY_PAGE}");
+ await page1.request.get("${server.PREFIX}/simple.json?context=1");
page2 = await browser.newPage();
await page2.goto("${server.EMPTY_PAGE}");
+ await page2.request.get("${server.PREFIX}/simple.json?context=2");
});
test.afterAll(async () => {
@@ -200,12 +202,46 @@ test('should not mixup network files between contexts', async ({ runInlineTest,
test('example', async ({ page }) => {
await page.goto("${server.EMPTY_PAGE}");
+ await page.request.get("${server.PREFIX}/simple.json?context=3");
});
`,
}, { workers: 1, timeout: 15000 });
expect(result.exitCode).toEqual(0);
expect(result.passed).toBe(1);
- expect(fs.existsSync(testInfo.outputPath('test-results', 'a-example', 'trace.zip'))).toBe(true);
+ const tracePath = testInfo.outputPath('test-results', 'a-example', 'trace.zip');
+ const { resources } = await parseTraceRaw(tracePath);
+ const traceEntries = [...resources].filter(([name]) => name.endsWith('.trace')).map(([name, content]) => ({
+ prefix: name.slice(0, -'.trace'.length),
+ contextOptions: JSON.parse(content.toString().split('\n')[0]),
+ })).filter(entry => entry.contextOptions.origin === 'library');
+ const traceEntriesByContextId = new Map<string, typeof traceEntries>();
+ for (const entry of traceEntries) {
+ const entries = traceEntriesByContextId.get(entry.contextOptions.contextId) || [];
+ entries.push(entry);
+ traceEntriesByContextId.set(entry.contextOptions.contextId, entries);
+ }
+ const contextTraces = [...traceEntriesByContextId.values()];
+ const browserTraces = contextTraces.filter(entries => entries[0].contextOptions.browserName);
+ const apiTraces = contextTraces.filter(entries => !entries[0].contextOptions.browserName);
+ expect(browserTraces).toHaveLength(3);
+ expect(apiTraces).toHaveLength(3);
+ for (const entries of browserTraces) {
+ const network = entries.map(entry => resources.get(entry.prefix + '.network')!.toString()).join('\n');
+ expect(network).not.toContain('?context=');
+ }
+ const apiURLs = [
+ server.PREFIX + '/simple.json?context=1',
+ server.PREFIX + '/simple.json?context=2',
+ server.PREFIX + '/simple.json?context=3',
+ ];
+ const apiURLsByTrace = apiTraces.map(entries => {
+ const network = entries.map(entry => resources.get(entry.prefix + '.network')!.toString()).join('\n');
+ return apiURLs.filter(url => network.includes(url));
+ });
+ expect(apiURLsByTrace.map(urls => urls.length)).toEqual([1, 1, 1]);
+ expect(apiURLsByTrace.flat().sort()).toEqual(apiURLs);
+ const trace = await parseTrace(tracePath);
+ expect(trace.model.resources.filter(resource => resource._apiRequest).map(resource => resource.request.url).sort()).toEqual(apiURLs);
});
test('should save sources when requested', async ({ runInlineTest }, testInfo) => {