Compare commits

..

31 commits

Author SHA1 Message Date
Yury Semikhatsky aac1613b01
cherry-pick(#34601): docs: breaking changes in java 1.50 (#34602) 2025-02-03 12:10:47 -08:00
Max Schmitt 0e99d48e3f cherry-pick(#34592): docs: v1.50 release notes for ports
Signed-off-by: Max Schmitt <max@schmitt.mx>
Co-authored-by: Simon Knott <info@simonknott.de>
2025-02-03 15:18:22 +01:00
Max Schmitt 9f60397d24 cherry-pick(#34594): Revert "chore(docs): clarify connection method via BrowserType.connect (#34560)" 2025-02-03 14:25:18 +01:00
Dmitry Gozman dbc685ca98
chore: mark v1.50.1 (#34575) 2025-01-31 16:02:33 +00:00
Adam Gastineau 13d80f184e
cherry-pick(#34560): chore(docs): clarify connection method via BrowserType.connect (#34562) 2025-01-30 12:36:40 -08:00
Dmitry Gozman 159210da82
cherry-pick(#34556): fix(toMatchAriaSnapshot): fail test run when updating missing snapshot (#34561) 2025-01-30 20:08:32 +00:00
Dmitry Gozman fbad9f7ff7
cherry-pick(#34537): feat: per-assertion snapshot path template in config (#34551) 2025-01-30 12:40:25 +00:00
Max Schmitt 67313faaa7 cherry-pick(#34550): roll follow-ups for .NET and Python 2025-01-30 12:07:42 +01:00
Pavel Feldman 4b7794b37a cherry-pick(#34544): fix(aria): disregard text area textContent 2025-01-29 17:18:41 -08:00
Dmitry Gozman 1efbedd3b3
cherry-pick(#34535): Revert "Reapply "fix(har timing): record connect timing for proxied connections" (#32855) (#33003)" (#34538) 2025-01-29 16:16:38 +00:00
Max Schmitt 1e258e0894
cherry-pick(#34420): chore(deps): bump vite from 5.4.6 to 5.4.14 (#34539) 2025-01-29 17:16:01 +01:00
Dmitry Gozman 7be4ef58de cherry-pick(#34522): test: fetch request through socks proxy over ipv4 2025-01-29 14:52:04 +00:00
Dmitry Gozman 7b3e590289
cherry-pick(#34530): fix(firefox): disable fetch keep-alive for now before a proper fix (#34534)
Co-authored-by: Andrey Lushnikov <aslushnikov@gmail.com>
2025-01-29 11:01:01 +00:00
Pavel Feldman 19fe83f9a1 cherry-pick(#34528): fix(codegen): attribute navigation to press/fill 2025-01-28 18:00:15 -08:00
Pavel Feldman 99ca8c0d43 cherry-pick(#34526): fix(recorder): do not reset inspect highlight on inactivity 2025-01-28 16:06:52 -08:00
Pavel Feldman 50a58f992b cherry-pick(#34524): chore: allow repetative application of rebaselines in the same session 2025-01-28 14:39:13 -08:00
Pavel Feldman 0213cf57bd cherry-pick(#34525): fix: follow the pseudo attr value in firefox computed 2025-01-28 14:38:46 -08:00
Dmitry Gozman 92916b8e91 cherry-pick(#34491): chore: remove unused headers 2025-01-28 09:55:49 +00:00
Pavel Feldman 2c85ade384 cherry-pick(#34473): fix: allow changed to be passed in config 2025-01-24 15:43:44 -08:00
Adam Gastineau b7b0f9571d cherry-pick(#34471): docs: remove toMatchAriaSnapshot path feature 2025-01-24 21:17:20 +01:00
Adam Gastineau 9d22178533
chore: mark v1.50.0 (#34447) 2025-01-23 05:38:26 -08:00
Dmitry Gozman 5d6ac9622d
cherry-pick(#34442): fix(test runner): respect updateSourceMethod from the config (#34445) 2025-01-23 13:04:09 +00:00
Max Schmitt 97b76b46af cherry-pick(#34440): chore(driver): roll driver to recent Node.js LTS version 2025-01-23 11:56:20 +01:00
Adam Gastineau 7bbcc3c624
cherry-pick(#34353): chore: move attachment link back to tree item, make it flash yellow (#34432)
Co-authored-by: Simon Knott <info@simonknott.de>
2025-01-22 10:06:07 -08:00
Adam Gastineau 2811a1d4f5
cherry-pick(#34430): docs: switch gracefulShutdown to primarily mention SIGTERM and add Docker comment (#34431) 2025-01-22 09:56:09 -08:00
Adam Gastineau 2b8d1ce260
cherry-pick(#34380): docs: release notes for v1.50 js (#34425) 2025-01-22 06:54:50 -08:00
Dmitry Gozman 715eb250e7
cherry-pick(#34409): fix(aria snapshot): make rebase work when options are specified (#34417) 2025-01-22 09:27:07 +00:00
Dmitry Gozman 6106ef020f
cherry-pick(#34410): fix(list reporter): do not break after output without trailing eol (#34412) 2025-01-22 07:53:36 +00:00
Dmitry Gozman 09cd74f7b0
cherry-pick(#34407): fix(step.skip): show a skipped indicator in UI mode (#34411) 2025-01-22 07:52:13 +00:00
Yury Semikhatsky cc6eb090ec
cherry-pick(#34386): chore: step timeout improvements (#34387) 2025-01-17 21:54:17 -08:00
Pavel Feldman cd02be37ae cherry-pick(#34379) chore: remove toMatchAriaSnapshot.path 2025-01-17 14:36:41 -08:00
689 changed files with 10661 additions and 42287 deletions

18
.eslintignore Normal file
View file

@ -0,0 +1,18 @@
test/assets/modernizr.js
/tests/third_party/
/packages/*/lib/
*.js
/packages/playwright-core/src/generated/*
/packages/playwright-core/src/third_party/
/packages/playwright-core/types/*
/packages/playwright-ct-core/src/generated/*
/index.d.ts
node_modules/
**/*.d.ts
output/
test-results/
/tests/components/
/tests/installation/fixture-scripts/
DEPS
.cache/
/utils/

View file

@ -0,0 +1,15 @@
module.exports = {
extends: "./.eslintrc.js",
parserOptions: {
ecmaVersion: 9,
sourceType: "module",
project: "./tsconfig.json",
},
rules: {
"@typescript-eslint/no-base-to-string": "error",
"@typescript-eslint/no-unnecessary-boolean-literal-compare": 2,
},
parserOptions: {
project: "./tsconfig.json"
},
};

137
.eslintrc.js Normal file
View file

@ -0,0 +1,137 @@
module.exports = {
parser: "@typescript-eslint/parser",
plugins: ["@typescript-eslint", "notice"],
parserOptions: {
ecmaVersion: 9,
sourceType: "module",
},
extends: [
"plugin:react/recommended",
"plugin:react-hooks/recommended"
],
settings: {
react: { version: "18" }
},
/**
* ESLint rules
*
* All available rules: http://eslint.org/docs/rules/
*
* Rules take the following form:
* "rule-name", [severity, { opts }]
* Severity: 2 == error, 1 == warning, 0 == off.
*/
rules: {
"@typescript-eslint/no-unused-vars": [2, {args: "none"}],
"@typescript-eslint/consistent-type-imports": [2, {disallowTypeAnnotations: false}],
/**
* Enforced rules
*/
// syntax preferences
"object-curly-spacing": ["error", "always"],
"quotes": [2, "single", {
"avoidEscape": true,
"allowTemplateLiterals": true
}],
"jsx-quotes": [2, "prefer-single"],
"no-extra-semi": 2,
"@typescript-eslint/semi": [2],
"comma-style": [2, "last"],
"wrap-iife": [2, "inside"],
"spaced-comment": [2, "always", {
"markers": ["*"]
}],
"eqeqeq": [2],
"accessor-pairs": [2, {
"getWithoutSet": false,
"setWithoutGet": false
}],
"brace-style": [2, "1tbs", {"allowSingleLine": true}],
"curly": [2, "multi-or-nest", "consistent"],
"new-parens": 2,
"arrow-parens": [2, "as-needed"],
"prefer-const": 2,
"quote-props": [2, "consistent"],
"nonblock-statement-body-position": [2, "below"],
// anti-patterns
"no-var": 2,
"no-with": 2,
"no-multi-str": 2,
"no-caller": 2,
"no-implied-eval": 2,
"no-labels": 2,
"no-new-object": 2,
"no-octal-escape": 2,
"no-self-compare": 2,
"no-shadow-restricted-names": 2,
"no-cond-assign": 2,
"no-debugger": 2,
"no-dupe-keys": 2,
"no-duplicate-case": 2,
"no-empty-character-class": 2,
"no-unreachable": 2,
"no-unsafe-negation": 2,
"radix": 2,
"valid-typeof": 2,
"no-implicit-globals": [2],
"no-unused-expressions": [2, { "allowShortCircuit": true, "allowTernary": true, "allowTaggedTemplates": true}],
"no-proto": 2,
// es2015 features
"require-yield": 2,
"template-curly-spacing": [2, "never"],
// spacing details
"space-infix-ops": 2,
"space-in-parens": [2, "never"],
"array-bracket-spacing": [2, "never"],
"comma-spacing": [2, { "before": false, "after": true }],
"keyword-spacing": [2, "always"],
"space-before-function-paren": [2, {
"anonymous": "never",
"named": "never",
"asyncArrow": "always"
}],
"no-whitespace-before-property": 2,
"keyword-spacing": [2, {
"overrides": {
"if": {"after": true},
"else": {"after": true},
"for": {"after": true},
"while": {"after": true},
"do": {"after": true},
"switch": {"after": true},
"return": {"after": true}
}
}],
"arrow-spacing": [2, {
"after": true,
"before": true
}],
"@typescript-eslint/func-call-spacing": 2,
"@typescript-eslint/type-annotation-spacing": 2,
// file whitespace
"no-multiple-empty-lines": [2, {"max": 2, "maxEOF": 0}],
"no-mixed-spaces-and-tabs": 2,
"no-trailing-spaces": 2,
"linebreak-style": [ process.platform === "win32" ? 0 : 2, "unix" ],
"indent": [2, 2, { "SwitchCase": 1, "CallExpression": {"arguments": 2}, "MemberExpression": 2 }],
"key-spacing": [2, {
"beforeColon": false
}],
"eol-last": 2,
// copyright
"notice/notice": [2, {
"mustMatch": "Copyright",
"templateFile": require("path").join(__dirname, "utils", "copyright.js"),
}],
// react
"react/react-in-jsx-scope": 0
}
};

View file

@ -35,7 +35,7 @@ jobs:
exit 1
fi
- name: Audit prod NPM dependencies
run: node utils/check_audit.js
run: npm audit --omit dev
lint-snippets:
name: "Lint snippets"
runs-on: ubuntu-latest

View file

@ -3,21 +3,9 @@ name: Roll Browser into Playwright
on:
repository_dispatch:
types: [roll_into_pw]
workflow_dispatch:
inputs:
browser:
description: 'Browser name, e.g. chromium'
required: true
type: string
revision:
description: 'Browser revision without v prefix, e.g. 1234'
required: true
type: string
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: 1
BROWSER: ${{ github.event.client_payload.browser || github.event.inputs.browser }}
REVISION: ${{ github.event.client_payload.revision || github.event.inputs.revision }}
permissions:
contents: write
@ -36,19 +24,19 @@ jobs:
run: npx playwright install-deps
- name: Roll to new revision
run: |
./utils/roll_browser.js $BROWSER $REVISION
./utils/roll_browser.js ${{ github.event.client_payload.browser }} ${{ github.event.client_payload.revision }}
npm run build
- name: Prepare branch
id: prepare-branch
run: |
BRANCH_NAME="roll-into-pw-${BROWSER}/${REVISION}"
BRANCH_NAME="roll-into-pw-${{ github.event.client_payload.browser }}/${{ github.event.client_payload.revision }}"
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_OUTPUT
git config --global user.name github-actions
git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com
git checkout -b "$BRANCH_NAME"
git add .
git commit -m "feat(${BROWSER}): roll to r${REVISION}"
git push origin $BRANCH_NAME --force
git commit -m "feat(${{ github.event.client_payload.browser }}): roll to r${{ github.event.client_payload.revision }}"
git push origin $BRANCH_NAME
- name: Create Pull Request
uses: actions/github-script@v7
with:
@ -59,7 +47,7 @@ jobs:
repo: 'playwright',
head: 'microsoft:${{ steps.prepare-branch.outputs.BRANCH_NAME }}',
base: 'main',
title: 'feat(${{ env.BROWSER }}): roll to r${{ env.REVISION }}',
title: 'feat(${{ github.event.client_payload.browser }}): roll to r${{ github.event.client_payload.revision }}',
});
await github.rest.issues.addLabels({
owner: 'microsoft',

View file

@ -7,8 +7,7 @@ on:
- main
paths:
- .github/workflows/tests_bidi.yml
- packages/playwright-core/src/server/bidi/**
- tests/bidi/**
- packages/playwright-core/src/server/bidi/*
schedule:
# Run every day at midnight
- cron: '0 0 * * *'

2
.gitignore vendored
View file

@ -35,4 +35,4 @@ test-results
.cache/
.eslintcache
playwright.env
/firefox/
firefox

View file

@ -1,35 +0,0 @@
# How to File a Bug Report That Actually Gets Resolved
Make sure youre on the latest Playwright release before filing. Check existing GitHub issues to avoid duplicates.
## Use the Template
Follow the **Bug Report** template. It guides you step-by-step:
- Fill it out thoroughly.
- Clearly list the steps needed to reproduce the bug.
- Provide what you expected to see versus what happened in reality.
- Include system info from `npx envinfo --preset playwright`.
## Keep Your Repro Minimal
We can't parse your entire code base. Reduce it down to the absolute essentials:
- Start a fresh project (`npm init playwright@latest new-project`).
- Add only the code/DOM needed to show the problem.
- Only use major frameworks if necessary (React, Angular, static HTTP server, etc.).
- Avoid adding extra libraries unless absolutely necessary. Note that we won't install any suspect dependencies.
## Why This Matters
- Most issues that lack a repro turn out to be misconfigurations or usage errors.
- We can't fix problems if we cant reproduce them ourselves.
- We cant debug entire private projects or handle sensitive credentials.
- Each confirmed bug will have a test in our repo, so your repro must be as clean as possible.
## More Help
- [Stack Overflows Minimal Reproducible Example Guide](https://stackoverflow.com/help/minimal-reproducible-example)
- [Playwright Debugging Tools](https://playwright.dev/docs/debug)
## Bottom Line
A well-isolated bug speeds up verification and resolution. Minimal, public repro or its unlikely we can assist.

View file

@ -1,6 +1,6 @@
# 🎭 Playwright
[![npm version](https://img.shields.io/npm/v/playwright.svg)](https://www.npmjs.com/package/playwright) <!-- GEN:chromium-version-badge -->[![Chromium version](https://img.shields.io/badge/chromium-134.0.6998.35-blue.svg?logo=google-chrome)](https://www.chromium.org/Home)<!-- GEN:stop --> <!-- GEN:firefox-version-badge -->[![Firefox version](https://img.shields.io/badge/firefox-135.0-blue.svg?logo=firefoxbrowser)](https://www.mozilla.org/en-US/firefox/new/)<!-- GEN:stop --> <!-- GEN:webkit-version-badge -->[![WebKit version](https://img.shields.io/badge/webkit-18.2-blue.svg?logo=safari)](https://webkit.org/)<!-- GEN:stop --> [![Join Discord](https://img.shields.io/badge/join-discord-infomational)](https://aka.ms/playwright/discord)
[![npm version](https://img.shields.io/npm/v/playwright.svg)](https://www.npmjs.com/package/playwright) <!-- GEN:chromium-version-badge -->[![Chromium version](https://img.shields.io/badge/chromium-133.0.6943.16-blue.svg?logo=google-chrome)](https://www.chromium.org/Home)<!-- GEN:stop --> <!-- GEN:firefox-version-badge -->[![Firefox version](https://img.shields.io/badge/firefox-134.0-blue.svg?logo=firefoxbrowser)](https://www.mozilla.org/en-US/firefox/new/)<!-- GEN:stop --> <!-- GEN:webkit-version-badge -->[![WebKit version](https://img.shields.io/badge/webkit-18.2-blue.svg?logo=safari)](https://webkit.org/)<!-- GEN:stop --> [![Join Discord](https://img.shields.io/badge/join-discord-infomational)](https://aka.ms/playwright/discord)
## [Documentation](https://playwright.dev) | [API reference](https://playwright.dev/docs/api/class-playwright)
@ -8,9 +8,9 @@ Playwright is a framework for Web Testing and Automation. It allows testing [Chr
| | Linux | macOS | Windows |
| :--- | :---: | :---: | :---: |
| Chromium <!-- GEN:chromium-version -->134.0.6998.35<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| Chromium <!-- GEN:chromium-version -->133.0.6943.16<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| WebKit <!-- GEN:webkit-version -->18.2<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| Firefox <!-- GEN:firefox-version -->135.0<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| Firefox <!-- GEN:firefox-version -->134.0<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
Headless execution is supported for all browsers on all platforms. Check out [system requirements](https://playwright.dev/docs/intro#system-requirements) for details.

View file

@ -1,3 +1,3 @@
REMOTE_URL="https://github.com/mozilla/gecko-dev"
BASE_BRANCH="release"
BASE_REVISION="5cfa81898f6eef8fb1abe463e5253cea5bc17f3f"
BASE_REVISION="bc78b98043438d8ee2727a483b6e10dedfda883f"

View file

@ -393,7 +393,7 @@ class PageTarget {
this._videoRecordingInfo = undefined;
this._screencastRecordingInfo = undefined;
this._dialogs = new Map();
this.forcedColors = 'none';
this.forcedColors = 'no-override';
this.disableCache = false;
this.mediumOverride = '';
this.crossProcessCookie = {
@ -635,8 +635,7 @@ class PageTarget {
}
updateForcedColorsOverride(browsingContext = undefined) {
const isActive = this.forcedColors === 'active' || this._browserContext.forcedColors === 'active';
(browsingContext || this._linkedBrowser.browsingContext).forcedColorsOverride = isActive ? 'active' : 'none';
(browsingContext || this._linkedBrowser.browsingContext).forcedColorsOverride = (this.forcedColors !== 'no-override' ? this.forcedColors : this._browserContext.forcedColors) || 'no-override';
}
async setInterceptFileChooserDialog(enabled) {
@ -859,8 +858,8 @@ function fromProtocolReducedMotion(reducedMotion) {
function fromProtocolForcedColors(forcedColors) {
if (forcedColors === 'active' || forcedColors === 'none')
return forcedColors;
if (!forcedColors)
return 'none';
if (forcedColors === null)
return undefined;
throw new Error('Unknown forced colors: ' + forcedColors);
}
@ -894,7 +893,7 @@ class BrowserContext {
this.forceOffline = false;
this.disableCache = false;
this.colorScheme = 'none';
this.forcedColors = 'none';
this.forcedColors = 'no-override';
this.reducedMotion = 'none';
this.videoRecordingOptions = undefined;
this.crossProcessCookie = {

View file

@ -105,10 +105,7 @@ class Juggler {
};
// Force create hidden window here, otherwise its creation later closes the web socket!
// Since https://phabricator.services.mozilla.com/D219834, hiddenDOMWindow is only available on MacOS.
if (Services.appShell.hasHiddenWindow) {
Services.appShell.hiddenDOMWindow;
}
Services.appShell.hiddenDOMWindow;
let pipeStopped = false;
let browserHandler;

File diff suppressed because it is too large Load diff

View file

@ -1,3 +1,3 @@
REMOTE_URL="https://github.com/WebKit/WebKit.git"
BASE_BRANCH="main"
BASE_REVISION="76c95d6131edd36775a5eac01e297926fc974be8"
BASE_REVISION="8ceb1da47e75a488ae4c12017a861636904acd4f"

View file

@ -33,7 +33,6 @@
#import <WebKit/WKUserContentControllerPrivate.h>
#import <WebKit/WKWebViewConfigurationPrivate.h>
#import <WebKit/WKWebViewPrivate.h>
#import <WebKit/WKWebpagePreferencesPrivate.h>
#import <WebKit/WKWebsiteDataStorePrivate.h>
#import <WebKit/WebNSURLExtras.h>
#import <WebKit/WebKit.h>
@ -241,8 +240,6 @@ const NSActivityOptions ActivityOptions =
configuration.preferences._hiddenPageDOMTimerThrottlingAutoIncreases = NO;
configuration.preferences._pageVisibilityBasedProcessSuppressionEnabled = NO;
configuration.preferences._domTimersThrottlingEnabled = NO;
// Do not auto play audio and video with sound.
configuration.defaultWebpagePreferences._autoplayPolicy = _WKWebsiteAutoplayPolicyAllowWithoutSound;
_WKProcessPoolConfiguration *processConfiguration = [[[_WKProcessPoolConfiguration alloc] init] autorelease];
processConfiguration.forceOverlayScrollbars = YES;
configuration.processPool = [[[WKProcessPool alloc] _initWithConfiguration:processConfiguration] autorelease];

File diff suppressed because it is too large Load diff

View file

@ -21,13 +21,6 @@ Creates new instances of [APIRequestContext].
### option: APIRequest.newContext.extraHTTPHeaders = %%-context-option-extrahttpheaders-%%
* since: v1.16
### option: APIRequest.newContext.failOnStatusCode
* since: v1.51
- `failOnStatusCode` <[boolean]>
Whether to throw on response codes other than 2xx and 3xx. By default response object is returned
for all status codes.
### option: APIRequest.newContext.httpCredentials = %%-context-option-httpcredentials-%%
* since: v1.16
@ -71,7 +64,6 @@ Methods like [`method: APIRequestContext.get`] take the base URL into considerat
- `localStorage` <[Array]<[Object]>>
- `name` <[string]>
- `value` <[string]>
- `indexedDB` ?<[Array]<[unknown]>> indexedDB to set for context
Populates context with given storage state. This option can be used to initialize context with logged-in information
obtained via [`method: BrowserContext.storageState`] or [`method: APIRequestContext.storageState`]. Either a path to the

View file

@ -880,7 +880,6 @@ context cookies from the response. The method will automatically follow redirect
- `localStorage` <[Array]<[Object]>>
- `name` <[string]>
- `value` <[string]>
- `indexedDB` <[Array]<[unknown]>>
Returns storage state for this request context, contains current cookies and local storage snapshot if it was passed to the constructor.
@ -891,9 +890,3 @@ Returns storage state for this request context, contains current cookies and loc
### option: APIRequestContext.storageState.path = %%-storagestate-option-path-%%
* since: v1.16
### option: APIRequestContext.storageState.indexedDB
* since: v1.51
- `indexedDB` ?<boolean>
Set to `true` to include IndexedDB in the storage state snapshot.

View file

@ -1511,9 +1511,8 @@ Whether to emulate network being offline for the browser context.
- `localStorage` <[Array]<[Object]>>
- `name` <[string]>
- `value` <[string]>
- `indexedDB` <[Array]<[unknown]>>
Returns storage state for this browser context, contains current cookies, local storage snapshot and IndexedDB snapshot.
Returns storage state for this browser context, contains current cookies and local storage snapshot.
## async method: BrowserContext.storageState
* since: v1.8
@ -1523,17 +1522,6 @@ Returns storage state for this browser context, contains current cookies, local
### option: BrowserContext.storageState.path = %%-storagestate-option-path-%%
* since: v1.8
### option: BrowserContext.storageState.indexedDB
* since: v1.51
- `indexedDB` ?<boolean>
Set to `true` to include IndexedDB in the storage state snapshot.
If your application uses IndexedDB to store authentication tokens, like Firebase Authentication, enable this.
:::note
IndexedDBs with typed arrays are currently not supported.
:::
## property: BrowserContext.tracing
* since: v1.12
- type: <[Tracing]>

View file

@ -89,17 +89,13 @@ class BrowserTypeExamples
* since: v1.8
- returns: <[Browser]>
This method attaches Playwright to an existing browser instance created via `BrowserType.launchServer` in Node.js.
:::note
The major and minor version of the Playwright instance that connects needs to match the version of Playwright that launches the browser (1.2.3 → is compatible with 1.2.x).
:::
This method attaches Playwright to an existing browser instance. When connecting to another browser launched via `BrowserType.launchServer` in Node.js, the major and minor version needs to match the client version (1.2.3 → is compatible with 1.2.x).
### param: BrowserType.connect.wsEndpoint
* since: v1.10
- `wsEndpoint` <[string]>
A Playwright browser websocket endpoint to connect to. You obtain this endpoint via `BrowserServer.wsEndpoint`.
A browser websocket endpoint to connect to.
### option: BrowserType.connect.headers
* since: v1.11
@ -156,10 +152,6 @@ The default browser context is accessible via [`method: Browser.contexts`].
Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers.
:::
:::note
This connection is significantly lower fidelity than the Playwright protocol connection via [`method: BrowserType.connect`]. If you are experiencing issues or attempting to use advanced functionality, you probably want to use [`method: BrowserType.connect`].
:::
**Usage**
```js

View file

@ -864,6 +864,31 @@ If [`param: expression`] throws or rejects, this method throws.
**Usage**
```js
const tweets = page.locator('.tweet .retweets');
expect(await tweets.evaluate(node => node.innerText)).toBe('10 retweets');
```
```java
Locator tweets = page.locator(".tweet .retweets");
assertEquals("10 retweets", tweets.evaluate("node => node.innerText"));
```
```python async
tweets = page.locator(".tweet .retweets")
assert await tweets.evaluate("node => node.innerText") == "10 retweets"
```
```python sync
tweets = page.locator(".tweet .retweets")
assert tweets.evaluate("node => node.innerText") == "10 retweets"
```
```csharp
var tweets = page.Locator(".tweet .retweets");
Assert.AreEqual("10 retweets", await tweets.EvaluateAsync("node => node.innerText"));
```
### param: Locator.evaluate.expression = %%-evaluate-expression-%%
* since: v1.14
@ -1090,9 +1115,6 @@ await rowLocator
### option: Locator.filter.hasNotText = %%-locator-option-has-not-text-%%
* since: v1.33
### option: Locator.filter.visible = %%-locator-option-visible-%%
* since: v1.51
## method: Locator.first
* since: v1.14
- returns: <[Locator]>
@ -2038,9 +2060,9 @@ Triggers a `change` and `input` event once all the provided options have been se
```html
<select multiple>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="red">Red</div>
<option value="green">Green</div>
<option value="blue">Blue</div>
</select>
```
@ -2335,7 +2357,7 @@ This method expects [Locator] to point to an
## async method: Locator.tap
* since: v1.14
Perform a tap gesture on the element matching the locator. For examples of emulating other gestures by manually dispatching touch events, see the [emulating legacy touch events](../touch-events.md) page.
Perform a tap gesture on the element matching the locator.
**Details**

View file

@ -2263,13 +2263,13 @@ assertThat(page.locator("body")).matchesAriaSnapshot("""
Asserts that the target element matches the given [accessibility snapshot](../aria-snapshots.md).
Snapshot is stored in a separate `.snapshot.yml` file in a location configured by `expect.toMatchAriaSnapshot.pathTemplate` and/or `snapshotPathTemplate` properties in the configuration file.
Snapshot is stored in a separate `.yml` file in a location configured by `expect.toMatchAriaSnapshot.pathTemplate` and/or `snapshotPathTemplate` properties in the configuration file.
**Usage**
```js
await expect(page.locator('body')).toMatchAriaSnapshot();
await expect(page.locator('body')).toMatchAriaSnapshot({ name: 'body.snapshot.yml' });
await expect(page.locator('body')).toMatchAriaSnapshot({ name: 'body.yml' });
```
### option: LocatorAssertions.toMatchAriaSnapshot#2.name

View file

@ -1309,18 +1309,6 @@ Emulates `'forced-colors'` media feature, supported values are `'active'` and `'
* langs: csharp, python
- `forcedColors` <[ForcedColors]<"active"|"none"|"null">>
### option: Page.emulateMedia.contrast
* since: v1.51
* langs: js, java
- `contrast` <null|[Contrast]<"no-preference"|"more">>
Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. Passing `null` disables contrast emulation.
### option: Page.emulateMedia.contrast
* since: v1.51
* langs: csharp, python
- `contrast` <[Contrast]<"no-preference"|"more"|"null">>
## async method: Page.evalOnSelector
* since: v1.9
* discouraged: This method does not wait for the element to pass actionability

View file

@ -296,18 +296,7 @@ Ensures the page is navigated to the given URL.
**Usage**
```js
// Check for the page URL to be 'https://playwright.dev/docs/intro' (including query string)
await expect(page).toHaveURL('https://playwright.dev/docs/intro');
// Check for the page URL to contain 'doc', followed by an optional 's', followed by '/'
await expect(page).toHaveURL(/docs?\//);
// Check for the predicate to be satisfied
// For example: verify query strings
await expect(page).toHaveURL(url => {
const params = url.searchParams;
return params.has('search') && params.has('options') && params.get('id') === '5';
});
await expect(page).toHaveURL(/.*checkout/);
```
```java
@ -334,18 +323,17 @@ expect(page).to_have_url(re.compile(".*checkout"))
await Expect(Page).ToHaveURLAsync(new Regex(".*checkout"));
```
### param: PageAssertions.toHaveURL.url
### param: PageAssertions.toHaveURL.urlOrRegExp
* since: v1.18
- `url` <[string]|[RegExp]|[function]\([URL]\):[boolean]>
- `urlOrRegExp` <[string]|[RegExp]>
Expected URL string, RegExp, or predicate receiving [URL] to match.
When [`option: Browser.newContext.baseURL`] is provided via the context options and the `url` argument is a string, the two values are merged via the [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor and used for the comparison against the current browser URL.
Expected URL string or RegExp.
### option: PageAssertions.toHaveURL.ignoreCase
* since: v1.44
- `ignoreCase` <[boolean]>
Whether to perform case-insensitive match. [`option: ignoreCase`] option takes precedence over the corresponding regular expression parameter if specified. A provided predicate ignores this flag.
Whether to perform case-insensitive match. [`option: ignoreCase`] option takes precedence over the corresponding regular expression flag if specified.
### option: PageAssertions.toHaveURL.timeout = %%-js-assertions-timeout-%%
* since: v1.18

View file

@ -4,8 +4,6 @@
The Touchscreen class operates in main-frame CSS pixels relative to the top-left corner of the viewport. Methods on the
touchscreen can only be used in browser contexts that have been initialized with `hasTouch` set to true.
This class is limited to emulating tap gestures. For examples of other gestures simulated by manually dispatching touch events, see the [emulating legacy touch events](../touch-events.md) page.
## async method: Touchscreen.tap
* since: v1.8

View file

@ -1,9 +1,7 @@
# class: WebSocket
* since: v1.8
The [WebSocket] class represents WebSocket connections within a page. It provides the ability to inspect and manipulate the data being transmitted and received.
If you want to intercept or modify WebSocket frames, consider using [WebSocketRoute].
The [WebSocket] class represents websocket connections in the page.
## event: WebSocket.close
* since: v1.8

View file

@ -259,12 +259,11 @@ Specify environment variables that will be visible to the browser. Defaults to `
- `httpOnly` <[boolean]>
- `secure` <[boolean]>
- `sameSite` <[SameSiteAttribute]<"Strict"|"Lax"|"None">> sameSite flag
- `origins` <[Array]<[Object]>>
- `origins` <[Array]<[Object]>> localStorage to set for context
- `origin` <[string]>
- `localStorage` <[Array]<[Object]>> localStorage to set for context
- `localStorage` <[Array]<[Object]>>
- `name` <[string]>
- `value` <[string]>
- `indexedDB` ?<[Array]<[unknown]>> indexedDB to set for context
Learn more about [storage state and auth](../auth.md).
@ -674,18 +673,6 @@ Emulates `'forced-colors'` media feature, supported values are `'active'`, `'non
Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See [`method: Page.emulateMedia`] for more details. Passing `'null'` resets emulation to system defaults. Defaults to `'none'`.
## context-option-contrast
* langs: js, java
- `contrast` <null|[ForcedColors]<"no-preference"|"more">>
Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See [`method: Page.emulateMedia`] for more details. Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.
## context-option-contrast-csharp-python
* langs: csharp, python
- `contrast` <[ForcedColors]<"no-preference"|"more"|"null">>
Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See [`method: Page.emulateMedia`] for more details. Passing `'null'` resets emulation to system defaults. Defaults to `'no-preference'`.
## context-option-logger
* langs: js
- `logger` <[Logger]>
@ -986,8 +973,6 @@ between the same pixel in compared images, between zero (strict) and one (lax),
- %%-context-option-reducedMotion-csharp-python-%%
- %%-context-option-forcedColors-%%
- %%-context-option-forcedColors-csharp-python-%%
- %%-context-option-contrast-%%
- %%-context-option-contrast-csharp-python-%%
- %%-context-option-logger-%%
- %%-context-option-videospath-%%
- %%-context-option-videosize-%%
@ -1155,11 +1140,6 @@ Note that outer and inner locators must belong to the same frame. Inner locator
Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element. When passed a [string], matching is case-insensitive and searches for a substring.
## locator-option-visible
- `visible` <[boolean]>
Only matches visible or invisible elements.
## locator-options-list-v1.14
- %%-locator-option-has-text-%%
- %%-locator-option-has-%%
@ -1210,7 +1190,6 @@ Specify screenshot type, defaults to `png`.
Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with
a pink box `#FF00FF` (customized by [`option: maskColor`]) that completely covers its bounding box.
The mask is also applied to invisible elements, see [Matching only visible elements](../locators.md#matching-only-visible-elements) to disable that.
## screenshot-option-mask-color
* since: v1.35

View file

@ -6,7 +6,7 @@ import LiteYouTube from '@site/src/components/LiteYouTube';
## Overview
With Playwright's Snapshot testing you can assert the accessibility tree of a page against a predefined snapshot template.
With the Playwright Snapshot testing you can assert the accessibility tree of a page against a predefined snapshot template.
```js
await page.goto('https://playwright.dev/');
@ -79,12 +79,12 @@ confirms that an input field has the expected value.
Assertion tests are specific and generally check the current state of an element or property
against an expected, predefined state.
They work well for predictable, single-value checks but are limited in scope when testing the
broader structure or variations.
broader structure or variations.
**Advantages**
- **Clarity**: The intent of the test is explicit and easy to understand.
- **Specificity**: Tests focus on particular aspects of functionality, making them more robust
against unrelated changes.
against unrelated changes.
- **Debugging**: Failures provide targeted feedback, pointing directly to the problematic aspect.
**Disadvantages**
@ -222,7 +222,7 @@ attributes.
```
In this example, the button role is matched, but the accessible name ("Submit") is not specified, allowing the test to
pass regardless of the button's label.
pass regardless of the buttons label.
<hr/>
@ -280,12 +280,12 @@ support regex patterns.
## Generating snapshots
Creating aria snapshots in Playwright helps ensure and maintain your application's structure.
Creating aria snapshots in Playwright helps ensure and maintain your applications structure.
You can generate snapshots in various ways depending on your testing setup and workflow.
### Generating snapshots with the Playwright code generator
### 1. Generating snapshots with the Playwright code generator
If you're using Playwright's [Code Generator](./codegen.md), generating aria snapshots is streamlined with its
If youre using Playwrights [Code Generator](./codegen.md), generating aria snapshots is streamlined with its
interactive interface:
- **"Assert snapshot" Action**: In the code generator, you can use the "Assert snapshot" action to automatically create
@ -296,18 +296,20 @@ recorded test flow.
aria snapshot for a selected locator, letting you explore, inspect, and verify element roles, attributes, and
accessible names to aid snapshot creation and review.
### Updating snapshots with `@playwright/test` and the `--update-snapshots` flag
* langs: js
### 2. Updating snapshots with `@playwright/test` and the `--update-snapshots` flag
When using the Playwright test runner (`@playwright/test`), you can automatically update snapshots with the `--update-snapshots` flag, `-u` for short.
Running tests with the `--update-snapshots` flag will update snapshots that did not match. Matching snapshots will not be updated.
When using the Playwright test runner (`@playwright/test`), you can automatically update snapshots by running tests with
the `--update-snapshots` flag:
```bash
npx playwright test --update-snapshots
```
Updating snapshots is useful when application structure changes require new snapshots as a baseline. Note that Playwright will wait for the maximum expect timeout specified in the test runner configuration to ensure the page is settled before taking the snapshot. It might be necessary to adjust the `--timeout` if the test hits the timeout while generating snapshots.
This command regenerates snapshots for assertions, including aria snapshots, replacing outdated ones. Its
useful when application structure changes require new snapshots as a baseline. Note that Playwright will wait for the
maximum expect timeout specified in the test runner configuration to ensure the
page is settled before taking the snapshot. It might be necessary to adjust the `--timeout` if the test hits the timeout
while generating snapshots.
#### Empty template for snapshot generation
@ -327,40 +329,10 @@ When updating snapshots, Playwright creates patch files that capture differences
applied, and committed to source control, allowing teams to track structural changes over time and ensure updates are
consistent with application requirements.
The way source code is updated can be changed using the `--update-source-method` flag. There are several options available:
- **"patch"** (default): Generates a unified diff file that can be applied to the source code using `git apply`.
- **"3way"**: Generates merge conflict markers in your source code, allowing you to choose whether to accept changes.
- **"overwrite"**: Overwrites the source code with the new snapshot values.
```bash
npx playwright test --update-snapshots --update-source-mode=3way
```
#### Snapshots as separate files
To store your snapshots in a separate file, use the `toMatchAriaSnapshot` method with the `name` option, specifying a `.snapshot.yml` file extension.
```js
await expect(page.getByRole('main')).toMatchAriaSnapshot({ name: 'main.snapshot.yml' });
```
By default, snapshots from a test file `example.spec.ts` are placed in the `example.spec.ts-snapshots` directory. As snapshots should be the same across browsers, only one snapshot is saved even if testing with multiple browsers. Should you wish, you can customize the [snapshot path template](./api/class-testconfig#test-config-snapshot-path-template) using the following configuration:
```js
export default defineConfig({
expect: {
toMatchAriaSnapshot: {
pathTemplate: '__snapshots__/{testFilePath}/{arg}{ext}',
},
},
});
```
### Using the `Locator.ariaSnapshot` method
### 3. Using the `Locator.ariaSnapshot` method
The [`method: Locator.ariaSnapshot`] method allows you to programmatically create a YAML representation of accessible
elements within a locator's scope, especially helpful for generating snapshots dynamically during test execution.
elements within a locators scope, especially helpful for generating snapshots dynamically during test execution.
**Example**:
@ -389,7 +361,7 @@ var snapshot = await page.Locator("body").AriaSnapshotAsync();
Console.WriteLine(snapshot);
```
This command outputs the aria snapshot within the specified locator's scope in YAML format, which you can validate
This command outputs the aria snapshot within the specified locators scope in YAML format, which you can validate
or store as needed.
## Accessibility tree examples

View file

@ -232,7 +232,7 @@ await page.goto('https://github.com/login')
# Interact with login form
await page.get_by_label("Username or email address").fill("username")
await page.get_by_label("Password").fill("password")
await page.get_by_role("button", name="Sign in").click()
await page.page.get_by_role("button", name="Sign in").click()
# Continue with the test
```
@ -266,9 +266,9 @@ existing authentication state instead.
Playwright provides a way to reuse the signed-in state in the tests. That way you can log
in only once and then skip the log in step for all of the tests.
Web apps use cookie-based or token-based authentication, where authenticated state is stored as [cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies), in [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Storage) or in [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API). Playwright provides [`method: BrowserContext.storageState`] method that can be used to retrieve storage state from authenticated contexts and then create new contexts with prepopulated state.
Web apps use cookie-based or token-based authentication, where authenticated state is stored as [cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) or in [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Storage). Playwright provides [`method: BrowserContext.storageState`] method that can be used to retrieve storage state from authenticated contexts and then create new contexts with prepopulated state.
Cookies, local storage and IndexedDB state can be used across different browsers. They depend on your application's authentication model which may require some combination of cookies, local storage or IndexedDB.
Cookies and local storage state can be used across different browsers. They depend on your application's authentication model: some apps might require both cookies and local storage.
The following code snippet retrieves state from an authenticated context and creates a new context with that state.
@ -583,7 +583,7 @@ test('admin and user', async ({ adminPage, userPage }) => {
### Session storage
Reusing authenticated state covers [cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies), [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Storage) and [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) based authentication. Rarely, [session storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) is used for storing information associated with the signed-in state. Session storage is specific to a particular domain and is not persisted across page loads. Playwright does not provide API to persist session storage, but the following snippet can be used to save/load session storage.
Reusing authenticated state covers [cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) and [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Storage) based authentication. Rarely, [session storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) is used for storing information associated with the signed-in state. Session storage is specific to a particular domain and is not persisted across page loads. Playwright does not provide API to persist session storage, but the following snippet can be used to save/load session storage.
```js
// Get session storage and store as env variable

View file

@ -804,7 +804,7 @@ Sharding in CircleCI is indexed with 0 which means that you will need to overrid
executor: pw-noble-development
parallelism: 4
steps:
- run: SHARD="$((${CIRCLE_NODE_INDEX}+1))"; npx playwright test --shard=${SHARD}/${CIRCLE_NODE_TOTAL}
- run: SHARD="$((${CIRCLE_NODE_INDEX}+1))"; npx playwright test -- --shard=${SHARD}/${CIRCLE_NODE_TOTAL}
```
### Jenkins

View file

@ -325,7 +325,7 @@ pwsh bin/Debug/netX/playwright.ps1 codegen --timezone="Europe/Rome" --geolocatio
### Preserve authenticated state
Run `codegen` with `--save-storage` to save [cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies), [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) and [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) data at the end of the session. This is useful to separately record an authentication step and reuse it later when recording more tests.
Run `codegen` with `--save-storage` to save [cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) and [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) at the end of the session. This is useful to separately record an authentication step and reuse it later when recording more tests.
```bash js
npx playwright codegen github.com/microsoft/playwright --save-storage=auth.json
@ -375,7 +375,7 @@ Make sure you only use the `auth.json` locally as it contains sensitive informat
#### Load authenticated state
Run with `--load-storage` to consume the previously loaded storage from the `auth.json`. This way, all [cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies), [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) and [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) data will be restored, bringing most web apps to the authenticated state without the need to login again. This means you can continue generating tests from the logged in state.
Run with `--load-storage` to consume the previously loaded storage from the `auth.json`. This way, all [cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) and [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) will be restored, bringing most web apps to the authenticated state without the need to login again. This means you can continue generating tests from the logged in state.
```bash js
npx playwright codegen --load-storage=auth.json github.com/microsoft/playwright

View file

@ -751,10 +751,10 @@ page.locator("x-details", new Page.LocatorOptions().setHasText("Details"))
.click();
```
```python async
await page.locator("x-details", has_text="Details").click()
await page.locator("x-details", has_text="Details" ).click()
```
```python sync
page.locator("x-details", has_text="Details").click()
page.locator("x-details", has_text="Details" ).click()
```
```csharp
await page
@ -1310,19 +1310,19 @@ Consider a page with two buttons, the first invisible and the second [visible](.
* This will only find a second button, because it is visible, and then click it.
```js
await page.locator('button').filter({ visible: true }).click();
await page.locator('button').locator('visible=true').click();
```
```java
page.locator("button").filter(new Locator.FilterOptions.setVisible(true)).click();
page.locator("button").locator("visible=true").click();
```
```python async
await page.locator("button").filter(visible=True).click()
await page.locator("button").locator("visible=true").click()
```
```python sync
page.locator("button").filter(visible=True).click()
page.locator("button").locator("visible=true").click()
```
```csharp
await page.Locator("button").Filter(new() { Visible = true }).ClickAsync();
await page.Locator("button").Locator("visible=true").ClickAsync();
```
## Lists

View file

@ -708,13 +708,9 @@ Playwright uses simplified glob patterns for URL matching in network interceptio
- A double `**` matches any characters including `/`
1. Question mark `?` matches any single character except `/`
1. Curly braces `{}` can be used to match a list of options separated by commas `,`
1. Square brackets `[]` can be used to match a set of characters
1. Backslash `\` can be used to escape any of special characters (note to escape backslash itself as `\\`)
Examples:
- `https://example.com/*.js` matches `https://example.com/file.js` but not `https://example.com/path/file.js`
- `https://example.com/\\?page=1` matches `https://example.com/?page=1` but not `https://example.com`
- `**/v[0-9]*` matches `https://example.com/v1/` but not `https://example.com/vote/`
- `**/*.js` matches both `https://example.com/file.js` and `https://example.com/path/file.js`
- `**/*.{png,jpg,jpeg}` matches all image requests

View file

@ -824,9 +824,9 @@ This version was also tested against the following stable channels:
```html
<select multiple>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="red">Red</div>
<option value="green">Green</div>
<option value="blue">Blue</div>
</select>
```

View file

@ -888,9 +888,9 @@ This version was also tested against the following stable channels:
```html
<select multiple>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="red">Red</div>
<option value="green">Green</div>
<option value="blue">Blue</div>
</select>
```

View file

@ -1498,9 +1498,9 @@ This version was also tested against the following stable channels:
```html
<select multiple>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="red">Red</div>
<option value="green">Green</div>
<option value="blue">Blue</div>
</select>
```

View file

@ -800,9 +800,9 @@ This version was also tested against the following stable channels:
```html
<select multiple>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="red">Red</div>
<option value="green">Green</div>
<option value="blue">Blue</div>
</select>
```

View file

@ -93,8 +93,8 @@ See [`property: TestConfig.reporter`].
## property: FullConfig.reportSlowTests
* since: v1.10
- type: <[null]|[Object]>
- `max` <[int]> The maximum number of slow test files to report.
- `threshold` <[float]> Test file duration in milliseconds that is considered slow.
- `max` <[int]> The maximum number of slow test files to report. Defaults to `5`.
- `threshold` <[float]> Test duration in milliseconds that is considered slow. Defaults to 15 seconds.
See [`property: TestConfig.reportSlowTests`].

View file

@ -1751,7 +1751,7 @@ Step name.
### param: Test.step.body
* since: v1.10
- `body` <[function]\([TestStepInfo]\):[Promise]<[any]>>
- `body` <[function]\(\):[Promise]<[any]>>
Step body.

View file

@ -237,12 +237,7 @@ export default defineConfig({
* since: v1.10
- type: ?<[Metadata]>
Metadata contains key-value pairs to be included in the report. For example, HTML report will display it as key-value pairs, and JSON report will include metadata serialized as json.
* Providing `gitCommit: 'generate'` property will populate it with the git commit details.
* Providing `gitDiff: 'generate'` property will populate it with the git diff details.
On selected CI providers, both will be generated automatically. Specifying values will prevent the automatic generation.
Metadata that will be put directly to the test report serialized as JSON.
**Usage**
@ -250,7 +245,7 @@ On selected CI providers, both will be generated automatically. Specifying value
import { defineConfig } from '@playwright/test';
export default defineConfig({
metadata: { title: 'acceptance tests' },
metadata: 'acceptance tests',
});
```
@ -429,7 +424,7 @@ export default defineConfig({
* since: v1.10
- type: ?<[null]|[Object]>
- `max` <[int]> The maximum number of slow test files to report. Defaults to `5`.
- `threshold` <[float]> Test file duration in milliseconds that is considered slow. Defaults to 5 minutes.
- `threshold` <[float]> Test duration in milliseconds that is considered slow. Defaults to 15 seconds.
Whether to report slow test files. Pass `null` to disable this feature.
@ -639,7 +634,7 @@ export default defineConfig({
- `timeout` ?<[int]> How long to wait for the process to start up and be available in milliseconds. Defaults to 60000.
- `gracefulShutdown` ?<[Object]> How to shut down the process. If unspecified, the process group is forcefully `SIGKILL`ed. If set to `{ signal: 'SIGTERM', timeout: 500 }`, the process group is sent a `SIGTERM` signal, followed by `SIGKILL` if it doesn't exit within 500ms. You can also use `SIGINT` as the signal instead. A `0` timeout means no `SIGKILL` will be sent. Windows doesn't support `SIGTERM` and `SIGINT` signals, so this option is ignored on Windows. Note that shutting down a Docker container requires `SIGTERM`.
- `signal` <["SIGINT"|"SIGTERM"]>
- `timeout` <[int]>
- `timeout` <[int]>
- `url` ?<[string]> The url on your http server that is expected to return a 2xx, 3xx, 400, 401, 402, or 403 status code when the server is ready to accept connections. Redirects (3xx status codes) are being followed and the new location is checked. Either `port` or `url` should be specified.
Launch a development web server (or multiple) during the tests.
@ -663,7 +658,7 @@ import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: {
command: 'npm run start',
url: 'http://localhost:3000',
url: 'http://127.0.0.1:3000',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
@ -692,19 +687,19 @@ export default defineConfig({
webServer: [
{
command: 'npm run start',
url: 'http://localhost:3000',
url: 'http://127.0.0.1:3000',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
{
command: 'npm run backend',
url: 'http://localhost:3333',
url: 'http://127.0.0.1:3333',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
}
],
use: {
baseURL: 'http://localhost:3000',
baseURL: 'http://127.0.0.1:3000',
},
});
```

View file

@ -507,27 +507,6 @@ export default defineConfig({
Learn more about [automatic screenshots](../test-use-options.md#recording-options).
## property: TestOptions.pageSnapshot
* since: v1.51
- type: <[PageSnapshotMode]<"off"|"on"|"only-on-failure">>
Whether to automatically capture a ARIA snapshot of the page after each test. Defaults to `'only-on-failure'`.
* `'off'`: Do not capture page snapshots.
* `'on'`: Capture page snapshot after each test.
* `'only-on-failure'`: Capture page snapshot after each test failure.
**Usage**
```js title="playwright.config.ts"
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
pageSnapshot: 'on',
},
});
```
## property: TestOptions.storageState = %%-js-python-context-option-storage-state-%%
* since: v1.10

View file

@ -183,10 +183,6 @@ Metadata that will be put directly to the test report serialized as JSON.
Project name is visible in the report and during test execution.
:::warning
Playwright executes the configuration file multiple times. Do not dynamically produce non-stable values in your configuration.
:::
## property: TestProject.snapshotDir
* since: v1.10
- type: ?<[string]>

View file

@ -1,103 +0,0 @@
# class: TestStepInfo
* since: v1.51
* langs: js
`TestStepInfo` contains information about currently running test step. It is passed as an argument to the step function. `TestStepInfo` provides utilities to control test step execution.
```js
import { test, expect } from '@playwright/test';
test('basic test', async ({ page, browserName }, TestStepInfo) => {
await test.step('check some behavior', async step => {
await step.skip(browserName === 'webkit', 'The feature is not available in WebKit');
// ... rest of the step code
await page.check('input');
});
});
```
## async method: TestStepInfo.attach
* since: v1.51
Attach a value or a file from disk to the current test step. Some reporters show test step attachments. Either [`option: path`] or [`option: body`] must be specified, but not both. Calling this method will attribute the attachment to the step, as opposed to [`method: TestInfo.attach`] which stores all attachments at the test level.
For example, you can attach a screenshot to the test step:
```js
import { test, expect } from '@playwright/test';
test('basic test', async ({ page }) => {
await page.goto('https://playwright.dev');
await test.step('check page rendering', async step => {
const screenshot = await page.screenshot();
await step.attach('screenshot', { body: screenshot, contentType: 'image/png' });
});
});
```
Or you can attach files returned by your APIs:
```js
import { test, expect } from '@playwright/test';
import { download } from './my-custom-helpers';
test('basic test', async ({}) => {
await test.step('check download behavior', async step => {
const tmpPath = await download('a');
await step.attach('downloaded', { path: tmpPath });
});
});
```
:::note
[`method: TestStepInfo.attach`] automatically takes care of copying attached files to a
location that is accessible to reporters. You can safely remove the attachment
after awaiting the attach call.
:::
### param: TestStepInfo.attach.name
* since: v1.51
- `name` <[string]>
Attachment name. The name will also be sanitized and used as the prefix of file name
when saving to disk.
### option: TestStepInfo.attach.body
* since: v1.51
- `body` <[string]|[Buffer]>
Attachment body. Mutually exclusive with [`option: path`].
### option: TestStepInfo.attach.contentType
* since: v1.51
- `contentType` <[string]>
Content type of this attachment to properly present in the report, for example `'application/json'` or `'image/png'`. If omitted, content type is inferred based on the [`option: path`], or defaults to `text/plain` for [string] attachments and `application/octet-stream` for [Buffer] attachments.
### option: TestStepInfo.attach.path
* since: v1.51
- `path` <[string]>
Path on the filesystem to the attached file. Mutually exclusive with [`option: body`].
## method: TestStepInfo.skip#1
* since: v1.51
Unconditionally skip the currently running step. Test step is immediately aborted. This is similar to [`method: Test.step.skip`].
## method: TestStepInfo.skip#2
* since: v1.51
Conditionally skips the currently running step with an optional description. This is similar to [`method: Test.step.skip`].
### param: TestStepInfo.skip#2.condition
* since: v1.51
- `condition` <[boolean]>
A skip condition. Test step is skipped when the condition is `true`.
### param: TestStepInfo.skip#2.description
* since: v1.51
- `description` ?<[string]>
Optional description that will be reflected in a test report.

View file

@ -110,7 +110,6 @@ Complete set of Playwright Test options is available in the [configuration file]
| `--ui` | Run tests in interactive UI mode. |
| `--ui-host <host>` | Host to serve UI on; specifying this option opens UI in a browser tab. |
| `--ui-port <port>` | Port to serve UI on, 0 for any free port; specifying this option opens UI in a browser tab. |
| `-u` or `--update-snapshots [mode]` | Update snapshots with actual results. Possible values are "all", "changed", "missing", and "none". Running tests without the flag defaults to "missing"; running tests with the flag but without a value defaults to "changed". |
| `--update-source-method [mode]` | Update snapshots with actual results. Possible values are "patch" (default), "3way" and "overwrite". "Patch" creates a unified diff file that can be used to update the source code later. "3way" generates merge conflict markers in source code. "Overwrite" overwrites the source code with the new snapshot values.|
| `-u` or `--update-snapshots [mode]` | Update snapshots with actual results. Possible values are "all", "changed", "missing", and "none". Not passing defaults to "missing"; passing without a value defaults to "changed". |
| `-j <workers>` or `--workers <workers>` | Number of concurrent workers or percentage of logical CPU cores, use 1 to run in a single worker (default: 50%). |
| `-x` | Stop after the first failure. |

View file

@ -853,14 +853,6 @@ export default defineConfig({
});
```
### How do I use CSS imports?
If you have a component that imports CSS, Vite will handle it automatically. You can also use CSS pre-processors such as Sass, Less, or Stylus, and Vite will handle them as well without any additional configuration. However, corresponding CSS pre-processor needs to be installed.
Vite has a hard requirement that all CSS Modules are named `*.module.[css extension]`. If you have a custom build config for your project normally and have imports of the form `import styles from 'styles.css'` you must rename your files to properly indicate they are to be treated as modules. You could also write a Vite plugin to handle this for you.
Check [Vite documentation](https://vite.dev/guide/features#css) for more details.
### How can I test components that uses Pinia?
Pinia needs to be initialized in `playwright/index.{js,ts,jsx,tsx}`. If you do this inside a `beforeMount` hook, the `initialState` can be overwritten on a per-test basis:

View file

@ -35,7 +35,7 @@ export default defineConfig({
use: {
// Base URL to use in actions like `await page.goto('/')`.
baseURL: 'http://localhost:3000',
baseURL: 'http://127.0.0.1:3000',
// Collect trace when retrying the failed test.
trace: 'on-first-retry',
@ -50,7 +50,7 @@ export default defineConfig({
// Run your local dev server before starting the tests.
webServer: {
command: 'npm run start',
url: 'http://localhost:3000',
url: 'http://127.0.0.1:3000',
reuseExistingServer: !process.env.CI,
},
});

View file

@ -407,8 +407,8 @@ Automatic fixtures are set up for each test/worker, even when the test does not
Here is an example fixture that automatically attaches debug logs when the test fails, so we can later review the logs in the reporter. Note how it uses [TestInfo] object that is available in each test/fixture to retrieve metadata about the test being run.
```js title="my-test.ts"
import debug from 'debug';
import fs from 'fs';
import * as debug from 'debug';
import * as fs from 'fs';
import { test as base } from '@playwright/test';
export const test = base.extend<{ saveLogs: void }>({

View file

@ -50,14 +50,6 @@ Start time of this particular test step.
List of steps inside this step.
## property: TestStep.annotations
* since: v1.51
- type: <[Array]<[Object]>>
- `type` <[string]> Annotation type, for example `'skip'`.
- `description` ?<[string]> Optional description.
The list of annotations applicable to the current test step.
## property: TestStep.attachments
* since: v1.50
- type: <[Array]<[Object]>>

View file

@ -18,13 +18,12 @@ UI Mode lets you explore, run, and debug tests with a time travel experience com
To open UI mode, run the following command in your terminal:
```bash
npx playwright test --ui
```
```bash
npx playwright test --ui
```
## Running your tests
Once you launch UI Mode you will see a list of all your test files. You can run all your tests by clicking the triangle icon in the sidebar. You can also run a single test file, a block of tests or a single test by hovering over the name and clicking on the triangle next to it.
Once you launch UI Mode you will see a list of all your test files. You can run all your tests by clicking the triangle icon in the sidebar. You can also run a single test file, a block of tests or a single test by hovering over the name and clicking on the triangle next to it.
![running tests in ui mode](https://github.com/microsoft/playwright/assets/13063165/6b87712f-64a5-4d73-a91d-6562b864712c)
@ -34,15 +33,17 @@ Filter tests by text or `@tag` or by passed, failed or skipped tests. You can al
![filtering tests in ui mode](https://github.com/microsoft/playwright/assets/13063165/6f05e589-036d-45d5-9078-38134e1261e4)
## Timeline view
At the top of the trace you can see a timeline view of your test with different colors to highlight navigation and actions. Hover back and forth to see an image snapshot for each action. Double click on an action to see the time range for that action. You can use the slider in the timeline to increase the actions selected and these will be shown in the Actions tab and all console logs and network logs will be filtered to only show the logs for the actions selected.
![timeline view in ui mode](https://github.com/microsoft/playwright/assets/13063165/811a9985-32aa-4a3e-9869-de32053cf468)
## Actions
In the Actions tab you can see what locator was used for every action and how long each one took to run. Hover over each action of your test and visually see the change in the DOM snapshot. Go back and forward in time and click an action to inspect and debug. Use the Before and After tabs to visually see what happened before and after the action.
In the Actions tab you can see what locator was used for every action and how long each one took to run. Hover over each action of your test and visually see the change in the DOM snapshot. Go back and forward in time and click an action to inspect and debug. Use the Before and After tabs to visually see what happened before and after the action.
![use before and after actions in ui mode](https://github.com/microsoft/playwright/assets/13063165/7b22fab5-7346-4b98-8fdd-a78ed280647f)
## Pop out and inspect the DOM
@ -59,7 +60,7 @@ Click on the pick locator button and hover over the DOM snapshot to see the loca
## Source
As you hover over each action of your test the line of code for that action is highlighted in the source panel. The button "Open in VSCode" is at the top-right of this section. Upon clicking the button, it will open your test in VS Code right at the line of code that you clicked on.
As you hover over each action of your test the line of code for that action is highlighted in the source panel.
![showing source code of tests in ui mode](https://github.com/microsoft/playwright/assets/13063165/49b9fa2a-8a57-4044-acaa-0a2ea4784c5c)
@ -107,7 +108,7 @@ Next to the Actions tab you will find the Metadata tab which will show you more
## Watch mode
Next to the name of each test in the sidebar you will find an eye icon. Clicking on the icon will activate watch mode which will re-run the test when you make changes to it. You can watch a number of tests at the same time be clicking the eye icon next to each one or all tests by clicking the eye icon at the top of the sidebar.
Next to the name of each test in the sidebar you will find an eye icon. Clicking on the icon will activate watch mode which will re-run the test when you make changes to it. You can watch a number of tests at the same time be clicking the eye icon next to each one or all tests by clicking the eye icon at the top of the sidebar. If you are using VS Code then you can easily open your test by clicking on the file icon next to the eye icon. This will open your test in VS Code right at the line of code that you clicked on.
![watch mode in ui mode](https://github.com/microsoft/playwright/assets/13063165/20d7d44c-b52d-43ff-8871-8b828671f3da)

View file

@ -17,7 +17,7 @@ import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
// Base URL to use in actions like `await page.goto('/')`.
baseURL: 'http://localhost:3000',
baseURL: 'http://127.0.0.1:3000',
// Populates context with given storage state.
storageState: 'state.json',

View file

@ -18,7 +18,7 @@ export default defineConfig({
// Run your local dev server before starting the tests
webServer: {
command: 'npm run start',
url: 'http://localhost:3000',
url: 'http://127.0.0.1:3000',
reuseExistingServer: !process.env.CI,
stdout: 'ignore',
stderr: 'pipe',
@ -52,7 +52,7 @@ export default defineConfig({
// Run your local dev server before starting the tests
webServer: {
command: 'npm run start',
url: 'http://localhost:3000',
url: 'http://127.0.0.1:3000',
reuseExistingServer: !process.env.CI,
timeout: 120 * 1000,
},
@ -63,7 +63,7 @@ export default defineConfig({
It is also recommended to specify the `baseURL` in the `use: {}` section of your config, so that tests can use relative urls and you don't have to specify the full URL over and over again.
When using [`method: Page.goto`], [`method: Page.route`], [`method: Page.waitForURL`], [`method: Page.waitForRequest`], or [`method: Page.waitForResponse`] it takes the base URL in consideration by using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL. For Example, by setting the baseURL to `http://localhost:3000` and navigating to `/login` in your tests, Playwright will run the test using `http://localhost:3000/login`.
When using [`method: Page.goto`], [`method: Page.route`], [`method: Page.waitForURL`], [`method: Page.waitForRequest`], or [`method: Page.waitForResponse`] it takes the base URL in consideration by using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL. For Example, by setting the baseURL to `http://127.0.0.1:3000` and navigating to `/login` in your tests, Playwright will run the test using `http://127.0.0.1:3000/login`.
```js title="playwright.config.ts"
import { defineConfig } from '@playwright/test';
@ -74,11 +74,11 @@ export default defineConfig({
// Run your local dev server before starting the tests
webServer: {
command: 'npm run start',
url: 'http://localhost:3000',
url: 'http://127.0.0.1:3000',
reuseExistingServer: !process.env.CI,
},
use: {
baseURL: 'http://localhost:3000',
baseURL: 'http://127.0.0.1:3000',
},
});
```
@ -89,7 +89,7 @@ Now you can use a relative path when navigating the page:
import { test } from '@playwright/test';
test('test', async ({ page }) => {
// This will navigate to http://localhost:3000/login
// This will navigate to http://127.0.0.1:3000/login
await page.goto('./login');
});
```
@ -106,19 +106,19 @@ export default defineConfig({
webServer: [
{
command: 'npm run start',
url: 'http://localhost:3000',
url: 'http://127.0.0.1:3000',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
{
command: 'npm run backend',
url: 'http://localhost:3333',
url: 'http://127.0.0.1:3333',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
}
],
use: {
baseURL: 'http://localhost:3000',
baseURL: 'http://127.0.0.1:3000',
},
});
```

View file

@ -1,13 +1,19 @@
---
id: touch-events
title: "Emulating legacy touch events"
title: "Emulating touch events"
---
## Introduction
Web applications that handle [touch events](https://developer.mozilla.org/en-US/docs/Web/API/Touch_events) to respond to gestures like swipe, pinch, and tap can be tested by manually dispatching [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)s to the page. The examples below demonstrate how to use [`method: Locator.dispatchEvent`] and pass [Touch](https://developer.mozilla.org/en-US/docs/Web/API/Touch) points as arguments.
Mobile web sites may listen to [touch events](https://developer.mozilla.org/en-US/docs/Web/API/Touch_events) and react to user touch gestures such as swipe, pinch, tap etc. To test this functionality you can manually generate [TouchEvent]s in the page context using [`method: Locator.evaluate`].
### Emulating pan gesture
If your web application relies on [pointer events](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events) instead of touch events, you can use [`method: Locator.click`] and raw [`Mouse`] events to simulate a single-finger touch, and this will trigger all the same pointer events.
### Dispatching TouchEvent
You can dispatch touch events to the page using [`method: Locator.dispatchEvent`]. [Touch](https://developer.mozilla.org/en-US/docs/Web/API/Touch) points can be passed as arguments, see examples below.
#### Emulating pan gesture
In the example below, we emulate pan gesture that is expected to move the map. The app under test only uses `clientX/clientY` coordinates of the touch point, so we initialize just that. In a more complex scenario you may need to also set `pageX/pageY/screenX/screenY`, if your app needs them.
@ -63,7 +69,7 @@ test(`pan gesture to move the map`, async ({ page }) => {
});
```
### Emulating pinch gesture
#### Emulating pinch gesture
In the example below, we emulate pinch gesture, i.e. two touch points moving closer to each other. It is expected to zoom out the map. The app under test only uses `clientX/clientY` coordinates of touch points, so we initialize just that. In a more complex scenario you may need to also set `pageX/pageY/screenX/screenY`, if your app needs them.

View file

@ -1,95 +0,0 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { fixupConfigRules } from '@eslint/compat';
import { FlatCompat } from '@eslint/eslintrc';
import js from '@eslint/js';
import typescriptEslint from '@typescript-eslint/eslint-plugin';
import tsParser from '@typescript-eslint/parser';
import notice from 'eslint-plugin-notice';
import path from 'path';
import { fileURLToPath } from 'url';
import stylistic from '@stylistic/eslint-plugin';
import { baseRules } from './eslint.config.mjs';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
allConfig: js.configs.all
});
const baseConfig = fixupConfigRules(compat.extends('plugin:react/recommended', 'plugin:react-hooks/recommended'));
const plugins = {
'@stylistic': stylistic,
'@typescript-eslint': typescriptEslint,
notice,
};
const ignores = [
'.github/',
'*.js',
'**/.cache/',
'**/*.d.ts',
'**/dist/**',
'index.d.ts',
'node_modules/',
'output/',
'packages/*/lib/',
'test-results/',
'tests/',
'utils/',
];
export default [
{ ignores },
{
plugins,
settings: {
react: { version: 'detect' },
}
},
...baseConfig,
packageSection('html-reporter'),
packageSection('recorder'),
packageSection('trace-viewer'),
];
function packageSection(packageName) {
return {
files: [
`packages/${packageName}/src/**/*.ts`,
`packages/${packageName}/src/**/*.tsx`,
`packages/web/src/**/*.ts`,
`packages/web/src/**/*.tsx`,
],
languageOptions: {
parser: tsParser,
ecmaVersion: 9,
sourceType: 'module',
parserOptions: {
project: path.join(__dirname, 'packages', packageName, 'tsconfig.json'),
},
},
rules: {
...baseRules,
'no-console': 2,
}
};
}

View file

@ -1,292 +0,0 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import typescriptEslint from '@typescript-eslint/eslint-plugin';
import tsParser from '@typescript-eslint/parser';
import notice from 'eslint-plugin-notice';
import path from 'path';
import { fileURLToPath } from 'url';
import stylistic from '@stylistic/eslint-plugin';
import importRules from 'eslint-plugin-import';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const plugins = {
'@stylistic': stylistic,
'@typescript-eslint': typescriptEslint,
notice,
import: importRules,
};
const ignores = [
'.github/',
'*.js',
'**/.cache/',
'**/*.d.ts',
'index.d.ts',
'node_modules/',
'output/',
'packages/*/lib/',
'packages/html-reporter/**',
'packages/playwright-core/src/generated/*',
'packages/playwright-core/src/third_party/',
'packages/playwright-core/types/*',
'packages/playwright-ct-core/src/generated/*',
'packages/recorder/**',
'packages/trace-viewer/**',
'packages/web/**',
'test-results/',
'tests/assets/',
'tests/components/',
'tests/installation/fixture-scripts/',
'tests/third_party/',
'utils/',
];
export const baseRules = {
'@typescript-eslint/no-unused-vars': [2, { args: 'none', caughtErrors: 'none' }],
/**
* Enforced rules
*/
// syntax preferences
'object-curly-spacing': ['error', 'always'],
'quotes': [2, 'single', {
'avoidEscape': true,
'allowTemplateLiterals': true
}],
'jsx-quotes': [2, 'prefer-single'],
'no-extra-semi': 2,
'@stylistic/semi': [2],
'comma-style': [2, 'last'],
'wrap-iife': [2, 'inside'],
'spaced-comment': [2, 'always', {
'markers': ['*']
}],
'eqeqeq': [2],
'accessor-pairs': [2, {
'getWithoutSet': false,
'setWithoutGet': false
}],
'brace-style': [2, '1tbs', { 'allowSingleLine': true }],
'curly': [2, 'multi-or-nest', 'consistent'],
'new-parens': 2,
'arrow-parens': [2, 'as-needed'],
'prefer-const': 2,
'quote-props': [2, 'consistent'],
'nonblock-statement-body-position': [2, 'below'],
// anti-patterns
'no-var': 2,
'no-with': 2,
'no-multi-str': 2,
'no-caller': 2,
'no-implied-eval': 2,
'no-labels': 2,
'no-new-object': 2,
'no-octal-escape': 2,
'no-self-compare': 2,
'no-shadow-restricted-names': 2,
'no-cond-assign': 2,
'no-debugger': 2,
'no-dupe-keys': 2,
'no-duplicate-case': 2,
'no-empty-character-class': 2,
'no-unreachable': 2,
'no-unsafe-negation': 2,
'radix': 2,
'valid-typeof': 2,
'no-implicit-globals': [2],
'no-unused-expressions': [2, { 'allowShortCircuit': true, 'allowTernary': true, 'allowTaggedTemplates': true }],
'no-proto': 2,
// es2015 features
'require-yield': 2,
'template-curly-spacing': [2, 'never'],
// spacing details
'space-infix-ops': 2,
'space-in-parens': [2, 'never'],
'array-bracket-spacing': [2, 'never'],
'comma-spacing': [2, { 'before': false, 'after': true }],
'keyword-spacing': [2, 'always'],
'space-before-function-paren': [2, {
'anonymous': 'never',
'named': 'never',
'asyncArrow': 'always'
}],
'no-whitespace-before-property': 2,
'keyword-spacing': [2, {
'overrides': {
'if': { 'after': true },
'else': { 'after': true },
'for': { 'after': true },
'while': { 'after': true },
'do': { 'after': true },
'switch': { 'after': true },
'return': { 'after': true }
}
}],
'arrow-spacing': [2, {
'after': true,
'before': true
}],
'@stylistic/func-call-spacing': 2,
'@stylistic/type-annotation-spacing': 2,
// file whitespace
'no-multiple-empty-lines': [2, { 'max': 2, 'maxEOF': 0 }],
'no-mixed-spaces-and-tabs': 2,
'no-trailing-spaces': 2,
'linebreak-style': [process.platform === 'win32' ? 0 : 2, 'unix'],
'indent': [2, 2, { 'SwitchCase': 1, 'CallExpression': { 'arguments': 2 }, 'MemberExpression': 2 }],
'key-spacing': [2, {
'beforeColon': false
}],
'eol-last': 2,
// copyright
'notice/notice': [2, {
'mustMatch': 'Copyright',
'templateFile': path.join(__dirname, 'utils', 'copyright.js'),
}],
// react
'react/react-in-jsx-scope': 0
};
const noFloatingPromisesRules = {
'@typescript-eslint/no-floating-promises': 'error',
};
const noBooleanCompareRules = {
'@typescript-eslint/no-unnecessary-boolean-literal-compare': 2,
};
const noWebGlobalsRules = {
'no-restricted-globals': [
'error',
{ 'name': 'window' },
{ 'name': 'document' },
{ 'name': 'globalThis' },
],
};
const noNodeGlobalsRules = {
'no-restricted-globals': [
'error',
{ 'name': 'process' },
],
};
const importOrderRules = {
'import/order': [2, {
'groups': ['builtin', 'external', 'internal', ['parent', 'sibling'], 'index', 'type'],
'newlines-between': 'always',
}],
'import/consistent-type-specifier-style': [2, 'prefer-top-level']
};
const languageOptions = {
parser: tsParser,
ecmaVersion: 9,
sourceType: 'module',
};
const languageOptionsWithTsConfig = {
parser: tsParser,
ecmaVersion: 9,
sourceType: 'module',
parserOptions: {
project: path.join(__dirname, 'tsconfig.json'),
},
};
export default [{
ignores,
}, {
files: ['**/*.ts'],
plugins,
languageOptions,
rules: baseRules,
}, {
files: ['packages/**/*.ts'],
languageOptions: languageOptionsWithTsConfig,
rules: {
'no-console': 2,
'no-restricted-properties': [2, {
'object': 'process',
'property': 'exit',
'message': 'Please use gracefullyProcessExitDoNotHang function to exit the process.',
}],
}
}, {
files: [
'packages/**/*.ts',
],
rules: {
...importOrderRules
},
}, {
files: ['packages/playwright/**/*.ts'],
rules: {
...noFloatingPromisesRules,
}
}, {
files: ['packages/playwright/src/reporters/**/*.ts'],
languageOptions: languageOptionsWithTsConfig,
rules: {
'no-console': 'off'
}
}, {
files: [
'packages/playwright-core/src/server/injected/**/*.ts',
'packages/playwright-core/src/server/isomorphic/**/*.ts',
'packages/playwright-core/src/utils/isomorphic/**/*.ts',
],
languageOptions: languageOptionsWithTsConfig,
rules: {
...noWebGlobalsRules,
...noFloatingPromisesRules,
...noBooleanCompareRules,
}
}, {
files: [
'packages/playwright-core/src/client/**/*.ts',
'packages/playwright-core/src/protocol/**/*.ts',
'packages/playwright-core/src/utils/**/*.ts',
],
languageOptions: languageOptionsWithTsConfig,
rules: {
...noNodeGlobalsRules,
...noFloatingPromisesRules,
...noBooleanCompareRules,
}
}, {
files: ['tests/**/*.spec.js', 'tests/**/*.ts'],
languageOptions: {
parser: tsParser,
ecmaVersion: 9,
sourceType: 'module',
parserOptions: {
project: path.join(__dirname, 'tests', 'tsconfig.json'),
},
},
rules: {
...noFloatingPromisesRules,
}
}];

7090
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
{
"name": "playwright-internal",
"private": true,
"version": "1.51.0-next",
"version": "1.50.1",
"description": "A high-level API to automate web browsers",
"repository": {
"type": "git",
@ -30,14 +30,14 @@
"ttest": "node ./tests/playwright-test/stable-test-runner/node_modules/@playwright/test/cli test --config=tests/playwright-test/playwright.config.ts",
"ct": "playwright test tests/components/test-all.spec.js --reporter=list",
"test": "playwright test --config=tests/library/playwright.config.ts",
"eslint": "eslint --cache && eslint -c eslint-react.config.mjs",
"eslint": "eslint --cache --report-unused-disable-directives --ext ts,tsx,js,jsx,mjs .",
"tsc": "tsc -p . && tsc -p packages/html-reporter/",
"build-installer": "babel -s --extensions \".ts\" --out-dir packages/playwright-core/lib/utils/ packages/playwright-core/src/utils",
"doc": "node utils/doclint/cli.js",
"lint": "npm run eslint && npm run tsc && npm run doc && npm run check-deps && node utils/generate_channels.js && node utils/generate_types/ && npm run lint-tests && npm run test-types && npm run lint-packages",
"lint-packages": "node utils/workspace.js --ensure-consistent",
"lint-tests": "node utils/lint_tests.js",
"flint": "concurrently \"npm run eslint\" \"npm run tsc\" \"npm run doc\" \"npm run check-deps\" \"node utils/generate_channels.js\" \"node utils/generate_types/\" \"npm run lint-tests\" \"npm run test-types\" \"npm run lint-packages\" \"node utils/doclint/linting-code-snippets/cli.js --js-only\"",
"flint": "concurrently \"npm run eslint\" \"npm run tsc\" \"npm run doc\" \"npm run check-deps\" \"node utils/generate_channels.js\" \"node utils/generate_types/\" \"npm run lint-tests\" \"npm run test-types\" \"npm run lint-packages\"",
"clean": "node utils/build/clean.js",
"build": "node utils/build/build.js",
"watch": "node utils/build/build.js --watch --lint",
@ -62,10 +62,6 @@
"@babel/plugin-transform-optional-chaining": "^7.23.4",
"@babel/plugin-transform-typescript": "^7.23.6",
"@babel/preset-react": "^7.23.3",
"@eslint/compat": "^1.2.6",
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^9.19.0",
"@stylistic/eslint-plugin": "^3.0.1",
"@types/babel__core": "^7.20.2",
"@types/codemirror": "^5.60.7",
"@types/formidable": "^2.0.4",
@ -75,9 +71,9 @@
"@types/react-dom": "^18.0.5",
"@types/ws": "^8.5.3",
"@types/xml2js": "^0.4.9",
"@typescript-eslint/eslint-plugin": "^8.23.0",
"@typescript-eslint/parser": "^8.23.0",
"@typescript-eslint/utils": "^8.23.0",
"@typescript-eslint/eslint-plugin": "^7.15.0",
"@typescript-eslint/parser": "^7.15.0",
"@typescript-eslint/utils": "^7.15.0",
"@vitejs/plugin-basic-ssl": "^1.1.0",
"@vitejs/plugin-react": "^4.2.1",
"@zip.js/zip.js": "^2.7.29",
@ -89,25 +85,24 @@
"cross-env": "^7.0.3",
"dotenv": "^16.4.5",
"electron": "^30.1.2",
"esbuild": "^0.25.0",
"eslint": "^9.19.0",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-notice": "^1.0.0",
"eslint-plugin-react": "^7.37.4",
"eslint-plugin-react-hooks": "^5.1.0",
"esbuild": "^0.18.11",
"eslint": "^8.55.0",
"eslint-plugin-internal-playwright": "file:utils/eslint-plugin-internal-playwright",
"eslint-plugin-notice": "^0.9.10",
"eslint-plugin-react": "^7.35.0",
"eslint-plugin-react-hooks": "^4.6.2",
"formidable": "^2.1.1",
"immutable": "^4.3.7",
"license-checker": "^25.0.1",
"markdown-to-jsx": "^7.7.3",
"mime": "^3.0.0",
"node-stream-zip": "^1.15.0",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"ssim.js": "^3.5.0",
"typescript": "^5.7.3",
"vite": "^6.1.0",
"typescript": "^5.7.2",
"vite": "^5.4.14",
"ws": "^8.17.1",
"xml2js": "^0.5.0",
"yaml": "2.6.0"
"yaml": "^2.6.0"
}
}

21
packages/.eslintrc.js Normal file
View file

@ -0,0 +1,21 @@
module.exports = {
"extends": "../.eslintrc.js",
/**
* ESLint rules
*
* All available rules: http://eslint.org/docs/rules/
*
* Rules take the following form:
* "rule-name", [severity, { opts }]
* Severity: 2 == error, 1 == warning, 0 == off.
*/
"rules": {
"no-console": 2,
"no-debugger": 2,
"no-restricted-properties": [2, {
"object": "process",
"property": "exit",
"message": "Please use gracefullyProcessExitDoNotHang function to exit the process.",
}],
}
};

View file

@ -15,7 +15,7 @@
-->
<!DOCTYPE html>
<html style='scrollbar-gutter: stable both-edges;'>
<html>
<head>
<meta charset='UTF-8'>
<meta name='color-scheme' content='dark light'>

View file

@ -23,11 +23,7 @@ export default defineConfig({
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
snapshotPathTemplate: '{testDir}/__screenshots__/{projectName}/{testFilePath}/{arg}{ext}',
reporter: process.env.CI ? [
['blob', { fileName: `${process.env.PWTEST_BOT_NAME}.zip` }],
] : [
['html']
],
reporter: process.env.CI ? 'blob' : 'html',
use: {
ctPort: 3101,
ctViteConfig: {

View file

@ -267,26 +267,6 @@ article, aside, details, figcaption, figure, footer, header, main, menu, nav, se
flex: none;
}
.button {
flex: none;
height: 24px;
border: 1px solid var(--color-btn-border);
outline: none;
color: var(--color-btn-text);
background: var(--color-btn-bg);
padding: 4px;
cursor: pointer;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 4px;
}
.button:not(:disabled):hover {
border-color: var(--color-btn-hover-border);
background-color: var(--color-btn-hover-bg);
}
@media only screen and (max-width: 600px) {
.subnav-item, .form-control {
border-radius: 0 !important;

View file

@ -39,7 +39,7 @@ export const CopyToClipboard: React.FunctionComponent<CopyToClipboardProps> = ({
});
}, [value]);
const iconElement = icon === 'check' ? icons.check() : icon === 'cross' ? icons.cross() : icons.copy();
return <button className='copy-icon' title='Copy to clipboard' aria-label='Copy to clipboard' onClick={handleCopy}>{iconElement}</button>;
return <button className='copy-icon' aria-label='Copy to clipboard' onClick={handleCopy}>{iconElement}</button>;
};
type CopyToClipboardContainerProps = CopyToClipboardProps & {

View file

@ -69,6 +69,22 @@ export const blank = () => {
return <svg className='octicon' viewBox='0 0 16 16' version='1.1' width='16' height='16' aria-hidden='true'></svg>;
};
export const externalLink = () => {
return <svg className='octicon' viewBox='0 0 16 16' width='16' height='16'><path fillRule='evenodd' d='M10.604 1h4.146a.25.25 0 01.25.25v4.146a.25.25 0 01-.427.177L13.03 4.03 9.28 7.78a.75.75 0 01-1.06-1.06l3.75-3.75-1.543-1.543A.25.25 0 0110.604 1zM3.75 2A1.75 1.75 0 002 3.75v8.5c0 .966.784 1.75 1.75 1.75h8.5A1.75 1.75 0 0014 12.25v-3.5a.75.75 0 00-1.5 0v3.5a.25.25 0 01-.25.25h-8.5a.25.25 0 01-.25-.25v-8.5a.25.25 0 01.25-.25h3.5a.75.75 0 000-1.5h-3.5z'></path></svg>;
};
export const calendar = () => {
return <svg className='octicon' viewBox='0 0 16 16' width='16' height='16'><path fillRule='evenodd' d='M4.75 0a.75.75 0 01.75.75V2h5V.75a.75.75 0 011.5 0V2h1.25c.966 0 1.75.784 1.75 1.75v10.5A1.75 1.75 0 0113.25 16H2.75A1.75 1.75 0 011 14.25V3.75C1 2.784 1.784 2 2.75 2H4V.75A.75.75 0 014.75 0zm0 3.5h8.5a.25.25 0 01.25.25V6h-11V3.75a.25.25 0 01.25-.25h2zm-2.25 4v6.75c0 .138.112.25.25.25h10.5a.25.25 0 00.25-.25V7.5h-11z'></path></svg>;
};
export const person = () => {
return <svg className='octicon' viewBox='0 0 16 16' width='16' height='16'><path fillRule='evenodd' d='M10.5 5a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0zm.061 3.073a4 4 0 10-5.123 0 6.004 6.004 0 00-3.431 5.142.75.75 0 001.498.07 4.5 4.5 0 018.99 0 .75.75 0 101.498-.07 6.005 6.005 0 00-3.432-5.142z'></path></svg>;
};
export const commit = () => {
return <svg className='octicon' viewBox='0 0 16 16' width='16' height='16'><path fillRule='evenodd' d='M10.5 7.75a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0zm1.43.75a4.002 4.002 0 01-7.86 0H.75a.75.75 0 110-1.5h3.32a4.001 4.001 0 017.86 0h3.32a.75.75 0 110 1.5h-3.32z'></path></svg>;
};
export const image = () => {
return <svg className='octicon' viewBox='0 0 48 48' version='1.1' width='20' height='20' aria-hidden='true'>
<path xmlns='http://www.w3.org/2000/svg' d='M11.85 32H36.2l-7.35-9.95-6.55 8.7-4.6-6.45ZM7 40q-1.2 0-2.1-.9Q4 38.2 4 37V11q0-1.2.9-2.1Q5.8 8 7 8h34q1.2 0 2.1.9.9.9.9 2.1v26q0 1.2-.9 2.1-.9.9-2.1.9Zm0-29v26-26Zm34 26V11H7v26Z'/>

View file

@ -1,67 +0,0 @@
/*
Copyright (c) Microsoft Corporation.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
.metadata-toggle {
cursor: pointer;
user-select: none;
margin-left: 5px;
color: var(--color-fg-default);
}
.metadata-view {
border: 1px solid var(--color-border-default);
border-radius: 6px;
margin-top: 8px;
}
.metadata-view .metadata-section {
margin: 8px 10px 8px 32px;
}
.metadata-view span:not(.copy-button-container),
.metadata-view a {
display: inline-block;
line-height: 24px;
}
.metadata-properties {
display: flex;
flex-direction: column;
align-items: normal;
gap: 8px;
}
.metadata-properties > div {
height: 24px;
}
.metadata-separator {
height: 1px;
border-bottom: 1px solid var(--color-border-default);
}
.metadata-view a {
color: var(--color-fg-default);
}
.copyable-property {
white-space: pre;
}
.copyable-property > span {
display: flex;
align-items: center;
}

View file

@ -17,12 +17,21 @@
import * as React from 'react';
import './colors.css';
import './common.css';
import * as icons from './icons';
import { AutoChip } from './chip';
import './reportView.css';
import './theme.css';
import './metadataView.css';
import type { Metadata } from '@playwright/test';
import type { CIInfo, GitCommitInfo, MetadataWithCommitInfo } from '@testIsomorphic/types';
import { CopyToClipboardContainer } from './copyToClipboard';
import { linkifyText } from '@web/renderUtils';
export type Metainfo = {
'revision.id'?: string;
'revision.author'?: string;
'revision.email'?: string;
'revision.subject'?: string;
'revision.timestamp'?: number | Date;
'revision.link'?: string;
'ci.link'?: string;
'timestamp'?: number
};
class ErrorBoundary extends React.Component<React.PropsWithChildren<{}>, { error: Error | null, errorInfo: React.ErrorInfo | null }> {
override state: { error: Error | null, errorInfo: React.ErrorInfo | null } = {
@ -37,12 +46,12 @@ class ErrorBoundary extends React.Component<React.PropsWithChildren<{}>, { error
override render() {
if (this.state.error || this.state.errorInfo) {
return (
<div className='metadata-view p-3'>
<p>An error was encountered when trying to render metadata.</p>
<AutoChip header={'Commit Metainfo Error'} dataTestId='metadata-error'>
<p>An error was encountered when trying to render Commit Metainfo. Please file a GitHub issue to report this error.</p>
<p>
<pre style={{ overflow: 'scroll' }}>{this.state.error?.message}<br/>{this.state.error?.stack}<br/>{this.state.errorInfo?.componentStack}</pre>
</p>
</div>
</AutoChip>
);
}
@ -50,70 +59,79 @@ class ErrorBoundary extends React.Component<React.PropsWithChildren<{}>, { error
}
}
export const MetadataView: React.FC<{ metadata: Metadata }> = params => {
return <ErrorBoundary><InnerMetadataView metadata={params.metadata}/></ErrorBoundary>;
export const MetadataView: React.FC<Metainfo> = metadata => <ErrorBoundary><InnerMetadataView {...metadata} /></ErrorBoundary>;
const InnerMetadataView: React.FC<Metainfo> = metadata => {
if (!Object.keys(metadata).find(k => k.startsWith('revision.') || k.startsWith('ci.')))
return null;
return (
<AutoChip header={
<span>
{metadata['revision.id'] && <span style={{ float: 'right' }}>
{metadata['revision.id'].slice(0, 7)}
</span>}
{metadata['revision.subject'] || 'Commit Metainfo'}
</span>} initialExpanded={false} dataTestId='metadata-chip'>
{metadata['revision.subject'] &&
<MetadataViewItem
testId='revision.subject'
content={<span>{metadata['revision.subject']}</span>}
/>
}
{metadata['revision.id'] &&
<MetadataViewItem
testId='revision.id'
content={<span>{metadata['revision.id']}</span>}
href={metadata['revision.link']}
icon='commit'
/>
}
{(metadata['revision.author'] || metadata['revision.email']) &&
<MetadataViewItem
content={`${metadata['revision.author']} ${metadata['revision.email']}`}
icon='person'
/>
}
{metadata['revision.timestamp'] &&
<MetadataViewItem
testId='revision.timestamp'
content={
<>
{Intl.DateTimeFormat(undefined, { dateStyle: 'full' }).format(metadata['revision.timestamp'])}
{' '}
{Intl.DateTimeFormat(undefined, { timeStyle: 'long' }).format(metadata['revision.timestamp'])}
</>
}
icon='calendar'
/>
}
{metadata['ci.link'] &&
<MetadataViewItem
content='CI/CD Logs'
href={metadata['ci.link']}
icon='externalLink'
/>
}
{metadata['timestamp'] &&
<MetadataViewItem
content={<span style={{ color: 'var(--color-fg-subtle)' }}>
Report generated on {Intl.DateTimeFormat(undefined, { dateStyle: 'full', timeStyle: 'long' }).format(metadata['timestamp'])}
</span>}></MetadataViewItem>
}
</AutoChip>
);
};
const InnerMetadataView: React.FC<{ metadata: Metadata }> = params => {
const commitInfo = params.metadata as MetadataWithCommitInfo;
const otherEntries = Object.entries(params.metadata).filter(([key]) => !ignoreKeys.has(key));
const hasMetadata = commitInfo.ci || commitInfo.gitCommit || otherEntries.length > 0;
if (!hasMetadata)
return;
return <div className='metadata-view'>
{commitInfo.ci && !commitInfo.gitCommit && <CiInfoView info={commitInfo.ci}/>}
{commitInfo.gitCommit && <GitCommitInfoView ci={commitInfo.ci} commit={commitInfo.gitCommit}/>}
{otherEntries.length > 0 && (commitInfo.gitCommit || commitInfo.ci) && <div className='metadata-separator' />}
<div className='metadata-section metadata-properties' role='list'>
{otherEntries.map(([propertyName, value]) => {
const valueString = typeof value !== 'object' || value === null || value === undefined ? String(value) : JSON.stringify(value);
const trimmedValue = valueString.length > 1000 ? valueString.slice(0, 1000) + '\u2026' : valueString;
return (
<div key={propertyName} className='copyable-property' role='listitem'>
<CopyToClipboardContainer value={valueString}>
<span style={{ fontWeight: 'bold' }} title={propertyName}>{propertyName}</span>
: <span title={trimmedValue}>{linkifyText(trimmedValue)}</span>
</CopyToClipboardContainer>
</div>
);
})}
const MetadataViewItem: React.FC<{ content: JSX.Element | string; icon?: keyof typeof icons, href?: string, testId?: string }> = ({ content, icon, href, testId }) => {
return (
<div className='my-1 hbox' data-testid={testId} >
<div className='mr-2'>
{icons[icon || 'blank']()}
</div>
<div style={{ flex: 1 }}>
{href ? <a href={href} target='_blank' rel='noopener noreferrer'>{content}</a> : content}
</div>
</div>
</div>;
};
const CiInfoView: React.FC<{ info: CIInfo }> = ({ info }) => {
const title = info.prTitle || `Commit ${info.commitHash}`;
const link = info.prHref || info.commitHref;
return <div className='metadata-section' role='list'>
<div role='listitem'>
<a href={link} target='_blank' rel='noopener noreferrer' title={title}>{title}</a>
</div>
</div>;
};
const GitCommitInfoView: React.FC<{ ci?: CIInfo, commit: GitCommitInfo }> = ({ ci, commit }) => {
const title = ci?.prTitle || commit.subject;
const link = ci?.prHref || ci?.commitHref;
const email = ` <${commit.author.email}>`;
const author = `${commit.author.name}${email}`;
const shortTimestamp = Intl.DateTimeFormat(undefined, { dateStyle: 'medium' }).format(commit.committer.time);
const longTimestamp = Intl.DateTimeFormat(undefined, { dateStyle: 'full', timeStyle: 'long' }).format(commit.committer.time);
return <div className='metadata-section' role='list'>
<div role='listitem'>
{link && <a href={link} target='_blank' rel='noopener noreferrer' title={title}>{title}</a>}
{!link && <span title={title}>{title}</span>}
</div>
<div role='listitem' className='hbox'>
<span className='mr-1'>{author}</span>
<span title={longTimestamp}> on {shortTimestamp}</span>
</div>
</div>;
};
const ignoreKeys = new Set(['ci', 'gitCommit', 'gitDiff', 'actualWorkers']);
export const isMetadataEmpty = (metadata: MetadataWithCommitInfo): boolean => {
const otherEntries = Object.entries(metadata).filter(([key]) => !ignoreKeys.has(key));
return !metadata.ci && !metadata.gitCommit && !otherEntries.length;
);
};

View file

@ -1,29 +0,0 @@
/*
Copyright (c) Microsoft Corporation.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import * as React from 'react';
import type { HTMLReport } from './types';
const HTMLReportContext = React.createContext<HTMLReport | undefined>(undefined);
export function HTMLReportContextProvider({ report, children }: React.PropsWithChildren<{ report: HTMLReport | undefined }>) {
return <HTMLReportContext.Provider value={report}>{children}</HTMLReportContext.Provider>;
}
export function useHTMLReport() {
return React.useContext(HTMLReportContext);
}

View file

@ -23,10 +23,11 @@ import { HeaderView } from './headerView';
import { Route, SearchParamsContext } from './links';
import type { LoadedReport } from './loadedReport';
import './reportView.css';
import type { Metainfo } from './metadataView';
import { MetadataView } from './metadataView';
import { TestCaseView } from './testCaseView';
import { TestFilesHeader, TestFilesView } from './testFilesView';
import './theme.css';
import { HTMLReportContextProvider } from './reportContext';
declare global {
interface Window {
@ -49,7 +50,6 @@ export const ReportView: React.FC<{
const searchParams = React.useContext(SearchParamsContext);
const [expandedFiles, setExpandedFiles] = React.useState<Map<string, boolean>>(new Map());
const [filterText, setFilterText] = React.useState(searchParams.get('q') || '');
const [metadataVisible, setMetadataVisible] = React.useState(false);
const testIdToFileIdMap = React.useMemo(() => {
const map = new Map<string, string>();
@ -73,11 +73,12 @@ export const ReportView: React.FC<{
return result;
}, [report, filter]);
return <HTMLReportContextProvider report={report?.json()}><div className='htmlreport vbox px-4 pb-4'>
return <div className='htmlreport vbox px-4 pb-4'>
<main>
{report?.json() && <HeaderView stats={report.json().stats} filterText={filterText} setFilterText={setFilterText}></HeaderView>}
{report?.json().metadata && <MetadataView {...report?.json().metadata as Metainfo} />}
<Route predicate={testFilesRoutePredicate}>
<TestFilesHeader report={report?.json()} filteredStats={filteredStats} metadataVisible={metadataVisible} toggleMetadataVisible={() => setMetadataVisible(visible => !visible)}/>
<TestFilesHeader report={report?.json()} filteredStats={filteredStats} />
<TestFilesView
tests={filteredTests.files}
expandedFiles={expandedFiles}
@ -89,7 +90,7 @@ export const ReportView: React.FC<{
{!!report && <TestCaseViewLoader report={report} tests={filteredTests.tests} testIdToFileIdMap={testIdToFileIdMap} />}
</Route>
</main>
</div></HTMLReportContextProvider>;
</div>;
};
const TestCaseViewLoader: React.FC<{

View file

@ -50,11 +50,6 @@
line-height: 24px;
}
.test-case-run-duration {
color: var(--color-fg-subtle);
padding-left: 8px;
}
.test-case-path {
flex: none;
align-items: center;

View file

@ -59,7 +59,7 @@ const testCase: TestCase = {
],
tags: [],
outcome: 'expected',
duration: 200,
duration: 10,
ok: true,
results: [result]
};
@ -215,37 +215,3 @@ test('should correctly render prev and next', async ({ mount }) => {
- text: "My test test.spec.ts:42 10ms"
`);
});
const testCaseWithTwoAttempts: TestCase = {
...testCase,
results: [
{
...result,
errors: ['Error message'],
status: 'failed',
duration: 50,
},
{
...result,
duration: 150,
status: 'passed',
},
],
};
test('total duration is selected run duration', async ({ mount, page }) => {
const component = await mount(<TestCaseView projectNames={['chromium', 'webkit']} test={testCaseWithTwoAttempts} prev={undefined} next={undefined} run={0}></TestCaseView>);
await expect(component).toMatchAriaSnapshot(`
- text: "My test test.spec.ts:42 200ms"
- text: "Run 50ms Retry #1 150ms"
`);
await page.locator('.tabbed-pane-tab-label', { hasText: 'Run50ms' }).click();
await expect(component).toMatchAriaSnapshot(`
- text: "My test test.spec.ts:42 200ms"
`);
await page.locator('.tabbed-pane-tab-label', { hasText: 'Retry #1150ms' }).click();
await expect(component).toMatchAriaSnapshot(`
- text: "My test test.spec.ts:42 200ms"
`);
});

View file

@ -77,10 +77,7 @@ export const TestCaseView: React.FC<{
{test && <TabbedPane tabs={
test.results.map((result, index) => ({
id: String(index),
title: <div style={{ display: 'flex', alignItems: 'center' }}>
{statusIcon(result.status)} {retryLabel(index)}
{(test.results.length > 1) && <span className='test-case-run-duration'>{msToString(result.duration)}</span>}
</div>,
title: <div style={{ display: 'flex', alignItems: 'center' }}>{statusIcon(result.status)} {retryLabel(index)}</div>,
render: () => <TestResultView test={test!} result={result} />
})) || []} selectedTab={String(selectedResultIndex)} setSelectedTab={id => setSelectedResultIndex(+id)} />}
</div>;

View file

@ -16,21 +16,18 @@
@import '@web/third_party/vscode/colors.css';
.test-error-container {
.test-error-view {
white-space: pre;
overflow: auto;
flex: none;
padding: 0;
background-color: var(--color-canvas-subtle);
border-radius: 6px;
padding: 16px;
line-height: initial;
margin-bottom: 6px;
}
.test-error-view {
padding: 16px;
}
.test-error-text {
font-family: monospace;
}

View file

@ -19,61 +19,13 @@ import * as React from 'react';
import './testErrorView.css';
import type { ImageDiff } from '@web/shared/imageDiffView';
import { ImageDiffView } from '@web/shared/imageDiffView';
import type { TestResult } from './types';
import { fixTestPrompt } from '@web/components/prompts';
import { useHTMLReport } from './reportContext';
import type { MetadataWithCommitInfo } from '@playwright/isomorphic/types';
export const TestErrorView: React.FC<{
error: string;
testId?: string;
result?: TestResult
}> = ({ error, testId, result }) => {
return (
<CodeSnippet code={error} testId={testId}>
<div style={{ float: 'right', margin: 10 }}>
<PromptButton error={error} result={result} />
</div>
</CodeSnippet>
);
};
export const CodeSnippet = ({ code, children, testId }: React.PropsWithChildren<{ code: string; testId?: string; }>) => {
const html = React.useMemo(() => ansiErrorToHtml(code), [code]);
return (
<div className='test-error-container test-error-text' data-testid={testId}>
{children}
<div className='test-error-view' dangerouslySetInnerHTML={{ __html: html || '' }}></div>
</div>
);
};
const PromptButton: React.FC<{
error: string;
result?: TestResult;
}> = ({ error, result }) => {
const report = useHTMLReport();
const commitInfo = report?.metadata as MetadataWithCommitInfo | undefined;
const prompt = React.useMemo(() => fixTestPrompt(
error,
commitInfo?.gitDiff,
result?.attachments.find(a => a.name === 'pageSnapshot')?.body
), [commitInfo, result, error]);
const [copied, setCopied] = React.useState(false);
return <button
className='button'
style={{ minWidth: 100 }}
onClick={async () => {
await navigator.clipboard.writeText(prompt);
setCopied(true);
setTimeout(() => {
setCopied(false);
}, 3000);
}}>
{copied ? 'Copied' : 'Copy as Prompt'}
</button>;
}> = ({ error, testId }) => {
const html = React.useMemo(() => ansiErrorToHtml(error), [error]);
return <div className='test-error-view test-error-text' data-testid={testId} dangerouslySetInnerHTML={{ __html: html || '' }}></div>;
};
export const TestScreenshotErrorView: React.FC<{

View file

@ -69,11 +69,4 @@
.test-file-test-status-icon {
flex: none;
}
.test-file-header-info {
display: flex;
align-items: center;
gap: 8px;
color: var(--color-fg-subtle);
}

View file

@ -21,8 +21,6 @@ import './testFileView.css';
import { msToString } from './utils';
import { AutoChip } from './chip';
import { TestErrorView } from './testErrorView';
import * as icons from './icons';
import { isMetadataEmpty, MetadataView } from './metadataView';
export const TestFilesView: React.FC<{
tests: TestFileSummary[],
@ -64,25 +62,17 @@ export const TestFilesView: React.FC<{
export const TestFilesHeader: React.FC<{
report: HTMLReport | undefined,
filteredStats?: FilteredStats,
metadataVisible: boolean,
toggleMetadataVisible: () => void,
}> = ({ report, filteredStats, metadataVisible, toggleMetadataVisible }) => {
}> = ({ report, filteredStats }) => {
if (!report)
return null;
return;
return <>
<div className='mx-1' style={{ display: 'flex', marginTop: 10 }}>
<div className='test-file-header-info'>
{!isMetadataEmpty(report.metadata) && <div className='metadata-toggle' role='button' onClick={toggleMetadataVisible} title={metadataVisible ? 'Hide metadata' : 'Show metadata'}>
{metadataVisible ? icons.downArrow() : icons.rightArrow()}Metadata
</div>}
{report.projectNames.length === 1 && !!report.projectNames[0] && <div data-testid='project-name'>Project: {report.projectNames[0]}</div>}
{filteredStats && <div data-testid='filtered-tests-count'>Filtered: {filteredStats.total} {!!filteredStats.total && ('(' + msToString(filteredStats.duration) + ')')}</div>}
</div>
<div className='mt-2 mx-1' style={{ display: 'flex' }}>
{report.projectNames.length === 1 && !!report.projectNames[0] && <div data-testid='project-name' style={{ color: 'var(--color-fg-subtle)' }}>Project: {report.projectNames[0]}</div>}
{filteredStats && <div data-testid='filtered-tests-count' style={{ color: 'var(--color-fg-subtle)', padding: '0 10px' }}>Filtered: {filteredStats.total} {!!filteredStats.total && ('(' + msToString(filteredStats.duration) + ')')}</div>}
<div style={{ flex: 'auto' }}></div>
<div data-testid='overall-time' style={{ color: 'var(--color-fg-subtle)', marginRight: '10px' }}>{report ? new Date(report.startTime).toLocaleString() : ''}</div>
<div data-testid='overall-duration' style={{ color: 'var(--color-fg-subtle)' }}>Total time: {msToString(report.duration ?? 0)}</div>
</div>
{metadataVisible && <MetadataView metadata={report.metadata}/>}
{!!report.errors.length && <AutoChip header='Errors' dataTestId='report-errors'>
{report.errors.map((error, index) => <TestErrorView key={'test-report-error-message-' + index} error={error}></TestErrorView>)}
</AutoChip>}

View file

@ -24,7 +24,7 @@ import { Anchor, AttachmentLink, generateTraceUrl, testResultHref } from './link
import { statusIcon } from './statusIcon';
import type { ImageDiff } from '@web/shared/imageDiffView';
import { ImageDiffView } from '@web/shared/imageDiffView';
import { CodeSnippet, TestErrorView, TestScreenshotErrorView } from './testErrorView';
import { TestErrorView, TestScreenshotErrorView } from './testErrorView';
import * as icons from './icons';
import './testResultView.css';
@ -90,7 +90,7 @@ export const TestResultView: React.FC<{
{errors.map((error, index) => {
if (error.type === 'screenshot')
return <TestScreenshotErrorView key={'test-result-error-message-' + index} errorPrefix={error.errorPrefix} diff={error.diff!} errorSuffix={error.errorSuffix}></TestScreenshotErrorView>;
return <TestErrorView key={'test-result-error-message-' + index} error={error.error!} result={result}></TestErrorView>;
return <TestErrorView key={'test-result-error-message-' + index} error={error.error!}></TestErrorView>;
})}
</AutoChip>}
{!!result.steps.length && <AutoChip header='Test Steps'>
@ -182,7 +182,7 @@ const StepTreeItem: React.FC<{
{step.count > 1 && <> <span className='test-result-counter'>{step.count}</span></>}
{step.location && <span className='test-result-path'> {step.location.file}:{step.location.line}</span>}
</span>} loadChildren={step.steps.length || step.snippet ? () => {
const snippet = step.snippet ? [<CodeSnippet testId='test-snippet' key='line' code={step.snippet} />] : [];
const snippet = step.snippet ? [<TestErrorView testId='test-snippet' key='line' error={step.snippet}/>] : [];
const steps = step.steps.map((s, i) => <StepTreeItem key={i} step={s} depth={depth + 1} result={result} test={test} />);
return snippet.concat(steps);
} : undefined} depth={depth}/>;

View file

@ -20,12 +20,10 @@
"@protocol/*": ["../protocol/src/*"],
"@web/*": ["../web/src/*"],
"@playwright/*": ["../playwright/src/*"],
"@recorder/*": ["../recorder/src/*"],
"@testIsomorphic/*": ["../playwright/src/isomorphic/*"],
"playwright-core/lib/*": ["../playwright-core/src/*"],
"playwright/lib/*": ["../playwright/src/*"],
}
},
"include": ["src", "../web/src"],
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}

View file

@ -17,7 +17,7 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { bundle } from './bundle';
import path from 'path';
import * as path from 'path';
// https://vitejs.dev/config/
export default defineConfig({

View file

@ -1,6 +1,6 @@
{
"name": "@playwright/browser-chromium",
"version": "1.51.0-next",
"version": "1.50.1",
"description": "Playwright package that automatically installs Chromium",
"repository": {
"type": "git",
@ -27,6 +27,6 @@
"install": "node install.js"
},
"dependencies": {
"playwright-core": "1.51.0-next"
"playwright-core": "1.50.1"
}
}

View file

@ -1,6 +1,6 @@
{
"name": "@playwright/browser-firefox",
"version": "1.51.0-next",
"version": "1.50.1",
"description": "Playwright package that automatically installs Firefox",
"repository": {
"type": "git",
@ -27,6 +27,6 @@
"install": "node install.js"
},
"dependencies": {
"playwright-core": "1.51.0-next"
"playwright-core": "1.50.1"
}
}

View file

@ -1,6 +1,6 @@
{
"name": "@playwright/browser-webkit",
"version": "1.51.0-next",
"version": "1.50.1",
"description": "Playwright package that automatically installs WebKit",
"repository": {
"type": "git",
@ -27,6 +27,6 @@
"install": "node install.js"
},
"dependencies": {
"playwright-core": "1.51.0-next"
"playwright-core": "1.50.1"
}
}

View file

@ -1,6 +1,6 @@
{
"name": "playwright-chromium",
"version": "1.51.0-next",
"version": "1.50.1",
"description": "A high-level API to automate Chromium",
"repository": {
"type": "git",
@ -30,6 +30,6 @@
"install": "node install.js"
},
"dependencies": {
"playwright-core": "1.51.0-next"
"playwright-core": "1.50.1"
}
}

View file

@ -1,25 +0,0 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { Browser } from './types/types';
export * from './types/types';
export type Options = {
headless?: boolean;
};
export const connect: (wsEndpoint: string, browserName: string, options: Options) => Promise<Browser>;

View file

@ -1,17 +0,0 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { connect } from './index.js';

View file

@ -1,34 +0,0 @@
{
"name": "@playwright/client",
"private": true,
"version": "1.51.0-next",
"description": "A thin client for Playwright",
"repository": {
"type": "git",
"url": "git+https://github.com/microsoft/playwright.git"
},
"homepage": "https://playwright.dev",
"engines": {
"node": ">=18"
},
"author": {
"name": "Microsoft Corporation"
},
"license": "Apache-2.0",
"exports": {
".": {
"types": "./index.d.ts",
"import": "./index.mjs",
"require": "./index.js",
"default": "./index.js"
},
"./package.json": "./package.json"
},
"scripts": {
"build": "esbuild ./src/index.ts --outdir=lib --format=cjs --bundle --platform=node --target=ES2019",
"watch": "esbuild ./src/index.ts --outdir=lib --format=cjs --bundle --platform=node --target=ES2019 --watch"
},
"dependencies": {
"playwright-core": "1.51.0-next"
}
}

View file

@ -1,40 +0,0 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the 'License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Connection } from '../../playwright-core/src/client/connection';
import { webPlatform } from './webPlatform';
import type { Browser } from '../../playwright-core/src/client/browser';
export type Options = {
headless?: boolean;
};
export async function connect(wsEndpoint: string, browserName: string, options: Options): Promise<Browser> {
const ws = new WebSocket(`${wsEndpoint}?browser=${browserName}&launch-options=${JSON.stringify(options)}`);
await new Promise((f, r) => {
ws.addEventListener('open', f);
ws.addEventListener('error', r);
});
const connection = new Connection(webPlatform);
connection.onmessage = message => ws.send(JSON.stringify(message));
ws.addEventListener('message', message => connection.dispatch(JSON.parse(message.data)));
ws.addEventListener('close', () => connection.close());
const playwright = await connection.initializePlaywright();
return playwright._preLaunchedBrowser();
}

View file

@ -1,48 +0,0 @@
/* eslint-disable no-console */
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { emptyPlatform } from '../../playwright-core/src/client/platform';
import type { Platform } from '../../playwright-core/src/client/platform';
export const webPlatform: Platform = {
...emptyPlatform,
name: 'web',
boxedStackPrefixes: () => [],
calculateSha1: async (text: string) => {
const bytes = new TextEncoder().encode(text);
const hashBuffer = await window.crypto.subtle.digest('SHA-1', bytes);
return Array.from(new Uint8Array(hashBuffer), b => b.toString(16).padStart(2, '0')).join('');
},
createGuid: () => {
return Array.from(window.crypto.getRandomValues(new Uint8Array(16)), b => b.toString(16).padStart(2, '0')).join('');
},
isLogEnabled(name: 'api' | 'channel') {
return true;
},
log(name: 'api' | 'channel', message: string | Error | object) {
console.debug(name, message);
},
showInternalStackFrames: () => true,
};

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,3 @@
module.exports = {
extends: "../../.eslintrc-with-ts-config.js",
};

View file

@ -19,6 +19,7 @@ This project incorporates components from the projects listed below. The origina
- diff@7.0.0 (https://github.com/kpdecker/jsdiff)
- dotenv@16.4.5 (https://github.com/motdotla/dotenv)
- end-of-stream@1.4.4 (https://github.com/mafintosh/end-of-stream)
- escape-string-regexp@2.0.0 (https://github.com/sindresorhus/escape-string-regexp)
- extract-zip@2.0.1 (https://github.com/maxogden/extract-zip)
- fd-slicer@1.1.0 (https://github.com/andrewrk/node-fd-slicer)
- get-stream@5.2.0 (https://github.com/sindresorhus/get-stream)
@ -45,6 +46,7 @@ This project incorporates components from the projects listed below. The origina
- socks-proxy-agent@6.1.1 (https://github.com/TooTallNate/node-socks-proxy-agent)
- socks@2.8.3 (https://github.com/JoshGlazebrook/socks)
- sprintf-js@1.1.3 (https://github.com/alexei/sprintf.js)
- stack-utils@2.0.5 (https://github.com/tapjs/stack-utils)
- wrappy@1.0.2 (https://github.com/npm/wrappy)
- ws@8.17.1 (https://github.com/websockets/ws)
- yaml@2.6.0 (https://github.com/eemeli/yaml)
@ -561,6 +563,20 @@ THE SOFTWARE.
=========================================
END OF end-of-stream@1.4.4 AND INFORMATION
%% escape-string-regexp@2.0.0 NOTICES AND INFORMATION BEGIN HERE
=========================================
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=========================================
END OF escape-string-regexp@2.0.0 AND INFORMATION
%% extract-zip@2.0.1 NOTICES AND INFORMATION BEGIN HERE
=========================================
Copyright (c) 2014 Max Ogden and other contributors
@ -1438,6 +1454,32 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================
END OF sprintf-js@1.1.3 AND INFORMATION
%% stack-utils@2.0.5 NOTICES AND INFORMATION BEGIN HERE
=========================================
The MIT License (MIT)
Copyright (c) Isaac Z. Schlueter <i@izs.me>, James Talmage <james@talmage.io> (github.com/jamestalmage), and Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=========================================
END OF stack-utils@2.0.5 AND INFORMATION
%% wrappy@1.0.2 NOTICES AND INFORMATION BEGIN HERE
=========================================
The ISC License
@ -1555,6 +1597,6 @@ END OF yazl@2.5.1 AND INFORMATION
SUMMARY BEGIN HERE
=========================================
Total Packages: 46
Total Packages: 48
=========================================
END OF SUMMARY

View file

@ -3,43 +3,31 @@
"browsers": [
{
"name": "chromium",
"revision": "1161",
"revision": "1155",
"installByDefault": true,
"browserVersion": "134.0.6998.35"
},
{
"name": "chromium-headless-shell",
"revision": "1161",
"installByDefault": true,
"browserVersion": "134.0.6998.35"
"browserVersion": "133.0.6943.16"
},
{
"name": "chromium-tip-of-tree",
"revision": "1304",
"revision": "1293",
"installByDefault": false,
"browserVersion": "135.0.7021.0"
},
{
"name": "chromium-tip-of-tree-headless-shell",
"revision": "1304",
"installByDefault": false,
"browserVersion": "135.0.7021.0"
"browserVersion": "133.0.6943.0"
},
{
"name": "firefox",
"revision": "1475",
"revision": "1471",
"installByDefault": true,
"browserVersion": "135.0"
"browserVersion": "134.0"
},
{
"name": "firefox-beta",
"revision": "1471",
"revision": "1467",
"installByDefault": false,
"browserVersion": "136.0b4"
"browserVersion": "133.0b9"
},
{
"name": "webkit",
"revision": "2140",
"revision": "2123",
"installByDefault": true,
"revisionOverrides": {
"debian11-x64": "2105",

View file

@ -25,6 +25,7 @@
"retry": "0.12.0",
"signal-exit": "3.0.7",
"socks-proxy-agent": "6.1.1",
"stack-utils": "2.0.5",
"ws": "8.17.1",
"yaml": "^2.6.0"
},
@ -167,7 +168,6 @@
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz",
"integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==",
"license": "MIT",
"engines": {
"node": ">=0.1.90"
}
@ -229,6 +229,14 @@
"url": "https://dotenvx.com"
}
},
"node_modules/escape-string-regexp": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz",
"integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==",
"engines": {
"node": ">=8"
}
},
"node_modules/graceful-fs": {
"version": "4.2.10",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.10.tgz",
@ -410,6 +418,17 @@
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",
"integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="
},
"node_modules/stack-utils": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.5.tgz",
"integrity": "sha512-xrQcmYhOsn/1kX+Vraq+7j4oE2j/6BFscZ0etmYg81xuM8Gq0022Pxb8+IqgOFUIaxHs0KaSb7T1+OegiNrNFA==",
"dependencies": {
"escape-string-regexp": "^2.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/ws": {
"version": "8.17.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz",

View file

@ -26,6 +26,7 @@
"retry": "0.12.0",
"signal-exit": "3.0.7",
"socks-proxy-agent": "6.1.1",
"stack-utils": "2.0.5",
"ws": "8.17.1",
"yaml": "^2.6.0"
},

View file

@ -14,8 +14,6 @@
* limitations under the License.
*/
/* eslint-disable import/order */
import colorsLibrary from 'colors/safe';
export const colors = colorsLibrary;
@ -56,6 +54,9 @@ export const progress = progressLibrary;
export { SocksProxyAgent } from 'socks-proxy-agent';
import StackUtilsLibrary from 'stack-utils';
export const StackUtils = StackUtilsLibrary;
import yamlLibrary from 'yaml';
export const yaml = yamlLibrary;

View file

@ -19,6 +19,7 @@ const semver = currentNodeVersion.split('.');
const [major] = [+semver[0]];
if (major < minimumMajorNodeVersion) {
// eslint-disable-next-line no-console
console.error(
'You are running Node.js ' +
currentNodeVersion +

View file

@ -1,6 +1,6 @@
{
"name": "playwright-core",
"version": "1.51.0-next",
"version": "1.50.1",
"description": "A high-level API to automate web browsers",
"repository": {
"type": "git",
@ -23,15 +23,15 @@
},
"./package.json": "./package.json",
"./lib/outofprocess": "./lib/outofprocess.js",
"./lib/image_tools/stats": "./lib/image_tools/stats.js",
"./lib/image_tools/compare": "./lib/image_tools/compare.js",
"./lib/image_tools/imageChannel": "./lib/image_tools/imageChannel.js",
"./lib/image_tools/colorUtils": "./lib/image_tools/colorUtils.js",
"./lib/cli/program": "./lib/cli/program.js",
"./lib/server/registry/index": "./lib/server/registry/index.js",
"./lib/remote/playwrightServer": "./lib/remote/playwrightServer.js",
"./lib/server": "./lib/server/index.js",
"./lib/server/utils/image_tools/stats": "./lib/server/utils/image_tools/stats.js",
"./lib/server/utils/image_tools/compare": "./lib/server/utils/image_tools/compare.js",
"./lib/server/utils/image_tools/imageChannel": "./lib/server/utils/image_tools/imageChannel.js",
"./lib/server/utils/image_tools/colorUtils": "./lib/server/utils/image_tools/colorUtils.js",
"./lib/server/registry/index": "./lib/server/registry/index.js",
"./lib/utils": "./lib/utils.js",
"./lib/utils": "./lib/utils/index.js",
"./lib/utilsBundle": "./lib/utilsBundle.js",
"./lib/zipBundle": "./lib/zipBundle.js",
"./types/protocol": "./types/protocol.d.ts",

View file

@ -1,27 +1,13 @@
[browserServerImpl.ts]
remote/
server/
server/utils
utils/isomorphic/
utilsBundle.ts
**
[androidServerImpl.ts]
remote/
server/
server/utils
utils/isomorphic/
utilsBundle.ts
**
[inProcessFactory.ts]
**
[inprocess.ts]
utils/
server/utils
[outofprocess.ts]
client/
protocol/
utils/
utils/isomorphic
server/utils

View file

@ -14,14 +14,13 @@
* limitations under the License.
*/
import { PlaywrightServer } from './remote/playwrightServer';
import { createPlaywright } from './server/playwright';
import { createGuid } from './server/utils/crypto';
import { ws } from './utilsBundle';
import type { BrowserServer } from './client/browserType';
import type { LaunchAndroidServerOptions } from './client/types';
import { ws } from './utilsBundle';
import type { WebSocketEventEmitter } from './utilsBundle';
import type { BrowserServer } from './client/browserType';
import { createGuid } from './utils';
import { createPlaywright } from './server/playwright';
import { PlaywrightServer } from './remote/playwrightServer';
export class AndroidServerLauncherImpl {
async launchServer(options: LaunchAndroidServerOptions = {}): Promise<BrowserServer> {

View file

@ -14,19 +14,19 @@
* limitations under the License.
*/
import { SocksProxy } from './server/utils/socksProxy';
import { PlaywrightServer } from './remote/playwrightServer';
import { helper } from './server/helper';
import type { LaunchServerOptions, Logger } from './client/types';
import { ws } from './utilsBundle';
import type { WebSocketEventEmitter } from './utilsBundle';
import type { BrowserServerLauncher, BrowserServer } from './client/browserType';
import { envObjectToArray } from './client/clientHelper';
import { createGuid } from './utils';
import type { ProtocolLogger } from './server/types';
import { serverSideCallMetadata } from './server/instrumentation';
import { createPlaywright } from './server/playwright';
import { createGuid } from './server/utils/crypto';
import { rewriteErrorMessage } from './utils/isomorphic/stackTrace';
import { ws } from './utilsBundle';
import type { BrowserServer, BrowserServerLauncher } from './client/browserType';
import type { LaunchServerOptions, Logger, Env } from './client/types';
import type { ProtocolLogger } from './server/types';
import type { WebSocketEventEmitter } from './utilsBundle';
import { PlaywrightServer } from './remote/playwrightServer';
import { helper } from './server/helper';
import { rewriteErrorMessage } from './utils/stackTrace';
import { SocksProxy } from './common/socksProxy';
export class BrowserServerLauncherImpl implements BrowserServerLauncher {
private _browserName: 'chromium' | 'firefox' | 'webkit' | 'bidiFirefox' | 'bidiChromium';
@ -84,12 +84,3 @@ function toProtocolLogger(logger: Logger | undefined): ProtocolLogger | undefine
logger.log('protocol', 'verbose', (direction === 'send' ? 'SEND ► ' : '◀ RECV ') + JSON.stringify(message), [], {});
} : undefined;
}
function envObjectToArray(env: Env): { name: string, value: string }[] {
const result: { name: string, value: string }[] = [];
for (const name in env) {
if (!Object.is(env[name], undefined))
result.push({ name, value: String(env[name]) });
}
return result;
}

View file

@ -1,11 +1,11 @@
[*]
../../
../client
../common
../debug/injected
../generated/
../server/
../server/injected/
../server/trace
../server/utils
../utils
../utilsBundle.ts

View file

@ -17,15 +17,13 @@
/* eslint-disable no-console */
import fs from 'fs';
import * as playwright from '../..';
import { PipeTransport } from '../server/utils/pipeTransport';
import { PlaywrightServer } from '../remote/playwrightServer';
import { DispatcherConnection, PlaywrightDispatcher, RootDispatcher, createPlaywright } from '../server';
import { gracefullyProcessExitDoNotHang } from '../server/utils/processLauncher';
import type { BrowserType } from '../client/browserType';
import type { LaunchServerOptions } from '../client/types';
import { createPlaywright, DispatcherConnection, RootDispatcher, PlaywrightDispatcher } from '../server';
import { PipeTransport } from '../protocol/transport';
import { PlaywrightServer } from '../remote/playwrightServer';
import { gracefullyProcessExitDoNotHang } from '../utils/processLauncher';
export function printApiJson() {
// Note: this file is generated by build-playwright-driver.sh

View file

@ -19,26 +19,22 @@
import fs from 'fs';
import os from 'os';
import path from 'path';
import * as playwright from '../..';
import { launchBrowserServer, printApiJson, runDriver, runServer } from './driver';
import { registry, writeDockerVersion } from '../server';
import { gracefullyProcessExitDoNotHang, isLikelyNpxGlobal } from '../utils';
import { runTraceInBrowser, runTraceViewerApp } from '../server/trace/viewer/traceViewer';
import { assert, getPackageManagerExecCommand } from '../utils';
import { wrapInASCIIBox } from '../server/utils/ascii';
import { dotenv, program } from '../utilsBundle';
import type { Browser } from '../client/browser';
import type { BrowserContext } from '../client/browserContext';
import type { BrowserType } from '../client/browserType';
import type { Page } from '../client/page';
import type { BrowserContextOptions, LaunchOptions } from '../client/types';
import type { Executable } from '../server';
import type { TraceViewerServerOptions } from '../server/trace/viewer/traceViewer';
import type { Command } from '../utilsBundle';
import { program, dotenv } from '../utilsBundle';
export { program } from '../utilsBundle';
import { runDriver, runServer, printApiJson, launchBrowserServer } from './driver';
import { runTraceInBrowser, runTraceViewerApp } from '../server/trace/viewer/traceViewer';
import type { TraceViewerServerOptions } from '../server/trace/viewer/traceViewer';
import * as playwright from '../..';
import type { BrowserContext } from '../client/browserContext';
import type { Browser } from '../client/browser';
import type { Page } from '../client/page';
import type { BrowserType } from '../client/browserType';
import type { BrowserContextOptions, LaunchOptions } from '../client/types';
import { wrapInASCIIBox, isLikelyNpxGlobal, assert, gracefullyProcessExitDoNotHang, getPackageManagerExecCommand } from '../utils';
import type { Executable } from '../server';
import { registry, writeDockerVersion } from '../server';
import { isTargetClosedError } from '../client/errors';
const packageJSON = require('../../package.json');
@ -552,7 +548,7 @@ async function openPage(context: BrowserContext, url: string | undefined): Promi
else if (!url.startsWith('http') && !url.startsWith('file://') && !url.startsWith('about:') && !url.startsWith('data:'))
url = 'http://' + url;
await page.goto(url).catch(error => {
if (process.env.PWTEST_CLI_AUTO_EXIT_WHEN) {
if (process.env.PWTEST_CLI_AUTO_EXIT_WHEN && isTargetClosedError(error)) {
// Tests with PWTEST_CLI_AUTO_EXIT_WHEN might close page too fast, resulting
// in a stray navigation aborted error. We should ignore it.
} else {

Some files were not shown because too many files have changed in this diff Show more