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(fetch): implement APIResponse.timing() (#41800)
Dmitry Gozmaneb874fac750e
diff --git a/docs/src/api/class-apiresponse.md b/docs/src/api/class-apiresponse.mdindex 48ca44eb8a..ae1f3de440 100644--- a/docs/src/api/class-apiresponse.md+++ b/docs/src/api/class-apiresponse.md@@ -118,6 +118,14 @@ Contains the status text of the response (e.g. usually an "OK" for a success).Returns the text representation of response body.+## method: APIResponse.timing = %%-resource-timing-%%+* since: v1.62++Returns resource timing information for given response. For redirected requests, returns the information for the last+request in the redirect chain. When the response is served [from the HAR file](../mock.md#replaying-from-har), timing+information is not available and all the values are -1. Find more information at+[Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).+## method: APIResponse.url* since: v1.16- returns: <[string]>diff --git a/docs/src/api/class-request.md b/docs/src/api/class-request.mdindex a37a5d5953..6ae84828f1 100644--- a/docs/src/api/class-request.md+++ b/docs/src/api/class-request.md@@ -322,29 +322,8 @@ Requests originated in a Service Worker do not have a [`method: Request.frame`]Returns resource size information for given request.-## method: Request.timing+## method: Request.timing = %%-resource-timing-%%* since: v1.8-- returns: <[Object]>- * alias-csharp: RequestTimingResult- * alias-java: Timing- - `startTime` <[float]> Request start time in milliseconds elapsed since January 1, 1970 00:00:00 UTC- - `domainLookupStart` <[float]> Time immediately before the browser starts the domain name lookup for the- resource. The value is given in milliseconds relative to `startTime`, -1 if not available.- - `domainLookupEnd` <[float]> Time immediately after the browser starts the domain name lookup for the resource.- The value is given in milliseconds relative to `startTime`, -1 if not available.- - `connectStart` <[float]> Time immediately before the user agent starts establishing the connection to the server- to retrieve the resource. The value is given in milliseconds relative to `startTime`, -1 if not available.- - `secureConnectionStart` <[float]> Time immediately before the browser starts the handshake process to secure the- current connection. The value is given in milliseconds relative to `startTime`, -1 if not available.- - `connectEnd` <[float]> Time immediately before the user agent starts establishing the connection to the server- to retrieve the resource. The value is given in milliseconds relative to `startTime`, -1 if not available.- - `requestStart` <[float]> Time immediately before the browser starts requesting the resource from the server,- cache, or local resource. The value is given in milliseconds relative to `startTime`, -1 if not available.- - `responseStart` <[float]> Time immediately after the browser receives the first byte of the response from the server,- cache, or local resource. The value is given in milliseconds relative to `startTime`, -1 if not available.- - `responseEnd` <[float]> Time immediately after the browser receives the last byte of the resource or immediately- before the transport connection is closed, whichever comes first. The value is given in milliseconds relative to- `startTime`, -1 if not available.Returns resource timing information for given request. Most of the timing values become available upon the response,`responseEnd` becomes available when request finishes. Find more information atdiff --git a/docs/src/api/params.md b/docs/src/api/params.mdindex 27ec2b1b06..ce5c909e6b 100644--- a/docs/src/api/params.md+++ b/docs/src/api/params.md@@ -2020,3 +2020,26 @@ In this config:* alias-java: ServerAddr- `ipAddress` <[string]> IPv4 or IPV6 address of the server.- `port` <[int]>++## resource-timing+- returns: <[Object]>+ * alias-csharp: RequestTimingResult+ * alias-java: Timing+ - `startTime` <[float]> Request start time in milliseconds elapsed since January 1, 1970 00:00:00 UTC+ - `domainLookupStart` <[float]> Time immediately before the client starts the domain name lookup for the+ resource. The value is given in milliseconds relative to `startTime`, -1 if not available.+ - `domainLookupEnd` <[float]> Time immediately after the client ends the domain name lookup for the resource.+ The value is given in milliseconds relative to `startTime`, -1 if not available.+ - `connectStart` <[float]> Time immediately before the client starts establishing the connection to the server+ to retrieve the resource. The value is given in milliseconds relative to `startTime`, -1 if not available.+ - `secureConnectionStart` <[float]> Time immediately before the client starts the handshake process to secure the+ current connection. The value is given in milliseconds relative to `startTime`, -1 if not available.+ - `connectEnd` <[float]> Time immediately after the client establishes the connection to the server+ to retrieve the resource. The value is given in milliseconds relative to `startTime`, -1 if not available.+ - `requestStart` <[float]> Time immediately before the client starts requesting the resource from the server,+ cache, or local resource. The value is given in milliseconds relative to `startTime`, -1 if not available.+ - `responseStart` <[float]> Time immediately after the client receives the first byte of the response from the server,+ cache, or local resource. The value is given in milliseconds relative to `startTime`, -1 if not available.+ - `responseEnd` <[float]> Time immediately after the client receives the last byte of the resource or immediately+ before the transport connection is closed, whichever comes first. The value is given in milliseconds relative to+ `startTime`, -1 if not available.diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.tsindex e0f0b6486d..3ab60c474d 100644--- a/packages/playwright-client/types/types.d.ts+++ b/packages/playwright-client/types/types.d.ts@@ -19908,6 +19908,68 @@ export interface APIResponse {*/text(): Promise<string>;+ /**+ * Returns resource timing information for given response. For redirected requests, returns the information for the+ * last request in the redirect chain. When the response is served [from the HAR file](https://playwright.dev/docs/mock#replaying-from-har),+ * timing information is not available and all the values are -1. Find more information at+ * [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).+ */+ timing(): {+ /**+ * Request start time in milliseconds elapsed since January 1, 1970 00:00:00 UTC+ */+ startTime: number;++ /**+ * Time immediately before the client starts the domain name lookup for the resource. The value is given in+ * milliseconds relative to `startTime`, -1 if not available.+ */+ domainLookupStart: number;++ /**+ * Time immediately after the client ends the domain name lookup for the resource. The value is given in milliseconds+ * relative to `startTime`, -1 if not available.+ */+ domainLookupEnd: number;++ /**+ * Time immediately before the client starts establishing the connection to the server to retrieve the resource. The+ * value is given in milliseconds relative to `startTime`, -1 if not available.+ */+ connectStart: number;++ /**+ * Time immediately before the client starts the handshake process to secure the current connection. The value is+ * given in milliseconds relative to `startTime`, -1 if not available.+ */+ secureConnectionStart: number;++ /**+ * Time immediately after the client establishes the connection to the server to retrieve the resource. The value is+ * given in milliseconds relative to `startTime`, -1 if not available.+ */+ connectEnd: number;++ /**+ * Time immediately before the client starts requesting the resource from the server, cache, or local resource. The+ * value is given in milliseconds relative to `startTime`, -1 if not available.+ */+ requestStart: number;++ /**+ * Time immediately after the client receives the first byte of the response from the server, cache, or local+ * resource. The value is given in milliseconds relative to `startTime`, -1 if not available.+ */+ responseStart: number;++ /**+ * Time immediately after the client receives the last byte of the resource or immediately before the transport+ * connection is closed, whichever comes first. The value is given in milliseconds relative to `startTime`, -1 if not+ * available.+ */+ responseEnd: number;+ };+/*** Contains the URL of the response.*/@@ -21991,49 +22053,49 @@ export interface Request {startTime: number;/**- * Time immediately before the browser starts the domain name lookup for the resource. The value is given in+ * Time immediately before the client starts the domain name lookup for the resource. The value is given in* milliseconds relative to `startTime`, -1 if not available.*/domainLookupStart: number;/**- * Time immediately after the browser starts the domain name lookup for the resource. The value is given in- * milliseconds relative to `startTime`, -1 if not available.+ * Time immediately after the client ends the domain name lookup for the resource. The value is given in milliseconds+ * relative to `startTime`, -1 if not available.*/domainLookupEnd: number;/**- * Time immediately before the user agent starts establishing the connection to the server to retrieve the resource.- * The value is given in milliseconds relative to `startTime`, -1 if not available.+ * Time immediately before the client starts establishing the connection to the server to retrieve the resource. The+ * value is given in milliseconds relative to `startTime`, -1 if not available.*/connectStart: number;/**- * Time immediately before the browser starts the handshake process to secure the current connection. The value is+ * Time immediately before the client starts the handshake process to secure the current connection. The value is* given in milliseconds relative to `startTime`, -1 if not available.*/secureConnectionStart: number;/**- * Time immediately before the user agent starts establishing the connection to the server to retrieve the resource.- * The value is given in milliseconds relative to `startTime`, -1 if not available.+ * Time immediately after the client establishes the connection to the server to retrieve the resource. The value is+ * given in milliseconds relative to `startTime`, -1 if not available.*/connectEnd: number;/**- * Time immediately before the browser starts requesting the resource from the server, cache, or local resource. The+ * Time immediately before the client starts requesting the resource from the server, cache, or local resource. The* value is given in milliseconds relative to `startTime`, -1 if not available.*/requestStart: number;/**- * Time immediately after the browser receives the first byte of the response from the server, cache, or local+ * Time immediately after the client receives the first byte of the response from the server, cache, or local* resource. The value is given in milliseconds relative to `startTime`, -1 if not available.*/responseStart: number;/**- * Time immediately after the browser receives the last byte of the resource or immediately before the transport+ * Time immediately after the client receives the last byte of the resource or immediately before the transport* connection is closed, whichever comes first. The value is given in milliseconds relative to `startTime`, -1 if not* available.*/diff --git a/packages/playwright-core/src/client/fetch.ts b/packages/playwright-core/src/client/fetch.tsindex 7764b6c338..73834d56e9 100644--- a/packages/playwright-core/src/client/fetch.ts+++ b/packages/playwright-core/src/client/fetch.ts@@ -30,6 +30,7 @@ import { mkdirIfNeeded } from './fileUtils';import { TimeoutSettings, kNoTimeout } from './timeoutSettings';import type { Playwright } from './playwright';+import type { ResourceTiming } from './network';import type { ClientCertificate, FilePayload, Headers, RemoteAddr, SecurityDetails, SetStorageState, StorageState, TimeoutOptions } from './types';import type { Serializable } from '../../types/structs';import type * as api from '../../types/types';@@ -350,6 +351,21 @@ export class APIResponse implements api.APIResponse {return this._initializer.serverAddr ?? null;}+ timing(): ResourceTiming {+ return {+ startTime: -1,+ domainLookupStart: -1,+ domainLookupEnd: -1,+ connectStart: -1,+ secureConnectionStart: -1,+ connectEnd: -1,+ requestStart: -1,+ responseStart: -1,+ ...this._initializer.timing,+ responseEnd: this._initializer.responseEndTiming ?? -1,+ };+ }+async body(): Promise<Buffer> {return await this._request._wrapApiCall(async () => {try {diff --git a/packages/playwright-core/src/server/fetch.ts b/packages/playwright-core/src/server/fetch.tsindex 7002a3be3b..4a71fd9d6c 100644--- a/packages/playwright-core/src/server/fetch.ts+++ b/packages/playwright-core/src/server/fetch.ts@@ -352,6 +352,7 @@ export abstract class APIRequestContext extends SdkObject {const requestOptions = { ...options, agent };const startAt = monotonicTime();+ const startAtWallTime = Date.now();let reusedSocketAt: number | undefined;let dnsLookupAt: number | undefined;let tcpConnectionAt: number | undefined;@@ -381,6 +382,19 @@ export abstract class APIRequestContext extends SdkObject {blocked: reusedSocketAt ? reusedSocketAt - startAt : -1,};+ // spec: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming+ const requestStartAt = connectEnd ?? reusedSocketAt;+ const resourceTiming: channels.ResourceTiming = {+ startTime: startAtWallTime,+ domainLookupStart: dnsLookupAt ? 0 : -1,+ domainLookupEnd: dnsLookupAt ? dnsLookupAt - startAt : -1,+ connectStart: tcpConnectionAt ? (dnsLookupAt ?? startAt) - startAt : -1,+ secureConnectionStart: tlsHandshakeAt && tcpConnectionAt ? tcpConnectionAt - startAt : -1,+ connectEnd: connectEnd ? connectEnd - startAt : -1,+ requestStart: requestStartAt ? requestStartAt - startAt : -1,+ responseStart: responseAt - startAt,+ };+const requestFinishedEvent: APIRequestFinishedEvent = {requestEvent,httpVersion: response.httpVersion,@@ -396,6 +410,7 @@ export abstract class APIRequestContext extends SdkObject {securityDetails,};this.emit(APIRequestContext.Events.RequestFinished, requestFinishedEvent);+ return { resourceTiming, responseEndTiming: endAt - startAt };};fetchLog(`← ${response.statusCode} ${response.statusMessage}`);for (const [name, value] of Object.entries(response.headers))@@ -493,7 +508,7 @@ export abstract class APIRequestContext extends SdkObject {const chunks: Buffer[] = [];const notifyBodyFinished = () => {const body = Buffer.concat(chunks);- notifyRequestFinished(body);+ const { resourceTiming, responseEndTiming } = notifyRequestFinished(body);fulfill({body,log,@@ -504,6 +519,8 @@ export abstract class APIRequestContext extends SdkObject {headers: toHeadersArray(response.rawHeaders),securityDetails,serverAddr: serverIPAddress !== undefined && serverPort !== undefined ? { ipAddress: serverIPAddress, port: serverPort } : undefined,+ timing: resourceTiming,+ responseEndTiming,},});};diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.tsindex e0f0b6486d..3ab60c474d 100644--- a/packages/playwright-core/types/types.d.ts+++ b/packages/playwright-core/types/types.d.ts@@ -19908,6 +19908,68 @@ export interface APIResponse {*/text(): Promise<string>;+ /**+ * Returns resource timing information for given response. For redirected requests, returns the information for the+ * last request in the redirect chain. When the response is served [from the HAR file](https://playwright.dev/docs/mock#replaying-from-har),+ * timing information is not available and all the values are -1. Find more information at+ * [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).+ */+ timing(): {+ /**+ * Request start time in milliseconds elapsed since January 1, 1970 00:00:00 UTC+ */+ startTime: number;++ /**+ * Time immediately before the client starts the domain name lookup for the resource. The value is given in+ * milliseconds relative to `startTime`, -1 if not available.+ */+ domainLookupStart: number;++ /**+ * Time immediately after the client ends the domain name lookup for the resource. The value is given in milliseconds+ * relative to `startTime`, -1 if not available.+ */+ domainLookupEnd: number;++ /**+ * Time immediately before the client starts establishing the connection to the server to retrieve the resource. The+ * value is given in milliseconds relative to `startTime`, -1 if not available.+ */+ connectStart: number;++ /**+ * Time immediately before the client starts the handshake process to secure the current connection. The value is+ * given in milliseconds relative to `startTime`, -1 if not available.+ */+ secureConnectionStart: number;++ /**+ * Time immediately after the client establishes the connection to the server to retrieve the resource. The value is+ * given in milliseconds relative to `startTime`, -1 if not available.+ */+ connectEnd: number;++ /**+ * Time immediately before the client starts requesting the resource from the server, cache, or local resource. The+ * value is given in milliseconds relative to `startTime`, -1 if not available.+ */+ requestStart: number;++ /**+ * Time immediately after the client receives the first byte of the response from the server, cache, or local+ * resource. The value is given in milliseconds relative to `startTime`, -1 if not available.+ */+ responseStart: number;++ /**+ * Time immediately after the client receives the last byte of the resource or immediately before the transport+ * connection is closed, whichever comes first. The value is given in milliseconds relative to `startTime`, -1 if not+ * available.+ */+ responseEnd: number;+ };+/*** Contains the URL of the response.*/@@ -21991,49 +22053,49 @@ export interface Request {startTime: number;/**- * Time immediately before the browser starts the domain name lookup for the resource. The value is given in+ * Time immediately before the client starts the domain name lookup for the resource. The value is given in* milliseconds relative to `startTime`, -1 if not available.*/domainLookupStart: number;/**- * Time immediately after the browser starts the domain name lookup for the resource. The value is given in- * milliseconds relative to `startTime`, -1 if not available.+ * Time immediately after the client ends the domain name lookup for the resource. The value is given in milliseconds+ * relative to `startTime`, -1 if not available.*/domainLookupEnd: number;/**- * Time immediately before the user agent starts establishing the connection to the server to retrieve the resource.- * The value is given in milliseconds relative to `startTime`, -1 if not available.+ * Time immediately before the client starts establishing the connection to the server to retrieve the resource. The+ * value is given in milliseconds relative to `startTime`, -1 if not available.*/connectStart: number;/**- * Time immediately before the browser starts the handshake process to secure the current connection. The value is+ * Time immediately before the client starts the handshake process to secure the current connection. The value is* given in milliseconds relative to `startTime`, -1 if not available.*/secureConnectionStart: number;/**- * Time immediately before the user agent starts establishing the connection to the server to retrieve the resource.- * The value is given in milliseconds relative to `startTime`, -1 if not available.+ * Time immediately after the client establishes the connection to the server to retrieve the resource. The value is+ * given in milliseconds relative to `startTime`, -1 if not available.*/connectEnd: number;/**- * Time immediately before the browser starts requesting the resource from the server, cache, or local resource. The+ * Time immediately before the client starts requesting the resource from the server, cache, or local resource. The* value is given in milliseconds relative to `startTime`, -1 if not available.*/requestStart: number;/**- * Time immediately after the browser receives the first byte of the response from the server, cache, or local+ * Time immediately after the client receives the first byte of the response from the server, cache, or local* resource. The value is given in milliseconds relative to `startTime`, -1 if not available.*/responseStart: number;/**- * Time immediately after the browser receives the last byte of the resource or immediately before the transport+ * Time immediately after the client receives the last byte of the resource or immediately before the transport* connection is closed, whichever comes first. The value is given in milliseconds relative to `startTime`, -1 if not* available.*/diff --git a/packages/protocol/spec/api.yml b/packages/protocol/spec/api.ymlindex e975594a6a..8528cb0098 100644--- a/packages/protocol/spec/api.yml+++ b/packages/protocol/spec/api.yml@@ -99,3 +99,5 @@ APIResponse:items: NameValuesecurityDetails: SecurityDetails?serverAddr: RemoteAddr?+ timing: ResourceTiming?+ responseEndTiming: float?diff --git a/packages/protocol/src/structs.d.ts b/packages/protocol/src/structs.d.tsindex f9b4623c3e..7d96e75d8d 100644--- a/packages/protocol/src/structs.d.ts+++ b/packages/protocol/src/structs.d.ts@@ -79,6 +79,8 @@ export type APIResponse = {headers: NameValue[],securityDetails?: SecurityDetails,serverAddr?: RemoteAddr,+ timing?: ResourceTiming,+ responseEndTiming?: number,};export type Metadata = {diff --git a/packages/protocol/src/validator.ts b/packages/protocol/src/validator.tsindex c6f3f894f3..d18c0b9138 100644--- a/packages/protocol/src/validator.ts+++ b/packages/protocol/src/validator.ts@@ -350,6 +350,8 @@ scheme.APIResponse = tObject({headers: tArray(tType('NameValue')),securityDetails: tOptional(tType('SecurityDetails')),serverAddr: tOptional(tType('RemoteAddr')),+ timing: tOptional(tType('ResourceTiming')),+ responseEndTiming: tOptional(tFloat),});scheme.ArtifactInitializer = tObject({absolutePath: tString,diff --git a/tests/library/browsercontext-fetch.spec.ts b/tests/library/browsercontext-fetch.spec.tsindex aac4b3646b..46831e62ca 100644--- a/tests/library/browsercontext-fetch.spec.ts+++ b/tests/library/browsercontext-fetch.spec.ts@@ -17,12 +17,15 @@import type { LookupAddress } from 'dns';import formidable from 'formidable';import fs from 'fs';+import http from 'http';import type { IncomingMessage } from 'http';+import https from 'https';import { pipeline } from 'stream';import zlib from 'zlib';import { contextTest as it, expect } from '../config/browserTest';import { suppressCertificateWarning } from '../config/utils';import { kTargetClosedErrorMessage } from '../config/errors';+import { TestServer } from '../config/testserver';it.skip(({ mode }) => mode !== 'default');@@ -55,6 +58,53 @@ it('fetch should work', async ({ context, server }) => {expect(await response.text()).toBe('{"foo": "bar"}\n');});+it('should return timing', async ({ context }) => {+ // Create a fresh server to guarantee a new connection, because keep-alive+ // sockets from other tests do not have dns/connect timings.+ const httpServer = http.createServer((req, res) => res.end('Hello'));+ const port = await new Promise<number>(resolve => httpServer.listen(0, () => resolve((httpServer.address() as any).port)));+ try {+ const response = await context.request.get(`http://localhost:${port}/`);+ expect(response.ok()).toBeTruthy();+ const timing = response.timing();+ expect(timing.startTime).toBeCloseTo(Date.now(), -4);+ expect(timing.domainLookupStart).toBe(0);+ expect(timing.domainLookupEnd).toBeGreaterThanOrEqual(timing.domainLookupStart);+ expect(timing.connectStart).toBe(timing.domainLookupEnd);+ expect(timing.secureConnectionStart).toBe(-1);+ expect(timing.connectEnd).toBeGreaterThanOrEqual(timing.connectStart);+ expect(timing.requestStart).toBe(timing.connectEnd);+ expect(timing.responseStart).toBeGreaterThanOrEqual(timing.requestStart);+ expect(timing.responseEnd).toBeGreaterThanOrEqual(timing.responseStart);+ expect(timing.responseEnd).toBeLessThan(60_000);+ } finally {+ await new Promise(resolve => httpServer.close(resolve));+ }+});++it('should return timing for https', async ({ context }) => {+ // Create a fresh server to guarantee a new connection, because keep-alive+ // sockets from other tests do not have dns/connect timings.+ const httpsServer = https.createServer(await TestServer.certOptions(), (req, res) => res.end('Hello'));+ const port = await new Promise<number>(resolve => httpsServer.listen(0, () => resolve((httpsServer.address() as any).port)));+ try {+ const response = await context.request.get(`https://localhost:${port}/`, { ignoreHTTPSErrors: true });+ expect(response.ok()).toBeTruthy();+ const timing = response.timing();+ expect(timing.startTime).toBeCloseTo(Date.now(), -4);+ expect(timing.domainLookupStart).toBe(0);+ expect(timing.domainLookupEnd).toBeGreaterThanOrEqual(timing.domainLookupStart);+ expect(timing.connectStart).toBe(timing.domainLookupEnd);+ expect(timing.secureConnectionStart).toBeGreaterThanOrEqual(timing.connectStart);+ expect(timing.connectEnd).toBeGreaterThanOrEqual(timing.secureConnectionStart);+ expect(timing.requestStart).toBe(timing.connectEnd);+ expect(timing.responseStart).toBeGreaterThanOrEqual(timing.requestStart);+ expect(timing.responseEnd).toBeGreaterThanOrEqual(timing.responseStart);+ } finally {+ await new Promise(resolve => httpsServer.close(resolve));+ }+});+it('should throw on network error', async ({ context, server }) => {server.setRoute('/test', (req, res) => {req.socket.destroy();diff --git a/tests/library/browsercontext-har.spec.ts b/tests/library/browsercontext-har.spec.tsindex 5b259b2555..4fc3406516 100644--- a/tests/library/browsercontext-har.spec.ts+++ b/tests/library/browsercontext-har.spec.ts@@ -636,6 +636,17 @@ it.describe('interceptAPIRequests', () => {const page2 = await context2.newPage();const replayed = await page2.request.get(server.PREFIX + '/api/data');expect(await replayed.json()).toEqual({ hello: 'live' });+ expect(replayed.timing()).toEqual({+ startTime: -1,+ domainLookupStart: -1,+ domainLookupEnd: -1,+ connectStart: -1,+ secureConnectionStart: -1,+ connectEnd: -1,+ requestStart: -1,+ responseStart: -1,+ responseEnd: -1,+ });await context2.close();});