HTTP traffic
Route rules
Make requests of the page fail, answer them with a mock response, or change the real request and response. Where a rule lives, when it ends, and which one wins.
New in Browser 21.1.0 A route rule sits on a context or a page and handles matching requests before they reach the network:
Where a request goes under each kind of rule.
| Keyword | The request | Use it to |
|---|---|---|
Abort Requests | fails with a network error | test an error path or an outage, block analytics |
Mock Responses | gets a mock response, the server never sees it | test the frontend without the backend, get a 500 on demand |
Modify Responses | reaches the server; you change the request and the real response | use another backend, add a header, set one JSON field to an edge case |
All three take matcher, times and on, and return the rule id. matcher
follows the shared rules; a function gets the
request URL:
url => url.searchParams.get('id') === '7'. Route rules see page traffic only, not
Send API Request.
Context or Page
on=Context, the default: every page of the active context, also pages opened later.on=Page: the active page only. The rule stays on that page; it does not followSwitch Page.
Both survive Go To. Another context gets neither, see
Browser, context and page.
When a rule ends
- Its context or page closes.
- You remove it with
Remove Route RuleorRemove All Route Rules. - It has handled
timesrequests.timesmust be 1 or more.
A context opened inside a test closes with it under the default
auto_closing_level=TEST, and its rules go with it.
Rule order
The newest rule wins, and a Page rule wins over a Context rule. When it ends, the next older rule takes over:
Outage and recovery
A fixed number of failures with times, or an outage that ends when the test
removes the rule:
Mock Responses with status=503 and times=1 does the same with an error
response instead of a network error.
Abort Requests
errorCode is the network error, failed by default; see
AbortErrorCode for all of them.
Chromium reports the matching error, net::ERR_TIMED_OUT here. Firefox and WebKit
report most codes as one generic failure, so check the error text only in Chromium.
Mock Responses
A mock response is a status (100 to 599, 200 by default), headers and at most
one payload. No payload is an empty body, as for a 204.
| Payload | Is | Content-Type |
|---|---|---|
body | Text, bytes, a Secret, or a JSON value, see Bodies | text: text/plain; charset=utf-8, bytes: application/octet-stream, JSON: application/json |
json | A JSON value. A string becomes a JSON string, in quotes | application/json |
path | The bytes of a file, binary too | from the extension, charset=utf-8 for text/; else application/octet-stream |
| none | An empty body | none; WebKit reports application/octet-stream |
headersis the whole header set: there is no real response to merge with. A Content-Type in it always wins.- JSON text you already have goes in
bodywith a Content-Type header. A JSONnullbody isbody=nullwith one. - A text file in another encoding than UTF-8 needs its Content-Type, with charset.
- Python reads
path, so the file needs to exist only where the tests run. - There is no reason phrase: the browser shows the standard one, or
Unknown.
Modify Responses
The request reaches the server, and only what you give changes. Give at least one; the page keeps the URL it asked for.
| Argument | Changes |
|---|---|
request_url | Where the request goes: absolute, or relative to the original URL |
request_method | The method the server gets |
request_headers | Merged onto the real request headers |
request_body | The body the server gets, see Bodies |
status | The status the page gets |
headers | Merged onto the real response headers |
body, json, path | Replace the real body, as in Mock Responses |
json_patch | Changes fields of the real JSON body |
Give at most one of body, json, path and json_patch.
Headers
headers and request_headers merge onto the real headers. Names compare
case-insensitively, and a value you give wins:
| Value | Header |
|---|---|
text, Secret, number, boolean | set to that value |
"" | sent empty |
None | removed |
Request URL, method and body
- A changed URL gets the cookies the context holds for that URL. The original
CookieandHostare not forwarded, so all three browsers behave alike. UseAdd Cookiefor a cookie on the new host. - A text or
bytesrequest_bodykeeps the original Content-Type unlessrequest_headerssets one; a JSON value setsapplication/json. The length is recalculated. GETorHEADwithoutrequest_bodysends no body, so an old form body is not carried along.
Response body
body, json and path replace the real body; the real status and headers stay.
The real Content-Encoding and Content-Length are dropped, because the page gets
the new body already decoded.
json_patch changes the real JSON body as an
RFC 7386 JSON Merge Patch: dictionaries
merge at every depth, ${None} deletes a key, anything else replaces the value
whole, a list included.
| Real body | json_patch | Page gets |
|---|---|---|
{"id": 7, "state": "open"} | {"state": "cancelled"} | {"id": 7, "state": "cancelled"} |
{"id": 7, "note": "x"} | {"note": None} | {"id": 7} |
{"order": {"id": 7, "total": 12}} | {"order": {"total": 0}} | {"order": {"id": 7, "total": 0}} |
{"items": [1, 2, 3]} | {"items": [4]} | {"items": [4]} |
json_patch takes only a dictionary; to replace the whole body, use json. The real
Content-Type stays.
Redirects, failures and timeouts
- The real request follows up to 20 redirects. The page gets the final response at the URL it asked for. The redirect target does not pass through route rules.
Modify Responsespasses as soon as the rule is added. When the real request fails later, because the server is unreachable, it times out orjson_patchmeets a body that is not JSON, the page request fails as a network error. The error goes toplaywright-log.txtwith the rule id, without Playwright's call log.- The timeout is the browser timeout when the rule is added. For a shorter one,
wrap the keyword in
Set Browser Timeout. It also bounds how longRemove Route Rulewaits for a request the rule is handling. - A replaced body and
request_bodycan be at most about 4 MB.json_patchis small however large the real body is.
Removing rules
Remove Route Rule removes one rule by its id, in
any context. Remove All Route Rules removes
the Context rules of the active context and the Page rules of all its pages.
- Both wait for a request the rule is handling, then the rule handles no more.
- An unknown or ended id, no rules, or no open context are logged, and the keyword passes. So both are safe in a teardown.
Remove All Route Rulesremoves only the rules of this library, not apage.routefrom a plugin or JavaScript extension.
Cross-origin requests
A cross-origin mock response needs no CORS headers, also with credentials. A mock
that sets its own Access-Control-Allow-Origin is checked like a real response, so
* with credentials fails. The preflight OPTIONS request never reaches a rule.
Service workers and the HTTP cache
- A request that a service worker answers never reaches a rule. Open the context
with
serviceWorkers=blockinNew Contextto route it. - Playwright turns off the HTTP cache once a context or page has a rule, so the page may send more requests than without it.
Logging
The keywords log the rule in log.html, with header names but never values or
bodies:
Each request a rule handles is logged only in
playwright-log.txt, so a rule that
blocks hundreds of analytics calls keeps log.html readable. Search it for the rule
id:
For tokens in headers or bodies, see Secrets.