From 8f83cf37d57d756f4d7da8bb118174bfb6045a0a Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Mon, 23 Nov 2026 09:40:17 -0800 Subject: [PATCH 1/3] devops: roll line by line, add the roll workflow, roll the driver to main - playwright-roll skill: port the upstream diff of the client and of the tests hunk by hunk; playwright/src/main/AGENTS.md has the rules. - agent-roll.yml: scheduled and manual roll by the bot. - update_readme.sh reads the browser versions from browsers.json with a Node.js script; roll_driver.sh installs the driver modules. - Move the driver from the v1.65.0 commit of release-1.65 to the nearest commit of main, and port the upstream test changes up to it. --- .claude/skills/playwright-roll/SKILL.md | 244 +++++++++--------- .github/workflows/agent-roll.yml | 74 ++++++ .github/workflows/verify_api.yml | 2 - AGENTS.md | 2 +- playwright/src/main/AGENTS.md | 140 ++++++++++ .../assets/serviceworkers/fetchdummy/sw.js | 4 + .../serviceworkers/slow-fallback/sw.html | 4 + .../assets/serviceworkers/slow-fallback/sw.js | 9 + .../tests/library/TestBrowsercontextHar.java | 47 ++++ .../library/TestBrowsercontextUserAgent.java | 19 ++ .../tests/library/TestCapabilities.java | 15 +- .../tests/library/TestPageClock.java | 45 +++- .../playwright/tests/library/TestPopup.java | 15 ++ .../playwright/tests/library/TestProxy.java | 12 +- .../playwright/tests/library/TestTap.java | 11 + .../library/chromium/TestConnectOverCdp.java | 77 +++++- .../tests/library/chromium/TestOopif.java | 2 + .../page/TestElementhandleScrollIntoView.java | 28 ++ .../tests/page/TestInterception.java | 17 ++ .../tests/page/TestPageAriaSnapshot.java | 36 +-- .../tests/page/TestPageAriaSnapshotAi.java | 78 +++--- .../tests/page/TestPageClickTimeout1.java | 18 -- .../tests/page/TestPageEvaluate.java | 1 + .../tests/page/TestPageEventNetwork.java | 64 ++++- .../tests/page/TestPageEventPageerror.java | 6 +- .../tests/page/TestPageFilechooser.java | 1 + .../playwright/tests/page/TestPageFocus.java | 17 ++ .../playwright/tests/page/TestPageGoto.java | 25 ++ .../playwright/tests/page/TestPageRoute.java | 22 ++ .../tests/page/TestPageScreenshot.java | 19 ++ .../tests/page/TestPageSetInputFiles.java | 31 +++ .../playwright/tests/page/TestRetarget.java | 2 + .../tests/page/TestSelectorsRole.java | 183 ++++--------- .../tests/page/TestToMatchAriaSnapshot.java | 4 + playwright/src/test/upstream_base.txt | 2 +- playwright/src/test/upstream_not_ported.txt | 6 +- playwright/src/test/upstream_registry.md | 46 +++- scripts/DRIVER_VERSION | 2 +- scripts/roll_driver.sh | 3 + scripts/update_readme.js | 53 ++++ scripts/update_readme.sh | 21 +- tools/update-docs-version/pom.xml | 49 ---- .../tools/UpdateBrowserVersions.java | 56 ---- 43 files changed, 1008 insertions(+), 504 deletions(-) create mode 100644 .github/workflows/agent-roll.yml create mode 100644 playwright/src/main/AGENTS.md create mode 100644 playwright/src/test/assets/serviceworkers/slow-fallback/sw.html create mode 100644 playwright/src/test/assets/serviceworkers/slow-fallback/sw.js create mode 100644 scripts/update_readme.js delete mode 100644 tools/update-docs-version/pom.xml delete mode 100644 tools/update-docs-version/src/main/java/com/microsoft/playwright/tools/UpdateBrowserVersions.java diff --git a/.claude/skills/playwright-roll/SKILL.md b/.claude/skills/playwright-roll/SKILL.md index 000e37a19..479f6cec0 100644 --- a/.claude/skills/playwright-roll/SKILL.md +++ b/.claude/skills/playwright-roll/SKILL.md @@ -1,15 +1,17 @@ --- name: playwright-roll -description: Roll Playwright Java to a new microsoft/playwright commit. Moves the commit in scripts/DRIVER_VERSION, builds the driver from source, generates the API, and ports the upstream changes of the client. +description: Roll Playwright Java to a new microsoft/playwright commit. Moves the commit in scripts/DRIVER_VERSION, builds the driver from source, generates the API, and ports the upstream diff of the client line by line. --- # Rolling Playwright -Read `AGENTS.md` and `ROLLING.md` first. +Read `AGENTS.md` and `playwright/src/main/AGENTS.md` first. -`scripts/DRIVER_VERSION` holds one commit of `microsoft/playwright`. We build the driver from source at that commit. `.upstream/` (gitignored) is a clone of `microsoft/playwright` at that commit. Read the upstream code there. Do not edit, commit or switch branches in `.upstream/`. +`scripts/DRIVER_VERSION` holds one commit of `microsoft/playwright`. `.upstream/` (gitignored) is a clone of `microsoft/playwright` at that commit. Read the upstream code there. Do not edit, commit or switch branches in `.upstream/`. A roll does not use the published npm packages or their versions. -A roll moves `scripts/DRIVER_VERSION` to a newer commit and ports the changes between the two commits. A roll does not use the published npm packages or their versions. +A roll moves `scripts/DRIVER_VERSION` to a newer commit and ports everything that changed in the client between the two commits. + +**The port is line by line.** The Java client is a line-by-line translation of the JS client, and a roll keeps it that way. You do not design anything. You take the upstream diff of a file and make the same change at the same place in the Java file, with the patterns of `playwright/src/main/AGENTS.md`. When a hunk does not translate with those patterns, stop and report the hunk. Do not invent a different implementation. ## 1. Roll @@ -21,187 +23,189 @@ A roll moves `scripts/DRIVER_VERSION` to a newer commit and ports the changes be Use the target that the user gives. If the user gives no target, roll `main` to upstream `main`, and roll a `release-1.X` branch of this repository to upstream `release-1.X`. -The script writes the commit to `scripts/DRIVER_VERSION`, rolls Node.js, builds the driver from `.upstream/`, generates the API and updates the README. Then get the two commits: +The script writes the commit to `scripts/DRIVER_VERSION`, rolls Node.js, builds the driver from `.upstream/`, generates the public API and the protocol types (`impl/protocol/`), updates the browser versions in the README and installs the new driver modules into the local Maven repository. Then get the two commits: ```bash old=$(git show HEAD:scripts/DRIVER_VERSION) new=$(cat scripts/DRIVER_VERSION) ``` -## 2. Find the changes to port - -List the upstream commits between the two commits that changed a path the Java client depends on: +The script does not compile the client. If it stops in the API generator, see *When the generator fails*. -- `docs/src/api/` — the input of the API generator. A new or removed method or option, or a changed `langs:` filter, comes from here. -- `packages/playwright-core/src/client/` — the JS client. The Java client is a port of it. -- `packages/isomorphic/` — selector engines, locator generation and parsing, and the aria snapshot code. The client and the server share this code. A change here can change client helpers such as `getByRoleSelector`. -- `packages/playwright/src/matchers/matchers.ts` — the assertion methods. A change here is usually a new option of `LocatorAssertions` or `PageAssertions`. -- `packages/protocol/spec/` — the wire protocol, one `*.yml` file for each area. A new method or event, a renamed parameter or a changed result changes the messages that the Java `*Impl` classes send and receive. +## 2. Compile ```bash -git -C .upstream log "$old..$new" --oneline --reverse -- \ - 'docs/src/api/' \ - 'packages/playwright-core/src/client/' \ - 'packages/isomorphic/' \ - 'packages/playwright/src/matchers/matchers.ts' \ - 'packages/protocol/spec/' +mvn -f playwright/pom.xml compile --no-transfer-progress 2>&1 | grep "ERROR" ``` -The list starts with the oldest commit. Do these steps for each commit: - -1. Read the commit: `git -C .upstream show `. -2. If the change is internal to JS (bundling, dispatchers, electron, mcp, dashboard, trace viewer, test runner), skip it. -3. If the commit changes `docs/src/api/` or types, read the `langs:` annotations. A feature with `langs: js` or `langs: js, python` does not apply to Java. -4. If the commit adds or changes a public method or option that applies to Java, port it. `roll_driver.sh` already generated the new types and options in the Java interfaces. Usually only the `*Impl` code is missing. -5. Make sure that a later commit did not revert the change. Look at the code at `$new` before you port. -6. Keep notes in a file (for example `/tmp/roll-notes.md`). For each upstream PR, write one line: ported, skipped or already supported, with the reason. The PR description comes from this file. +The errors are the first part of the to-do list: a new method of a public interface that no `*Impl` has, a removed or renamed protocol parameter, a changed result type. Do not fix them one by one with stubs. Step 3 fixes them, because each one comes from an upstream hunk. -## 3. The roll PR - -The PR contains: - -- the new commit in `scripts/DRIVER_VERSION`, and the new `scripts/NODE_VERSION` if Node.js changed; -- the generated interfaces from `roll_driver.sh`; -- the `*Impl` code for each ported feature, the same as the upstream JS client (`.upstream/packages/playwright-core/src/client`); -- changes to the generator (import lists, special cases) if there are new types; -- one small test for each new public API: a listener for a new event, a call for a new method, a regression test for a changed return type. +## 3. Port the client -Title: `chore(driver): roll to ()`. `` is the version that the driver reports. Read it from the source, not from npm: +List each changed upstream file with the Java files that port it: ```bash -node -p "require('./.upstream/packages/playwright-core/package.json').version" # for example 1.67.0-next +git -C .upstream diff --name-only "$old" "$new" -- \ + packages/playwright-core/src/client \ + packages/isomorphic \ + packages/protocol/src/serializers.ts \ + packages/playwright/src/matchers/matchers.ts | +while read -r f; do + echo "$f -> $(grep -rlE "^// Port of .*\b$(basename "$f")" playwright/src/main/java | xargs -r -n1 basename | tr '\n' ' ')" +done ``` -Description: list each upstream PR that you ported, each PR that you skipped (with the reason), and each PR that Java already supported. +- A file with Java files after the arrow: port it. +- `matchers.ts`: its ports are `LocatorAssertionsImpl`, `PageAssertionsImpl`, `APIResponseAssertionsImpl` and `AssertionsBase`. +- A file with nothing after the arrow has no port. If it is in `client/` and new in this roll (`git -C .upstream diff --diff-filter=A --name-only "$old" "$new" -- packages/playwright-core/src/client`), port it as a new Java file, unless section 8 of `playwright/src/main/AGENTS.md` lists it. Otherwise skip it. -## Mimicking the JavaScript implementation +For each file to port, do these steps: -The Java client is a port of the JS client in `.upstream/packages/playwright-core/src/client/`. When implementing a new or changed method, always read the corresponding JS file first and mirror its logic: +1. Read the diff: `git -C .upstream diff "$old" "$new" -- `. +2. Open the Java file. For each hunk, find the Java lines that correspond to the lines around the hunk. They have the same names and the same order. +3. Make the same change there: add the lines that the hunk adds, remove the lines that it removes, change the lines that it changes. Translate each statement with `playwright/src/main/AGENTS.md`. +4. Skip a hunk only for one of these reasons, and write it down: + - the member is not in the Java API: its docs in `.upstream/docs/src/api/` have `* langs:` without `java`; + - the hunk changes something that section 8 of `playwright/src/main/AGENTS.md` lists as not ported; + - the hunk changes only a comment, an import or a TypeScript type. +5. A new method of a generated interface needs its `@Override` method in the `*Impl`, at the place where the method is in the `.ts` file. -``` -.upstream/packages/playwright-core/src/client/browserContext.ts -.upstream/packages/playwright-core/src/client/page.ts -.upstream/packages/playwright-core/src/client/tracing.ts -.upstream/packages/playwright-core/src/client/video.ts -.upstream/packages/playwright-core/src/client/locator.ts -.upstream/packages/playwright-core/src/client/network.ts -... -``` +Keep notes in a file in your scratch directory: one line per upstream file, with what you ported and what you skipped. The PR description comes from this file. -Key translation rules: +Changes in the server, the injected scripts and the dispatchers need nothing: they come with the new driver. A change of `packages/protocol/spec/` needs nothing by itself: `roll_driver.sh` generated the new protocol types, and the client hunk that uses them is in the list above. -**Protocol calls** — `await this._channel.methodName(params)` → `sendMessage("methodName", params, NO_TIMEOUT)` +Compile again until there are no errors. An error that is left after all hunks are ported means that a hunk is missing or wrong. Read the upstream file at `$new` again; do not add a stub. -**Extracting a returned channel object from a result** — JS uses `SomeClass.from(result.foo)` which resolves the JS-side object for a channel reference. In Java, the object was already created when the server sent `__create__`, so extract it from the connection: `connection.getExistingObject(result.getAsJsonObject("foo").get("guid").getAsString())` +## 4. Port the tests -**Async/await** — all `await` calls become synchronous `sendMessage(...)` calls since the Java client is synchronous. +The ports of the upstream tests are line by line too, with the rules of `playwright/src/test/AGENTS.md`. Each roll ports every change of the upstream tests between the two commits. The commit that the ports are at is in `playwright/src/test/upstream_base.txt`; after a roll it is `$new`. -**`undefined` / optional params** — JS `options?.foo` checks translate to `if (options != null && options.foo != null)` null checks before adding to the params `JsonObject`. +List each changed spec file with the Java class that ports it: -**`_channel` fields** — the JS `this._channel.foo` maps to calling `sendMessage("foo", ...)` on `this` in the Impl class. +```bash +base=$(grep -v '^#' playwright/src/test/upstream_base.txt | cut -d' ' -f1) +git -C .upstream diff --numstat "$base" "$new" -- tests/page tests/library | +while read -r added removed f; do + echo "+$added -$removed $f -> $(grep -rl "Port of $f\b" playwright/src/test/java | xargs -r -n1 basename)" +done +git -C .upstream diff --stat "$base" "$new" -- tests/assets tests/config +git -C .upstream diff "$base" "$new" -- tests/registry.md | grep '^[-+]|' +``` -**Channel object references in params** — when a JS call passes a channel object as a param (e.g. `{ frame: frame._channel }`), in Java pass the guid: `params.addProperty("frame", ((FrameImpl) frame).guid)`. +For each spec file with a Java class, read `git -C .upstream diff "$base" "$new" -- ` and make the same change at the same place in the Java class, hunk by hunk: -**Module-level state** — JS sometimes keeps state at module level (e.g. the call id counter in `createCallIdGenerator()`). Don't translate it into a `static` field with atomics; keep it per `Connection` (or per object) as a plain field. Each connection is used from one thread, so the port should not change the threading model. +- a changed line of a test: change the Java statement that ports it; +- a new test: a new method at the same place, between the same neighbors; +- a removed test: remove the method; +- a changed title: change the `@DisplayName` and the method name. -## Fixing generator and compilation errors +A spec file without a Java class is in `playwright/src/test/upstream_not_ported.txt`. A new test in it needs no rule when a file or subsystem rule covers it. A new upstream test that Java cannot run gets a rule there with the reason. -After running `./scripts/roll_driver.sh`, the build often fails because the generated Java interfaces reference new types or methods that the generator doesn't know how to handle yet, and the `*Impl` classes don't implement new interface methods. +A changed file in `tests/assets` is copied to the same path in the Java test assets. A change in `tests/config/testserver` is ported to the test server of the harness (`com.microsoft.playwright.fixtures`). -### API generator fixes (scripts/generate_java_api.mts) +Then move the base: -The generator has hardcoded lists that control which imports are added to each generated file. When new classes appear in the API, add them to the relevant lists in `INTERFACE_IMPORTS`: -- `options.*` import list — add new classes that use types from the options package -- `java.util.*` import list — add new classes that use `List`, `Map`, etc. -- `java.util.function.Consumer` list — add new classes with `Consumer`-typed event handlers +```bash +cp .upstream/tests/registry.md playwright/src/test/upstream_registry.md +git -C .upstream log -1 --format='%H %cs %s' "$new" # the new last line of upstream_base.txt +python3 scripts/check_test_registry.py +``` -Type mapping: when JS-only types (like `Disposable`) are used as return types in Java-compatible methods, add a mapping in `BUILTIN_TYPES`. For example, `Disposable` → `AutoCloseable`. +The checker lists each test that is in the registry and not ported, and each ported test that the registry does not have any more. -Event handler generation: events with `void` type generate invalid `Consumer`. Handle this case in `Event.writeListenerMethods` by emitting `Runnable` instead. +A test marked `@Fixme("driver: ...")` or `@Fixme("java: ...")` may pass now. It fails when it does: remove the mark then. Never change a port to make it pass. -Type names: give every new object type an explicit alias upstream. When a roll brings in a new object type (an option or return value written as `<[Object]>` in `docs/src/api/`), it should usually have its own `* alias: ` line. Without one, each language's generator makes up a name, and the Java one can be vague (e.g. `Style`) or differ between Java and .NET. -- Prefer a plain `alias:` so every language gets the same name. Use `alias-java:` / `alias-csharp:` only when a language really needs a different name. -- Add the aliases in a small upstream docs PR (e.g. microsoft/playwright#43164, `Style` → `ScreencastActionStyle`). Don't special-case names in the generator. -- After the upstream change lands, roll to a driver that includes it. Don't hand-edit the generated files. +Upstream tests cover a new API. Add a Java-only test in `com/microsoft/playwright/` only for what upstream does not test: a Java overload, a Java-only option type. -After editing the generator, re-run it. Node.js runs the TypeScript file as is: -``` -node scripts/generate_java_api.mts .upstream -``` +## 5. Check -### Impl class fixes (playwright/src/main/java/com/microsoft/playwright/impl/) +Run each changed test class on the three browsers, then the full suite: -After regenerating, compile `playwright/` to find what's missing: -``` -mvn -f playwright/pom.xml compile 2>&1 | grep "ERROR" +```bash +mvn test -f playwright/pom.xml -D test= --no-transfer-progress +mvn test -f playwright/pom.xml --no-transfer-progress ``` -Common patterns: +A failure in a class that the roll did not change may be a flake, or older than the roll. Run the test alone, and run it on `HEAD` without the roll. Say in the PR which one it is. Never change a test or the client to make a test pass in a way that upstream does not have. + +Then read `git diff upstream/main` end to end: -**Return type changed (e.g. `void` → `AutoCloseable`):** Update the method signature in the Impl class and return an appropriate `AutoCloseable`. Check the JS client to see what kind of disposable is used: -- If JS returns `DisposableObject.from(result.disposable)` — the server created a disposable channel object. Extract its guid from the protocol result and return `connection.getExistingObject(guid)` (a `DisposableObject`). -- If JS returns `new DisposableStub(() => this.someCleanup())` — it's a local callback. Return `new DisposableStub(this::someCleanup)` in Java. -- Examples: `addInitScript`/`exposeBinding`/`exposeFunction` → `DisposableObject`; `route(...)` → `DisposableStub(() -> unroute(...))`; `Tracing.group` → `DisposableStub(this::groupEnd)`; `Video.start` → `DisposableStub(this::stop)`. +- **Removed generated methods** — `git diff upstream/main -- playwright/src/main/java/com/microsoft/playwright/*.java | grep '^-.*;'`. A return type change like `void` → `AutoCloseable` still compiles for callers but breaks code compiled against the previous jar. Call these out in the PR. +- **Behavior beyond upstream** — every added line of `impl/` has an upstream line that it translates, or a `// java:` comment. Remove anything else. +- **Stray files** — local config such as `.claude/settings.json`, or unrelated edits like `examples/pom.xml`, must not be committed. -**New method missing:** Add a stub implementation. Common patterns: -- Simple protocol message: `sendMessage("methodName", params, NO_TIMEOUT)` -- New property accessor (e.g. from initializer): `return initializer.get("fieldName").getAsString()` -- Delegation to mainFrame (for Page methods): `return mainFrame.locator(":root").method(...)` +## 6. The roll PR -**New interface entirely (e.g. `Debugger`):** Create a new `*Impl` class extending `ChannelOwner`, implement the interface, and register the type in `Connection.java`'s switch statement. Initialize the field from the parent's initializer in the parent's constructor (e.g. `connection.getExistingObject(initializer.getAsJsonObject("debugger").get("guid").getAsString())`). +The PR contains: -**Field visibility:** If a field needs to be accessed from a sibling Impl class (e.g. setting `existingResponse` on `RequestImpl` from `BrowserContextImpl`), change it from `private` to package-private. +- the new commit in `scripts/DRIVER_VERSION`, and the new `scripts/NODE_VERSION` if Node.js changed; +- the generated interfaces and protocol types from `roll_driver.sh`; +- the ported hunks in `impl/`; +- the ported tests, the registry copy and `upstream_base.txt`; +- changes to the generator, if step 1 needed them. -**`ListenerCollection` only supports `Consumer`, not `Runnable`.** For void events that use `Runnable` handlers, maintain a plain `List` instead. +Title: `chore(driver): roll to ()`. `` is the version that the driver reports. Read it from the source, not from npm: -**Protocol changes that remove events** — when a method's response now returns an object directly instead of via a subsequent event, update the Impl to capture it from the `sendMessage` result and remove the old event handler. Example: `videoStart` used to fire a `"video"` page event to deliver the artifact; it now returns the artifact directly in the response. Check git history of the upstream JS client when tests hang unexpectedly. +```bash +node -p "require('./.upstream/packages/playwright-core/package.json').version" # for example 1.67.0-next +``` -**Protocol parameter renames** — protocol parameter names can change between versions (e.g. `wsEndpoint` → `endpoint` in `BrowserType.connect`). When a test fails with `expected string, got undefined` or similar validation errors from the driver, check `packages/protocol/spec/*.yml` for the current parameter names and update the corresponding `params.addProperty(...)` call in the Impl class. Also check the JS client (`src/client/`) to see how it builds the params object. +Description: what you ported and what you skipped, with the reason, from your notes. Put the list of the upstream commits in a `
` block: -## Rebuilding the driver modules after a roll +```bash +git -C .upstream log "$old..$new" --oneline --reverse -- \ + docs/src/api packages/playwright-core/src/client packages/isomorphic \ + packages/playwright/src/matchers/matchers.ts packages/protocol/spec +``` -`./scripts/roll_driver.sh` does the full roll. It moves `scripts/DRIVER_VERSION` to the new commit. It builds the driver from `.upstream/` into `driver/src/main/resources/driver/package/` and `driver-bundle/src/main/resources/driver//`. It generates the Java interfaces from the upstream docs, and it updates the README. If all steps pass, the next `mvn` command uses the new driver. +## When the generator fails -If a step fails, the script stops before Maven installs the new driver. The most frequent cause is the API generator, which fails on a new type (see *Fixing generator and compilation errors*). After that, the test JVM loads the **old** driver from `target/classes` or from the installed jar, although the source resources already hold the new driver. +`roll_driver.sh` stops when `scripts/generate_java_api.mts` fails on a new type. Fix the generator, then run the rest of the script by hand and go on with step 2: -To correct this, install the two driver modules one time before you run the tests again: -``` -mvn -f driver/pom.xml install -DskipTests -mvn -f driver-bundle/pom.xml install -DskipTests +```bash +./scripts/generate_api.sh +./scripts/update_readme.sh +mvn -B clean install -D skipTests --no-transfer-progress -pl driver,driver-bundle ``` -If `scripts/generate_api.sh` prints `.upstream/ is not at ...`, run `scripts/build_driver.sh`. +The generator has hardcoded lists that control which imports are added to each generated file. When new classes appear in the API, add them to the relevant lists in `INTERFACE_IMPORTS`: -## Porting and verifying tests +- `options.*` import list — add new classes that use types from the options package +- `java.util.*` import list — add new classes that use `List`, `Map`, etc. +- `java.util.function.Consumer` list — add new classes with `Consumer`-typed event handlers -**Before porting an upstream test file, check the API exists in Java.** The upstream repo may have test files for brand-new APIs that haven't been added to the Java interface yet (e.g., `screencast.spec.ts` tests `page.screencast` which may not be in the generated `Page.java`). Check `git diff main --name-only` to see what interfaces were added this roll, and verify the method exists in the generated Java interface before porting. +Type mapping: when JS-only types (like `Disposable`) are used as return types in Java-compatible methods, add a mapping in `BUILTIN_TYPES`. For example, `Disposable` → `AutoCloseable`. -**Java test file names don't always match upstream spec names.** `TestScreencast.java` tests `recordVideo` video-file recording (which corresponds to `video.spec.ts`), not the newer `page.screencast` streaming API (`screencast.spec.ts`). When comparing coverage, check test *content*, not just file names. +Type names: give every new object type an explicit alias upstream. When a roll brings in a new object type (an option or return value written as `<[Object]>` in `docs/src/api/`), it should usually have its own `* alias: ` line. Without one, each language's generator makes up a name, and the Java one can be vague (e.g. `Style`) or differ between Java and .NET. -**Remove tests for behavior that was removed upstream.** When the JS client drops a client-side error check (e.g., "Page is not yet closed before saveAs", "Page did not produce any video frames"), delete the corresponding Java tests rather than trying to keep them passing. Check the upstream `tests/library/` spec to confirm the behavior is gone. +- Prefer a plain `alias:` so every language gets the same name. Use `alias-java:` / `alias-csharp:` only when a language really needs a different name. +- Add the aliases in a small upstream docs PR (e.g. microsoft/playwright#43164, `Style` → `ScreencastActionStyle`). Don't special-case names in the generator. +- After the upstream change lands, roll to a driver that includes it. Don't hand-edit the generated files. -**Run the full suite to catch regressions, re-run flaky failures in isolation.** Some tests (e.g., `TestClientCertificates#shouldKeepSupportingHttp`) time out only under heavy parallel load. Run the failing test alone to confirm it's flaky before investigating further. +## When a test uses the old driver -**Don't change the driver environment per test.** The driver is a JVM-wide singleton, so `Playwright.CreateOptions.env` (e.g. `PWTEST_UNDER_TEST`) only applies to the first `Playwright.create()` in the JVM. Forcing a new driver instance from a test breaks unrelated tests (`ClosedFileSystemException`). Test through what the public API exposes instead — e.g. screencast action decorations render in a closed shadow root, so the style test checks screencast frames for the decoration's pixels rather than querying the DOM. +If `roll_driver.sh` stopped before its last step, Maven did not install the new driver. The test JVM then loads the **old** driver from `target/classes` or from the installed jar, although the source resources already hold the new one. The sign is a driver validation error such as `expected string, got undefined` for a parameter that the client does send. Install the two driver modules once: -## Reviewing the diff before the PR +```bash +mvn -B clean install -D skipTests --no-transfer-progress -pl driver,driver-bundle +``` -Before opening the PR (and before pushing follow-ups), read `git diff upstream/main` end to end: -- **Removed generated methods** — `git diff upstream/main -- playwright/src/main/java/com/microsoft/playwright/*.java | grep '^-.*;'`. A return type change like `void` → `AutoCloseable` still compiles for callers but breaks code compiled against the previous jar. Call these out in the PR. -- **Behavior beyond upstream** — client-side checks or fixes not in the JS client (e.g. an option that was never sent). Keep them only if deliberate, and list them in the PR. -- **Stray files** — local config such as `.claude/settings.json`, or unrelated edits like `examples/pom.xml`, must not be committed. +If `scripts/generate_api.sh` prints `.upstream/ is not at ...`, run `scripts/build_driver.sh`. -## Diagnosing hanging tests +When the driver is the new one and the error stays, a protocol hunk is not ported: compare the params of the call with `.upstream/packages/protocol/spec/*.yml` and with the JS client. -When `mvn test` hangs and surefire eventually times the JVM out, it writes thread dumps to `playwright/target/surefire-reports/-jvmRun*.dump`. To find the stuck test: +## When a test hangs -``` +When `mvn test` hangs and surefire times the JVM out, it writes thread dumps to `playwright/target/surefire-reports/-jvmRun*.dump`. To find the stuck test: + +```bash grep "com.microsoft.playwright.Test" playwright/target/surefire-reports/*-jvmRun1.dump | sort -u ``` -Each line is a stack frame inside a test method — typically you'll see one or two test methods blocked on a `Future.get()`, `waitForCondition`, or similar. That's the hanging test. +Each line is a stack frame inside a test method. The test that is blocked in `runUntil`, `Future.get()` or a wait is the hanging one. + +1. Run it alone: `mvn -f playwright/pom.xml test -D test='TestClass#testMethod'`. If it passes alone, it is a flake under parallel load. Note it and move on. +2. If it hangs alone, a protocol change is the usual cause: a method that returned its object in an event now returns it in the response, or the reverse. Read the diff of the JS method again and port it as it is. +3. Then look for an upstream fix of the same test: `git -C .upstream log --oneline -- tests/library/.spec.ts`. Port the fix as upstream wrote it. -When you've identified a hanging test: -1. Run it in isolation: `mvn -f playwright/pom.xml test -Dtest='TestClass#testMethod'`. If it passes alone, it's a parallel-load flake — note it but move on. -2. If it still hangs in isolation, look for a recent fix in the upstream repo for the *same* test name. Use `git -C .upstream log --oneline -- tests/library/.spec.ts`. Upstream fixes for client-side hangs are often small and portable (e.g. `about:blank` → `server.EMPTY_PAGE` from microsoft/playwright#39840 fixed `route-web-socket.spec.ts` arraybuffer hangs — apparently some browser changed the WebSocket origin policy on `about:blank`). -3. When porting an upstream fix, mirror the helper signature change rather than hard-coding workarounds. E.g. if upstream added a `server` parameter to `setupWS`, do the same in Java by injecting `Server server` via the JUnit fixture (`@FixtureTest` already wires up `ServerLifecycle`, so adding `Server server` to the test method signature is enough — no class-level boilerplate). Watch for local-variable shadowing when you add a `Server server` parameter to a method that already has a `WebSocketRoute server` local; rename the local. +Don't change the driver environment per test. The driver is a JVM-wide singleton, so `Playwright.CreateOptions.env` applies only to the first `Playwright.create()` in the JVM. diff --git a/.github/workflows/agent-roll.yml b/.github/workflows/agent-roll.yml new file mode 100644 index 000000000..41de44833 --- /dev/null +++ b/.github/workflows/agent-roll.yml @@ -0,0 +1,74 @@ +# Rolls a branch of Playwright Java to a new microsoft/playwright commit: the tip of the branch +# with the same name, unless told otherwise. So main rolls to main, and release-1.xx rolls to +# release-1.xx. Starts the Playwright bot with the task below. The bot starts from the branch, +# does the roll with the playwright-roll skill of that branch, and opens the pull request to the +# branch as the app. +name: "Agent: roll Playwright" + +on: + # Mon, Wed and Fri at 9:37 UTC: 2:37 at night Pacific time, 1:37 in winter. Not on the hour, when + # GitHub delays scheduled runs. A scheduled roll is a roll of main. It skips while a roll pull + # request to main is open. + schedule: + - cron: "37 9 * * 1,3,5" + workflow_dispatch: + inputs: + branch: + description: "Branch to roll, in microsoft/playwright-java and in microsoft/playwright: main or release-1.xx" + default: "main" + ref: + description: "microsoft/playwright branch, tag or commit to roll to; empty for the tip of the branch above" + default: "" + +permissions: {} + +jobs: + start: + name: Hand the task to the bot + if: github.repository == 'microsoft/playwright-java' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + pull-requests: read + env: + BRANCH: ${{ inputs.branch || 'main' }} + steps: + # A manual run rolls anyway: a maintainer asked for it. The skill gives the title of a roll. + - name: Look for an open roll pull request + id: open + if: github.event_name == 'schedule' + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: | + pr=$(gh pr list --state open --base "$BRANCH" --author app/microsoft-playwright-automation --json number,title \ + --jq '[.[] | select(.title | startswith("chore(driver): roll to")) | .number] | first // empty') + if [[ -n "$pr" ]]; then + echo "pr=$pr" >> "$GITHUB_OUTPUT" + echo "Skipped: roll pull request #$pr to $BRANCH is open." >> "$GITHUB_STEP_SUMMARY" + fi + - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + if: steps.open.outputs.pr == '' + id: app-token + with: + client-id: ${{ vars.PLAYWRIGHT_APP_CLIENT_ID }} + private-key: ${{ secrets.PLAYWRIGHT_PRIVATE_KEY }} + owner: microsoft + repositories: devops.playwright.dev + permission-actions: write + - name: Start the bot + if: steps.open.outputs.pr == '' + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + REF: ${{ inputs.ref || inputs.branch || 'main' }} + run: | + # The bot checks the name again. This check gives the error here, in the run that a + # maintainer started. + if [[ ! "$BRANCH" =~ ^(main|release-[0-9]+\.[0-9]+)$ ]]; then + echo "::error::branch must be main or release-1.xx, got '$BRANCH'" + exit 1 + fi + task="Roll the $BRANCH branch of Playwright Java to $REF of microsoft/playwright, as the playwright-roll skill, .claude/skills/playwright-roll/SKILL.md, says. Your checkout is the $BRANCH branch, not main: the old pin is its scripts/DRIVER_VERSION. The pull request goes to the $BRANCH branch. In the pull-request call, base is $BRANCH, commit is the output of git rev-parse origin/$BRANCH, and the patch is against that commit. When the roll is not complete, open the pull request anyway: the pin and the generated files are a start for a maintainer. Say in it what is left." + gh workflow run task.yml --repo microsoft/devops.playwright.dev --ref main \ + -f repo="$GITHUB_REPOSITORY" -f branch="$BRANCH" -f task="$task" + echo "Started the roll of $BRANCH to $REF of microsoft/playwright." >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/verify_api.yml b/.github/workflows/verify_api.yml index d450ee716..7a826ba25 100644 --- a/.github/workflows/verify_api.yml +++ b/.github/workflows/verify_api.yml @@ -28,8 +28,6 @@ jobs: run: scripts/generate_api.sh - name: Build & Install run: mvn -B install -D skipTests --no-transfer-progress - - name: Install browsers - run: mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps" -f playwright/pom.xml --no-transfer-progress - name: Update browser versions in README run: scripts/update_readme.sh - name: Verify API is up to date diff --git a/AGENTS.md b/AGENTS.md index cdf233e20..7cb7764b7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # Playwright Java -The Java client is a port of the JavaScript client in `~/code/playwright/packages/playwright-core/src/client/`. When implementing or changing a method, read the corresponding JS file first and mirror its logic. +The Java client is a port of the JavaScript client in `~/code/playwright/packages/playwright-core/src/client/`. It is a line-by-line translation: when implementing or changing a method, read the corresponding JS file first and translate it statement by statement. `playwright/src/main/AGENTS.md` has the rules. Paths such as `~/code/playwright` in this file assume that you check the repos out in `~/code`. Use the `gh` cli to interact with GitHub. diff --git a/playwright/src/main/AGENTS.md b/playwright/src/main/AGENTS.md new file mode 100644 index 000000000..188128d7a --- /dev/null +++ b/playwright/src/main/AGENTS.md @@ -0,0 +1,140 @@ +# How to port the JavaScript client to Java + +These rules say how to write `playwright/src/main/java/com/microsoft/playwright/impl` from +`packages/playwright-core/src/client` in `microsoft/playwright`. Use them at each roll and for +every fix, for every new or changed line of the client. The upstream code is in `.upstream/`, +the checkout at the commit in `scripts/DRIVER_VERSION`. The steps of a roll are in the +`playwright-roll` skill. + +The port is line by line. A reviewer reads the `.ts` file and the `.java` file side by side. +Each JavaScript statement maps to one Java statement, or to one of the fixed patterns in this +document. The Java does what the JavaScript does, in the same order, with the same names, the +same conditions and the same error messages. Port from the upstream source in front of you, +never from memory of what the method does. + +Do not improve the code while you port it: no extra check, no early return, no helper, no +reordering and no renaming that upstream does not have. When the upstream code looks wrong, +port it as it is and report it. + +The existing code is the reference for every pattern below. Before you port a hunk, read the +Java code around the place it goes to, and write the new lines the same way. + +## 1. Files and names + +- The first line after the license header names the upstream file: `// Port of page.ts.` + To find the port of an upstream file: `grep -rlE "^// Port of .*\bpage\.ts" playwright/src/main/java`. + One upstream file can have several Java files, one per class (`network.ts` is `RequestImpl`, + `ResponseImpl`, `RouteImpl`, `WebSocketImpl`, ...). A new upstream file is a new Java file + with that header. +- A class that implements a public interface is `Impl` (`Page` is `PageImpl`). A + helper class keeps the upstream name (`Waiter`, `HarRouter`, `TimeoutSettings`). +- The members keep the upstream order. A new upstream member goes where it is in the `.ts` file, + between the same neighbors. +- The names are the upstream names without the leading underscore: `_closeReason` is + `closeReason`, `_onRoute()` is `onRoute()`. Constants of `events.ts` are upper case: + `Events.Page.Close` is `Events.Page.CLOSE`. +- The code targets Java 8. No `var`, no records, no `List.of()`, no text blocks. +- Do not edit a generated file: the public interfaces and options, and everything in + `impl/protocol/`. `scripts/generate_api.sh` writes them. + +## 2. Statements + +| JavaScript | Java | +|---|---| +| `await x` | the plain call. The Java client is synchronous. | +| `options = {}` as the parameter default | `if (options == null) { options = new FooOptions(); }` as the first statement | +| `options.foo ?? 0`, `options.foo === undefined ? a : b` | `options.foo == null ? ... : ...` | +| `if (options.flag)` on an optional boolean | `if (options.flag != null && options.flag)` | +| `throw new Error('...')` | `throw new PlaywrightException("...")` with the same message | +| `new TargetClosedError(...)`, `TimeoutError` | the classes of the same name | +| a template string | string concatenation, the same text | +| `Promise.all(list.map(x => x.foo()))` | a loop that calls `foo()` on each one, in the list order | +| an overload on the argument type (`string \| Function \| RegExp`) | one Java overload per type, each calls a shared private method | + +## 3. Protocol calls + +`impl/protocol/` has the generated types of `packages/protocol/spec/*.yml`: one +`Channel` per object, and for each method `Params` and +`Result` (`PageReloadParams`, `CDPSessionSendResult`); for each event +`Event` (`PageDownloadEvent`). + +- `this._channel.foo(params, timeout)` is `channel.foo(params, timeout)`. Each class has + `final Channel channel = new Channel(this);`. +- An object literal is the params class, one assignment per field, in the upstream order: + + ```ts + await this._channel.send({ method, params }, { timeout: options.timeout ?? 0 }); + ``` + ```java + CDPSessionSendParams args = new CDPSessionSendParams(); + args.params = params; + args.method = method; + ``` +- `{ ...options, waitUntil }` is `toProtocol(options, PageReloadParams.class)`, then one + assignment per extra field. +- `kNoTimeout` is `NO_TIMEOUT`. `this._timeoutSettings.timeout(options)` is + `timeoutSettings.timeout(options.timeout)`; the same for `navigationTimeout`. +- `Foo.from(result.foo)` and `Foo.fromNullable(result.foo)` are `result.foo`: the generated + result already holds the impl object. `from` is not ported. +- A channel object in the params (`{ frame: frame._channel }`) is the impl object itself, + assigned to the field. +- `this._wrapApiCall(async () => { ... }, { internal: true })` is + `wrapApiCall(() -> { ... }, title, internal)`. + +## 4. Events + +- `this._channel.on('foo', ...)` in the upstream constructor is a `case "foo":` in the + `handleEvent(String event, JsonObject params)` override of the class. The cases keep the + order of the constructor. Parse the params with + `connection.protocolGson().fromJson(params, PageFooEvent.class)`, then write the body of + the upstream listener. +- `this.emit(Events.Page.Close, this)` is `emit(Events.Page.CLOSE, this)`. +- `_setEventToSubscriptionMapping(new Map([...]))` is `setEventToSubscriptionMapping(mapping)` + with the same entries. +- Each event of the public interface has `onFoo(handler)` and `offFoo(handler)`, which call + `on(Events.Page.FOO, handler)` and `off(...)`. They are at the end of the class. +- `waitForEvent(event, optionsOrPredicate)` is one typed `waitForFoo(options, callback)` per + event of the public interface. It calls the private `waitForEvent(event, predicate, timeout, + code)` of the class, which is the port of the upstream method on `Waiter`. + +## 5. Promises + +The Java client has one thread and no promises. A call that waits pumps the connection. + +- A promise that upstream awaits at once is a plain call. +- A promise that upstream keeps and awaits later is a `Waitable`: `WaitableResult` for a + `ManualPromise`, `WaitableRace` for `Promise.race`, `sendMessageAsync(...)` for a channel + call that is not awaited. `runUntil(code, waitable)` runs the code and pumps until the + waitable is done. +- Module-level state (a counter, a cache) is a plain field of the `Connection` or of the + object. No `static` state, no atomics, no `synchronized`, no locks: each connection is used + from one thread. + +## 6. A new class + +For a new `ChannelOwner` upstream (`Debugger`): write `Impl extends ChannelOwner +implements ` with the `channel` field and the constructor +`(ChannelOwner parent, String type, String guid, JsonObject initializer)`, and add it to the +`factories` map of `Connection.java`, where the other types are. + +## 7. Deviations + +When the Java cannot be the same as the JavaScript, add a `// java: ` comment at that +line. Say what differs and why, in one or two lines. Use it for: + +- code with no counterpart upstream: `// java: helpers with no counterpart upstream.` +- an upstream member that is left out: `// java: from is not ported, generated results already hold the impl object.` +- a different type or shape: `// java: the parsed JSON is a JsonElement.` + +Do not mark a plain rename, a plain `await` or one of the patterns above. Write no other +comments: upstream comments are not copied. + +## 8. What is not ported + +- A member with `* langs: js` (or a list without `java`) in `docs/src/api/*.md`. Check the + docs, not the name. +- `android.ts`, `electron.ts`, `channels.d.ts`, `types.ts`. +- `AbortSignal` and the `signal` options. +- `[Symbol.asyncDispose]`: a public disposable is `AutoCloseable.close()`. +- `assertMaxArguments` and `isFunction`: a Java expression is always a `String`. +- JavaScript-only plumbing: the `Proxy` objects and the protocol validators. diff --git a/playwright/src/test/assets/serviceworkers/fetchdummy/sw.js b/playwright/src/test/assets/serviceworkers/fetchdummy/sw.js index 4e82651a4..cb74db620 100644 --- a/playwright/src/test/assets/serviceworkers/fetchdummy/sw.js +++ b/playwright/src/test/assets/serviceworkers/fetchdummy/sw.js @@ -1,4 +1,8 @@ self.addEventListener('fetch', event => { + if (event.request.url.endsWith('/headers')) { + event.respondWith(new Response(JSON.stringify(Object.fromEntries(event.request.headers)))); + return; + } if (event.request.url.endsWith('.html') || event.request.url.includes('passthrough')) { event.respondWith(fetch(event.request)); return; diff --git a/playwright/src/test/assets/serviceworkers/slow-fallback/sw.html b/playwright/src/test/assets/serviceworkers/slow-fallback/sw.html new file mode 100644 index 000000000..b29d3f2e3 --- /dev/null +++ b/playwright/src/test/assets/serviceworkers/slow-fallback/sw.html @@ -0,0 +1,4 @@ + diff --git a/playwright/src/test/assets/serviceworkers/slow-fallback/sw.js b/playwright/src/test/assets/serviceworkers/slow-fallback/sw.js new file mode 100644 index 000000000..22027322c --- /dev/null +++ b/playwright/src/test/assets/serviceworkers/slow-fallback/sw.js @@ -0,0 +1,9 @@ +self.addEventListener('install', () => self.skipWaiting()); + +self.addEventListener('activate', event => event.waitUntil(self.clients.claim())); + +self.addEventListener('fetch', () => { + // Hold the request for a while, then let it fall back to the network. + const start = Date.now(); + while (Date.now() - start < 500) {} +}); diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsercontextHar.java b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsercontextHar.java index 1d32e9cc9..da3856b5e 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsercontextHar.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsercontextHar.java @@ -16,6 +16,10 @@ package com.microsoft.playwright.tests.library; +import java.util.zip.ZipOutputStream; +import java.util.zip.ZipEntry; +import java.util.stream.Stream; +import java.io.ByteArrayOutputStream; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.microsoft.playwright.Browser; @@ -325,6 +329,49 @@ void shouldRoundTripHarZip(ContextFactory contextFactory, TestServer server, Tes page2.navigate(server.PREFIX + "/one-style.html"); assertTrue(page2.content().contains("hello, world!")); assertThat(page2.locator("body")).hasCSS("background-color", "rgb(255, 192, 203)"); + + // Java: yazl.ZipFile is a ZipOutputStream over the chunks. + ByteArrayOutputStream chunks = new ByteArrayOutputStream(); + try (ZipOutputStream zipFile = new ZipOutputStream(chunks)) { + List entries; + try (Stream files = Files.list(harDir)) { + entries = files.map(file -> file.getFileName().toString()).sorted().collect(Collectors.toList()); + } + for (String entry : entries) { + zipFile.putNextEntry(new ZipEntry(entry.equals("har.har") ? "Recording.HAR" : entry)); + zipFile.write(Files.readAllBytes(harDir.resolve(entry))); + zipFile.closeEntry(); + } + } + Path uppercaseHarPath = testInfo.outputPath("uppercase.har.zip"); + Files.write(uppercaseHarPath, chunks.toByteArray()); + + // Java: unrouteAll() has no behavior option. + context2.unrouteAll(); + context2.routeFromHAR(uppercaseHarPath, new BrowserContext.RouteFromHAROptions().setNotFound(HarNotFound.ABORT)); + page2.reload(); + assertTrue(page2.content().contains("hello, world!")); + assertThat(page2.locator("body")).hasCSS("background-color", "rgb(255, 192, 203)"); + } + + @PlaywrightTest + @DisplayName("HA-114 should reject a malformed har.zip") + void shouldRejectAMalformedHarZip(ContextFactory contextFactory, TestInfo testInfo) throws IOException { + // Java: yazl.ZipFile is a ZipOutputStream over the chunks. + ByteArrayOutputStream chunks = new ByteArrayOutputStream(); + try (ZipOutputStream zipFile = new ZipOutputStream(chunks)) { + zipFile.putNextEntry(new ZipEntry("aa/x.har")); + zipFile.write("{}".getBytes(StandardCharsets.UTF_8)); + zipFile.closeEntry(); + } + // yauzl reports '..' in an entry name as an 'error' event while reading entries. + byte[] zip = new String(chunks.toByteArray(), StandardCharsets.ISO_8859_1).replace("aa/x.har", "../x.har").getBytes(StandardCharsets.ISO_8859_1); + Path harPath = testInfo.outputPath("malformed.har.zip"); + Files.write(harPath, zip); + + BrowserContext context = contextFactory.newContext(); + PlaywrightException error = assertThrows(PlaywrightException.class, () -> context.routeFromHAR(harPath)); + assertTrue(error.getMessage().contains("invalid relative path: ../x.har")); } @PlaywrightTest diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsercontextUserAgent.java b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsercontextUserAgent.java index 607b8962a..d1912c4c7 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsercontextUserAgent.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsercontextUserAgent.java @@ -17,6 +17,8 @@ package com.microsoft.playwright.tests.library; +import com.microsoft.playwright.Route; +import com.microsoft.playwright.Request; import com.microsoft.playwright.Browser; import com.microsoft.playwright.BrowserContext; import com.microsoft.playwright.Page; @@ -57,6 +59,23 @@ void shouldWork(Browser browser, TestServer server) throws Exception { } } + @PlaywrightTest + @DisplayName("UA-007 should preserve custom user agent in route.fetch") + void shouldPreserveCustomUserAgentInRouteFetch(ContextFactory contextFactory, TestServer server) throws Exception { + BrowserContext context = contextFactory.newContext(new Browser.NewContextOptions().setUserAgent("my-custom-user-agent")); + Page page = context.newPage(); + page.route("**/empty.html", route -> { + route.fulfill(new Route.FulfillOptions().setResponse(route.fetch())); + }); + CompletableFuture serverRequestFuture = server.waitForRequest("/empty.html"); + Request request = page.waitForRequest(server.EMPTY_PAGE, () -> { + page.navigate(server.EMPTY_PAGE); + }); + TestServer.Request serverRequest = serverRequestFuture.get(); + assertEquals("my-custom-user-agent", request.headers().get("user-agent")); + assertEquals("my-custom-user-agent", serverRequest.headers.get("user-agent")); + } + @PlaywrightTest @DisplayName("UA-002 should work for subframes") void shouldWorkForSubframes(Browser browser, TestServer server) throws Exception { diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestCapabilities.java b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestCapabilities.java index fb4cec0c3..835445999 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestCapabilities.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestCapabilities.java @@ -549,12 +549,25 @@ void shouldNotAutoPlayAudio(Page page, BrowserName browserName) { @PlaywrightTest @DisplayName("CA-029 should not crash on feature detection for PublicKeyCredential") - void shouldNotCrashOnFeatureDetectionForPublicKeyCredential(Page page, TestServer server) { + void shouldNotCrashOnFeatureDetectionForPublicKeyCredential(Page page, TestServer server, BrowserContext context) { page.navigate(server.EMPTY_PAGE); + assertEquals("function", page.evaluate("() => typeof PublicKeyCredential")); + assertEquals("PublicKeyCredential", page.evaluate("() => PublicKeyCredential.name")); + assertEquals(false, page.evaluate("() => ({}) instanceof PublicKeyCredential")); + assertEquals(true, page.evaluate("() => {\n" + + " try {\n" + + " new PublicKeyCredential();\n" + + " return false;\n" + + " } catch (e) {\n" + + " return e instanceof TypeError;\n" + + " }\n" + + "}")); page.evaluate("async () => {\n" + " await PublicKeyCredential.getClientCapabilities();\n" + " await PublicKeyCredential.isConditionalMediationAvailable();\n" + " await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n" + "}"); + context.credentials().install(); + assertEquals("function", page.evaluate("() => typeof PublicKeyCredential")); } } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestPageClock.java b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestPageClock.java index 85be43c1a..a7ab57286 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestPageClock.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestPageClock.java @@ -40,6 +40,7 @@ import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; +import static org.junit.jupiter.api.Assertions.assertNull; import static com.microsoft.playwright.fixtures.Utils.mapOf; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -223,12 +224,15 @@ void passes2Hours34MinutesAnd10Seconds(Page page, Calls calls) { @PlaywrightTest @DisplayName("CK-012 throws for invalid format") - void throwsForInvalidFormat(Page page, Calls calls) { + void throwsForInvalidFormat(Page page, Calls calls, TestServer server) { page.evaluate("async () => {\n" + " setInterval(window.stub, 10000);\n" + " }"); assertThrows(PlaywrightException.class, () -> page.clock().runFor("12:02:34:10")); + // Java: runFor(NaN) and fastForward(Infinity) are not ported, Clock.runFor() and Clock.fastForward() take a long or a String. assertEquals(Collections.emptyList(), calls); + page.navigate(server.EMPTY_PAGE); + assertEquals(1000, page.evaluate("() => Date.now()")); } @PlaywrightTest @@ -263,15 +267,21 @@ void ignoresTimersWhichWouldntBeRun(Page page, Calls calls) { @PlaywrightTest @DisplayName("CK-015 pushes back execution time for skipped timers") - void pushesBackExecutionTimeForSkippedTimers(Page page, Calls calls) { + void pushesBackExecutionTimeForSkippedTimers(Page page, Calls calls, TestServer server) { + page.navigate(server.EMPTY_PAGE); page.evaluate("async () => {\n" + " setTimeout(() => {\n" + " window.stub(Date.now());\n" + " }, 1000);\n" + " }"); - page.clock().fastForward(2000); - assertEquals(Arrays.asList(Arrays.asList(1000 + 2000)), calls); + long fiftyDays = 50L * 24 * 60 * 60 * 1000; + page.clock().fastForward(fiftyDays); + // Java: a whole number that does not fit an int comes from the page as a Double. + assertEquals(Arrays.asList(Arrays.asList((double) (1000 + fiftyDays))), calls); + assertEquals((double) (1000 + fiftyDays), page.evaluate("() => Date.now()")); + page.reload(); + assertEquals((double) (1000 + fiftyDays), page.evaluate("() => Date.now()")); } @PlaywrightTest @@ -662,16 +672,24 @@ void runForShouldNotRunNestedImmediateFromMicrotask(Page page, Calls calls) { @DisplayName("CK-045 should stay paused on the next page when an init script reads the time") void shouldStayPausedOnTheNextPageWhenAnInitScriptReadsTheTime(Page page, TestServer server) { // { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/43214' } } + // { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/43869' } } + server.setRoute("/timer.html", (req, res) -> { + res.setHeader("Content-Type", "text/html"); + res.end(""); + }); page.clock().install(new com.microsoft.playwright.Clock.InstallOptions().setTime(0)); page.clock().pauseAt(1000); // Java: addInitScript() takes the script, not a function. page.addInitScript("Date.now()"); page.navigate(server.EMPTY_PAGE); page.clock().runFor(1000); - page.navigate(server.PREFIX + "/title.html"); + page.navigate(server.PREFIX + "/timer.html"); assertEquals(2000, page.evaluate("() => Date.now()")); page.waitForTimeout(500); assertEquals(2000, page.evaluate("() => Date.now()")); + assertNull(page.evaluate("() => document.documentElement.dataset.fired")); + page.clock().runFor(0); + assertEquals("true", page.evaluate("() => document.documentElement.dataset.fired")); } @PlaywrightTest @@ -683,6 +701,23 @@ void shouldNotAdvancePerformanceNowBeforeTheFirstClockCallOnANewPage(Page page, page.waitForTimeout(500); assertEquals(Arrays.asList(0, 1000), page.evaluate("() => [performance.now(), Date.now()]")); } + + @PlaywrightTest + @DisplayName("CK-220 should keep timers scheduled during load pending when paused") + void shouldKeepTimersScheduledDuringLoadPendingWhenPaused(Page page, TestServer server) { + // { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/43869' } } + server.setRoute("/timer.html", (req, res) -> { + res.setHeader("Content-Type", "text/html"); + res.end(""); + }); + page.clock().install(new com.microsoft.playwright.Clock.InstallOptions().setTime(0)); + page.clock().pauseAt(1000); + page.navigate(server.PREFIX + "/timer.html"); + page.waitForTimeout(500); + assertNull(page.evaluate("() => document.documentElement.dataset.fired")); + page.clock().runFor(0); + assertEquals("true", page.evaluate("() => document.documentElement.dataset.fired")); + } } @Nested diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestPopup.java b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestPopup.java index dce712659..49e0a5b75 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestPopup.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestPopup.java @@ -203,6 +203,21 @@ void shouldRespectRoutesFromBrowserContextWhenUsingWindowOpen(Browser browser, T context.close(); } + @PlaywrightTest + @DisplayName("PO-029 should load subresources of an about:blank popup when the opener has routes") + @DisabledOnBrowser(value = BrowserName.CHROMIUM, reason = "fixme: Subresources of an about:blank popup are paused on the opener target and never continued") + void shouldLoadSubresourcesOfAnAboutBlankPopupWhenTheOpenerHasRoutes(Browser browser, TestServer server) { + BrowserContext context = browser.newContext(); + Page page = context.newPage(); + page.route("**/*", route -> route.resume()); + page.navigate(server.EMPTY_PAGE); + Page popup = page.waitForPopup(() -> { + page.evaluate("url => window.open('').document.write(``)", server.PREFIX + "/pptr.png"); + }); + popup.waitForFunction("() => document.querySelector('img')?.naturalWidth > 0"); + context.close(); + } + @PlaywrightTest @DisplayName("PO-023 BrowserContext.addInitScript should apply to an in-process popup") void browserContextAddInitScriptShouldApplyToAnInProcessPopup(Browser browser, TestServer server) { diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestProxy.java b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestProxy.java index 8a7a9907b..6e14567bf 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestProxy.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestProxy.java @@ -43,12 +43,14 @@ import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicReference; +import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -64,8 +66,16 @@ void shouldUseProxy(BrowserType browserType, TestServer server) { }); Browser browser = browserType.launch(Env.launchOptions().setProxy(new Proxy(server.HOST))); Page page = browser.newPage(); - page.navigate("http://non-existent.test/target.html"); + String url = "http://staging.example.org/target.html"; + List requests = new ArrayList<>(); + page.onRequest(request -> { + if (request.isNavigationRequest()) + requests.add(request.url()); + }); + page.navigate(url); assertEquals("Served by the proxy", page.title()); + assertEquals(url, page.url()); + assertEquals(asList(url), requests); browser.close(); } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestTap.java b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestTap.java index 8ed46ade3..c731be05e 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestTap.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestTap.java @@ -16,6 +16,8 @@ package com.microsoft.playwright.tests.library; +import java.util.stream.Collectors; +import java.util.List; import com.microsoft.playwright.Browser; import com.microsoft.playwright.ElementHandle; import com.microsoft.playwright.JSHandle; @@ -41,6 +43,7 @@ Browser.NewContextOptions contextOptions(Browser.NewContextOptions contextOption } @PlaywrightTest + @SuppressWarnings("unchecked") @DisplayName("TA-001 should send all of the correct events @smoke") void shouldSendAllOfTheCorrectEvents(Page page) { page.setContent("\n" + @@ -58,6 +61,14 @@ void shouldSendAllOfTheCorrectEvents(Page page) { "mouseover", "mouseenter", "mousemove", "mousedown", "mouseup", "click"), eventsHandle.jsonValue()); + + eventsHandle.evaluate("events => events.length = 0"); + page.locator("#b").evaluate("target => {\n" + + " target.addEventListener('pointerdown', event => event.preventDefault(), { once: true });\n" + + "}"); + page.tap("#b"); + List events = ((List) eventsHandle.jsonValue()).stream().filter(event -> asList("pointerdown", "pointerup", "mousedown", "mouseup", "click").contains(event)).collect(Collectors.toList()); + assertEquals(asList("pointerdown", "pointerup", "click"), events); } @PlaywrightTest diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/library/chromium/TestConnectOverCdp.java b/playwright/src/test/java/com/microsoft/playwright/tests/library/chromium/TestConnectOverCdp.java index dd230f41f..05f396443 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/library/chromium/TestConnectOverCdp.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/library/chromium/TestConnectOverCdp.java @@ -17,6 +17,8 @@ package com.microsoft.playwright.tests.library.chromium; +import com.google.gson.JsonObject; +import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.microsoft.playwright.Browser; import com.microsoft.playwright.BrowserContext; @@ -57,6 +59,7 @@ import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; import static com.microsoft.playwright.fixtures.ChildProcessFactory.findFreePort; import static com.microsoft.playwright.fixtures.Utils.asset; @@ -104,14 +107,20 @@ private static void connectIgnoringErrors(BrowserType browserType, String endpoi @PlaywrightTest @DisplayName("CD-001 should connect to an existing cdp session") - void shouldConnectToAnExistingCdpSession(BrowserType browserType) { - int port = findFreePort(); - Browser browserServer = browserType.launch(remoteDebuggingPort(port)); + void shouldConnectToAnExistingCdpSession(BrowserType browserType, CreateUserDataDir createUserDataDir) throws IOException { + Path configHome = createUserDataDir.create(); + Path userDataDir = configHome.resolve("google-chrome"); + BrowserContext browserServer = browserType.launchPersistentContext(userDataDir, Env.launchPersistentContextOptions() + .setArgs(Arrays.asList("--remote-debugging-port=0"))); try { + String port = new String(Files.readAllBytes(userDataDir.resolve("DevToolsActivePort")), StandardCharsets.UTF_8).split("\n")[0]; Browser cdpBrowser = browserType.connectOverCDP("http://127.0.0.1:" + port + "/"); List contexts = cdpBrowser.contexts(); assertEquals(1, contexts.size()); cdpBrowser.close(); + + // Java: the Linux part starts a Node.js client in a child process (connectOverCDP('chrome') with + // CHROME_USER_DATA_DIR, CHROME_CONFIG_HOME and XDG_CONFIG_HOME in its environment); it is not ported. } finally { browserServer.close(); } @@ -733,4 +742,66 @@ void noDefaultsShouldNotAffectNewContexts(BrowserType browserType, TestServer se browserServer.close(); } } + + @PlaywrightTest + @DisplayName("CD-053 should connect when another client inspects a terminated shared worker") + void shouldConnectWhenAnotherClientInspectsATerminatedSharedWorker(BrowserType browserType, TestServer server) { + assumeFalse(true, "fixme: test.fixme() in the upstream file"); + int port = findFreePort(); + Browser browser = browserType.launch(remoteDebuggingPort(port)); + try { + // Another client inspects the shared worker. + Page page = browser.newPage(); + CDPSession inspector = browser.newBrowserCDPSession(); + CompletableFuture workerCreated = new CompletableFuture<>(); + inspector.on("Target.targetCreated", event -> { + JsonObject targetInfo = event.getAsJsonObject("targetInfo"); + if ("shared_worker".equals(targetInfo.get("type").getAsString())) + workerCreated.complete(targetInfo.get("targetId").getAsString()); + }); + JsonObject discoverParams = new JsonObject(); + discoverParams.addProperty("discover", true); + inspector.send("Target.setDiscoverTargets", discoverParams); + page.navigate(server.PREFIX + "/shared-worker/shared-worker.html"); + assertEquals("echo:hello", page.evaluate("window.sharedWorkerResponsePromise")); + page.waitForCondition(workerCreated::isDone); + String workerTargetId = workerCreated.getNow(null); + JsonObject attachParams = new JsonObject(); + attachParams.addProperty("targetId", workerTargetId); + attachParams.addProperty("flatten", true); + inspector.send("Target.attachToTarget", attachParams); + + // The last client of the shared worker goes away, so the worker is terminated. + // The inspector stays attached, so the worker target lingers without a browser context. + page.close(); + // Java: expect.poll(...).toBe(false), with the intervals and timeout of expect.poll. + int[] intervals = {100, 250, 500, 1000}; + long deadline = System.currentTimeMillis() + 5000; + boolean lingers; + for (int i = 0;; i++) { + lingers = false; + for (JsonElement info : inspector.send("Target.getTargets").getAsJsonArray("targetInfos")) { + if (workerTargetId.equals(info.getAsJsonObject().get("targetId").getAsString())) + lingers = true; + } + if (!lingers || System.currentTimeMillis() >= deadline) + break; + try { + Thread.sleep(intervals[Math.min(i, intervals.length - 1)]); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + } + assertFalse(lingers); + + // A new client auto-attaches to the lingering worker target. + Browser cdpBrowser = browserType.connectOverCDP("http://127.0.0.1:" + port + "/"); + Page page2 = cdpBrowser.contexts().get(0).newPage(); + assertEquals(2, page2.evaluate("1 + 1")); + cdpBrowser.close(); + } finally { + browser.close(); + } + } } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/library/chromium/TestOopif.java b/playwright/src/test/java/com/microsoft/playwright/tests/library/chromium/TestOopif.java index 80a8deeb7..09490b6e2 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/library/chromium/TestOopif.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/library/chromium/TestOopif.java @@ -17,6 +17,7 @@ package com.microsoft.playwright.tests.library.chromium; +import static com.microsoft.playwright.fixtures.Utils.rafraf; import com.google.gson.JsonObject; import com.microsoft.playwright.Browser; import com.microsoft.playwright.BrowserContext; @@ -220,6 +221,7 @@ void shouldTakeScreenshot(Page page, Browser browser, TestServer server, TestInf page.navigate(server.PREFIX + "/dynamic-oopif.html"); assertEquals(2, page.frames().size()); assertOOPIFCount(browser, 1); + rafraf(page.frames().get(1)); testInfo.expectToMatchSnapshot(page.screenshot(), "screenshot-oopif.png"); } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestElementhandleScrollIntoView.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestElementhandleScrollIntoView.java index 6b2ebba09..36ac9e947 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestElementhandleScrollIntoView.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestElementhandleScrollIntoView.java @@ -91,6 +91,34 @@ void shouldScrollDisplayContentsIntoView(Page page, BrowserName browserName, Bro assertTrue(Math.abs(((Number) scrollTop).doubleValue() - 350) < 1); } + @PlaywrightTest + @DisplayName("EH-124 should scroll nested display:contents into view") + void shouldScrollNestedDisplayContentsIntoView(Page page) { + page.setContent("\n" + + " \n" + + "
\n" + + "
\n" + + "
Hello
Sibling
\n" + + "
\n" + + "
\n" + + " "); + ElementHandle div = page.querySelector("#outer"); + div.scrollIntoViewIfNeeded(); + // The first box in the flattened subtree of #outer is #target, two levels down, + // not the tall sibling. No whitespace text nodes inside #outer: in Firefox they + // get boxes of their own, which would hide a fallback that only looks one level down. + Object targetIsVisible = page.evalOnSelector("#target", "target => {\n" + + " const container = document.getElementById('container').getBoundingClientRect();\n" + + " const rect = target.getBoundingClientRect();\n" + + " return rect.top >= container.top && rect.bottom <= container.bottom;\n" + + "}"); + assertEquals(true, targetIsVisible); + } + @PlaywrightTest @DisplayName("EH-097 should work for visibility:hidden element") void shouldWorkForVisibilityHiddenElement(Page page) { diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestInterception.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestInterception.java index 9fe8d20c1..ba7d7b74c 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestInterception.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestInterception.java @@ -34,6 +34,7 @@ import java.util.HashMap; import java.util.Map; +import static com.microsoft.playwright.fixtures.Utils.mapOf; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; import static com.microsoft.playwright.fixtures.Utils.browserMajorVersion; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -66,6 +67,7 @@ void shouldWorkWithNavigation(Page page, TestServer server) { } @PlaywrightTest + @SuppressWarnings("unchecked") @DisplayName("RO-152 should intercept after a service worker") void shouldInterceptAfterAServiceWorker(Page page, TestServer server, BrowserName browserName) { page.navigate(server.PREFIX + "/serviceworkers/fetchdummy/sw.html"); @@ -88,6 +90,21 @@ void shouldInterceptAfterAServiceWorker(Page page, TestServer server, BrowserNam Object swResponse2 = page.evaluate("() => window['fetchDummy']('foo')"); assertEquals("responseFromServiceWorker:foo", swResponse2); + // Frozen WebKit predates the header preservation fix. + { + Map headers = mapOf( + "cache-control", "max-age=12345", + "accept-language", "fr-CH", + "accept", "application/custom"); + Map receivedHeaders = (Map) page.evaluate("async headers => {\n" + + " const response = await fetch('headers', { headers });\n" + + " return response.json();\n" + + "}", headers); + // Java: toMatchObject(headers) checks the entries of headers. + for (Map.Entry header : headers.entrySet()) + assertEquals(header.getValue(), receivedHeaders.get(header.getKey())); + } + // Page route is not applied to service worker initiated fetch. Object nonInterceptedResponse = page.evaluate("() => window['fetchDummy']('passthrough')"); assertEquals("FAILURE: Not Found", nonInterceptedResponse); diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageAriaSnapshot.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageAriaSnapshot.java index 67431c70d..adb12dc70 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageAriaSnapshot.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageAriaSnapshot.java @@ -958,38 +958,16 @@ void shouldNotIncludeHiddenIframes(Page page) { } @PlaywrightTest - @DisplayName("AR-046 should not include inert elements") - @Fixme("driver: the bundled driver does not skip inert elements, snapshot has - button \"Hello\", - button \"Yay\", - paragraph: Some text, - paragraph: Visible inert text, - button \"Save\"") - void shouldNotIncludeInertElements(Page page) { + @DisplayName("AR-171 should include inert elements and elements outside of a modal dialog") + void shouldIncludeInertElementsAndElementsOutsideOfAModalDialog(Page page) { page.setContent("\n" + " \n" + " \n" + "
\n" + " \n" + - "

