diff --git a/README.md b/README.md index e047cfc6..24966857 100644 --- a/README.md +++ b/README.md @@ -11,9 +11,9 @@ Playwright is a Java library to automate [Chromium](https://www.chromium.org/Hom | | Linux | macOS | Windows | | :--- | :---: | :---: | :---: | -| Chromium 124.0.6367.18 | :white_check_mark: | :white_check_mark: | :white_check_mark: | +| Chromium 125.0.6422.14 | :white_check_mark: | :white_check_mark: | :white_check_mark: | | WebKit 17.4 | ✅ | ✅ | ✅ | -| Firefox 124.0 | :white_check_mark: | :white_check_mark: | :white_check_mark: | +| Firefox 125.0.1 | :white_check_mark: | :white_check_mark: | :white_check_mark: | Headless execution is supported for all the browsers on all platforms. Check out [system requirements](https://playwright.dev/java/docs/intro#system-requirements) for details. diff --git a/playwright/src/main/java/com/microsoft/playwright/APIRequestContext.java b/playwright/src/main/java/com/microsoft/playwright/APIRequestContext.java index 7336ceb4..b617be8a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/APIRequestContext.java +++ b/playwright/src/main/java/com/microsoft/playwright/APIRequestContext.java @@ -91,10 +91,11 @@ public interface APIRequestContext { void dispose(); /** * Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and update - * context cookies from the response. The method will automatically follow redirects. JSON objects can be passed directly - * to the request. + * context cookies from the response. The method will automatically follow redirects. * *

Usage + * + *

JSON objects can be passed directly to the request: *

{@code
    * Map data = new HashMap();
    * data.put("title", "Book Title");
@@ -102,8 +103,9 @@ public interface APIRequestContext {
    * request.fetch("https://example.com/api/createBook", RequestOptions.create().setMethod("post").setData(data));
    * }
* - *

The common way to send file(s) in the body of a request is to encode it as form fields with {@code multipart/form-data} - * encoding. You can achieve that with Playwright API like this: + *

The common way to send file(s) in the body of a request is to upload them as form fields with {@code + * multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code + * multipart} parameter: *

{@code
    * // Pass file path to the form data constructor:
    * Path file = Paths.get("team.csv");
@@ -114,7 +116,7 @@ public interface APIRequestContext {
    * // Or you can pass the file content directly as FilePayload object:
    * FilePayload filePayload = new FilePayload("f.js", "text/javascript",
    *       "console.log(2022);".getBytes(StandardCharsets.UTF_8));
-   * APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
+   * APIResponse response = request.fetch("https://example.com/api/uploadScript",
    *   RequestOptions.create().setMethod("post").setMultipart(
    *     FormData.create().set("fileField", filePayload)));
    * }
@@ -127,10 +129,11 @@ public interface APIRequestContext { } /** * Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and update - * context cookies from the response. The method will automatically follow redirects. JSON objects can be passed directly - * to the request. + * context cookies from the response. The method will automatically follow redirects. * *

Usage + * + *

JSON objects can be passed directly to the request: *

{@code
    * Map data = new HashMap();
    * data.put("title", "Book Title");
@@ -138,8 +141,9 @@ public interface APIRequestContext {
    * request.fetch("https://example.com/api/createBook", RequestOptions.create().setMethod("post").setData(data));
    * }
* - *

The common way to send file(s) in the body of a request is to encode it as form fields with {@code multipart/form-data} - * encoding. You can achieve that with Playwright API like this: + *

The common way to send file(s) in the body of a request is to upload them as form fields with {@code + * multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code + * multipart} parameter: *

{@code
    * // Pass file path to the form data constructor:
    * Path file = Paths.get("team.csv");
@@ -150,7 +154,7 @@ public interface APIRequestContext {
    * // Or you can pass the file content directly as FilePayload object:
    * FilePayload filePayload = new FilePayload("f.js", "text/javascript",
    *       "console.log(2022);".getBytes(StandardCharsets.UTF_8));
-   * APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
+   * APIResponse response = request.fetch("https://example.com/api/uploadScript",
    *   RequestOptions.create().setMethod("post").setMultipart(
    *     FormData.create().set("fileField", filePayload)));
    * }
@@ -162,10 +166,11 @@ public interface APIRequestContext { APIResponse fetch(String urlOrRequest, RequestOptions params); /** * Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and update - * context cookies from the response. The method will automatically follow redirects. JSON objects can be passed directly - * to the request. + * context cookies from the response. The method will automatically follow redirects. * *

Usage + * + *

JSON objects can be passed directly to the request: *

{@code
    * Map data = new HashMap();
    * data.put("title", "Book Title");
@@ -173,8 +178,9 @@ public interface APIRequestContext {
    * request.fetch("https://example.com/api/createBook", RequestOptions.create().setMethod("post").setData(data));
    * }
* - *

The common way to send file(s) in the body of a request is to encode it as form fields with {@code multipart/form-data} - * encoding. You can achieve that with Playwright API like this: + *

The common way to send file(s) in the body of a request is to upload them as form fields with {@code + * multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code + * multipart} parameter: *

{@code
    * // Pass file path to the form data constructor:
    * Path file = Paths.get("team.csv");
@@ -185,7 +191,7 @@ public interface APIRequestContext {
    * // Or you can pass the file content directly as FilePayload object:
    * FilePayload filePayload = new FilePayload("f.js", "text/javascript",
    *       "console.log(2022);".getBytes(StandardCharsets.UTF_8));
-   * APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
+   * APIResponse response = request.fetch("https://example.com/api/uploadScript",
    *   RequestOptions.create().setMethod("post").setMultipart(
    *     FormData.create().set("fileField", filePayload)));
    * }
@@ -198,10 +204,11 @@ public interface APIRequestContext { } /** * Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and update - * context cookies from the response. The method will automatically follow redirects. JSON objects can be passed directly - * to the request. + * context cookies from the response. The method will automatically follow redirects. * *

Usage + * + *

JSON objects can be passed directly to the request: *

{@code
    * Map data = new HashMap();
    * data.put("title", "Book Title");
@@ -209,8 +216,9 @@ public interface APIRequestContext {
    * request.fetch("https://example.com/api/createBook", RequestOptions.create().setMethod("post").setData(data));
    * }
* - *

The common way to send file(s) in the body of a request is to encode it as form fields with {@code multipart/form-data} - * encoding. You can achieve that with Playwright API like this: + *

The common way to send file(s) in the body of a request is to upload them as form fields with {@code + * multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code + * multipart} parameter: *

{@code
    * // Pass file path to the form data constructor:
    * Path file = Paths.get("team.csv");
@@ -221,7 +229,7 @@ public interface APIRequestContext {
    * // Or you can pass the file content directly as FilePayload object:
    * FilePayload filePayload = new FilePayload("f.js", "text/javascript",
    *       "console.log(2022);".getBytes(StandardCharsets.UTF_8));
-   * APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
+   * APIResponse response = request.fetch("https://example.com/api/uploadScript",
    *   RequestOptions.create().setMethod("post").setMultipart(
    *     FormData.create().set("fileField", filePayload)));
    * }
@@ -337,7 +345,8 @@ public interface APIRequestContext { * } * *

The common way to send file(s) in the body of a request is to upload them as form fields with {@code - * multipart/form-data} encoding. You can achieve that with Playwright API like this: + * multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code + * multipart} parameter: *

{@code
    * // Pass file path to the form data constructor:
    * Path file = Paths.get("team.csv");
@@ -346,9 +355,9 @@ public interface APIRequestContext {
    *     FormData.create().set("fileField", file)));
    *
    * // Or you can pass the file content directly as FilePayload object:
-   * FilePayload filePayload = new FilePayload("f.js", "text/javascript",
+   * FilePayload filePayload1 = new FilePayload("f1.js", "text/javascript",
    *       "console.log(2022);".getBytes(StandardCharsets.UTF_8));
-   * APIResponse response = request.post("https://example.com/api/uploadTeamList",
+   * APIResponse response = request.post("https://example.com/api/uploadScript",
    *   RequestOptions.create().setMultipart(
    *     FormData.create().set("fileField", filePayload)));
    * }
@@ -384,7 +393,8 @@ public interface APIRequestContext { * } * *

The common way to send file(s) in the body of a request is to upload them as form fields with {@code - * multipart/form-data} encoding. You can achieve that with Playwright API like this: + * multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code + * multipart} parameter: *

{@code
    * // Pass file path to the form data constructor:
    * Path file = Paths.get("team.csv");
@@ -393,9 +403,9 @@ public interface APIRequestContext {
    *     FormData.create().set("fileField", file)));
    *
    * // Or you can pass the file content directly as FilePayload object:
-   * FilePayload filePayload = new FilePayload("f.js", "text/javascript",
+   * FilePayload filePayload1 = new FilePayload("f1.js", "text/javascript",
    *       "console.log(2022);".getBytes(StandardCharsets.UTF_8));
-   * APIResponse response = request.post("https://example.com/api/uploadTeamList",
+   * APIResponse response = request.post("https://example.com/api/uploadScript",
    *   RequestOptions.create().setMultipart(
    *     FormData.create().set("fileField", filePayload)));
    * }
diff --git a/playwright/src/main/java/com/microsoft/playwright/BrowserContext.java b/playwright/src/main/java/com/microsoft/playwright/BrowserContext.java index 4fb123ad..6d4f0693 100644 --- a/playwright/src/main/java/com/microsoft/playwright/BrowserContext.java +++ b/playwright/src/main/java/com/microsoft/playwright/BrowserContext.java @@ -49,10 +49,9 @@ public interface BrowserContext extends AutoCloseable { * *

Emitted when new background page is created in the context. *

{@code
-   * Page backgroundPage = context.waitForBackgroundPage(() -> {
-   *   page.getByText("activate extension").click();
+   * context.onBackgroundPage(backgroundPage -> {
+   *   System.out.println(backgroundPage.url());
    * });
-   * System.out.println(backgroundPage.evaluate("location.href"));
    * }
*/ void onBackgroundPage(Consumer handler); @@ -128,7 +127,10 @@ public interface BrowserContext extends AutoCloseable { * *

The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a * popup with {@code window.open('http://example.com')}, this event will fire when the network request to - * "http://example.com" is done and its response has started loading in the popup. + * "http://example.com" is done and its response has started loading in the popup. If you would like to route/listen to + * this network request, use {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} and {@link + * com.microsoft.playwright.BrowserContext#onRequest BrowserContext.onRequest()} respectively instead of similar methods on + * the {@code Page}. *

{@code
    * Page newPage = context.waitForPage(() -> {
    *   page.getByText("open new page").click();
diff --git a/playwright/src/main/java/com/microsoft/playwright/Frame.java b/playwright/src/main/java/com/microsoft/playwright/Frame.java
index 7765f553..d6e030e0 100644
--- a/playwright/src/main/java/com/microsoft/playwright/Frame.java
+++ b/playwright/src/main/java/com/microsoft/playwright/Frame.java
@@ -4989,6 +4989,9 @@ public interface Frame {
    * 

This returns when the frame reaches a required load state, {@code load} by default. The navigation must have been * committed when this method is called. If current document has already reached the required state, resolves immediately. * + *

NOTE: Most of the time, this method is not needed because Playwright auto-waits before every action. + * *

Usage *

{@code
    * frame.click("button"); // Click triggers navigation.
@@ -5014,6 +5017,9 @@ public interface Frame {
    * 

This returns when the frame reaches a required load state, {@code load} by default. The navigation must have been * committed when this method is called. If current document has already reached the required state, resolves immediately. * + *

NOTE: Most of the time, this method is not needed because Playwright auto-waits before every action. + * *

Usage *

{@code
    * frame.click("button"); // Click triggers navigation.
@@ -5031,6 +5037,9 @@ public interface Frame {
    * 

This returns when the frame reaches a required load state, {@code load} by default. The navigation must have been * committed when this method is called. If current document has already reached the required state, resolves immediately. * + *

NOTE: Most of the time, this method is not needed because Playwright auto-waits before every action. + * *

Usage *

{@code
    * frame.click("button"); // Click triggers navigation.
diff --git a/playwright/src/main/java/com/microsoft/playwright/Page.java b/playwright/src/main/java/com/microsoft/playwright/Page.java
index 8990cc3c..747f274c 100644
--- a/playwright/src/main/java/com/microsoft/playwright/Page.java
+++ b/playwright/src/main/java/com/microsoft/playwright/Page.java
@@ -242,7 +242,10 @@ public interface Page extends AutoCloseable {
    *
    * 

The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a * popup with {@code window.open('http://example.com')}, this event will fire when the network request to - * "http://example.com" is done and its response has started loading in the popup. + * "http://example.com" is done and its response has started loading in the popup. If you would like to route/listen to + * this network request, use {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} and {@link + * com.microsoft.playwright.BrowserContext#onRequest BrowserContext.onRequest()} respectively instead of similar methods on + * the {@code Page}. *

{@code
    * Page popup = page.waitForPopup(() -> {
    *   page.getByText("open the popup").click();
@@ -2327,6 +2330,35 @@ public interface Page extends AutoCloseable {
       return this;
     }
   }
+  class AddLocatorHandlerOptions {
+    /**
+     * By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then Playwright
+     * will continue with the action/assertion that triggered the handler. This option allows to opt-out of this behavior, so
+     * that overlay can stay visible after the handler has run.
+     */
+    public Boolean noWaitAfter;
+    /**
+     * Specifies the maximum number of times this handler should be called. Unlimited by default.
+     */
+    public Integer times;
+
+    /**
+     * By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then Playwright
+     * will continue with the action/assertion that triggered the handler. This option allows to opt-out of this behavior, so
+     * that overlay can stay visible after the handler has run.
+     */
+    public AddLocatorHandlerOptions setNoWaitAfter(boolean noWaitAfter) {
+      this.noWaitAfter = noWaitAfter;
+      return this;
+    }
+    /**
+     * Specifies the maximum number of times this handler should be called. Unlimited by default.
+     */
+    public AddLocatorHandlerOptions setTimes(int times) {
+      this.times = times;
+      return this;
+    }
+  }
   class ReloadOptions {
     /**
      * Maximum operation time in milliseconds, defaults to 30 seconds, pass {@code 0} to disable timeout. The default value can
@@ -6058,9 +6090,7 @@ public interface Page extends AutoCloseable {
    */
   List querySelectorAll(String selector);
   /**
-   * NOTE: This method is experimental and its behavior may change in the upcoming releases.
-   *
-   * 

When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to + * When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to * automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making them * tricky to handle in automated tests. * @@ -6077,6 +6107,8 @@ public interface Page extends AutoCloseable { * assertion check. When overlay is visible, Playwright calls the handler first, and then proceeds with the * action/assertion. Note that the handler is only called when you perform an action/assertion - if the overlay becomes * visible but you don't perform any actions, the handler will not be triggered. + *

  • After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible anymore. You + * can opt-out of this behavior with {@code noWaitAfter}.
  • *
  • The execution time of the handler counts towards the timeout of the action/assertion that executed the handler. If your * handler takes too long, it might cause timeouts.
  • *
  • You can register multiple handlers. However, only a single handler will be running at a time. Make sure the actions @@ -6122,24 +6154,135 @@ public interface Page extends AutoCloseable { * }
  • * *

    An example with a custom callback on every actionability check. It uses a {@code } locator that is always visible, - * so the handler is called before every actionability check: + * so the handler is called before every actionability check. It is important to specify {@code noWaitAfter}, because the + * handler does not hide the {@code } element. *

    {@code
        * // Setup the handler.
        * page.addLocatorHandler(page.locator("body")), () => {
        *   page.evaluate("window.removeObstructionsForTestIfNeeded()");
    -   * });
    +   * }, new Page.AddLocatorHandlerOptions.setNoWaitAfter(true));
        *
        * // Write the test as usual.
        * page.goto("https://example.com");
        * page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
        * }
    * + *

    Handler takes the original locator as an argument. You can also automatically remove the handler after a number of + * invocations by setting {@code times}: + *

    {@code
    +   * page.addLocatorHandler(page.getByLabel("Close"), locator => {
    +   *   locator.click();
    +   * }, new Page.AddLocatorHandlerOptions().setTimes(1));
    +   * }
    + * * @param locator Locator that triggers the handler. * @param handler Function that should be run once {@code locator} appears. This function should get rid of the element that blocks * actions like click. * @since v1.42 */ - void addLocatorHandler(Locator locator, Runnable handler); + default void addLocatorHandler(Locator locator, Consumer handler) { + addLocatorHandler(locator, handler, null); + } + /** + * When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to + * automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making them + * tricky to handle in automated tests. + * + *

    This method lets you set up a special function, called a handler, that activates when it detects that overlay is + * visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there. + * + *

    Things to keep in mind: + *

      + *
    • When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as a part of + * your normal test flow, instead of using {@link com.microsoft.playwright.Page#addLocatorHandler + * Page.addLocatorHandler()}.
    • + *
    • Playwright checks for the overlay every time before executing or retrying an action that requires an actionability check, or before performing an auto-waiting + * assertion check. When overlay is visible, Playwright calls the handler first, and then proceeds with the + * action/assertion. Note that the handler is only called when you perform an action/assertion - if the overlay becomes + * visible but you don't perform any actions, the handler will not be triggered.
    • + *
    • After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible anymore. You + * can opt-out of this behavior with {@code noWaitAfter}.
    • + *
    • The execution time of the handler counts towards the timeout of the action/assertion that executed the handler. If your + * handler takes too long, it might cause timeouts.
    • + *
    • You can register multiple handlers. However, only a single handler will be running at a time. Make sure the actions + * within a handler don't depend on another handler.
    • + *
    + * + *

    NOTE: Running the handler will alter your page state mid-test. For example it will change the currently focused element and + * move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on the focus and + * mouse state being unchanged.

    For example, consider a test that calls {@link + * com.microsoft.playwright.Locator#focus Locator.focus()} followed by {@link com.microsoft.playwright.Keyboard#press + * Keyboard.press()}. If your handler clicks a button between these two actions, the focused element most likely will be + * wrong, and key press will happen on the unexpected element. Use {@link com.microsoft.playwright.Locator#press + * Locator.press()} instead to avoid this problem.

    Another example is a series of mouse actions, where {@link + * com.microsoft.playwright.Mouse#move Mouse.move()} is followed by {@link com.microsoft.playwright.Mouse#down + * Mouse.down()}. Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse + * down. Prefer self-contained actions like {@link com.microsoft.playwright.Locator#click Locator.click()} that do not rely + * on the state being unchanged by a handler. + * + *

    Usage + * + *

    An example that closes a "Sign up to the newsletter" dialog when it appears: + *

    {@code
    +   * // Setup the handler.
    +   * page.addLocatorHandler(page.getByText("Sign up to the newsletter"), () => {
    +   *   page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("No thanks")).click();
    +   * });
    +   *
    +   * // Write the test as usual.
    +   * page.goto("https://example.com");
    +   * page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
    +   * }
    + * + *

    An example that skips the "Confirm your security details" page when it is shown: + *

    {@code
    +   * // Setup the handler.
    +   * page.addLocatorHandler(page.getByText("Confirm your security details")), () => {
    +   *   page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Remind me later")).click();
    +   * });
    +   *
    +   * // Write the test as usual.
    +   * page.goto("https://example.com");
    +   * page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
    +   * }
    + * + *

    An example with a custom callback on every actionability check. It uses a {@code } locator that is always visible, + * so the handler is called before every actionability check. It is important to specify {@code noWaitAfter}, because the + * handler does not hide the {@code } element. + *

    {@code
    +   * // Setup the handler.
    +   * page.addLocatorHandler(page.locator("body")), () => {
    +   *   page.evaluate("window.removeObstructionsForTestIfNeeded()");
    +   * }, new Page.AddLocatorHandlerOptions.setNoWaitAfter(true));
    +   *
    +   * // Write the test as usual.
    +   * page.goto("https://example.com");
    +   * page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
    +   * }
    + * + *

    Handler takes the original locator as an argument. You can also automatically remove the handler after a number of + * invocations by setting {@code times}: + *

    {@code
    +   * page.addLocatorHandler(page.getByLabel("Close"), locator => {
    +   *   locator.click();
    +   * }, new Page.AddLocatorHandlerOptions().setTimes(1));
    +   * }
    + * + * @param locator Locator that triggers the handler. + * @param handler Function that should be run once {@code locator} appears. This function should get rid of the element that blocks + * actions like click. + * @since v1.42 + */ + void addLocatorHandler(Locator locator, Consumer handler, AddLocatorHandlerOptions options); + /** + * Removes all locator handlers added by {@link com.microsoft.playwright.Page#addLocatorHandler Page.addLocatorHandler()} + * for a specific locator. + * + * @param locator Locator passed to {@link com.microsoft.playwright.Page#addLocatorHandler Page.addLocatorHandler()}. + * @since v1.44 + */ + void removeLocatorHandler(Locator locator); /** * This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the main * resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. @@ -6175,6 +6318,9 @@ public interface Page extends AutoCloseable { * this issue. We recommend disabling Service Workers * when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}. * + *

    NOTE: {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use + * {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead. + * *

    Usage * *

    An example of a naive handler that aborts all image requests: @@ -6231,6 +6377,9 @@ public interface Page extends AutoCloseable { * this issue. We recommend disabling Service Workers * when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}. * + *

    NOTE: {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use + * {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead. + * *

    Usage * *

    An example of a naive handler that aborts all image requests: @@ -6285,6 +6434,9 @@ public interface Page extends AutoCloseable { * this issue. We recommend disabling Service Workers * when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}. * + *

    NOTE: {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use + * {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead. + * *

    Usage * *

    An example of a naive handler that aborts all image requests: @@ -6341,6 +6493,9 @@ public interface Page extends AutoCloseable { * this issue. We recommend disabling Service Workers * when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}. * + *

    NOTE: {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use + * {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead. + * *

    Usage * *

    An example of a naive handler that aborts all image requests: @@ -6395,6 +6550,9 @@ public interface Page extends AutoCloseable { * this issue. We recommend disabling Service Workers * when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}. * + *

    NOTE: {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use + * {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead. + * *

    Usage * *

    An example of a naive handler that aborts all image requests: @@ -6451,6 +6609,9 @@ public interface Page extends AutoCloseable { * this issue. We recommend disabling Service Workers * when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}. * + *

    NOTE: {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use + * {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead. + * *

    Usage * *

    An example of a naive handler that aborts all image requests: @@ -7588,6 +7749,9 @@ public interface Page extends AutoCloseable { *

    This resolves when the page reaches a required load state, {@code load} by default. The navigation must have been * committed when this method is called. If current document has already reached the required state, resolves immediately. * + *

    NOTE: Most of the time, this method is not needed because Playwright auto-waits before every action. + * *

    Usage *

    {@code
        * page.getByRole(AriaRole.BUTTON).click(); // Click triggers navigation.
    @@ -7621,6 +7785,9 @@ public interface Page extends AutoCloseable {
        * 

    This resolves when the page reaches a required load state, {@code load} by default. The navigation must have been * committed when this method is called. If current document has already reached the required state, resolves immediately. * + *

    NOTE: Most of the time, this method is not needed because Playwright auto-waits before every action. + * *

    Usage *

    {@code
        * page.getByRole(AriaRole.BUTTON).click(); // Click triggers navigation.
    @@ -7646,6 +7813,9 @@ public interface Page extends AutoCloseable {
        * 

    This resolves when the page reaches a required load state, {@code load} by default. The navigation must have been * committed when this method is called. If current document has already reached the required state, resolves immediately. * + *

    NOTE: Most of the time, this method is not needed because Playwright auto-waits before every action. + * *

    Usage *

    {@code
        * page.getByRole(AriaRole.BUTTON).click(); // Click triggers navigation.
    diff --git a/playwright/src/main/java/com/microsoft/playwright/assertions/LocatorAssertions.java b/playwright/src/main/java/com/microsoft/playwright/assertions/LocatorAssertions.java
    index 7c38506a..55f3476a 100644
    --- a/playwright/src/main/java/com/microsoft/playwright/assertions/LocatorAssertions.java
    +++ b/playwright/src/main/java/com/microsoft/playwright/assertions/LocatorAssertions.java
    @@ -17,6 +17,7 @@
     package com.microsoft.playwright.assertions;
     
     import java.util.regex.Pattern;
    +import com.microsoft.playwright.options.AriaRole;
     
     /**
      * The {@code LocatorAssertions} class provides assertion methods that can be used to make assertions about the {@code
    @@ -253,6 +254,60 @@ public interface LocatorAssertions {
           return this;
         }
       }
    +  class HasAccessibleDescriptionOptions {
    +    /**
    +     * Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
    +     * expression flag if specified.
    +     */
    +    public Boolean ignoreCase;
    +    /**
    +     * Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
    +     */
    +    public Double timeout;
    +
    +    /**
    +     * Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
    +     * expression flag if specified.
    +     */
    +    public HasAccessibleDescriptionOptions setIgnoreCase(boolean ignoreCase) {
    +      this.ignoreCase = ignoreCase;
    +      return this;
    +    }
    +    /**
    +     * Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
    +     */
    +    public HasAccessibleDescriptionOptions setTimeout(double timeout) {
    +      this.timeout = timeout;
    +      return this;
    +    }
    +  }
    +  class HasAccessibleNameOptions {
    +    /**
    +     * Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
    +     * expression flag if specified.
    +     */
    +    public Boolean ignoreCase;
    +    /**
    +     * Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
    +     */
    +    public Double timeout;
    +
    +    /**
    +     * Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
    +     * expression flag if specified.
    +     */
    +    public HasAccessibleNameOptions setIgnoreCase(boolean ignoreCase) {
    +      this.ignoreCase = ignoreCase;
    +      return this;
    +    }
    +    /**
    +     * Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
    +     */
    +    public HasAccessibleNameOptions setTimeout(double timeout) {
    +      this.timeout = timeout;
    +      return this;
    +    }
    +  }
       class HasAttributeOptions {
         /**
          * Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
    @@ -350,6 +405,20 @@ public interface LocatorAssertions {
           return this;
         }
       }
    +  class HasRoleOptions {
    +    /**
    +     * Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
    +     */
    +    public Double timeout;
    +
    +    /**
    +     * Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
    +     */
    +    public HasRoleOptions setTimeout(double timeout) {
    +      this.timeout = timeout;
    +      return this;
    +    }
    +  }
       class HasTextOptions {
         /**
          * Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
    @@ -1076,6 +1145,126 @@ public interface LocatorAssertions {
        * @since v1.20
        */
       void containsText(Pattern[] expected, ContainsTextOptions options);
    +  /**
    +   * Ensures the {@code Locator} points to an element with a given accessible description.
    +   *
    +   * 

    Usage + *

    {@code
    +   * Locator locator = page.getByTestId("save-button");
    +   * assertThat(locator).hasAccessibleDescription("Save results to disk");
    +   * }
    + * + * @param description Expected accessible description. + * @since v1.44 + */ + default void hasAccessibleDescription(String description) { + hasAccessibleDescription(description, null); + } + /** + * Ensures the {@code Locator} points to an element with a given accessible description. + * + *

    Usage + *

    {@code
    +   * Locator locator = page.getByTestId("save-button");
    +   * assertThat(locator).hasAccessibleDescription("Save results to disk");
    +   * }
    + * + * @param description Expected accessible description. + * @since v1.44 + */ + void hasAccessibleDescription(String description, HasAccessibleDescriptionOptions options); + /** + * Ensures the {@code Locator} points to an element with a given accessible description. + * + *

    Usage + *

    {@code
    +   * Locator locator = page.getByTestId("save-button");
    +   * assertThat(locator).hasAccessibleDescription("Save results to disk");
    +   * }
    + * + * @param description Expected accessible description. + * @since v1.44 + */ + default void hasAccessibleDescription(Pattern description) { + hasAccessibleDescription(description, null); + } + /** + * Ensures the {@code Locator} points to an element with a given accessible description. + * + *

    Usage + *

    {@code
    +   * Locator locator = page.getByTestId("save-button");
    +   * assertThat(locator).hasAccessibleDescription("Save results to disk");
    +   * }
    + * + * @param description Expected accessible description. + * @since v1.44 + */ + void hasAccessibleDescription(Pattern description, HasAccessibleDescriptionOptions options); + /** + * Ensures the {@code Locator} points to an element with a given accessible name. + * + *

    Usage + *

    {@code
    +   * Locator locator = page.getByTestId("save-button");
    +   * assertThat(locator).hasAccessibleName("Save to disk");
    +   * }
    + * + * @param name Expected accessible name. + * @since v1.44 + */ + default void hasAccessibleName(String name) { + hasAccessibleName(name, null); + } + /** + * Ensures the {@code Locator} points to an element with a given accessible name. + * + *

    Usage + *

    {@code
    +   * Locator locator = page.getByTestId("save-button");
    +   * assertThat(locator).hasAccessibleName("Save to disk");
    +   * }
    + * + * @param name Expected accessible name. + * @since v1.44 + */ + void hasAccessibleName(String name, HasAccessibleNameOptions options); + /** + * Ensures the {@code Locator} points to an element with a given accessible name. + * + *

    Usage + *

    {@code
    +   * Locator locator = page.getByTestId("save-button");
    +   * assertThat(locator).hasAccessibleName("Save to disk");
    +   * }
    + * + * @param name Expected accessible name. + * @since v1.44 + */ + default void hasAccessibleName(Pattern name) { + hasAccessibleName(name, null); + } + /** + * Ensures the {@code Locator} points to an element with a given accessible name. + * + *

    Usage + *

    {@code
    +   * Locator locator = page.getByTestId("save-button");
    +   * assertThat(locator).hasAccessibleName("Save to disk");
    +   * }
    + * + * @param name Expected accessible name. + * @since v1.44 + */ + void hasAccessibleName(Pattern name, HasAccessibleNameOptions options); /** * Ensures the {@code Locator} points to an element with given attribute. * @@ -1456,6 +1645,42 @@ public interface LocatorAssertions { * @since v1.20 */ void hasJSProperty(String name, Object value, HasJSPropertyOptions options); + /** + * Ensures the {@code Locator} points to an element with a given ARIA + * role. + * + *

    Note that role is matched as a string, disregarding the ARIA role hierarchy. For example, asserting a superclass role + * {@code "checkbox"} on an element with a subclass role {@code "switch"} will fail. + * + *

    Usage + *

    {@code
    +   * Locator locator = page.getByTestId("save-button");
    +   * assertThat(locator).hasRole(AriaRole.BUTTON);
    +   * }
    + * + * @param role Required aria role. + * @since v1.44 + */ + default void hasRole(AriaRole role) { + hasRole(role, null); + } + /** + * Ensures the {@code Locator} points to an element with a given ARIA + * role. + * + *

    Note that role is matched as a string, disregarding the ARIA role hierarchy. For example, asserting a superclass role + * {@code "checkbox"} on an element with a subclass role {@code "switch"} will fail. + * + *

    Usage + *

    {@code
    +   * Locator locator = page.getByTestId("save-button");
    +   * assertThat(locator).hasRole(AriaRole.BUTTON);
    +   * }
    + * + * @param role Required aria role. + * @since v1.44 + */ + void hasRole(AriaRole role, HasRoleOptions options); /** * Ensures the {@code Locator} points to an element with the given text. All nested elements will be considered when * computing the text content of the element. You can use regular expressions for the value as well. diff --git a/playwright/src/main/java/com/microsoft/playwright/assertions/PageAssertions.java b/playwright/src/main/java/com/microsoft/playwright/assertions/PageAssertions.java index fb5e4de4..2c8e7fa7 100644 --- a/playwright/src/main/java/com/microsoft/playwright/assertions/PageAssertions.java +++ b/playwright/src/main/java/com/microsoft/playwright/assertions/PageAssertions.java @@ -52,11 +52,24 @@ public interface PageAssertions { } } class HasURLOptions { + /** + * Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular + * expression flag if specified. + */ + public Boolean ignoreCase; /** * Time to retry the assertion for in milliseconds. Defaults to {@code 5000}. */ public Double timeout; + /** + * Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular + * expression flag if specified. + */ + public HasURLOptions setIgnoreCase(boolean ignoreCase) { + this.ignoreCase = ignoreCase; + return this; + } /** * Time to retry the assertion for in milliseconds. Defaults to {@code 5000}. */ diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java index 213436a4..9a037966 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java @@ -29,6 +29,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.Base64; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import static com.microsoft.playwright.impl.Serialization.*; @@ -86,7 +87,7 @@ class APIRequestContextImpl extends ChannelOwner implements APIRequestContext { for (Map.Entry e : options.params.entrySet()) { queryParams.put(e.getKey(), "" + e.getValue()); } - params.add("params", toNameValueArray(queryParams)); + params.add("params", toNameValueArray(queryParams.entrySet())); } if (options.method != null) { params.addProperty("method", options.method); @@ -149,9 +150,9 @@ class APIRequestContextImpl extends ChannelOwner implements APIRequestContext { return false; } - private static JsonArray serializeMultipartData(Map data) { + private static JsonArray serializeMultipartData(List> data) { JsonArray result = new JsonArray(); - for (Map.Entry e : data.entrySet()) { + for (Map.Entry e : data) { FilePayload filePayload = null; if (e.getValue() instanceof FilePayload) { filePayload = (FilePayload) e.getValue(); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/AssertionsBase.java b/playwright/src/main/java/com/microsoft/playwright/impl/AssertionsBase.java index 1c9650dc..9c00602d 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/AssertionsBase.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/AssertionsBase.java @@ -20,6 +20,7 @@ import com.microsoft.playwright.PlaywrightException; import org.opentest4j.AssertionFailedError; import org.opentest4j.ValueWrapper; +import java.lang.reflect.Field; import java.util.Collection; import java.util.List; import java.util.regex.Pattern; @@ -91,4 +92,17 @@ class AssertionsBase { } return expected; } + + static Boolean shouldIgnoreCase(Object options) { + if (options == null) { + return null; + } + try { + Field fromField = options.getClass().getDeclaredField("ignoreCase"); + Object value = fromField.get(options); + return (Boolean) value; + } catch (NoSuchFieldException | IllegalAccessException e) { + return null; + } + } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/FormDataImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/FormDataImpl.java index 4b2a135d..2575edbb 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FormDataImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FormDataImpl.java @@ -20,39 +20,93 @@ import com.microsoft.playwright.options.FilePayload; import com.microsoft.playwright.options.FormData; import java.nio.file.Path; -import java.util.LinkedHashMap; -import java.util.Map; +import java.util.*; +import java.util.stream.Collectors; public class FormDataImpl implements FormData { - Map fields = new LinkedHashMap<>(); + static class Field implements Map.Entry { + final String name; + final Object value; + + private Field(String name, Object value) { + this.name = name; + this.value = value; + } + + @Override + public String getKey() { + return name; + } + + @Override + public Object getValue() { + return value; + } + + @Override + public Object setValue(Object value) { + throw new UnsupportedOperationException(); + } + } + List fields = new ArrayList(); + + @Override + public FormData append(String name, String value) { + return appendImpl(name, value); + } + + @Override + public FormData append(String name, boolean value) { + return appendImpl(name, value); + } + + @Override + public FormData append(String name, int value) { + return appendImpl(name, value); + } + + @Override + public FormData append(String name, Path value) { + return appendImpl(name, value); + } + + @Override + public FormData append(String name, FilePayload value) { + return appendImpl(name, value); + } @Override public FormData set(String name, String value) { - fields.put(name, value); - return this; + return setImpl(name, value); } @Override public FormData set(String name, boolean value) { - fields.put(name, value); - return this; + return setImpl(name, value); } @Override public FormData set(String name, int value) { - fields.put(name, value); - return this; + return setImpl(name, value); } @Override public FormData set(String name, Path value) { - fields.put(name, value); - return this; + return setImpl(name, value); } @Override public FormData set(String name, FilePayload value) { - fields.put(name, value); + return setImpl(name, value); + } + + private FormData setImpl(String name, Object value) { + fields = fields.stream().filter(f -> !name.equals(f.name)).collect(Collectors.toList()); + return appendImpl(name, value); + } + + private FormData appendImpl(String name, Object value) { + fields.add(new Field(name, value)); return this; } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java b/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java index 42239337..ee9aa936 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java @@ -33,6 +33,7 @@ class JsonPipe extends ChannelOwner implements Transport { private ListenerCollection listeners = new ListenerCollection<>(); private enum EventType { CLOSE } private boolean isClosed; + private String closeReason = "Browser has been closed"; JsonPipe(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); @@ -97,13 +98,19 @@ class JsonPipe extends ChannelOwner implements Transport { incoming.add(params.get("message").getAsJsonObject()); } else if ("closed".equals(event)) { isClosed = true; + if (params.has("reason")) { + String reason = params.get("reason").getAsString(); + if (reason.trim().length() > 0) { + closeReason = reason; + } + } listeners.notify(EventType.CLOSE, this); } } private void checkIfClosed() { if (isClosed) { - throw new PlaywrightException("Browser has been closed"); + throw new PlaywrightException(closeReason); } } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorAssertionsImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorAssertionsImpl.java index 04585a5d..83264ea3 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorAssertionsImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorAssertionsImpl.java @@ -18,6 +18,7 @@ package com.microsoft.playwright.impl; import com.microsoft.playwright.Locator; import com.microsoft.playwright.assertions.LocatorAssertions; +import com.microsoft.playwright.options.AriaRole; import java.lang.reflect.Field; import java.util.ArrayList; @@ -82,6 +83,36 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse expectImpl("to.contain.text.array", list, patterns, "Locator expected to contain text", convertType(options, FrameExpectOptions.class)); } + @Override + public void hasAccessibleDescription(String description, HasAccessibleDescriptionOptions options) { + ExpectedTextValue expected = new ExpectedTextValue(); + expected.string = description; + expected.ignoreCase = shouldIgnoreCase(options); + expectImpl("to.have.accessible.description", expected, description, "Locator expected to have accessible description", convertType(options, FrameExpectOptions.class)); + } + + @Override + public void hasAccessibleDescription(Pattern pattern, HasAccessibleDescriptionOptions options) { + ExpectedTextValue expected = expectedRegex(pattern); + expected.ignoreCase = shouldIgnoreCase(options); + expectImpl("to.have.accessible.description", expected, pattern, "Locator expected to have accessible description", convertType(options, FrameExpectOptions.class)); + } + + @Override + public void hasAccessibleName(String name, HasAccessibleNameOptions options) { + ExpectedTextValue expected = new ExpectedTextValue(); + expected.string = name; + expected.ignoreCase = shouldIgnoreCase(options); + expectImpl("to.have.accessible.name", expected, name, "Locator expected to have accessible name", convertType(options, FrameExpectOptions.class)); + } + + @Override + public void hasAccessibleName(Pattern pattern, HasAccessibleNameOptions options) { + ExpectedTextValue expected = expectedRegex(pattern); + expected.ignoreCase = shouldIgnoreCase(options); + expectImpl("to.have.accessible.name", expected, pattern, "Locator expected to have accessible name", convertType(options, FrameExpectOptions.class)); + } + @Override public void hasAttribute(String name, String text, HasAttributeOptions options) { ExpectedTextValue expected = new ExpectedTextValue(); @@ -206,6 +237,13 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse expectImpl("to.have.property", list, value, "Locator expected to have JavaScript property '" + name + "'", commonOptions); } + @Override + public void hasRole(AriaRole role, HasRoleOptions options) { + ExpectedTextValue expected = new ExpectedTextValue(); + expected.string = role.toString().toLowerCase(); + expectImpl("to.have.role", expected, expected.string, "Locator expected to have role", convertType(options, FrameExpectOptions.class)); + } + @Override public void hasText(String text, HasTextOptions options) { ExpectedTextValue expected = new ExpectedTextValue(); @@ -366,17 +404,4 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse String message = "Locator expected to be " + (attached ? "attached" : "detached"); expectTrue(attached ? "to.be.attached" : "to.be.detached", message, frameOptions); } - - private static Boolean shouldIgnoreCase(Object options) { - if (options == null) { - return null; - } - try { - Field fromField = options.getClass().getDeclaredField("ignoreCase"); - Object value = fromField.get(options); - return (Boolean) value; - } catch (NoSuchFieldException | IllegalAccessException e) { - return null; - } - } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java index f999d8fb..b97a54fb 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java @@ -624,6 +624,20 @@ class LocatorImpl implements Locator { return "Locator@" + selector; } + @Override + public boolean equals(Object obj) { + if (!(obj instanceof LocatorImpl)) { + return false; + } + LocatorImpl locator = (LocatorImpl) obj; + return frame.equals(locator.frame) && selector.equals(locator.selector); + } + + @Override + public int hashCode() { + return frame.hashCode() ^ selector.hashCode(); + } + FrameExpectResult expect(String expression, FrameExpectOptions options) { return frame.withLogging("Locator.expect", () -> expectImpl(expression, options)); } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PageAssertionsImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PageAssertionsImpl.java index ee6e7158..b103d4ff 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageAssertionsImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageAssertionsImpl.java @@ -21,6 +21,7 @@ import com.microsoft.playwright.assertions.PageAssertions; import java.util.regex.Pattern; +import static com.microsoft.playwright.impl.LocatorAssertionsImpl.shouldIgnoreCase; import static com.microsoft.playwright.impl.UrlMatcher.resolveUrl; import static com.microsoft.playwright.impl.Utils.convertType; @@ -57,6 +58,7 @@ public class PageAssertionsImpl extends AssertionsBase implements PageAssertions url = resolveUrl(actualPage.context().baseUrl, url); } expected.string = url; + expected.ignoreCase = shouldIgnoreCase(options); expectImpl("to.have.url", expected, url, "Page URL expected to be", convertType(options, FrameExpectOptions.class)); } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java index fbe2de39..f4c2fdb2 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java @@ -49,7 +49,34 @@ public class PageImpl extends ChannelOwner implements Page { private ViewportSize viewport; private final Router routes = new Router(); private final Set frames = new LinkedHashSet<>(); - private final Map locatorHandlers = new HashMap<>(); + private final Map locatorHandlers = new HashMap<>(); + + private static class LocatorHandler { + private final Locator locator; + private final Consumer handler; + private Integer times; + + LocatorHandler(Locator locator, Consumer handler, Integer times) { + this.locator = locator; + this.handler = handler; + this.times = times; + } + + boolean call() { + if (shouldRemove()) { + return true; + } + if (times != null) { + --times; + } + handler.accept(locator); + return shouldRemove(); + } + + private boolean shouldRemove() { + return times != null && times == 0; + } + } private static final Map eventSubscriptions() { Map result = new HashMap<>(); @@ -530,29 +557,55 @@ public class PageImpl extends ChannelOwner implements Page { } @Override - public void addLocatorHandler(Locator locator, Runnable handler) { + public void addLocatorHandler(Locator locator, Consumer handler, AddLocatorHandlerOptions options) { LocatorImpl locatorImpl = (LocatorImpl) locator; if (locatorImpl.frame != mainFrame) { throw new PlaywrightException("Locator must belong to the main frame of this page"); } + if (options == null) { + options = new AddLocatorHandlerOptions(); + } + if (options.times != null && options.times == 0) { + return; + } + AddLocatorHandlerOptions finalOptions = options; withLogging("Page.addLocatorHandler", () -> { JsonObject params = new JsonObject(); params.addProperty("selector", locatorImpl.selector); + if (finalOptions.noWaitAfter != null && finalOptions.noWaitAfter) { + params.addProperty("noWaitAfter", true); + } + params.addProperty("selector", locatorImpl.selector); JsonObject json = (JsonObject) sendMessage("registerLocatorHandler", params); int uid = json.get("uid").getAsInt(); - locatorHandlers.put(uid, handler); + locatorHandlers.put(uid, new LocatorHandler(locator, handler, finalOptions.times)); }); } - private void onLocatorHandlerTriggered(int uid) { - try { - Runnable handler = locatorHandlers.get(uid); - if (handler != null) { - handler.run(); + @Override + public void removeLocatorHandler(Locator locator) { + for (Map.Entry entry: locatorHandlers.entrySet()) { + if (entry.getValue().locator.equals(locator)) { + locatorHandlers.remove(locator); + JsonObject params = new JsonObject(); + params.addProperty("uid", entry.getKey()); + try { + sendMessage("unregisterLocatorHandler", params); + } catch (PlaywrightException e) { + } } + } + } + + private void onLocatorHandlerTriggered(int uid) { + boolean remove = false; + try { + LocatorHandler handler = locatorHandlers.get(uid); + remove = handler != null && handler.call(); } finally { JsonObject params = new JsonObject(); params.addProperty("uid", uid); + params.addProperty("remove", remove); sendMessageAsync("resolveLocatorHandlerNoReply", params); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Serialization.java b/playwright/src/main/java/com/microsoft/playwright/impl/Serialization.java index 8b2588bc..6ddef2c4 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Serialization.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Serialization.java @@ -351,7 +351,7 @@ class Serialization { throw new PlaywrightException("Value cannot be null"); } } - return toNameValueArray(map); + return toNameValueArray(map.entrySet()); } static void addHarUrlFilter(JsonObject options, Object urlFilter) { @@ -364,9 +364,9 @@ class Serialization { } } - static JsonArray toNameValueArray(Map map) { + static JsonArray toNameValueArray(Iterable> collection) { JsonArray array = new JsonArray(); - for (Map.Entry e : map.entrySet()) { + for (Map.Entry e : collection) { JsonObject item = new JsonObject(); item.addProperty("name", e.getKey()); if (e.getValue() instanceof FilePayload) { diff --git a/playwright/src/main/java/com/microsoft/playwright/options/FormData.java b/playwright/src/main/java/com/microsoft/playwright/options/FormData.java index 82459869..057758a0 100644 --- a/playwright/src/main/java/com/microsoft/playwright/options/FormData.java +++ b/playwright/src/main/java/com/microsoft/playwright/options/FormData.java @@ -32,6 +32,141 @@ import java.nio.file.Path; * }
    */ public interface FormData { + /** + * Appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. File + * values can be passed either as {@code Path} or as {@code FilePayload}. Multiple fields with the same name can be added. + * + *

    The difference between {@link com.microsoft.playwright.FormData#set FormData.set()} and {@link + * com.microsoft.playwright.FormData#append FormData.append()} is that if the specified key already exists, {@link + * com.microsoft.playwright.FormData#set FormData.set()} will overwrite all existing values with the new one, whereas + * {@link com.microsoft.playwright.FormData#append FormData.append()} will append the new value onto the end of the + * existing set of values. + *

    {@code
    +   * import com.microsoft.playwright.options.FormData;
    +   * ...
    +   * FormData form = FormData.create()
    +   *     // Only name and value are set.
    +   *     .append("firstName", "John")
    +   *     // Name and value are set, filename and Content-Type are inferred from the file path.
    +   *     .append("attachment", Paths.get("pic.jpg"))
    +   *     // Name, value, filename and Content-Type are set.
    +   *     .append("attachment", new FilePayload("table.csv", "text/csv", Files.readAllBytes(Paths.get("my-tble.csv"))));
    +   * page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
    +   * }
    + * + * @param name Field name. + * @param value Field value. + * @since v1.44 + */ + FormData append(String name, String value); + /** + * Appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. File + * values can be passed either as {@code Path} or as {@code FilePayload}. Multiple fields with the same name can be added. + * + *

    The difference between {@link com.microsoft.playwright.FormData#set FormData.set()} and {@link + * com.microsoft.playwright.FormData#append FormData.append()} is that if the specified key already exists, {@link + * com.microsoft.playwright.FormData#set FormData.set()} will overwrite all existing values with the new one, whereas + * {@link com.microsoft.playwright.FormData#append FormData.append()} will append the new value onto the end of the + * existing set of values. + *

    {@code
    +   * import com.microsoft.playwright.options.FormData;
    +   * ...
    +   * FormData form = FormData.create()
    +   *     // Only name and value are set.
    +   *     .append("firstName", "John")
    +   *     // Name and value are set, filename and Content-Type are inferred from the file path.
    +   *     .append("attachment", Paths.get("pic.jpg"))
    +   *     // Name, value, filename and Content-Type are set.
    +   *     .append("attachment", new FilePayload("table.csv", "text/csv", Files.readAllBytes(Paths.get("my-tble.csv"))));
    +   * page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
    +   * }
    + * + * @param name Field name. + * @param value Field value. + * @since v1.44 + */ + FormData append(String name, boolean value); + /** + * Appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. File + * values can be passed either as {@code Path} or as {@code FilePayload}. Multiple fields with the same name can be added. + * + *

    The difference between {@link com.microsoft.playwright.FormData#set FormData.set()} and {@link + * com.microsoft.playwright.FormData#append FormData.append()} is that if the specified key already exists, {@link + * com.microsoft.playwright.FormData#set FormData.set()} will overwrite all existing values with the new one, whereas + * {@link com.microsoft.playwright.FormData#append FormData.append()} will append the new value onto the end of the + * existing set of values. + *

    {@code
    +   * import com.microsoft.playwright.options.FormData;
    +   * ...
    +   * FormData form = FormData.create()
    +   *     // Only name and value are set.
    +   *     .append("firstName", "John")
    +   *     // Name and value are set, filename and Content-Type are inferred from the file path.
    +   *     .append("attachment", Paths.get("pic.jpg"))
    +   *     // Name, value, filename and Content-Type are set.
    +   *     .append("attachment", new FilePayload("table.csv", "text/csv", Files.readAllBytes(Paths.get("my-tble.csv"))));
    +   * page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
    +   * }
    + * + * @param name Field name. + * @param value Field value. + * @since v1.44 + */ + FormData append(String name, int value); + /** + * Appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. File + * values can be passed either as {@code Path} or as {@code FilePayload}. Multiple fields with the same name can be added. + * + *

    The difference between {@link com.microsoft.playwright.FormData#set FormData.set()} and {@link + * com.microsoft.playwright.FormData#append FormData.append()} is that if the specified key already exists, {@link + * com.microsoft.playwright.FormData#set FormData.set()} will overwrite all existing values with the new one, whereas + * {@link com.microsoft.playwright.FormData#append FormData.append()} will append the new value onto the end of the + * existing set of values. + *

    {@code
    +   * import com.microsoft.playwright.options.FormData;
    +   * ...
    +   * FormData form = FormData.create()
    +   *     // Only name and value are set.
    +   *     .append("firstName", "John")
    +   *     // Name and value are set, filename and Content-Type are inferred from the file path.
    +   *     .append("attachment", Paths.get("pic.jpg"))
    +   *     // Name, value, filename and Content-Type are set.
    +   *     .append("attachment", new FilePayload("table.csv", "text/csv", Files.readAllBytes(Paths.get("my-tble.csv"))));
    +   * page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
    +   * }
    + * + * @param name Field name. + * @param value Field value. + * @since v1.44 + */ + FormData append(String name, Path value); + /** + * Appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. File + * values can be passed either as {@code Path} or as {@code FilePayload}. Multiple fields with the same name can be added. + * + *

    The difference between {@link com.microsoft.playwright.FormData#set FormData.set()} and {@link + * com.microsoft.playwright.FormData#append FormData.append()} is that if the specified key already exists, {@link + * com.microsoft.playwright.FormData#set FormData.set()} will overwrite all existing values with the new one, whereas + * {@link com.microsoft.playwright.FormData#append FormData.append()} will append the new value onto the end of the + * existing set of values. + *

    {@code
    +   * import com.microsoft.playwright.options.FormData;
    +   * ...
    +   * FormData form = FormData.create()
    +   *     // Only name and value are set.
    +   *     .append("firstName", "John")
    +   *     // Name and value are set, filename and Content-Type are inferred from the file path.
    +   *     .append("attachment", Paths.get("pic.jpg"))
    +   *     // Name, value, filename and Content-Type are set.
    +   *     .append("attachment", new FilePayload("table.csv", "text/csv", Files.readAllBytes(Paths.get("my-tble.csv"))));
    +   * page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
    +   * }
    + * + * @param name Field name. + * @param value Field value. + * @since v1.44 + */ + FormData append(String name, FilePayload value); /** * Creates new instance of {@code FormData}. * @@ -51,7 +186,7 @@ public interface FormData { * // Name and value are set, filename and Content-Type are inferred from the file path. * .set("profilePicture1", Paths.get("john.jpg")) * // Name, value, filename and Content-Type are set. - * .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg")))); + * .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg")))) * .set("age", 30); * page.request().post("http://localhost/submit", RequestOptions.create().setForm(form)); * }
    @@ -72,7 +207,7 @@ public interface FormData { * // Name and value are set, filename and Content-Type are inferred from the file path. * .set("profilePicture1", Paths.get("john.jpg")) * // Name, value, filename and Content-Type are set. - * .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg")))); + * .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg")))) * .set("age", 30); * page.request().post("http://localhost/submit", RequestOptions.create().setForm(form)); * }
    @@ -93,7 +228,7 @@ public interface FormData { * // Name and value are set, filename and Content-Type are inferred from the file path. * .set("profilePicture1", Paths.get("john.jpg")) * // Name, value, filename and Content-Type are set. - * .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg")))); + * .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg")))) * .set("age", 30); * page.request().post("http://localhost/submit", RequestOptions.create().setForm(form)); * }
    @@ -114,7 +249,7 @@ public interface FormData { * // Name and value are set, filename and Content-Type are inferred from the file path. * .set("profilePicture1", Paths.get("john.jpg")) * // Name, value, filename and Content-Type are set. - * .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg")))); + * .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg")))) * .set("age", 30); * page.request().post("http://localhost/submit", RequestOptions.create().setForm(form)); * }
    @@ -135,7 +270,7 @@ public interface FormData { * // Name and value are set, filename and Content-Type are inferred from the file path. * .set("profilePicture1", Paths.get("john.jpg")) * // Name, value, filename and Content-Type are set. - * .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg")))); + * .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg")))) * .set("age", 30); * page.request().post("http://localhost/submit", RequestOptions.create().setForm(form)); * }
    diff --git a/playwright/src/test/java/com/microsoft/playwright/TestBrowserContextFetch.java b/playwright/src/test/java/com/microsoft/playwright/TestBrowserContextFetch.java index 9987556e..a316571f 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestBrowserContextFetch.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestBrowserContextFetch.java @@ -591,6 +591,46 @@ public class TestBrowserContextFetch extends TestBase { assertEquals(200, response.status()); } + @Test + public void shouldSupportRepeatingNamesInMultipartFormData() throws InterruptedException, ExecutionException { + Future serverRequest = server.futureRequest("/empty.html"); + + FilePayload file1 = new FilePayload("f.js", "text/javascript", + "var x = 10;\r\n;console.log(x);".getBytes(StandardCharsets.UTF_8)); + FilePayload file2 = new FilePayload("f2.txt", "text/plain", + "hello".getBytes(StandardCharsets.UTF_8)); + APIResponse response = context.request().post(server.EMPTY_PAGE, RequestOptions.create().setMultipart( + FormData.create() + .set("name", "John") + .append("name", "Doe") + .append("file", file1) + .append("file", file2))); + + assertEquals("POST", serverRequest.get().method); + List contentType = serverRequest.get().headers.get("content-type"); + assertNotNull(contentType); + assertEquals(1, contentType.size()); + assertTrue(contentType.get(0).contains("multipart/form-data"), contentType.get(0)); + + String body = new String(serverRequest.get().postBody); + assertTrue(body.contains("content-disposition: form-data; name=\"name\"\r\n" + + "\r\n" + + "John"), body); + assertTrue(body.contains("content-disposition: form-data; name=\"name\"\r\n" + + "\r\n" + + "Doe"), body); + assertTrue(body.contains("content-disposition: form-data; name=\"file\"; filename=\"f.js\"\r\n" + + "content-type: text/javascript\r\n" + + "\r\n" + + "var x = 10;\r\n" + + ";console.log(x);"), body); + assertTrue(body.contains("content-disposition: form-data; name=\"file\"; filename=\"f2.txt\"\r\n" + + "content-type: text/plain\r\n" + + "\r\n" + + "hello"), body); + assertEquals(200, response.status()); + } + @Test void shouldSupportMultipartFormDataWithPathValues(@TempDir Path tmp) throws ExecutionException, InterruptedException, IOException { Future serverRequest = server.futureRequest("/empty.html"); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestBrowserTypeConnect.java b/playwright/src/test/java/com/microsoft/playwright/TestBrowserTypeConnect.java index 4a23eedc..d5df75c3 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestBrowserTypeConnect.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestBrowserTypeConnect.java @@ -238,7 +238,7 @@ public class TestBrowserTypeConnect extends TestBase { } assertFalse(remote.isConnected()); PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.evaluate("1 + 1")); - assertTrue(e.getMessage().contains("Browser has been closed"), e.getMessage()); + assertTrue(e.getMessage().contains("Browser has been closed") || e.getMessage().contains("Browser closed"), e.getMessage()); assertFalse(remote.isConnected()); } @@ -259,7 +259,7 @@ public class TestBrowserTypeConnect extends TestBase { } assertFalse(browser.isConnected()); PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.waitForNavigation(() -> {})); - assertTrue(e.getMessage().contains("Page closed") || e.getMessage().contains("Browser has been closed"), e.getMessage()); + assertTrue(e.getMessage().contains("Browser closed") || e.getMessage().contains("Page closed") || e.getMessage().contains("Browser has been closed"), e.getMessage()); } @Test diff --git a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions2.java b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions2.java index 26a75b71..bf6615ad 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions2.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions2.java @@ -17,9 +17,12 @@ package com.microsoft.playwright; import com.microsoft.playwright.assertions.LocatorAssertions; +import com.microsoft.playwright.options.AriaRole; import org.junit.jupiter.api.Test; import org.opentest4j.AssertionFailedError; +import java.util.regex.Pattern; + import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; import static org.junit.jupiter.api.Assertions.*; @@ -115,4 +118,36 @@ public class TestLocatorAssertions2 extends TestBase { page.setContent("
    Text content
    "); assertThat(page.locator("no-such-thing")).not().isAttached(new LocatorAssertions.IsAttachedOptions().setTimeout(1)); } + + @Test + public void toHaveAccessibleName() { + page.setContent("
    "); + + assertThat(page.locator("div")).hasAccessibleName("Hello"); + assertThat(page.locator("div")).not().hasAccessibleName("hello"); + assertThat(page.locator("div")).hasAccessibleName("hello", new LocatorAssertions.HasAccessibleNameOptions().setIgnoreCase(true)); + assertThat(page.locator("div")).hasAccessibleName(Pattern.compile("ell\\w")); + assertThat(page.locator("div")).not().hasAccessibleName(Pattern.compile("hello")); + assertThat(page.locator("div")).hasAccessibleName(Pattern.compile("hello"), new LocatorAssertions.HasAccessibleNameOptions().setIgnoreCase(true)); + } + + @Test + public void toHaveAccessibleDescription() { + page.setContent("
    "); + + assertThat(page.locator("div")).hasAccessibleDescription("Hello"); + assertThat(page.locator("div")).not().hasAccessibleDescription("hello"); + assertThat(page.locator("div")).hasAccessibleDescription("hello", new LocatorAssertions.HasAccessibleDescriptionOptions().setIgnoreCase(true)); + assertThat(page.locator("div")).hasAccessibleDescription(Pattern.compile("ell\\w")); + assertThat(page.locator("div")).not().hasAccessibleDescription(Pattern.compile("hello")); + assertThat(page.locator("div")).hasAccessibleDescription(Pattern.compile("hello"), new LocatorAssertions.HasAccessibleDescriptionOptions().setIgnoreCase(true)); + } + + @Test + public void toHaveRole() { + page.setContent("
    Button!
    "); + + assertThat(page.locator("div")).hasRole(AriaRole.BUTTON); + assertThat(page.locator("div")).not().hasRole(AriaRole.CHECKBOX); + } } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestPageAddLocatorHandler.java b/playwright/src/test/java/com/microsoft/playwright/TestPageAddLocatorHandler.java index 6aa9889e..49a615f4 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestPageAddLocatorHandler.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestPageAddLocatorHandler.java @@ -16,6 +16,8 @@ package com.microsoft.playwright; +import com.microsoft.playwright.options.AriaRole; +import com.microsoft.playwright.options.WaitForSelectorState; import org.junit.jupiter.api.Test; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; @@ -29,11 +31,13 @@ public class TestPageAddLocatorHandler extends TestBase { int[] beforeCount = {0}; int[] afterCount = {0}; - page.addLocatorHandler(page.getByText("This interstitial covers the button"), () -> { + Locator originalLocator = page.getByText("This interstitial covers the button"); + page.addLocatorHandler(originalLocator, locator -> { + assertEquals(originalLocator, locator); ++beforeCount[0]; page.locator("#close").click(); ++afterCount[0]; - }); + }, new Page.AddLocatorHandlerOptions().setNoWaitAfter(true)); String[][] argsList = { {"mouseover", "1"}, @@ -73,10 +77,10 @@ public class TestPageAddLocatorHandler extends TestBase { void shouldWorkWithCustomCheck() { page.navigate(server.PREFIX + "/input/handle-locator.html"); - page.addLocatorHandler(page.locator("body"), () -> { + page.addLocatorHandler(page.locator("body"), locator -> { if (page.getByText("This interstitial covers the button").isVisible()) page.locator("#close").click(); - }); + }, new Page.AddLocatorHandlerOptions().setNoWaitAfter(true)); String[][] argsList = { {"mouseover", "2"}, @@ -103,7 +107,7 @@ public class TestPageAddLocatorHandler extends TestBase { void shouldWorkWithLocatorHover() { page.navigate(server.PREFIX + "/input/handle-locator.html"); - page.addLocatorHandler(page.getByText("This interstitial covers the button"), () -> { + page.addLocatorHandler(page.getByText("This interstitial covers the button"), locator -> { page.locator("#close").click(); }); @@ -120,7 +124,7 @@ public class TestPageAddLocatorHandler extends TestBase { void shouldNotWorkWithForceTrue() { page.navigate(server.PREFIX + "/input/handle-locator.html"); - page.addLocatorHandler(page.getByText("This interstitial covers the button"), () -> { + page.addLocatorHandler(page.getByText("This interstitial covers the button"), locator -> { page.locator("#close").click(); }); @@ -138,7 +142,7 @@ public class TestPageAddLocatorHandler extends TestBase { void shouldThrowWhenPageCloses() { page.navigate(server.PREFIX + "/input/handle-locator.html"); - page.addLocatorHandler(page.getByText("This interstitial covers the button"), () -> { + page.addLocatorHandler(page.getByText("This interstitial covers the button"), locator -> { page.close(); }); @@ -156,7 +160,7 @@ public class TestPageAddLocatorHandler extends TestBase { page.navigate(server.PREFIX + "/input/handle-locator.html"); int[] called = {0}; - page.addLocatorHandler(page.getByText("This interstitial covers the button"), () -> { + page.addLocatorHandler(page.getByText("This interstitial covers the button"), locator -> { ++called[0]; page.locator("#close").click(); }); @@ -169,4 +173,168 @@ public class TestPageAddLocatorHandler extends TestBase { assertThat(page.locator("#interstitial")).not().isVisible(); assertEquals(1, called[0]); } + + @Test + public void shouldWorkWhenOwnerFrameDetaches() { + Page page = browser.newPage(); + page.navigate(server.EMPTY_PAGE); + + page.evaluate("() => {\n" + + " const iframe = document.createElement('iframe');\n" + + " iframe.src = 'data:text/html,hello from iframe';\n" + + " document.body.append(iframe);\n" + + "\n" + + " const target = document.createElement('button');\n" + + " target.textContent = 'Click me';\n" + + " target.id = 'target';\n" + + " target.addEventListener('click', () => window._clicked = true);\n" + + " document.body.appendChild(target);\n" + + "\n" + + " const closeButton = document.createElement('button');\n" + + " closeButton.textContent = 'close';\n" + + " closeButton.id = 'close';\n" + + " closeButton.addEventListener('click', () => iframe.remove());\n" + + " document.body.appendChild(closeButton);\n" + + " }"); + + page.addLocatorHandler(page.frameLocator("iframe").locator("body"), locator -> { + page.locator("#close").click(); + }); + + page.locator("#target").click(); + assertNull(page.querySelector("iframe")); + assertTrue((Boolean) page.evaluate("window._clicked")); + } + + @Test + public void shouldWorkWithTimesOption() { + Page page = browser.newPage(); + page.navigate(server.PREFIX + "/input/handle-locator.html"); + + int[] called = {0}; + page.addLocatorHandler(page.locator("body"), locator -> { + ++called[0]; + }, new Page.AddLocatorHandlerOptions().setNoWaitAfter(true).setTimes(2)); + + page.locator("#aside").hover(); + page.evaluate("() => {\n" + + " window.clicked = 0;\n" + + " window.setupAnnoyingInterstitial('mouseover', 4);\n" + + " }"); + + PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.locator("#target").click(new Locator.ClickOptions().setTimeout(3_000))); + assertEquals(2, called[0]); + assertEquals(0, (int) page.evaluate("window.clicked")); + assertTrue(page.locator("#interstitial").isVisible()); + assertTrue(e.getMessage().contains("Timeout 3000ms exceeded"), e.getMessage()); + assertTrue(e.getMessage().contains("
    This interstitial covers the button
    from
    subtree intercepts pointer events"), e.getMessage()); + } + + @Test + public void shouldWaitForHiddenByDefault() { + Page page = browser.newPage(); + page.navigate(server.PREFIX + "/input/handle-locator.html"); + + int[] called = {0}; + page.addLocatorHandler(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("close")), button -> { + ++called[0]; + button.click(); + }); + + page.locator("#aside").hover(); + page.evaluate("() => {" + + "window.clicked = 0;" + + "window.setupAnnoyingInterstitial('timeout', 1);" + + "}"); + + page.locator("#target").click(); + assertEquals(1, (int) page.evaluate("window.clicked")); + assertFalse(page.locator("#interstitial").isVisible()); + assertEquals(1, called[0]); + } + + @Test + public void shouldWaitForHiddenByDefault2() { + Page page = browser.newPage(); + page.navigate(server.PREFIX + "/input/handle-locator.html"); + + int[] called = {0}; + page.addLocatorHandler(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("close")), button -> { + ++called[0]; + }); + + page.locator("#aside").hover(); + page.evaluate("() => {" + + "window.clicked = 0;" + + "window.setupAnnoyingInterstitial('hide', 1);" + + "}"); + + PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.locator("#target").click(new Locator.ClickOptions().setTimeout(3_000))); + assertEquals(0, (int) page.evaluate("window.clicked")); + assertThat(page.locator("#interstitial")).isVisible(); + assertEquals(1, called[0]); + assertTrue(e.getMessage().contains("locator handler has finished, waiting for getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"close\")) to be hidden"), e.getMessage()); + } + + @Test + public void shouldWorkWithNoWaitAfter() { + Page page = browser.newPage(); + page.navigate(server.PREFIX + "/input/handle-locator.html"); + + int[] called = {0}; + page.addLocatorHandler(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("close")), button -> { + ++called[0]; + if (called[0] == 1) { + button.click(); + } else { + page.locator("#interstitial").waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.HIDDEN)); + } + }, new Page.AddLocatorHandlerOptions().setNoWaitAfter(true)); + + page.locator("#aside").hover(); + page.evaluate("() => {" + + "window.clicked = 0;" + + "window.setupAnnoyingInterstitial('timeout', 1);" + + "}"); + + page.locator("#target").click(); + assertEquals(1, (int) page.evaluate("window.clicked")); + assertThat(page.locator("#interstitial")).not().isVisible(); + assertEquals(2, called[0]); + } + + @Test + public void shouldRemoveLocatorHandler() { + Page page = browser.newPage(); + page.navigate(server.PREFIX + "/input/handle-locator.html"); + + int[] called = {0}; + page.addLocatorHandler(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("close")), button -> { + ++called[0]; + button.click(); + }); + + page.evaluate("() => {" + + "window.clicked = 0;" + + "window.setupAnnoyingInterstitial('hide', 1);" + + "}"); + + page.locator("#target").click(); + assertEquals(1, called[0]); + assertEquals(1, (int) page.evaluate("window.clicked")); + assertThat(page.locator("#interstitial")).not().isVisible(); + + page.evaluate("() => {" + + "window.clicked = 0;" + + "window.setupAnnoyingInterstitial('hide', 1);" + + "}"); + + page.removeLocatorHandler(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("close"))); + + PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.locator("#target").click(new Locator.ClickOptions().setTimeout(3_000))); + assertEquals(1, called[0]); + assertEquals(0, (int) page.evaluate("window.clicked")); + assertThat(page.locator("#interstitial")).isVisible(); + assertTrue(e.getMessage().contains("Timeout 3000ms exceeded")); + } } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestPageAssertions.java b/playwright/src/test/java/com/microsoft/playwright/TestPageAssertions.java index 0fea8864..fa06987a 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestPageAssertions.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestPageAssertions.java @@ -58,6 +58,12 @@ public class TestPageAssertions extends TestBase { assertThat(page).not().hasURL("about:blank", new PageAssertions.HasURLOptions().setTimeout(1000)); } + @Test + public void hasUrlSupportIgnoreCase() { + page.navigate("data:text/html,
    A
    "); + assertThat(page).hasURL("DATA:teXT/HTml,
    a
    ", new PageAssertions.HasURLOptions().setIgnoreCase(true)); + } + @Test void hasURLRegexPass() { page.navigate("data:text/html,
    A
    "); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestPageScreenshot.java b/playwright/src/test/java/com/microsoft/playwright/TestPageScreenshot.java index d13346cd..795ed35f 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestPageScreenshot.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestPageScreenshot.java @@ -252,8 +252,20 @@ public class TestPageScreenshot extends TestBase { assertThrows(AssertionError.class, () -> assertArrayEquals(screenshot1, screenshot2)); } + static boolean isScreenshotTestDisabled() { + if (isWebKit()) { + // Array lengths differ. + return true; + } + if (getBrowserChannelFromEnv() != null) { + // Stable builds may have different expectations. + return true; + } + return false; + } + @Test - @DisabledIf(value="com.microsoft.playwright.TestBase#isWebKit", disabledReason="array lengths differ") + @DisabledIf(value="com.microsoft.playwright.TestPageScreenshot#isScreenshotTestDisabled", disabledReason="array lengths differ") void shouldHideElementsBasedOnAttr() throws IOException { page.setViewportSize(500, 500); page.navigate(server.PREFIX + "/grid.html"); @@ -269,7 +281,7 @@ public class TestPageScreenshot extends TestBase { } @Test - @DisabledIf(value="com.microsoft.playwright.TestBase#isWebKit", disabledReason="array lengths differ") + @DisabledIf(value="com.microsoft.playwright.TestPageScreenshot#isScreenshotTestDisabled", disabledReason="array lengths differ") void shouldRemoveElementsBasedOnAttr() throws IOException { page.setViewportSize(500, 500); page.navigate(server.PREFIX + "/grid.html"); diff --git a/playwright/src/test/resources/expectations/hide-should-work-chromium.png b/playwright/src/test/resources/expectations/hide-should-work-chromium.png index dd0549a4..b1f96e04 100644 Binary files a/playwright/src/test/resources/expectations/hide-should-work-chromium.png and b/playwright/src/test/resources/expectations/hide-should-work-chromium.png differ diff --git a/playwright/src/test/resources/expectations/remove-should-work-chromium.png b/playwright/src/test/resources/expectations/remove-should-work-chromium.png index d35ddd42..38c89d7a 100644 Binary files a/playwright/src/test/resources/expectations/remove-should-work-chromium.png and b/playwright/src/test/resources/expectations/remove-should-work-chromium.png differ diff --git a/playwright/src/test/resources/input/handle-locator.html b/playwright/src/test/resources/input/handle-locator.html index 865fb536..f8f2111c 100644 --- a/playwright/src/test/resources/input/handle-locator.html +++ b/playwright/src/test/resources/input/handle-locator.html @@ -50,9 +50,16 @@ }, false); close.addEventListener('click', () => { - interstitial.classList.remove('visible'); - target.classList.remove('hidden'); - target.classList.remove('removed'); + const closeInterstitial = () => { + interstitial.classList.remove('visible'); + target.classList.remove('hidden'); + target.classList.remove('removed'); + }; + + if (interstitial.classList.contains('timeout')) + setTimeout(closeInterstitial, 3000); + else + closeInterstitial(); }); let timesToShow = 0; @@ -65,9 +72,11 @@ if (!timesToShow && event !== 'none') target.removeEventListener(event, listener, capture === 'capture'); }; - if (event === 'hide') { + if (event === 'hide' || event === 'timeout') { target.classList.add('hidden'); listener(); + if (event === 'timeout') + interstitial.classList.add('timeout'); } else if (event === 'remove') { target.classList.add('removed'); listener(); diff --git a/scripts/CLI_VERSION b/scripts/CLI_VERSION index 78962f5e..f9727641 100644 --- a/scripts/CLI_VERSION +++ b/scripts/CLI_VERSION @@ -1 +1 @@ -1.44.0-alpha-2024-04-02 +1.44.0-alpha-2024-04-27 diff --git a/tools/api-generator/src/main/java/com/microsoft/playwright/tools/ApiGenerator.java b/tools/api-generator/src/main/java/com/microsoft/playwright/tools/ApiGenerator.java index c47ac289..23bb8258 100644 --- a/tools/api-generator/src/main/java/com/microsoft/playwright/tools/ApiGenerator.java +++ b/tools/api-generator/src/main/java/com/microsoft/playwright/tools/ApiGenerator.java @@ -294,6 +294,7 @@ class TypeRef extends Element { customTypeNames.put("Frame.setInputFiles.files", "FilePayload"); customTypeNames.put("Page.setInputFiles.files", "FilePayload"); customTypeNames.put("Page.setInputFiles.files", "FilePayload"); + customTypeNames.put("FormData.append.value", "FilePayload"); customTypeNames.put("FormData.set.value", "FilePayload"); customTypeNames.put("Locator.dragTo.options.sourcePosition", "Position"); @@ -996,6 +997,9 @@ class Interface extends TypeDefinition { if ("CDPSession".equals(jsonName)) { output.add("import com.google.gson.JsonObject;"); } + if ("LocatorAssertions".equals(jsonName)) { + output.add("import com.microsoft.playwright.options.AriaRole;"); + } if ("PlaywrightAssertions".equals(jsonName)) { output.add("import com.microsoft.playwright.APIResponse;"); output.add("import com.microsoft.playwright.Locator;"); @@ -1215,6 +1219,11 @@ public class ApiGenerator { } } + // No options under assertions. + if (packageName.contains(".assertions")) { + return; + } + dir = new File(dir, "options"); for (TypeDefinition e : topLevelTypes.values()) { List lines = new ArrayList<>();