Some text

\n" + "
\n" + - "

Visible inert text

\n" + - " \n" + - " "); - - checkAndMatchSnapshot(page.locator("body"), "\n" + - " - button \"Hi\"\n" + - " - paragraph: Visible text\n" + - " - button\n" + - " "); - } - - @PlaywrightTest - @DisplayName("AR-047 should only include the modal dialog content") - @Fixme("driver: the bundled driver does not limit the snapshot to the modal dialog, it also has - heading \"Title\", - button \"Outside\" and - button \"Inert inside\"") - void shouldOnlyIncludeTheModalDialogContent(Page page) { - page.setContent("\n" + - "

Title

\n" + - " \n" + " \n" + - "

Dialog

\n" + " \n" + - "
\n" + "
\n" + " \n" + - " "); - - String snapshot = snapshotForAI(page); - expectToContainYaml(snapshot, "\n" + - " - generic:\n" + - " - button: Outside\n" + - " - dialog [ref=e1]:\n" + - " - button \"Inside\" [active] [ref=e2]\n" + - " "); - } } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageClickTimeout1.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageClickTimeout1.java index 24939a736..b147c76db 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageClickTimeout1.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageClickTimeout1.java @@ -54,22 +54,4 @@ void shouldTimeoutWaitingForInertElementToBecomeNonInert(Page page) { assertTrue(error.getMessage().contains("element is inert")); assertTrue(error.getMessage().contains("retrying click action")); } - - @PlaywrightTest - @DisplayName("CL-113 should timeout waiting for element outside of a modal dialog") - @Fixme("java: the error message has no 'page.click: ' prefix and the bundled driver 1.64.1 does not report 'element is inert' in the call log") - void shouldTimeoutWaitingForElementOutsideOfAModalDialog(Page page) { - page.setContent("\n" + - " \n" + - " \n" + - " \n" + - " "); - PlaywrightException error = assertThrows(PlaywrightException.class, - () -> page.click("text=Click target", new Page.ClickOptions().setTimeout(3000))); - assertNull(page.evaluate("window.__CLICKED")); - assertTrue(error.getMessage().contains("page.click: Timeout 3000ms exceeded.")); - assertTrue(error.getMessage().contains("element is inert")); - } } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageEvaluate.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageEvaluate.java index 35d262dd8..ea71159dc 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageEvaluate.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageEvaluate.java @@ -631,6 +631,7 @@ void shouldSimulateAUserGesture(Page page) { @PlaywrightTest @DisplayName("EV-063 should throw a nice error after a navigation") void shouldThrowANiceErrorAfterANavigation(Page page) { + assumeFalse("frozen".equals(System.getenv("PW_CLOCK"))); PlaywrightException[] error = {null}; page.waitForNavigation(() -> { error[0] = assertThrows(PlaywrightException.class, () -> page.evaluate("() => new Promise(f => setTimeout(() => {\n" + diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageEventNetwork.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageEventNetwork.java index 631fffda3..ae7e68007 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageEventNetwork.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageEventNetwork.java @@ -17,6 +17,8 @@ package com.microsoft.playwright.tests.page; +import java.util.Collections; +import com.microsoft.playwright.PlaywrightException; import com.microsoft.playwright.Page; import com.microsoft.playwright.Request; import com.microsoft.playwright.Response; @@ -34,6 +36,7 @@ import java.util.concurrent.CompletableFuture; import java.util.regex.Pattern; +import static org.junit.jupiter.api.Assertions.assertThrows; import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -153,9 +156,8 @@ void shouldSupportRedirects(Page page, TestServer server) { } @PlaywrightTest - @DisplayName("NE-090 should resolve responses after a navigation") - @DisabledOnBrowser(value = BrowserName.CHROMIUM, reason = "fixme") - void shouldResolveResponsesAfterANavigation(Page page, TestServer server) throws Exception { + @DisplayName("NE-090 should resolve responses after a cross-process navigation") + void shouldResolveResponsesAfterACrossProcessNavigation(Page page, TestServer server, BrowserName browserName) throws Exception { CompletableFuture responseFromServerPromise = new CompletableFuture<>(); server.setRoute("/foo", (message, response) -> { responseFromServerPromise.complete(response); @@ -166,6 +168,11 @@ void shouldResolveResponsesAfterANavigation(Page page, TestServer server) throws page.evaluate("url => void fetch(url)", server.PREFIX + "/foo"); }); TestServer.Response responseFromServer = responseFromServerPromise.get(); + Request[] failedPromise = {null}; + page.onRequestFailed(r -> { + if (failedPromise[0] == null) + failedPromise[0] = r; + }); // navigate, which should cancel the request page.navigate(server.CROSS_PROCESS_PREFIX); // make sure we aren't stalling this request on the server @@ -173,5 +180,56 @@ void shouldResolveResponsesAfterANavigation(Page page, TestServer server) throws // the response should resolve to null, because the page navigated. // Java: request.response() keeps its result once the page has navigated, so it runs after the navigation. assertNull(request.response()); + // the request should fail with the browser's "canceled" error. + page.waitForCondition(() -> failedPromise[0] != null); + assertEquals(request, failedPromise[0]); + assertTrue(request.failure().contains(browserName == BrowserName.CHROMIUM ? "net::ERR_ABORTED" : browserName == BrowserName.FIREFOX ? "NS_BINDING_ABORTED" : "cancelled")); + } + + @PlaywrightTest + @DisplayName("NE-143 should resolve responses after a same-process navigation") + void shouldResolveResponsesAfterASameProcessNavigation(Page page, TestServer server, BrowserName browserName) throws Exception { + CompletableFuture responseFromServerPromise = new CompletableFuture<>(); + server.setRoute("/foo", (message, response) -> { + responseFromServerPromise.complete(response); + }); + server.setRoute("/streaming", (message, response) -> { + response.writeHead(200, "Content-Type", "text/plain"); + response.write("partial body"); + }); + page.navigate(server.EMPTY_PAGE); + Request[] requestPromise = {null}; + Response streamingResponse = page.waitForResponse(server.PREFIX + "/streaming", () -> { + requestPromise[0] = page.waitForRequest(server.PREFIX + "/foo", () -> { + // start a long running request and wait until it hits the server + page.evaluate("url => void fetch(url)", server.PREFIX + "/foo"); + }); + // start a request that never finishes streaming its body + page.evaluate("url => void fetch(url)", server.PREFIX + "/streaming"); + }); + TestServer.Response responseFromServer = responseFromServerPromise.get(); + Request request = requestPromise[0]; + List failedRequests = new ArrayList<>(); + page.onRequestFailed(r -> failedRequests.add(r)); + // navigate within the same process, which should cancel the requests + page.navigate(server.PREFIX + "/title.html"); + // make sure we aren't stalling this request on the server + responseFromServer.end("done"); + // the response should resolve to null, because the page navigated. + // Java: request.response() keeps its result once the page has navigated, so it runs after the navigation. + assertNull(request.response()); + // both requests should fail with the browser's "canceled" error. + String errorText = browserName == BrowserName.CHROMIUM ? "net::ERR_ABORTED" : browserName == BrowserName.FIREFOX ? "NS_BINDING_ABORTED" : "cancelled"; + List failedUrls = new ArrayList<>(); + for (Request r : failedRequests) + failedUrls.add(r.url()); + Collections.sort(failedUrls); + assertEquals(asList(server.PREFIX + "/foo", server.PREFIX + "/streaming"), failedUrls); + assertTrue(request.failure().contains(errorText)); + assertTrue(streamingResponse.request().failure().contains(errorText)); + // the partial body should not be available anymore. + // Java: streamingResponse.text() runs after the navigation, it cannot be pending while the page navigates on the same thread. + PlaywrightException streamingTextError = assertThrows(PlaywrightException.class, () -> streamingResponse.text()); + assertTrue(streamingTextError.getMessage().contains("navigated away")); } } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageEventPageerror.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageEventPageerror.java index 7ad09b3ed..4ec6bb000 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageEventPageerror.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageEventPageerror.java @@ -17,6 +17,7 @@ package com.microsoft.playwright.tests.page; +import com.microsoft.playwright.Browser; import com.microsoft.playwright.ConsoleMessage; import com.microsoft.playwright.Page; import com.microsoft.playwright.fixtures.BrowserName; @@ -32,6 +33,7 @@ import java.util.List; import java.util.function.Consumer; +import static com.microsoft.playwright.fixtures.Utils.browserMajorVersion; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -67,7 +69,7 @@ private static PageError waitForPageError(Page page, Runnable action) { @PlaywrightTest @DisplayName("ER-001 should fire") - void shouldFire(Page page, TestServer server, BrowserName browserName) { + void shouldFire(Page page, TestServer server, BrowserName browserName, Browser browser) { String url = server.PREFIX + "/error.html"; PageError error = waitForPageError(page, () -> page.navigate(url)); assertEquals("Error", error.name); @@ -120,7 +122,7 @@ void shouldFire(Page page, TestServer server, BrowserName browserName) { }); PageError crossOriginError = waitForPageError(page, () -> page.navigate(server.PREFIX + "/cross-origin-error.html")); assertEquals("Fancy error!", crossOriginError.message); - if (browserName == BrowserName.CHROMIUM) { + if (browserName == BrowserName.CHROMIUM && browserMajorVersion(browser) >= 155) { assertEquals("Uncaught Error: Fancy error!\n" + " at c (" + crossOriginUrl + ":14:11)\n" + " at b (" + crossOriginUrl + ":10:5)\n" + diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageFilechooser.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageFilechooser.java index 532482f5c..63ad3a770 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageFilechooser.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageFilechooser.java @@ -410,6 +410,7 @@ void routeActivationPage(Page page, TestServer server) { @DisplayName("FC-026 should not open file chooser without user activation") @DisabledOnBrowser(value = BrowserName.WEBKIT, reason = "fixme: WebKit opens the file chooser from input.click() without user activation") void shouldNotOpenFileChooserWithoutUserActivation(Page page, TestServer server, BrowserName browserName) { + assumeFalse("frozen".equals(System.getenv("PW_CLOCK"))); AtomicInteger choosers = new AtomicInteger(); page.onFileChooser(chooser -> choosers.incrementAndGet()); diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageFocus.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageFocus.java index 06cff5732..f16644912 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageFocus.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageFocus.java @@ -269,4 +269,21 @@ void shouldTabFromAnIframeToItsParent(Page page, TestServer server) { page.keyboard().press("Tab"); assertThat(page.locator("#outer")).isFocused(); } + + @PlaywrightTest + @DisplayName("FO-013 should move focus from the parent into its iframe") + void shouldMoveFocusFromTheParentIntoItsIframe(Page page, TestServer server) { + server.setRoute("/frame.html", (req, res) -> { + res.setHeader("content-type", "text/html"); + res.end(""); + }); + page.navigate(server.EMPTY_PAGE); + page.setContent(""); + page.locator("#outer").focus(); + assertThat(page.locator("#outer")).isFocused(); + // Call native focus() exactly once, locator.focus() would hide the bug by calling it twice. + page.evaluate("() => document.querySelector('iframe').contentDocument.querySelector('input').focus()"); + assertThat(page.locator("iframe")).isFocused(); + assertThat(page.frameLocator("iframe").locator("#inner")).isFocused(); + } } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageGoto.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageGoto.java index 1b9670c24..255fadc21 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageGoto.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageGoto.java @@ -799,9 +799,34 @@ void shouldFailWhenNavigatingAndShowTheUrlAtTheErrorMessage(Page page, TestServe @PlaywrightTest @DisplayName("NA-051 should be able to navigate to a page controlled by service worker") void shouldBeAbleToNavigateToAPageControlledByServiceWorker(Page page, TestServer server) { + String transaction = "async function transaction(value) {\n" + + " const db = await new Promise((resolve, reject) => {\n" + + " const request = indexedDB.open('roundtrip', 1);\n" + + " request.onupgradeneeded = () => request.result.createObjectStore('items');\n" + + " request.onsuccess = () => resolve(request.result);\n" + + " request.onerror = () => reject(request.error);\n" + + " });\n" + + " return new Promise((resolve, reject) => {\n" + + " const tx = db.transaction('items', 'readwrite');\n" + + " const request = tx.objectStore('items').get('name');\n" + + " request.onsuccess = () => {\n" + + " if (value)\n" + + " tx.objectStore('items').put(value, 'name');\n" + + " };\n" + + " tx.oncomplete = () => resolve(request.result);\n" + + " tx.onerror = tx.onabort = () => reject(tx.error);\n" + + " });\n" + + "}"; + page.navigate(server.PREFIX + "/serviceworkers/fetch/sw.html"); page.evaluate("() => window['activationPromise']"); page.navigate(server.PREFIX + "/serviceworkers/fetch/sw.html"); + page.waitForFunction("() => !!navigator.serviceWorker.controller"); + page.evaluate(transaction, "value"); + page.navigate(server.CROSS_PROCESS_PREFIX + "/empty.html"); + page.goBack(); + page.waitForFunction("() => !!navigator.serviceWorker.controller"); + assertEquals("value", page.evaluate(transaction, null)); } @PlaywrightTest diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageRoute.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageRoute.java index 8e81a0e05..e7433cf13 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageRoute.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageRoute.java @@ -288,6 +288,7 @@ void shouldWorkWithRedirectInsideSyncXHR(Page page, TestServer server) { @DisplayName("RO-012 should pause intercepted XHR until continue") @DisabledOnBrowser(value = BrowserName.WEBKIT, reason = "fixme: Redirected request is not paused in WebKit") void shouldPauseInterceptedXHRUntilContinue(Page page, TestServer server) { + assumeFalse("frozen".equals(System.getenv("PW_CLOCK"))); page.navigate(server.EMPTY_PAGE); Route[] routePromise = {null}; page.route("**/global-var.html", route -> routePromise[0] = route); @@ -1340,4 +1341,25 @@ void shouldBeAbleToInterceptEveryNavigationToAPageControlledByServiceWorker(Page page.navigate(URL); assertEquals(2, interceptions[0]); } + + @PlaywrightTest + @DisplayName("RO-202 should continue a request reported while interception was disabled") + void shouldContinueARequestReportedWhileInterceptionWasDisabled(Page page, TestServer server) { + page.navigate(server.PREFIX + "/serviceworkers/slow-fallback/sw.html"); + page.evaluate("() => window['activationPromise']"); + + Consumer handler = route -> route.fulfill(new Route.FulfillOptions().setBody("mocked")); + page.route("**/never-requested", handler); + page.unroute("**/never-requested"); + // The service worker holds the request, so it reaches the network + // after interception is enabled again. + // Java: the page keeps the promise of the fetch, a second evaluate awaits it. + page.waitForRequest("**/simple.json", () -> { + page.evaluate("() => {\n" + + " window.__bodyPromise = fetch('/simple.json').then(response => response.text());\n" + + "}"); + }); + page.route("**/never-requested", handler); + assertEquals("{\"foo\": \"bar\"}\n", page.evaluate("() => window.__bodyPromise")); + } } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageScreenshot.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageScreenshot.java index 9145acbc1..c470437cb 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageScreenshot.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageScreenshot.java @@ -541,6 +541,25 @@ void shouldWorkWithArrayDeleted(Page page, TestServer server, TestInfo testInfo) // SS-039 should take fullPage screenshots during navigation: not ported, see upstream_not_ported.txt. + @PlaywrightTest + @DisplayName("SS-096 should not wait for unused font face with failed local() source") + @DisabledOnBrowser(value = BrowserName.WEBKIT, reason = "fixme: Fixed upstream in https://commits.webkit.org/323883@main") + void shouldNotWaitForUnusedFontFaceWithFailedLocalSource(Page page, TestServer server) { + page.navigate(server.EMPTY_PAGE); + page.setContent("\n" + + " \n" + + "
hello
\n" + + " "); + page.screenshot(); + assertEquals("loaded", page.evaluate("() => document.fonts.status")); + } + @Nested class MaskOption { @PlaywrightTest diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageSetInputFiles.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageSetInputFiles.java index b89b1262e..3acf6b234 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageSetInputFiles.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageSetInputFiles.java @@ -17,6 +17,8 @@ package com.microsoft.playwright.tests.page; +import com.microsoft.playwright.fixtures.DisabledOnBrowser; +import com.microsoft.playwright.fixtures.BrowserName; import com.microsoft.playwright.ElementHandle; import com.microsoft.playwright.JSHandle; import com.microsoft.playwright.Locator; @@ -39,6 +41,7 @@ import java.util.List; import java.util.Map; +import static com.microsoft.playwright.fixtures.Utils.mapOf; import static com.microsoft.playwright.fixtures.Utils.asset; import static com.microsoft.playwright.fixtures.Utils.relativeToCwd; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -329,4 +332,32 @@ void shouldPreserveLastModifiedTimestamp(Page page) throws Exception { "expected: " + expectedTimestamps + "; actual: " + timestamps); } } + + @PlaywrightTest + @DisplayName("IF-022 should store an uploaded file in IndexedDB") + @DisabledOnBrowser(value = BrowserName.WEBKIT, reason = "fixme: WebKit does not support storing files in IndexedDB in private browsing.") + void shouldStoreAnUploadedFileInIndexedDB(Page page, TestServer server) { + page.navigate(server.PREFIX + "/input/fileupload.html"); + Locator input = page.locator("input[type=file]"); + input.setInputFiles(asset("file-to-upload.txt")); + Object storedFile = input.evaluate("async input => {\n" + + " const db = await new Promise((resolve, reject) => {\n" + + " const request = indexedDB.open('file-upload');\n" + + " request.onupgradeneeded = () => request.result.createObjectStore('files');\n" + + " request.onsuccess = () => resolve(request.result);\n" + + " request.onerror = () => reject(request.error);\n" + + " });\n" + + " const file = await new Promise((resolve, reject) => {\n" + + " const transaction = db.transaction('files', 'readwrite');\n" + + " const store = transaction.objectStore('files');\n" + + " store.put(input.files[0], 'file');\n" + + " const request = store.get('file');\n" + + " transaction.oncomplete = () => resolve(request.result);\n" + + " transaction.onabort = () => reject(transaction.error);\n" + + " });\n" + + " db.close();\n" + + " return { name: file.name, text: await file.text() };\n" + + "}"); + assertEquals(mapOf("name", "file-to-upload.txt", "text", "contents of the file"), storedFile); + } } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestRetarget.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestRetarget.java index 2682dfb56..996b1f4dd 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestRetarget.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestRetarget.java @@ -192,6 +192,8 @@ void enabledDisabledRetargeting(Page page) { {domInLink(""), false, "input"}, {domInButton("", disabled()), false, "input"}, {domInLabel(""), false, "li"}, + {domInLabel(""), false, "option >> nth=0"}, + {domInLabel(""), false, "optgroup"}, }; for (Object[] c : cases) { String dom = (String) c[0]; diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestSelectorsRole.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestSelectorsRole.java index 0490ab288..7f8433cb4 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestSelectorsRole.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestSelectorsRole.java @@ -35,6 +35,7 @@ import java.util.Collections; import java.util.regex.Pattern; +import static com.microsoft.playwright.fixtures.Utils.browserMajorVersion; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; import static org.junit.jupiter.api.Assertions.assertAll; @@ -110,6 +111,34 @@ void shouldSupportChecked(Page page) { assertEquals(Arrays.asList(""), page.locator("role=checkbox[checked=\"mixed\"]").evaluateAll("els => els.map(e => e.outerHTML)")); assertEquals(Arrays.asList("", "", "", "
Hi
", "
Hello
", "
Unknown
"), page.locator("role=checkbox").evaluateAll("els => els.map(e => e.outerHTML)")); + + page.setContent("\n" + + "
Remember me
\n" + + " \n" + + " \n" + + "
Save
\n" + + " "); + Locator checkbox = page.getByRole(AriaRole.CHECKBOX); + assertEquals(1, page.getByRole(AriaRole.CHECKBOX, new Page.GetByRoleOptions().setChecked(true)).count()); + assertEquals(1, page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setPressed(true)).count()); + assertEquals(1, page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setExpanded(true)).count()); + assertEquals(1, page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Save")).count()); + assertThat(checkbox).isChecked(); + assertThat(checkbox).not().isEditable(); + assertThat(page.locator("body")).matchesAriaSnapshot("\n" + + " - checkbox \"Remember me\" [checked]\n" + + " - button \"Bold\" [pressed]\n" + + " - button \"Menu\" [expanded]\n" + + " - button \"Save\"\n" + + " "); + checkbox.check(); + assertThat(checkbox).hasAttribute("aria-checked", "True"); + + checkbox.evaluate("element => element.setAttribute('aria-checked', 'Mixed')"); + page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Bold")).evaluate("element => element.setAttribute('aria-pressed', 'Mixed')"); + assertEquals(1, page.locator("role=checkbox[checked=mixed]").count()); + assertEquals(1, page.locator("role=button[pressed=mixed]").count()); } @PlaywrightTest @@ -318,14 +347,21 @@ void shouldFilterHiddenUnlessExplicitlyAskedFor(Page page) { @PlaywrightTest @DisplayName("SE-060 should support name") - void shouldSupportName(Page page) { + void shouldSupportName(Page page, BrowserName browserName, Browser browser) { page.setContent("\n" + "
\n" + "
\n" + "
\n" + "
\n" + "
\n" + + "\n" + + " Chosen name\n" + + "
\n" + " "); + + Locator group = page.getByRole(AriaRole.GROUP); + assertThat(group).hasAccessibleName("Chosen name"); + assertEquals(Arrays.asList("
"), page.locator("role=button[name=\"Hello\"]").evaluateAll("els => els.map(e => e.outerHTML)")); assertEquals(Arrays.asList("
"), page.locator("role=button[name=\" \n Hello \"]").evaluateAll("els => els.map(e => e.outerHTML)")); assertEquals(Arrays.asList("
"), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Hello")).evaluateAll("els => els.map(e => e.outerHTML)")); @@ -345,6 +381,15 @@ void shouldSupportName(Page page) { assertEquals(Arrays.asList("
"), page.locator("role=button[name=Hello]").evaluateAll("els => els.map(e => e.outerHTML)")); assertEquals(Arrays.asList("
"), page.locator("role=button[name=123][include-hidden]").evaluateAll("els => els.map(e => e.outerHTML)")); assertEquals(Arrays.asList("
"), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("123").setIncludeHidden(true)).evaluateAll("els => els.map(e => e.outerHTML)")); + + // Old electron/android do not have this API. + boolean isMissingAriaLabelledByElements = browserName == BrowserName.CHROMIUM && browserMajorVersion(browser) < 135; + if (!isMissingAriaLabelledByElements) { + group.evaluate("element => {\n" + + " element.ariaLabelledByElements = [document.querySelector('#title')];\n" + + "}"); + assertEquals(Arrays.asList("
"), page.getByRole(AriaRole.GROUP, new Page.GetByRoleOptions().setName("Chosen name").setExact(true)).evaluateAll("els => els.map(e => e.outerHTML)")); + } } @PlaywrightTest @@ -441,140 +486,4 @@ void shouldNotMatchScopeByDefault(Page page) { assertThat(children).hasCount(2); assertThat(children).hasText(new String[] {"child 1", "child 2"}); } - - @PlaywrightTest - @DisplayName("SE-066 should not match inert elements, unless explicitly asked for") - @Fixme("driver: the driver 1.64.1 does not skip inert elements in role selectors: getByRole(BUTTON) returns , , ... instead of the three visible buttons") - void shouldNotMatchInertElementsUnlessExplicitlyAskedFor(Page page) { - page.setContent("\n" + - " \n" + - " \n" + - "
\n" + - " \n" + - "
\n" + - "
\n" + - " \n" + - "
\n" + - "
\n" + - " \n" + - " "); - assertEquals(Arrays.asList("", "", ""), page.getByRole(AriaRole.BUTTON).evaluateAll("els => els.map(e => e.outerHTML)")); - assertEquals(Arrays.asList("", "", "", "", "", "", ""), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setIncludeHidden(true)).evaluateAll("els => els.map(e => e.outerHTML)")); - assertThat(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Yay"))).hasCount(0); - assertThat(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Yay").setIncludeHidden(true))).hasCount(1); - - // Inert content does not contribute to the accessible name. - assertThat(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Save"))).hasCount(0); - assertThat(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Save").setIncludeHidden(true))).hasCount(1); - - page.locator("#container").evaluate("e => e.removeAttribute('inert')"); - assertEquals(Arrays.asList("", "", "", "", ""), page.getByRole(AriaRole.BUTTON).evaluateAll("els => els.map(e => e.outerHTML)")); - } - - @PlaywrightTest - @DisplayName("SE-067 should not match elements outside of a modal dialog") - @Fixme("driver: the driver 1.64.1 does not skip elements outside of a modal dialog in role selectors: expected <[]> but was <[, , , ]>") - void shouldNotMatchElementsOutsideOfAModalDialog(Page page) { - page.setContent("\n" + - " \n" + - " \n" + - " \n" + - "
\n" + - "
\n" + - " \n" + - " \n" + - " "); - assertEquals(Arrays.asList(""), page.getByRole(AriaRole.BUTTON).evaluateAll("els => els.map(e => e.outerHTML)")); - assertEquals(Arrays.asList("", "", "", ""), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setIncludeHidden(true)).evaluateAll("els => els.map(e => e.outerHTML)")); - assertThat(page.getByRole(AriaRole.DIALOG)).hasCount(1); - assertThat(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Outside"))).hasCount(0); - - page.locator("#dialog").evaluate("e => e.close()"); - assertEquals(Arrays.asList("", ""), page.getByRole(AriaRole.BUTTON).evaluateAll("els => els.map(e => e.outerHTML)")); - } - - @PlaywrightTest - @DisplayName("SE-068 should match the topmost modal dialog") - @Fixme("driver: the driver 1.64.1 does not skip elements outside of the topmost modal dialog in role selectors: expected <[]> but was <[, , ]>") - void shouldMatchTheTopmostModalDialog(Page page) { - page.setContent("\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "
\n" + - " \n" + - "
\n" + - " \n" + - " "); - assertEquals(Arrays.asList(""), page.getByRole(AriaRole.BUTTON).evaluateAll("els => els.map(e => e.outerHTML)")); - - page.locator("#inner").evaluate("e => e.close()"); - assertEquals(Arrays.asList(""), page.getByRole(AriaRole.BUTTON).evaluateAll("els => els.map(e => e.outerHTML)")); - - // Modal dialog inside an inert subtree is not inert. - page.locator("#outer").evaluate("e => e.close()"); - page.locator("#escaping").evaluate("e => e.showModal()"); - assertEquals(Arrays.asList(""), page.getByRole(AriaRole.BUTTON).evaluateAll("els => els.map(e => e.outerHTML)")); - } - - @PlaywrightTest - @DisplayName("SE-069 should respect PLAYWRIGHT_SKIP_INERT_CHECK") - void shouldRespectPLAYWRIGHTSKIPINERTCHECK(TestServer server, BrowserName browserName) { - // Java: process.env of the in-process driver is the env of the driver process that a new Playwright starts. - try (Playwright playwright = Playwright.create(new Playwright.CreateOptions().setEnv(Collections.singletonMap("PLAYWRIGHT_SKIP_INERT_CHECK", "1"))); - Browser browser = browserName.browserType(playwright).launch(Env.launchOptions())) { - Page page = browser.newPage(); - // Navigation creates a fresh injected script that reads the env variable. - page.navigate(server.EMPTY_PAGE); - page.setContent("\n" + - " \n" + - "
\n" + - " \n" + - " \n" + - " "); - assertEquals(Arrays.asList("", "", ""), page.getByRole(AriaRole.BUTTON).evaluateAll("els => els.map(e => e.outerHTML)")); - } - } - - @PlaywrightTest - @DisplayName("SE-070 should respect PLAYWRIGHT_SKIP_DIALOG_CHECK") - @Fixme("driver: the driver 1.64.1 does not skip inert elements in role selectors, so is returned: expected <[, ]> but was <[, , ]>") - void shouldRespectPLAYWRIGHTSKIPDIALOGCHECK(TestServer server, BrowserName browserName) { - // Java: process.env of the in-process driver is the env of the driver process that a new Playwright starts. - try (Playwright playwright = Playwright.create(new Playwright.CreateOptions().setEnv(Collections.singletonMap("PLAYWRIGHT_SKIP_DIALOG_CHECK", "1"))); - Browser browser = browserName.browserType(playwright).launch(Env.launchOptions())) { - Page page = browser.newPage(); - // Navigation creates a fresh injected script that reads the env variable. - page.navigate(server.EMPTY_PAGE); - page.setContent("\n" + - " \n" + - "
\n" + - " \n" + - " \n" + - " "); - assertEquals(Arrays.asList("", ""), page.getByRole(AriaRole.BUTTON).evaluateAll("els => els.map(e => e.outerHTML)")); - } - } - } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestToMatchAriaSnapshot.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestToMatchAriaSnapshot.java index f63e9dc6c..7a3c78437 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestToMatchAriaSnapshot.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestToMatchAriaSnapshot.java @@ -1112,10 +1112,14 @@ void invalidAttribute(Page page) { page.setContent("\n" + " \n" + " \n" + + " \n" + + " \n" + " "); assertThat(page).matchesAriaSnapshot("\n" + " - textbox \"Bio\" [invalid=grammar]\n" + " - textbox \"Note\" [invalid=spelling]\n" + + " - textbox \"Mixed-case grammar\" [invalid=grammar]\n" + + " - textbox \"Mixed-case spelling\" [invalid=spelling]\n" + " "); // A `grammar` value is distinct from a plain `true` invalid state. diff --git a/playwright/src/test/upstream_base.txt b/playwright/src/test/upstream_base.txt index 2127e74f9..2564e253b 100644 --- a/playwright/src/test/upstream_base.txt +++ b/playwright/src/test/upstream_base.txt @@ -5,4 +5,4 @@ # git log ..main --oneline -- tests/page tests/library tests/registry.md # git diff ..main -- tests/page tests/library tests/registry.md # and move this line forward together with the registry copy and the ports. -8c1b148f3d73120aa90f10119920358062fda177 2026-10-25 docs(ci): align upload-artifact to v5 in CI guides (#43624) +26137face0500cacddf90c767dc1364da7262559 2026-11-04 docs(release-notes): update Chromium version for 1.65 (#43914) diff --git a/playwright/src/test/upstream_not_ported.txt b/playwright/src/test/upstream_not_ported.txt index 47ab30cda..3454689bb 100644 --- a/playwright/src/test/upstream_not_ported.txt +++ b/playwright/src/test/upstream_not_ported.txt @@ -74,7 +74,6 @@ CL-043 java: concurrent: page.evaluate while page.click is pending CL-044 java: concurrent: page.evaluate while page.click is pending CL-049 java: concurrent: page.evaluate while page.click is pending CL-050 java: concurrent: page.evaluate while page.click is pending -CL-051 java: concurrent: page.evaluate while page.click is pending CL-052 java: concurrent: page.evaluate while page.click is pending CL-053 java: concurrent: page.evaluate while page.click is pending CL-055 java: concurrent: page.evaluate while page.click is pending @@ -215,7 +214,7 @@ FI-020 java: concurrent: page.evaluate while page.fill is pending FI-021 java: concurrent: page.evaluate while page.fill is pending FI-022 java: concurrent: page.evaluate while page.fill is pending FI-034 java: concurrent: page.evaluate while page.fill is pending -FI-035 java: concurrent: page.evaluate while page.fill is pending +SO-034 java: concurrent: expect(locator).toHaveValue while locator.selectOption is pending # page/page-filechooser FC-003 page.prependListener() is a Node.js EventEmitter method; the Java event API has only onX() and offX(). FC-006 page.addListener() and page.removeListener() are Node.js EventEmitter aliases of on() and off(); the Java event API has only onX() and offX() (covered by FC-005). @@ -303,7 +302,7 @@ IS-021 page.addInitScript(script, arg, { exposeFunctions }) takes a functio IS-022 page.addInitScript(script, arg, { exposeFunctions }) takes a function argument and an options object; the Java addInitScript() takes only a String or a Path. IS-023 page.addInitScript(script, arg, { exposeFunctions }) takes a function argument and an options object; the Java addInitScript() takes only a String or a Path. # page/page-add-locator-handler -LH-005 The never-settling handler (new Promise(() => {})) has no Java equivalent: handlers run on the thread that dispatches client messages, so a handler that never returns hangs the client for good (a handler waiting in page.waitForTimeout(9999999) hangs the run). +LH-005 The handler that stays pending until the test releases it (await releaseHandler, resolved after the click has timed out) has no Java equivalent: handlers run on the thread that dispatches client messages, so a handler that does not return hangs the client (a handler waiting in page.waitForTimeout(9999999) hangs the run). LH-008 Uses expect(page).toHaveScreenshot(); it is not in the Java API. # page/page-set-input-files IF-009 TODO harness: needs formidable, a multipart/form-data parser for the request of the test server. @@ -694,6 +693,7 @@ MC-016 TODO harness: needs startRemoteServer (the remoteServer fixture is b MC-017 TODO harness: needs startRemoteServer (the remoteServer fixture is browserType.launchServer({ _sharedBrowser: true }), which the Java API does not have; the harness has no remote server and childProcess to start the driver's launch-server). MC-018 TODO harness: needs startRemoteServer (the remoteServer fixture is browserType.launchServer({ _sharedBrowser: true }), which the Java API does not have; the harness has no remote server and childProcess to start the driver's launch-server). MC-019 Calls the internal context._startRecording() / _stopRecording() with JavaScript recorder callbacks. +MC-020 TODO harness: needs startRemoteServer (the remoteServer fixture is browserType.launchServer({ _sharedBrowser: true }), which the Java API does not have; the harness has no remote server and childProcess to start the driver's launch-server). # library/network-timeout NE-128 Calls utils.httpRequest() of the Node.js driver code, which the Java client does not have. NE-129 Calls utils.httpRequest() of the Node.js driver code, which the Java client does not have. diff --git a/playwright/src/test/upstream_registry.md b/playwright/src/test/upstream_registry.md index ad2c6a1c5..2ea010316 100644 --- a/playwright/src/test/upstream_registry.md +++ b/playwright/src/test/upstream_registry.md @@ -59,7 +59,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `DI` | Dialog | `page/page-dialog` | | `DO` | Download | `library/{download, downloads-path}` | | `DV` | Device | `library/{browsercontext-device, browsercontext-dsf, browsercontext-viewport-mobile}` | -| `EE` | Event emitter | `page/page-listeners`
`library/events/{add-listeners, check-listener-leaks, events-list, listener-count, listeners-side-effects, listeners, max-listeners, method-names, modify-in-emit, num-args, once, prepend, remove-all-listeners-wait, remove-all-listeners, remove-listeners, set-max-listeners-side-effects, special-event-names, subclass, symbols}` | +| `EE` | Event emitter | `page/page-listeners`
`library/events/{add-listeners, check-listener-leaks, events-list, listener-count, listeners-side-effects, listeners, max-listeners, method-names, modify-in-emit, num-args, once, prepend, remove-all-listeners-wait, remove-all-listeners, remove-listeners, set-max-listeners-side-effects, special-event-names, subclass, symbols, listener-errors}` | | `EF` | Expose function | `page/page-expose-function`
`library/browsercontext-expose-function` | | `EH` | ElementHandle | `page/{elementhandle-bounding-box, elementhandle-click, elementhandle-content-frame, elementhandle-convenience, elementhandle-eval-on-selector, elementhandle-misc, elementhandle-owner-frame, elementhandle-press, elementhandle-query-selector, elementhandle-screenshot, elementhandle-scroll-into-view, elementhandle-select-text, elementhandle-type, elementhandle-wait-for-element-state}` | | `EM` | Emulation | `page/page-emulate-media`
`library/{emulation-focus, emulation-coop}` | @@ -78,6 +78,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `GN` | Locator and selector generator | `library/{locator-generator, selector-generator}` | | `HA` | HAR | `library/{har, browsercontext-har, har-websocket}` | | `HE` | Headful | `library/headful` | +| `HS` | HTTP server | `library/unit/http-server` | | `HT` | Hit target | `library/hit-target` | | `IF` | Input files | `page/page-set-input-files` | | `IN` | Inspector | `library/inspector/{pause, recorder-api, console-api, title}` | @@ -184,8 +185,6 @@ subsystem, add a row to the Subsystems table. Then update this file: | `AR-043` | `page/page-aria-snapshot.spec.ts` | should snapshot with box from locator | | `AR-044` | `page/page-aria-snapshot.spec.ts` | should not include box when option is omitted | | `AR-045` | `page/page-aria-snapshot.spec.ts` | should not include hidden iframes | -| `AR-046` | `page/page-aria-snapshot.spec.ts` | should not include inert elements | -| `AR-047` | `page/page-aria-snapshot.spec.ts` | should only include the modal dialog content | | `AR-048` | `page/page-aria-snapshot-ai.spec.ts` | should generate refs | | `AR-049` | `page/page-aria-snapshot-ai.spec.ts` | should list iframes | | `AR-050` | `page/page-aria-snapshot-ai.spec.ts` | should snapshot a locator inside an iframe | @@ -232,8 +231,6 @@ subsystem, add a row to the Subsystems table. Then update this file: | `AR-091` | `page/page-aria-snapshot-ai.spec.ts` | should annotate aria-hidden elements | | `AR-092` | `page/page-aria-snapshot-ai.spec.ts` | should only annotate the top element in a hidden subtree | | `AR-093` | `page/page-aria-snapshot-ai.spec.ts` | should not include hidden iframes | -| `AR-094` | `page/page-aria-snapshot-ai.spec.ts` | should not generate refs for inert elements | -| `AR-095` | `page/page-aria-snapshot-ai.spec.ts` | should not generate refs for elements outside of a modal dialog | | `AR-096` | `page/page-aria-snapshot-json.spec.ts` | should snapshot roles, names and text | | `AR-097` | `page/page-aria-snapshot-json.spec.ts` | should snapshot flags as properties | | `AR-098` | `page/page-aria-snapshot-json.spec.ts` | should snapshot link url and textbox value | @@ -309,6 +306,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `AR-168` | `library/role-utils.spec.ts` | should resolve css content property for an element | | `AR-169` | `library/role-utils.spec.ts` | should ignore invalid aria-labelledby | | `AR-170` | `library/role-utils.spec.ts` | should support search element | +| `AR-171` | `page/page-aria-snapshot.spec.ts` | should include inert elements and elements outside of a modal dialog | ### AT — Add script and style tags @@ -609,6 +607,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `BT-101` | `library/browsertype-launch-selenium.spec.ts` | selenium grid 4.8.3 standalone chromium broken driver | | `BT-102` | `library/browsertype-launch-selenium.spec.ts` | selenium grid 3.141.59 standalone non-chromium | | `BT-103` | `library/browsertype-launch-selenium.spec.ts` | selenium grid 3.141.59 standalone chromium through run-driver | +| `BT-104` | `library/browsertype-launch-server.spec.ts` | launch server › should handle timeout | ### BU — Before unload @@ -765,6 +764,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `CD-050` | `library/chromium/session.spec.ts` | should emit close event when session is detached | | `CD-051` | `library/chromium/session.spec.ts` | should emit close event when page closes | | `CD-052` | `library/chromium/session.spec.ts` | should work with newBrowserCDPSession | +| `CD-053` | `library/chromium/connect-over-cdp.spec.ts` | should connect when another client inspects a terminated shared worker | ### CF — Code frame @@ -1225,6 +1225,8 @@ subsystem, add a row to the Subsystems table. Then update this file: | `CK-217` | `library/unit/clock.spec.ts` | Intl API › Creates a RelativeTimeFormat like normal | | `CK-218` | `library/unit/clock.spec.ts` | works with slow setTimeout in busy embedder | | `CK-219` | `library/unit/clock.spec.ts` | works with slow setTimeout in busy embedder when not paused | +| `CK-220` | `library/page-clock.spec.ts` | while on pause › should keep timers scheduled during load pending when paused | +| `CK-221` | `library/unit/clock.spec.ts` | runFor › should wait for an in-progress timer after replay pauses the clock | ### CL — Click @@ -1280,7 +1282,6 @@ subsystem, add a row to the Subsystems table. Then update this file: | `CL-048` | `page/page-click.spec.ts` | should fail when obscured and not waiting for hit target | | `CL-049` | `page/page-click.spec.ts` | should wait for button to be enabled | | `CL-050` | `page/page-click.spec.ts` | should wait for element to become non-inert | -| `CL-051` | `page/page-click.spec.ts` | should wait for modal dialog to close | | `CL-052` | `page/page-click.spec.ts` | should wait for input to be enabled | | `CL-053` | `page/page-click.spec.ts` | should wait for select to be enabled | | `CL-054` | `page/page-click.spec.ts` | should click disabled div | @@ -1342,7 +1343,6 @@ subsystem, add a row to the Subsystems table. Then update this file: | `CL-110` | `page/page-click-timeout-1.spec.ts` | should avoid side effects after timeout | | `CL-111` | `page/page-click-timeout-1.spec.ts` | should timeout waiting for button to be enabled | | `CL-112` | `page/page-click-timeout-1.spec.ts` | should timeout waiting for inert element to become non-inert | -| `CL-113` | `page/page-click-timeout-1.spec.ts` | should timeout waiting for element outside of a modal dialog | | `CL-114` | `page/page-click-timeout-2.spec.ts` | should timeout waiting for display:none to be gone | | `CL-115` | `page/page-click-timeout-2.spec.ts` | should timeout waiting for visibility:hidden to be gone | | `CL-116` | `page/page-click-timeout-3.spec.ts` | should fail when element jumps during hit testing | @@ -1838,6 +1838,10 @@ subsystem, add a row to the Subsystems table. Then update this file: | `EE-054` | `library/events/subclass.spec.ts` | myee instance | | `EE-055` | `library/events/subclass.spec.ts` | MyEE2 instance | | `EE-056` | `library/events/symbols.spec.ts` | should support symbols | +| `EE-057` | `library/events/listener-errors.spec.ts` | should report synchronous listener errors and continue dispatch | +| `EE-058` | `library/events/listener-errors.spec.ts` | should capture rejections from promises and thenables | +| `EE-059` | `library/events/listener-errors.spec.ts` | should read then only once and handle errors while inspecting thenables | +| `EE-060` | `library/events/listener-errors.spec.ts` | should not swallow unhandled rejections or recurse on error listener failures | ### EF — Expose function @@ -1999,6 +2003,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `EH-121` | `page/elementhandle-wait-for-element-state.spec.ts` | should wait for button with an aria-disabled parent | | `EH-122` | `page/elementhandle-wait-for-element-state.spec.ts` | should wait for stable position | | `EH-123` | `page/elementhandle-wait-for-element-state.spec.ts` | should wait for editable input | +| `EH-124` | `page/elementhandle-scroll-into-view.spec.ts` | should scroll nested display:contents into view | ### EM — Emulation @@ -2856,7 +2861,6 @@ subsystem, add a row to the Subsystems table. Then update this file: | `FI-032` | `page/page-fill.spec.ts` | fill back to back | | `FI-033` | `page/page-fill.spec.ts` | should fill contenteditable with focus handler that collapses selection | | `FI-034` | `page/page-fill.spec.ts` | should retry on inert element | -| `FI-035` | `page/page-fill.spec.ts` | should retry on element outside of a modal dialog | | `FI-036` | `page/page-fill.spec.ts` | should fail with a nice error on inert element | ### FO — Focus @@ -2875,6 +2879,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `FO-010` | `page/page-focus.spec.ts` | keeps focus on element when attempting to focus a non-focusable element | | `FO-011` | `page/page-focus.spec.ts` | should move focus from an iframe to its parent | | `FO-012` | `page/page-focus.spec.ts` | should tab from an iframe to its parent | +| `FO-013` | `page/page-focus.spec.ts` | should move focus from the parent into its iframe | ### FR — Frame @@ -3039,6 +3044,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `GN-102` | `library/selector-generator.spec.ts` | selector generator › should generate noText: ignore aria-describedby pointing inside the element | | `GN-103` | `library/selector-generator.spec.ts` | selector generator › should prefer role with hasText to css with hasText | | `GN-104` | `library/selector-generator.spec.ts` | selector generator › should not use icon fonts aria name | +| `GN-105` | `library/selector-generator.spec.ts` | selector generator › should not throw for slotted element when host shadow root has a twin | ### HA — HAR @@ -3157,6 +3163,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `HA-111` | `library/har-websocket.spec.ts` | should still allow routeWebSocket to modify messages when capturing HAR | | `HA-112` | `library/har-websocket.spec.ts` | should respect PLAYWRIGHT\_HAR\_NO\_WEBSOCKET\_FRAMES | | `HA-113` | `library/har.spec.ts` | should store binary content with a textual mime type as base64 | +| `HA-114` | `library/browsercontext-har.spec.ts` | should reject a malformed har.zip | ### HE — Headful @@ -3179,6 +3186,13 @@ subsystem, add a row to the Subsystems table. Then update this file: | `HE-015` | `library/headful.spec.ts` | headless and headful should use same default fonts | | `HE-016` | `library/headful.spec.ts` | should have the same hyphen rendering on headless and headed | +### HS — HTTP server + +| ID | File | Title | +|---|---|---| +| `HS-001` | `library/unit/http-server.spec.ts` | should not serve files through a symlink that leaves the folder | +| `HS-002` | `library/unit/http-server.spec.ts` | should close upgrade requests to unknown paths | + ### HT — Hit target | ID | File | Title | @@ -3231,6 +3245,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `IF-019` | `page/page-set-input-files.spec.ts` | input event.composed should be true and cross shadow dom boundary | | `IF-020` | `page/page-set-input-files.spec.ts` | input should trigger events when files changed second time | | `IF-021` | `page/page-set-input-files.spec.ts` | should preserve lastModified timestamp | +| `IF-022` | `page/page-set-input-files.spec.ts` | should store an uploaded file in IndexedDB | ### IN — Inspector @@ -3727,6 +3742,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `MC-017` | `library/multiclient.spec.ts` | screencast should deliver cached last frame to a new client | | `MC-018` | `library/multiclient.spec.ts` | should stop tracing upon disconnect | | `MC-019` | `library/multiclient.spec.ts` | should not deliver an action buffered before the second recording started | +| `MC-020` | `library/multiclient.spec.ts` | should run locator handlers after reconnecting with a pending callback | ### MO — Mouse @@ -3950,7 +3966,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `NE-087` | `page/page-event-network.spec.ts` | Page.Events.RequestFinished @smoke | | `NE-088` | `page/page-event-network.spec.ts` | should fire events in proper order | | `NE-089` | `page/page-event-network.spec.ts` | should support redirects | -| `NE-090` | `page/page-event-network.spec.ts` | should resolve responses after a navigation | +| `NE-090` | `page/page-event-network.spec.ts` | should resolve responses after a cross-process navigation | | `NE-091` | `page/page-event-request.spec.ts` | should fire for navigation requests | | `NE-092` | `page/page-event-request.spec.ts` | should fire for iframes | | `NE-093` | `page/page-event-request.spec.ts` | should fire for fetches | @@ -4003,6 +4019,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `NE-140` | `library/ignorehttpserrors.spec.ts` | should work with WebSocket | | `NE-141` | `library/ignorehttpserrors.spec.ts` | should fail with WebSocket if not ignored | | `NE-142` | `library/ignorehttpserrors.spec.ts` | serviceWorker should intercept document request | +| `NE-143` | `page/page-event-network.spec.ts` | should resolve responses after a same-process navigation | ### OO — OOPIF @@ -4172,6 +4189,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `PO-026` | `library/popup.spec.ts` | should not dispatch binding on a closed page | | `PO-027` | `library/popup.spec.ts` | should not throttle rAF in the opener page | | `PO-028` | `library/popup.spec.ts` | should not throw when click closes popup | +| `PO-029` | `library/popup.spec.ts` | should load subresources of an about:blank popup when the opener has routes | ### PR — Proxy @@ -4528,6 +4546,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `RO-199` | `library/unroute-behavior.spec.ts` | route.fulfill should not throw if page has been closed | | `RO-200` | `library/unroute-behavior.spec.ts` | should not continue requests in flight (page) | | `RO-201` | `library/unroute-behavior.spec.ts` | should not continue requests in flight (context) | +| `RO-202` | `page/page-route.spec.ts` | should continue a request reported while interception was disabled | ### SC — Screencast @@ -4641,11 +4660,6 @@ subsystem, add a row to the Subsystems table. Then update this file: | `SE-063` | `page/selectors-role.spec.ts` | hidden with shadow dom slots | | `SE-064` | `page/selectors-role.spec.ts` | should support output accessible name | | `SE-065` | `page/selectors-role.spec.ts` | should not match scope by default | -| `SE-066` | `page/selectors-role.spec.ts` | should not match inert elements, unless explicitly asked for | -| `SE-067` | `page/selectors-role.spec.ts` | should not match elements outside of a modal dialog | -| `SE-068` | `page/selectors-role.spec.ts` | should match the topmost modal dialog | -| `SE-069` | `page/selectors-role.spec.ts` | should respect PLAYWRIGHT\_SKIP\_INERT\_CHECK | -| `SE-070` | `page/selectors-role.spec.ts` | should respect PLAYWRIGHT\_SKIP\_DIALOG\_CHECK | | `SE-071` | `page/selectors-get-by.spec.ts` | getByTestId should work | | `SE-072` | `page/selectors-get-by.spec.ts` | getByTestId with custom testId should work | | `SE-073` | `page/selectors-get-by.spec.ts` | getByTestId with comma-separated testIdAttributes should match any | @@ -4859,6 +4873,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `SO-031` | `page/page-select-option.spec.ts` | should wait for option to be enabled | | `SO-032` | `page/page-select-option.spec.ts` | should wait for optgroup to be enabled | | `SO-033` | `page/page-select-option.spec.ts` | should wait for select to be swapped | +| `SO-034` | `page/page-select-option.spec.ts` | should wait for select to become non-inert | ### SQ — Sequence @@ -4980,6 +4995,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `SS-093` | `library/screenshot.spec.ts` | element screenshot › should capture full element when larger than viewport with device scale factor and scale:css | | `SS-094` | `library/screenshot.spec.ts` | element screenshot › page screenshot should capture css transform with device pixels | | `SS-095` | `page/page-screenshot.spec.ts` | page screenshot › should capture webgl canvas after its drawing buffer is resized | +| `SS-096` | `page/page-screenshot.spec.ts` | page screenshot › should not wait for unused font face with failed local() source | ### ST — Storage @@ -5232,6 +5248,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `TV-133` | `library/snapshot-renderer.spec.ts` | snapshot renderer still renders ordinary custom elements | | `TV-134` | `library/snapshot-renderer.spec.ts` | stripAnsiEscapes should not exhibit polynomial backtracking | | `TV-135` | `library/snapshot-renderer.spec.ts` | stripAnsiEscapes handles common ANSI sequences after fix | +| `TV-136` | `library/snapshot-renderer.spec.ts` | snapshot renderer selects the nearest out-of-order screencast frame | ### TZ — Timezone @@ -5254,6 +5271,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `UA-004` | `library/browsercontext-user-agent.spec.ts` | should make a copy of default options | | `UA-005` | `library/browsercontext-user-agent.spec.ts` | custom user agent for download | | `UA-006` | `library/browsercontext-user-agent.spec.ts` | should work for navigator.userAgentData and sec-ch-ua headers | +| `UA-007` | `library/browsercontext-user-agent.spec.ts` | should preserve custom user agent in route.fetch | ### VI — Video diff --git a/scripts/DRIVER_VERSION b/scripts/DRIVER_VERSION index 7f0db5693..f555418ea 100644 --- a/scripts/DRIVER_VERSION +++ b/scripts/DRIVER_VERSION @@ -1 +1 @@ -a1f35e1955976e84411f9c10358228a80b763ebe +26137face0500cacddf90c767dc1364da7262559 diff --git a/scripts/roll_driver.sh b/scripts/roll_driver.sh index 23022b61f..def3c7ebb 100755 --- a/scripts/roll_driver.sh +++ b/scripts/roll_driver.sh @@ -52,6 +52,9 @@ echo $NEW_COMMIT > ./DRIVER_VERSION ./generate_api.sh ./update_readme.sh +# The playwright module takes the driver from the local Maven repository. +(cd .. && mvn -B clean install -D skipTests --no-transfer-progress -pl driver,driver-bundle) + echo "" echo "Rolled the driver from $OLD_COMMIT to $NEW_COMMIT." echo "To list the upstream commits of the roll, run:" diff --git a/scripts/update_readme.js b/scripts/update_readme.js new file mode 100644 index 000000000..3cc23a106 --- /dev/null +++ b/scripts/update_readme.js @@ -0,0 +1,53 @@ +#!/usr/bin/env node +/** + * 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. + */ + +// Writes the browser versions of the driver to README.md. The versions come from +// packages/playwright-core/browsers.json of the upstream checkout, which upstream keeps equal +// to the versions that the browsers report (utils/doclint/cli.js). +// +// Usage: node scripts/update_readme.js + +const fs = require('fs'); +const path = require('path'); + +const upstreamDir = process.argv[2]; +if (!upstreamDir) { + console.error('Usage: node scripts/update_readme.js '); + process.exit(1); +} + +const browsersJSON = JSON.parse(fs.readFileSync(path.join(upstreamDir, 'packages', 'playwright-core', 'browsers.json'), 'utf8')); +const params = new Map(); +for (const name of ['chromium', 'firefox', 'webkit']) { + const browser = browsersJSON.browsers.find(b => b.name === name); + if (!browser || !browser.browserVersion) { + console.error(`ERROR: browsers.json has no browserVersion for "${name}"`); + process.exit(1); + } + params.set(`${name}-version`, browser.browserVersion); +} + +const readmePath = path.join(__dirname, '..', 'README.md'); +let content = fs.readFileSync(readmePath, 'utf8'); +content = content.replace(/([^<]*)/ig, (match, p1) => { + if (!params.has(p1)) { + console.error(`ERROR: Invalid generate parameter "${p1}" in "${match}"`); + process.exit(1); + } + return `${params.get(p1)}`; +}); +fs.writeFileSync(readmePath, content); diff --git a/scripts/update_readme.sh b/scripts/update_readme.sh index 11e670191..a8007ec9f 100755 --- a/scripts/update_readme.sh +++ b/scripts/update_readme.sh @@ -3,15 +3,20 @@ set -e set +x -trap "cd $(pwd -P)" EXIT +trap 'cd $(pwd -P)' EXIT +cd "$(dirname "$0")/.." -cd "$(dirname $0)/.." +DRIVER_VERSION=$(head -1 ./scripts/DRIVER_VERSION) -# Remove artifacts from previous driver (for local builds). -mvn clean - -# Built from source and do local install. -mvn install --no-transfer-progress -D skipTests +if [[ -n "$PW_SRC_DIR" ]]; then + UPSTREAM_DIR="$PW_SRC_DIR" +else + UPSTREAM_DIR="./.upstream" + if [[ "$(git -C "$UPSTREAM_DIR" rev-parse HEAD 2> /dev/null)" != "$DRIVER_VERSION" ]]; then + echo ".upstream/ is not at $DRIVER_VERSION, the commit in scripts/DRIVER_VERSION. Run: scripts/build_driver.sh" + exit 1 + fi +fi echo "Updating browser versions in README.md" -mvn compile exec:java --f ./tools/update-docs-version -D exec.mainClass=com.microsoft.playwright.tools.UpdateBrowserVersions +node ./scripts/update_readme.js "$UPSTREAM_DIR" diff --git a/tools/update-docs-version/pom.xml b/tools/update-docs-version/pom.xml deleted file mode 100644 index cf24731ad..000000000 --- a/tools/update-docs-version/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - 4.0.0 - - com.microsoft.playwright - update-version - 1.50.0-SNAPSHOT - Playwright - Update Version in Documentation - - This is an internal module used to update versions in the documentation based on - current driver. - - - 1.8 - 2.8.6 - UTF-8 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.12.1 - - ${compiler.version} - ${compiler.version} - - - - - - - com.microsoft.playwright - playwright - ${project.version} - - - - - snapshots-repo - https://oss.sonatype.org/content/repositories/snapshots - false - true - - - diff --git a/tools/update-docs-version/src/main/java/com/microsoft/playwright/tools/UpdateBrowserVersions.java b/tools/update-docs-version/src/main/java/com/microsoft/playwright/tools/UpdateBrowserVersions.java deleted file mode 100644 index 3cd8217cf..000000000 --- a/tools/update-docs-version/src/main/java/com/microsoft/playwright/tools/UpdateBrowserVersions.java +++ /dev/null @@ -1,56 +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. - */ - -package com.microsoft.playwright.tools; - -import com.microsoft.playwright.Browser; -import com.microsoft.playwright.BrowserType; -import com.microsoft.playwright.Playwright; - -import java.io.FileWriter; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Arrays; -import java.util.List; - -import static java.nio.charset.StandardCharsets.UTF_8; - -public class UpdateBrowserVersions { - public static void main(String[] args) throws Exception { - Path path = Paths.get("README.md"); - String readme = new String(Files.readAllBytes(path), UTF_8); - - Playwright playwright = Playwright.create(); - List browserTypes = Arrays.asList( - playwright.chromium(), - playwright.webkit(), - playwright.firefox() - ); - for (BrowserType browserType : browserTypes) { - Browser browser = browserType.launch(); - String version = browser.version(); - browser.close(); - readme = readme.replaceAll( - "([^<]+)", - "" + version + ""); - try (FileWriter writer = new FileWriter(path.toFile())) { - writer.write(readme); - } - } - playwright.close(); - } -} From 1e3ae390c9dbf76945f0885193bbecdbbe042d24 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Mon, 23 Nov 2026 10:10:16 -0800 Subject: [PATCH 2/3] test: set TCP_NODELAY on the sockets of the test server The server writes the headers and the body of a response separately. With Nagle's algorithm the body waited for the delayed ACK of the browser, 40 ms per response on a keep-alive connection. LO-182 races a navigation against a query in the frame and failed on WebKit on Ubuntu. --- .../java/com/microsoft/playwright/fixtures/TestServer.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/playwright/src/test/java/com/microsoft/playwright/fixtures/TestServer.java b/playwright/src/test/java/com/microsoft/playwright/fixtures/TestServer.java index e9c09cc6d..6e6a7f49f 100644 --- a/playwright/src/test/java/com/microsoft/playwright/fixtures/TestServer.java +++ b/playwright/src/test/java/com/microsoft/playwright/fixtures/TestServer.java @@ -928,6 +928,9 @@ public static final class Connection { this.socket = socket; OutputStream out; try { + // Node's http server sets TCP_NODELAY on its sockets. Without it the body, written after + // the headers, waits for the delayed ACK of the browser: 40 ms per response on Linux. + socket.setTcpNoDelay(true); out = socket.getOutputStream(); } catch (IOException e) { out = null; From 49aca860c918ba5abd39234c5c44e531f3907c0d Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Mon, 23 Nov 2026 10:32:52 -0800 Subject: [PATCH 3/3] docs: add ARCHITECTURE.md The driver, the wire protocol, the object model, the threading model, the generated API and the test harness of the Java client. --- AGENTS.md | 2 +- ARCHITECTURE.md | 167 ++++++++++++++++++++++++++++++++++ playwright/src/main/AGENTS.md | 3 +- 3 files changed, 170 insertions(+), 2 deletions(-) create mode 100644 ARCHITECTURE.md diff --git a/AGENTS.md b/AGENTS.md index 7cb7764b7..f69309157 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # Playwright Java -The Java client is a port of the JavaScript client in `~/code/playwright/packages/playwright-core/src/client/`. It is a line-by-line translation: when implementing or changing a method, read the corresponding JS file first and translate it statement by statement. `playwright/src/main/AGENTS.md` has the rules. +The Java client is a port of the JavaScript client in `~/code/playwright/packages/playwright-core/src/client/`. It is a line-by-line translation: when implementing or changing a method, read the corresponding JS file first and translate it statement by statement. `playwright/src/main/AGENTS.md` has the rules. `ARCHITECTURE.md` describes the driver, the wire protocol, the object model, the threading model and the test harness. Paths such as `~/code/playwright` in this file assume that you check the repos out in `~/code`. Use the `gh` cli to interact with GitHub. diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 000000000..2309468a5 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,167 @@ +# Playwright Java architecture + +How the Java client is built: the driver, the wire protocol, the object model, the threading model, the generated API and the test harness. Read it before you change `playwright/src/main/java/com/microsoft/playwright/impl` or the `driver` module. The upstream checkout in `.upstream/` is the reference for client logic, protocol and tests. The rules for porting the client are in `playwright/src/main/AGENTS.md`, the rules for porting the tests in `playwright/src/test/AGENTS.md`. + +## Contracts + +Four things are contracts, and the tests check them; everything else is an implementation choice. + +- **The public API**: `com.microsoft.playwright`, `.options` and `.assertions`. Generated from the upstream API docs; the test sources compile against it. +- **The driver and protocol**: the stock Node.js `playwright-core` driver, spoken to over the same JSON protocol as every other language port. Java never talks to a browser. +- **The execution model**: a synchronous, single-threaded API; events are delivered only while the caller is inside a Playwright call. +- **The error surface**: `PlaywrightException`, `TimeoutError`, `TargetClosedError`, and driver error text that the tests check with `contains`. + +## Repository layout + +| Path | Role | +| --- | --- | +| `driver/` | `Driver`, `DriverJar`, `DriverLogging` plus the resource `driver/package/` = the `playwright-core` package built from source by `scripts/build_driver.sh` (not in git) | +| `driver-bundle/` | resource `driver//node` for `mac`, `mac-arm64`, `linux`, `linux-arm64`, `win32_x64` (same script); optional when `PLAYWRIGHT_NODEJS_PATH` is set | +| `playwright/` | the client: generated API packages, hand-written `impl`, the `junit` package, and all tests | +| `.upstream/` | gitignored checkout of `microsoft/playwright` at the commit in `scripts/DRIVER_VERSION`; the driver, the API docs and the protocol spec are all read from it | +| `scripts/` | `DRIVER_VERSION` (an upstream commit), `NODE_VERSION`, `build_driver.sh`, `generate_api.sh` (runs `generate_java_api.mts` and `generate_java_channels.js`), `roll_driver.sh`, release helpers | + +Java 8 source level. Gson for all JSON, JSpecify for nullness, opentest4j for assertion errors. Roll and release steps are in `ROLLING.md` and the `playwright-roll` / `playwright-java-release` skills. + +## The driver + +- `scripts/DRIVER_VERSION` pins a `microsoft/playwright` commit and `scripts/NODE_VERSION` the Node.js version; `scripts/build_driver.sh` builds `playwright-core` from `.upstream/` at that commit. The package and the Node.js binaries ship as jar resources. +- Resolution (`Driver.newInstance`): `playwright.cli.dir` / `PLAYWRIGHT_DRIVER_DIR` set → use that directory as is. Otherwise the class named by `playwright.driver.impl` (default `DriverJar`) extracts the resources into a `playwright-java-*` temp dir (under `playwright.driver.tmpdir`), copes with nested Spring Boot jars and sets executable bits. Node.js comes from `PLAYWRIGHT_NODEJS_PATH` / `playwright.nodejs.path` or the bundle. +- One install per JVM (`Driver.ensureDriverInstalled`): the first `Playwright.create()` runs `node cli.js install` unless `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` or `SELENIUM_REMOTE_URL` is set. `PlaywrightImpl.createImpl(options, true)` forces a fresh driver process for tests. +- Process: ` package/cli.js run-driver`; env = JVM env + `CreateOptions.env` + `PW_LANG_NAME=java`, `PW_LANG_NAME_VERSION=`, `PW_CLI_DISPLAY_VERSION=`. stdin/stdout are the pipe, stderr is inherited. `Playwright.close()` closes stdin and waits up to 30 s. +- `CLI.main` passes every subcommand to `cli.js` (`codegen`, `install`, `show-trace`, ...); only `install-driver` is handled in Java. +- `DEBUG=pw:install|pw:channel|pw:api` logs like upstream; `PLAYWRIGHT_JAVA_SRC` enables `StackTraceCollector` so traces and the inspector show Java source. + +## Wire protocol + +The schema is upstream `packages/protocol/spec/*.yml`; the generated `channels.d.ts` and `validator.ts` are the fastest way to look up a command. Java uses classes generated from the same spec: `scripts/generate_java_channels.js` writes `com.microsoft.playwright.impl.protocol` (one public class per file, upstream `channels.d.ts` names: `Channel` with ` method(, Double timeout)`, `Params`/`Result`, `Initializer`, `Event`, structs). `Connection.protocolGson()` maps a `ChannelOwner` to `{guid}` and `byte[]` to base64. `Utils.toProtocol(options, Params.class)` converts an options object; the overload with an owner resolves channel references. The package is excluded from the javadoc jar. + +- **Framing**: 4-byte little-endian length + UTF-8 JSON, both directions, over the driver's stdin/stdout. +- **Call**: `{id: "abcd@17", guid, method, params, metadata: {timeout?, title?, internal?, location?}}`. Other objects are referenced as `{guid}`. `timeout` never goes in `params`, only in `metadata.timeout`, and the server enforces it. The validator drops unknown keys. While tracing, the stack goes separately via `LocalUtils.addStackToTracingNoReply`. +- **Reply**: `{id, result}` or `{id, error: {error: {message, name, stack}}, errorDetails?, log?}`. `name` is `TimeoutError`, `TargetClosedError` or `Error`, mapped to `TimeoutError`, `TargetClosedError`, `DriverException`. +- **Event**: `{guid, method, params}`. Structural: `__create__ {type, guid, initializer}` (always before any reference to the guid); `__adopt__ {guid}` (a Page adopts `mainFrame`; a BrowserContext adopts `debugger`, `requestContext`, `tracing`; an APIRequestContext adopts `tracing`); `__dispose__ {reason?}` (`"gc"` = evicted; later calls throw `The object has been collected to prevent unbounded heap growth.`). Client-only: `__waitInfo__` (wait steps in the trace) and `updateSubscription {event, enabled}` for opt-in events. +- **Bootstrap**: the synthetic `Root` (guid `""`) sends `initialize {sdkLanguage: "java", supportsLoneSurrogates: true}`; the driver creates the three `BrowserType`s, `Android`, `Electron`, `LocalUtils`, then `Playwright`, and replies `{playwright: {guid}}`. A `connect()` connection bootstraps the same way and its `Playwright` carries `preLaunchedBrowser`. +- **Values** (`Serialization`, upstream `serializers.ts`): `SerializedArgument {value, handles}`; `SerializedValue` sets one of `n b s v d u bi r e a o h id/ref m se` (`ta` and `fn` are unsupported). Results: whole numbers become `Integer`, others `Double`; objects `LinkedHashMap`; arrays `ArrayList`; `null` and `undefined` both `null`. Unsupported Java types throw `PlaywrightException("Unsupported type of argument: ...")`. +- **Options**: one configured Gson instance: enums lowercased (`_` to `-`), `Optional.empty()` is an explicit null (`"no-override"`), `Map` becomes `[{name, value}]`, `Path` a string, handles and locators their refs. A few parameters are massaged after serialization (`recordVideo`, `viewport`/`noDefaultViewport`, `acceptDownloads`, client certificates, HAR options). Binary data is base64. + +## Object model + +Every server object has one Java `ChannelOwner` with the same guid, holding `connection`, `parent`, `type`, `guid`, `initializer` and its children. `Connection` owns the transport, the guid registry, pending callbacks, the id counter, the tracing counter, the current step title, `env`, `isRemote` and `LocalUtils`, and instantiates objects by `type` through a factory map as `connection.ts` does (unknown type → `PlaywrightException("Unknown type ...")`; `SocksSupport`, `Android*`, `Electron` are ignored). + +The tree as the driver creates it: + +``` +Root > BrowserType x3, LocalUtils, Playwright (> APIRequestContext from newRequest) +BrowserType > Browser > BrowserContext > Page, Tracing, Debugger, APIRequestContext (adopted), + Request, Response, Route, WebSocketRoute, BindingCall, + Dialog, CDPSession, Artifact (downloads, videos) +Page > Frame (main frame adopted), Worker, WebSocket +Frame > JSHandle, ElementHandle +``` + +- Initializers are read lazily and may only reference guids created earlier. +- Two kinds of impl classes: channel-backed (`PageImpl`, `FrameImpl`, `RequestImpl`, `TracingImpl`, `Stream`, ...) and pure client objects without a guid (`LocatorImpl`, `KeyboardImpl`, `MouseImpl`, `DownloadImpl` wrapping an `ArtifactImpl`, `ConsoleMessageImpl`, `SelectorsImpl`, `RouteHandler`, the `*AssertionsImpl`, ...). +- Same guid, same instance: tests compare `Frame`, `Page`, `Request` and `BrowserContext` with `==` and `assertEquals`. +- State only the client holds: listener maps and `updateSubscription`; `Page.frames`, `Frame.childFrames` and `loadStates` fed by `frameAttached`/`frameDetached`/`navigated`/`loadstate`; the route handler lists (`RouteHandler`, `WebSocketRouteHandler`, `HarRouter`); binding maps; `TimeoutSettings`; close reasons and `isClosed`/`isDetached`; `Selectors` registrations sent with every `newContext`; tracing chunk and HAR bookkeeping; `Browser.contexts` and `BrowserContext.pages`. + +## Threading model + +Only `PipeTransport` has threads of its own: + +``` +API thread --serialize--> outgoing queue --> Writer thread --> driver stdin +API thread <--poll 10 ms-- incoming queue <-- Reader thread <-- driver stdout +``` + +- **API thread**: the caller. It serializes the message, enqueues it and pumps until its reply arrives. +- **Reader thread**: reads frames from stdout into a bounded `ArrayBlockingQueue(1000)`. Never interrupted on close, so the driver can flush and exit. A closed pipe surfaces as `PlaywrightException("Failed to read message from driver, pipe closed.")`. +- **Writer thread**: takes strings from a bounded queue, writes frames, flushes when the queue is empty. `close()` closes stdin and interrupts only this thread. + +No timer thread: timeouts are `System.nanoTime` deadlines polled by the loop. The loop is `ChannelOwner.runUntil(code, waitable)`: run `code`, then `while (!waitable.isDone()) connection.processOneMessage()`, which polls for at most 10 ms and dispatches one message (a reply completes its `WaitableResult`; `__create__`/`__adopt__`/`__dispose__` edit the tree; anything else is `handleEvent`). + +Rules the harness relies on: + +1. Events are delivered only inside a Playwright call. State set by a handler is awaited with `page.waitForCondition(...)`; `future.get()` hangs. +2. Handlers are re-entrant: a route handler that calls `route.fulfill()` runs a nested loop that may complete the outer call and deliver more events first. +3. Wire order is dispatch order, one message per iteration. Listener lists are copied before notification, so a handler may remove itself. +4. An event wait is `WaitableRace(WaitableEvent, close helper → TargetClosedError, WaitableTimeout)`. The event subscribes before the callback runs, so `waitForPopup(() -> click())` never misses. +5. `console`, `dialog`, `dialogClosed`, `request`, `response`, `requestFinished`, `requestFailed` and `fileChooser` are opt-in: `updateSubscription` is sent asynchronously when the first listener is added. A dialog with no listener is dismissed client-side (accepted for `beforeunload`). +6. `sendMessageAsync` (route actions, `updateSubscription`, `BindingCall` replies) does not pump; `sendMessageNoReply` registers no callback. +7. Driver errors are re-thrown on the API thread as a new exception of the same class, so the stack trace points at the caller. `isSafeCloseError` filters the "has been closed" family in close paths. +8. One `Playwright` per worker, not per thread: the harness creates fixtures on a fork-join thread and runs the test body on a separate timeout thread. Strictly sequential use from different threads must work: no `ThreadLocal`, no thread affinity. +9. `connect()` layers a second `Connection` over a `JsonPipe` of the first; the same thread pumps both. +10. A hung driver is caught by a `timeout + 10 s` guard: `TimeoutError("Timeout ms exceeded while waiting for the driver to respond to . The driver is not responding.")`. + +## Generated API + +- `scripts/generate_api.sh` requires `.upstream/` at the pinned commit (or `PW_SRC_DIR`), runs `scripts/generate_java_api.mts`, which parses `docs/src/api/*.md` with the upstream parser, and then `scripts/generate_java_channels.js` for the protocol types. The markdown docs are the source of truth; every Java-specific name comes from `langs:` / `alias-java:` annotations there. `verify_api.yml` fails CI on any diff. +- Generated: one interface per class in `com.microsoft.playwright` (with nested `XxxOptions`), `assertions/*`, every enum and object type in `options/`, `ScreencastFrame`. Hand-written: `CLI`, `PlaywrightException`, `TimeoutError`, the `package-info.java` files (`@NullMarked`), `Annotate`, `BindingCallback`, `FunctionCallback`, `BrowserChannel`. Generated code calls `PlaywrightImpl.create`, `FormDataImpl`, `RequestOptionsImpl`, the three `*AssertionsImpl` and `AssertionsTimeout` by name. +- Shape rules: optional parameters produce `default` overloads from last to first; a union parameter produces one overload per member (`String | Pattern | Predicate`); waits are `waitForX(Options, Runnable)`, there is no `waitForEvent`; events are `onX`/`offX(Consumer)`; option fields are public and boxed, `T|null` fields are `Optional`, setters are fluent. `Playwright`, `Browser`, `BrowserContext` and `Page` are `AutoCloseable`. +- The `@Nullable` annotations are part of the compiled contract: NullAway consumers break without them. + +## Mapping to upstream + +Each client class is a line-by-line translation of one file of `packages/playwright-core/src/client/`: the same member order, the upstream names without the leading underscore, the same statements. A ported file starts with `// Port of .ts.` and marks each Java-specific spot with `// java: `. To find the port of a file: `grep -rlE "^// Port of .*\bpage\.ts" playwright/src/main/java`. The rules are in `playwright/src/main/AGENTS.md`. + +What does not follow from the file names: + +- `network.ts` is one class per upstream class: `RequestImpl`, `ResponseImpl`, `RouteImpl`, `WebSocketImpl`, `WebSocketRouteImpl`, `RawHeaders`, `RouteHandler`, `WebSocketRouteHandler`. `fetch.ts` is `APIRequestImpl`, `APIRequestContextImpl`, `APIResponseImpl`. +- `connect.ts` is `Connect` (static `connectToBrowser`, `connectToEndpoint`); `JsonPipe` is also the transport (`JsonPipeTransport` upstream). `PlaywrightImpl` has the Java-only driver start-up at the bottom. +- `packages/protocol/src/serializers.ts` is the first part of `Serialization` (`parseSerializedValue`, `serializeValue`, ...); its Gson configuration and adapters below are Java-only. +- The helpers of `packages/isomorphic/` without client state are in the subpackage `impl.isomorphic` (`Headers`, `StringUtils`, `MimeType`, `Time`, `LocatorUtils`). `manualPromise.ts` is `LongStandingScope` and `urlMatch.ts` is `UrlMatcher`, both in `impl`: the first is built on `ChannelOwner` and `Waitable`, the second has the driver convert globs (`LocalUtils.globToRegex`). +- `packages/playwright/src/matchers/*.ts` is `AssertionsBase`, the `*AssertionsImpl` and `AssertionsTimeout`. They are not a line-by-line port. +- `android.ts` and `electron.ts` are not ported. +- `Utils` holds only helpers with no upstream counterpart (Gson `convertType`/`clone`, `toProtocol`, `writeToFile`, regex flag conversion). + +Deliberate divergences that the tests encode: callback-style `waitForX`; `waitForCondition` on page and context; no `page.goto:` prefix in error messages (tests that need it are `@Fixme`); locator actions that need an element resolve a handle, act and dispose it; `selectors()` is a per-`Playwright` client registry; close methods swallow safe close errors; enums go through Gson adapters. + +## Timeouts and errors + +- `TimeoutSettings`: 30 000 ms for actions and navigations, 180 000 ms for launch and connect; a page chains to its context. Order: explicit option, `setDefaultNavigationTimeout` (navigation only), `setDefaultTimeout`, parent, constant. `APIRequestContext` has its own instance. Timeout `0` waits forever. +- Server-enforced timeouts travel in `metadata.timeout` and fail with the server's message (`Timeout 30000ms exceeded.` plus the call log). Client-side waits go through `Waiter` as upstream (`createForEvent`, `rejectOnEvent`, `rejectOnTimeout`, `waitForEvent`, `dispose`); the timeout message names the event, `Timeout ms exceeded while waiting for event ""`. `connect()` races the Playwright initialization against its timeout. Assertions default to 5 000 ms (`setDefaultAssertionTimeout`). +- Waitables: `WaitableResult` (a reply), `WaitableEvent` (a listener hit), `WaitablePredicate` (polled), `WaitableTimeout`, `WaitableNever`, `WaitableRace`; plus the page close helper (`TargetClosedError`), the frame detach helper (`Navigating frame was detached!`) and the frame navigation and load-state helpers. +- Exceptions: `PlaywrightException` (base) and `TimeoutError` are public; `impl.TargetClosedError` is public with the default message `Target page, context or browser has been closed`; `DriverException` wraps other server errors; `ServerErrorWithDetails` carries `errorDetails` for `expect`; assertions throw `AssertionFailedError`. +- A driver error message is `SerializedError.Error.toString()` (`Error {\n message='...'\n name='...'\n stack='...'\n}`) followed by `\nCall log:\n- ...`. Tests `contains`-check the upstream text inside `message=`. Quirk: log lines carry a doubled `- - ` prefix. + +## Assertions + +`assertThat(locator | page | response)`; `.not()` flips `isNot`. Locator and page matchers send one `Frame.expect` command with `FrameExpectOptions {selector, expression, expressionArg, expectedText[], expectedNumber, expectedValue, useInnerText, isNot, timeout}` under the title `Assert "hasText"`, and the server polls. The expression ids and the `ExpectedTextValue` flags (`normalizeWhiteSpace`, `ignoreCase`, `matchSubstring`) are copied from upstream `matchers.ts` (`to.have.text`, `to.be.visible`, `to.have.url`, `to.match.aria`, ...). A failure becomes `AssertionFailedError` with `` (`Locator expected to have text`, or `expected not to`), then `\nExpected: ...\nReceived: ...`, then `\nCall log:` when present, with expected and actual passed as `ValueWrapper`s; the ported `expect-matcher-result` tests snapshot these strings. `APIResponseAssertions.isOK()` is client-side: `Response status expected to be within [200..299] range, was ` plus the call log from `fetchLog` and `\nResponse text:` for textual MIME types. + +## Client-side subsystems + +Each is a thin layer over a server feature, with sequencing the tests observe: + +- **Routing**: `route()` prepends a `RouteHandler` to the list of the page or context and sends `setNetworkInterceptionPatterns`; on a `route` event the page router runs before the context router, newest handler first, honouring `times` and `fallback()`; when nothing handles it, `route.resume()`. Globs are compiled by `LocalUtils.globToRegex`; `unroute` compares `UrlMatcher`s. +- **HAR**: `routeFromHAR` replays through `LocalUtils.harOpen`/`harLookup` or records through `TracingImpl` (`harStart`/`harExport`). +- **WebSocket routing**: the `WebSocketRouteHandler` list plus `setWebSocketInterceptionPatterns`; `WebSocketRouteImpl` models both ends and sends `ensureOpened` when the handler did not connect to the server. +- **Bindings**: `exposeBinding {name, needsHandle}`; duplicates throw `Function "x" has been already registered`; `bindingCall` events are answered with `resolve`/`reject` asynchronously. +- **Downloads, videos, uploads**: `Artifact` commands (`pathAfterFinished`, `saveAs`, `stream`, ...); over `connect()`, `path()` throws and content streams through `Stream`/`WritableStream`; uploads send `localPaths` locally and `createTempFiles` plus streams remotely; payloads are size-checked. +- **Dialogs**: may arrive before their page exists; auto-dismissed when nobody listens. +- **Tracing**: `tracingStart` (option names rewritten), `tracingStartChunk`, `LocalUtils.tracingStarted` for a `stacksId`; `Connection.tracingCount` turns on stack shipping; `tracingStopChunk {mode}` then `LocalUtils.zip` locally or artifact save plus append remotely. +- **Selectors**: `SelectorsImpl` keeps engines and `testIdAttributeName` per `Playwright` and sends them with every context; locator builders only concatenate `internal:` selector strings. +- **Clock, CDP, screencast, storage, credentials, debugger, WebMCP**: thin command wrappers; the screencast acknowledges every frame with `screencastFrameAck`. + +## Test harness + +- `com.microsoft.playwright.fixtures` is a JUnit 5 port of upstream `browserTest.ts`: `@PlaywrightTest` runs once per browser in `BROWSER`, fixtures resolve by parameter type with `@Fixture(scope = TEST | WORKER)` overrides, and `TestServer` is a hand-written HTTP/1.1 and WebSocket server. The port rules are in `playwright/src/test/AGENTS.md`. +- Workers (`WorkerPool`) each own one `Playwright`; a worker serves one test at a time but not one thread (`separate_thread` timeout mode). +- `@Fixme("java: ..." | "driver: ..." | "harness: ...")` is a strict expected failure: a test that starts passing fails with `Test marked @Fixme passed, remove the annotation`. Most marks are for the missing `page.goto:` prefix and the JavaScript-style `Locator.toString()`. +- `upstream_base.txt` pins the ported upstream commit; `upstream_not_ported.txt` lists the exclusions, concurrent-call tests among them. + +Internals the tests reach into: + +| Symbol | Used by | +| --- | --- | +| `impl.PlaywrightImpl.createImpl(CreateOptions, boolean forceNewDriver)` | tests that need a fresh driver | +| `((PlaywrightImpl) pw).localUtils().globToRegex(glob, baseURL, webSocketUrl)` | interception tests | +| `impl.TargetClosedError` and its default message | 13 files | +| a `Process` field `driverProcess` on the class `Playwright.create()` returns | `TestUnresponsiveDriver` | +| a superclass `ChannelOwner` with a field `guid` | a connect test | +| `impl.driver.Driver.ensureDriverInstalled`, `createAndInstall`, `driverDir()`, `createProcessBuilder()`; `impl.driver.jar.DriverJar` with a no-arg constructor and `installDriverTo(Path)`; the properties `playwright.cli.dir`, `playwright.driver.tmpdir`, `playwright.nodejs.path`, `playwright.driver.impl`; env `PLAYWRIGHT_DOWNLOAD_HOST`, `PLAYWRIGHT_BROWSERS_PATH`, `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD`; the message `Failed to create driver` | driver and server tests | +| `impl.junit.BrowserContextOptionsExtension.getContextOptions`, `PlaywrightExtension.getOrCreatePlaywright` | junit tests | +| `StackTraceCollector`: exactly one `src/.java` entry per trace; `PLAYWRIGHT_JAVA_SRC` read from `CreateOptions.env` before the process env | tracing tests | +| public option fields (`LaunchOptions.headless`/`channel`, `CreateOptions.env`, `ConnectOptions.headers`, `BoundingBox`, `ViewportSize`, `Cookie.url`) | harness | + +Exact strings: `Locator@`, `JSHandle@`, `selectors.register: Selector engine name may only contain [a-zA-Z0-9_] characters`, `Connecting over CDP is only supported in Chromium and WebKit.`, `Malformed endpoint. Did you use launchServer method?`, `Timeout 100ms exceeded while waiting for the driver to respond to waitForFunction`. An exception thrown by a handler propagates out of the call that dispatched it. + +Quirks that no test depends on: the doubled call-log prefix, `metadata.wallTime` (ignored by the server), `__abort__` never sent, `ta`/`fn` values unsupported. diff --git a/playwright/src/main/AGENTS.md b/playwright/src/main/AGENTS.md index 188128d7a..7cc3afaee 100644 --- a/playwright/src/main/AGENTS.md +++ b/playwright/src/main/AGENTS.md @@ -4,7 +4,8 @@ These rules say how to write `playwright/src/main/java/com/microsoft/playwright/ `packages/playwright-core/src/client` in `microsoft/playwright`. Use them at each roll and for every fix, for every new or changed line of the client. The upstream code is in `.upstream/`, the checkout at the commit in `scripts/DRIVER_VERSION`. The steps of a roll are in the -`playwright-roll` skill. +`playwright-roll` skill. `ARCHITECTURE.md` at the repo root describes the driver, the protocol, +the object model and the threading model that this code runs on. The port is line by line. A reviewer reads the `.ts` file and the `.java` file side by side. Each JavaScript statement maps to one Java statement, or to one of the fixed patterns in this