From bb4f3297e8782ac6d80ea6f0699fbcc8ee9a79eb Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Fri, 7 Oct 2022 16:20:04 -0700 Subject: [PATCH 001/420] feat: roll 1.27.0 alpha oct 5 2022 (#1091) --- README.md | 4 +- .../playwright/APIRequestContext.java | 180 +++++++ .../com/microsoft/playwright/Browser.java | 8 +- .../microsoft/playwright/BrowserContext.java | 6 +- .../com/microsoft/playwright/BrowserType.java | 4 +- .../com/microsoft/playwright/Download.java | 8 +- .../microsoft/playwright/ElementHandle.java | 18 +- .../com/microsoft/playwright/FileChooser.java | 2 +- .../java/com/microsoft/playwright/Frame.java | 463 ++++++++++++++-- .../microsoft/playwright/FrameLocator.java | 412 ++++++++++++++- .../com/microsoft/playwright/JSHandle.java | 16 +- .../com/microsoft/playwright/Locator.java | 471 ++++++++++++++++- .../java/com/microsoft/playwright/Page.java | 493 ++++++++++++++++-- .../com/microsoft/playwright/Selectors.java | 7 + .../com/microsoft/playwright/Tracing.java | 4 +- .../java/com/microsoft/playwright/Worker.java | 16 +- .../assertions/LocatorAssertions.java | 34 +- .../playwright/assertions/PageAssertions.java | 2 +- .../playwright/impl/BrowserTypeImpl.java | 4 +- .../microsoft/playwright/impl/Connection.java | 11 +- .../microsoft/playwright/impl/FrameImpl.java | 61 +++ .../playwright/impl/FrameLocatorImpl.java | 68 ++- .../playwright/impl/LocatorImpl.java | 120 +++-- .../playwright/impl/LocatorUtils.java | 132 +++++ .../microsoft/playwright/impl/PageImpl.java | 71 +++ .../playwright/impl/SharedSelectors.java | 7 + .../playwright/options/AriaRole.java | 102 ++++ .../playwright/TestBrowserContextFetch.java | 21 + .../playwright/TestLocatorFrame.java | 36 +- .../playwright/TestSelectorsGetBy.java | 142 +++++ .../playwright/TestSelectorsRole.java | 385 ++++++++++++++ scripts/CLI_VERSION | 2 +- .../playwright/tools/ApiGenerator.java | 2 +- 33 files changed, 3080 insertions(+), 232 deletions(-) create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/LocatorUtils.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/options/AriaRole.java create mode 100644 playwright/src/test/java/com/microsoft/playwright/TestSelectorsGetBy.java create mode 100644 playwright/src/test/java/com/microsoft/playwright/TestSelectorsRole.java diff --git a/README.md b/README.md index 8ff1b91a9..6413d8b0f 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 106.0.5249.30 | :white_check_mark: | :white_check_mark: | :white_check_mark: | +| Chromium 107.0.5304.18 | :white_check_mark: | :white_check_mark: | :white_check_mark: | | WebKit 16.0 | ✅ | ✅ | ✅ | -| Firefox 104.0 | :white_check_mark: | :white_check_mark: | :white_check_mark: | +| Firefox 105.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/next/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 6570d5324..c4810ab55 100644 --- a/playwright/src/main/java/com/microsoft/playwright/APIRequestContext.java +++ b/playwright/src/main/java/com/microsoft/playwright/APIRequestContext.java @@ -86,6 +86,31 @@ default APIResponse delete(String url) { * 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: + *

{@code
+   * Map data = new HashMap();
+   * data.put("title", "Book Title");
+   * data.put("body", "John Doe");
+   * 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: + *

{@code
+   * // Pass file path to the form data constructor:
+   * Path file = Paths.get("team.csv");
+   * APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
+   *   RequestOptions.create().setMethod("post").setMultipart(
+   *     FormData.create().set("fileField", file)));
+   *
+   * // 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",
+   *   RequestOptions.create().setMethod("post").setMultipart(
+   *     FormData.create().set("fileField", filePayload)));
+   * }
+ * * @param urlOrRequest Target URL or Request to get all parameters from. */ default APIResponse fetch(String urlOrRequest) { @@ -95,6 +120,31 @@ default APIResponse fetch(String urlOrRequest) { * 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: + *

{@code
+   * Map data = new HashMap();
+   * data.put("title", "Book Title");
+   * data.put("body", "John Doe");
+   * 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: + *

{@code
+   * // Pass file path to the form data constructor:
+   * Path file = Paths.get("team.csv");
+   * APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
+   *   RequestOptions.create().setMethod("post").setMultipart(
+   *     FormData.create().set("fileField", file)));
+   *
+   * // 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",
+   *   RequestOptions.create().setMethod("post").setMultipart(
+   *     FormData.create().set("fileField", filePayload)));
+   * }
+ * * @param urlOrRequest Target URL or Request to get all parameters from. * @param params Optional request parameters. */ @@ -103,6 +153,31 @@ default APIResponse fetch(String urlOrRequest) { * 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: + *

{@code
+   * Map data = new HashMap();
+   * data.put("title", "Book Title");
+   * data.put("body", "John Doe");
+   * 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: + *

{@code
+   * // Pass file path to the form data constructor:
+   * Path file = Paths.get("team.csv");
+   * APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
+   *   RequestOptions.create().setMethod("post").setMultipart(
+   *     FormData.create().set("fileField", file)));
+   *
+   * // 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",
+   *   RequestOptions.create().setMethod("post").setMultipart(
+   *     FormData.create().set("fileField", filePayload)));
+   * }
+ * * @param urlOrRequest Target URL or Request to get all parameters from. */ default APIResponse fetch(Request urlOrRequest) { @@ -112,6 +187,31 @@ default APIResponse fetch(Request urlOrRequest) { * 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: + *

{@code
+   * Map data = new HashMap();
+   * data.put("title", "Book Title");
+   * data.put("body", "John Doe");
+   * 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: + *

{@code
+   * // Pass file path to the form data constructor:
+   * Path file = Paths.get("team.csv");
+   * APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
+   *   RequestOptions.create().setMethod("post").setMultipart(
+   *     FormData.create().set("fileField", file)));
+   *
+   * // 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",
+   *   RequestOptions.create().setMethod("post").setMultipart(
+   *     FormData.create().set("fileField", filePayload)));
+   * }
+ * * @param urlOrRequest Target URL or Request to get all parameters from. * @param params Optional request parameters. */ @@ -121,6 +221,13 @@ default APIResponse fetch(Request urlOrRequest) { * response. The method will populate request cookies from the context and update context cookies from the response. The * method will automatically follow redirects. * + *

Request parameters can be configured with {@code params} option, they will be serialized into the URL search parameters: + *

{@code
+   * request.get("https://example.com/api/getText", RequestOptions.create()
+   *   .setQueryParam("isbn", "1234")
+   *   .setQueryParam("page", 23));
+   * }
+ * * @param url Target URL. */ default APIResponse get(String url) { @@ -131,6 +238,13 @@ default APIResponse get(String url) { * response. The method will populate request cookies from the context and update context cookies from the response. The * method will automatically follow redirects. * + *

Request parameters can be configured with {@code params} option, they will be serialized into the URL search parameters: + *

{@code
+   * request.get("https://example.com/api/getText", RequestOptions.create()
+   *   .setQueryParam("isbn", "1234")
+   *   .setQueryParam("page", 23));
+   * }
+ * * @param url Target URL. * @param params Optional request parameters. */ @@ -178,6 +292,39 @@ default APIResponse patch(String url) { * 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: + *

{@code
+   * Map data = new HashMap();
+   * data.put("title", "Book Title");
+   * data.put("body", "John Doe");
+   * request.post("https://example.com/api/createBook", RequestOptions.create().setData(data));
+   * }
+ * + *

To send form data to the server use {@code form} option. Its value will be encoded into the request body with + * {@code application/x-www-form-urlencoded} encoding (see below how to use {@code multipart/form-data} form encoding to send files): + *

{@code
+   * request.post("https://example.com/api/findBook", RequestOptions.create().setForm(
+   *     FormData.create().set("title", "Book Title").set("body", "John Doe")
+   * ));
+   * }
+ * + *

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: + *

{@code
+   * // Pass file path to the form data constructor:
+   * Path file = Paths.get("team.csv");
+   * APIResponse response = request.post("https://example.com/api/uploadTeamList",
+   *   RequestOptions.create().setMultipart(
+   *     FormData.create().set("fileField", file)));
+   *
+   * // 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.post("https://example.com/api/uploadTeamList",
+   *   RequestOptions.create().setMultipart(
+   *     FormData.create().set("fileField", filePayload)));
+   * }
+ * * @param url Target URL. */ default APIResponse post(String url) { @@ -188,6 +335,39 @@ default APIResponse post(String url) { * 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: + *

{@code
+   * Map data = new HashMap();
+   * data.put("title", "Book Title");
+   * data.put("body", "John Doe");
+   * request.post("https://example.com/api/createBook", RequestOptions.create().setData(data));
+   * }
+ * + *

To send form data to the server use {@code form} option. Its value will be encoded into the request body with + * {@code application/x-www-form-urlencoded} encoding (see below how to use {@code multipart/form-data} form encoding to send files): + *

{@code
+   * request.post("https://example.com/api/findBook", RequestOptions.create().setForm(
+   *     FormData.create().set("title", "Book Title").set("body", "John Doe")
+   * ));
+   * }
+ * + *

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: + *

{@code
+   * // Pass file path to the form data constructor:
+   * Path file = Paths.get("team.csv");
+   * APIResponse response = request.post("https://example.com/api/uploadTeamList",
+   *   RequestOptions.create().setMultipart(
+   *     FormData.create().set("fileField", file)));
+   *
+   * // 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.post("https://example.com/api/uploadTeamList",
+   *   RequestOptions.create().setMultipart(
+   *     FormData.create().set("fileField", filePayload)));
+   * }
+ * * @param url Target URL. * @param params Optional request parameters. */ diff --git a/playwright/src/main/java/com/microsoft/playwright/Browser.java b/playwright/src/main/java/com/microsoft/playwright/Browser.java index acb80d75f..4a38dbda1 100644 --- a/playwright/src/main/java/com/microsoft/playwright/Browser.java +++ b/playwright/src/main/java/com/microsoft/playwright/Browser.java @@ -143,7 +143,7 @@ class NewContextOptions { public Proxy proxy; /** * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If {@code attach} - * is specified, resources are persistet as separate files and all of these files are archived along with the HAR file. + * is specified, resources are persisted as separate files and all of these files are archived along with the HAR file. * Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification. */ public HarContentPolicy recordHarContent; @@ -381,7 +381,7 @@ public NewContextOptions setProxy(Proxy proxy) { } /** * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If {@code attach} - * is specified, resources are persistet as separate files and all of these files are archived along with the HAR file. + * is specified, resources are persisted as separate files and all of these files are archived along with the HAR file. * Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification. */ public NewContextOptions setRecordHarContent(HarContentPolicy recordHarContent) { @@ -623,7 +623,7 @@ class NewPageOptions { public Proxy proxy; /** * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If {@code attach} - * is specified, resources are persistet as separate files and all of these files are archived along with the HAR file. + * is specified, resources are persisted as separate files and all of these files are archived along with the HAR file. * Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification. */ public HarContentPolicy recordHarContent; @@ -861,7 +861,7 @@ public NewPageOptions setProxy(Proxy proxy) { } /** * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If {@code attach} - * is specified, resources are persistet as separate files and all of these files are archived along with the HAR file. + * is specified, resources are persisted as separate files and all of these files are archived along with the HAR file. * Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification. */ public NewPageOptions setRecordHarContent(HarContentPolicy recordHarContent) { diff --git a/playwright/src/main/java/com/microsoft/playwright/BrowserContext.java b/playwright/src/main/java/com/microsoft/playwright/BrowserContext.java index b1ec96121..8f4f54b86 100644 --- a/playwright/src/main/java/com/microsoft/playwright/BrowserContext.java +++ b/playwright/src/main/java/com/microsoft/playwright/BrowserContext.java @@ -404,7 +404,7 @@ default List cookies() { * "\n" + * "\n" + * "
"); - * page.locator("button").click(); + * page.getByRole("button").click(); * } * } * } @@ -463,7 +463,7 @@ default void exposeBinding(String name, BindingCallback callback) { * "\n" + * "\n" + * "
"); - * page.locator("button").click(); + * page.getByRole("button").click(); * } * } * } @@ -533,7 +533,7 @@ default void exposeBinding(String name, BindingCallback callback) { * "\n" + * "\n" + * "
\n"); - * page.locator("button").click(); + * page.getByRole("button").click(); * } * } * } diff --git a/playwright/src/main/java/com/microsoft/playwright/BrowserType.java b/playwright/src/main/java/com/microsoft/playwright/BrowserType.java index 885b98ce1..78606ae13 100644 --- a/playwright/src/main/java/com/microsoft/playwright/BrowserType.java +++ b/playwright/src/main/java/com/microsoft/playwright/BrowserType.java @@ -515,7 +515,7 @@ class LaunchPersistentContextOptions { public Proxy proxy; /** * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If {@code attach} - * is specified, resources are persistet as separate files and all of these files are archived along with the HAR file. + * is specified, resources are persisted as separate files and all of these files are archived along with the HAR file. * Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification. */ public HarContentPolicy recordHarContent; @@ -861,7 +861,7 @@ public LaunchPersistentContextOptions setProxy(Proxy proxy) { } /** * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If {@code attach} - * is specified, resources are persistet as separate files and all of these files are archived along with the HAR file. + * is specified, resources are persisted as separate files and all of these files are archived along with the HAR file. * Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification. */ public LaunchPersistentContextOptions setRecordHarContent(HarContentPolicy recordHarContent) { diff --git a/playwright/src/main/java/com/microsoft/playwright/Download.java b/playwright/src/main/java/com/microsoft/playwright/Download.java index 220f36be9..3a74d7eb1 100644 --- a/playwright/src/main/java/com/microsoft/playwright/Download.java +++ b/playwright/src/main/java/com/microsoft/playwright/Download.java @@ -27,14 +27,8 @@ *

Download event is emitted once the download starts. Download path becomes available once download completes: *

{@code
  * // wait for download to start
- * Download download  = page.waitForDownload(() -> page.locator("a").click());
- * // wait for download to complete
- * Path path = download.path();
- * }
- *
{@code
- * // wait for download to start
  * Download download = page.waitForDownload(() -> {
- *   page.locator("a").click();
+ *   page.getByText("Download file").click();
  * });
  * // wait for download to complete
  * Path path = download.path();
diff --git a/playwright/src/main/java/com/microsoft/playwright/ElementHandle.java b/playwright/src/main/java/com/microsoft/playwright/ElementHandle.java
index 0e3081e70..2e6ed98b3 100644
--- a/playwright/src/main/java/com/microsoft/playwright/ElementHandle.java
+++ b/playwright/src/main/java/com/microsoft/playwright/ElementHandle.java
@@ -51,7 +51,7 @@
  * 

With the locator, every time the {@code element} is used, up-to-date DOM element is located in the page using the selector. So * in the snippet below, underlying DOM element is going to be located twice. *

{@code
- * Locator locator = page.locator("text=Submit");
+ * Locator locator = page.getByText("Submit");
  * locator.hover();
  * locator.click();
  * }
@@ -1438,8 +1438,8 @@ default void dispatchEvent(String type) { * * @param selector A selector to query for. See working with selectors for more * details. - * @param expression JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted - * as a function. Otherwise, evaluated as an expression. + * @param expression JavaScript expression to be evaluated in the browser context. If the expresion evaluates to a function, the function is + * automatically invoked. */ default Object evalOnSelector(String selector, String expression) { return evalOnSelector(selector, expression, null); @@ -1464,8 +1464,8 @@ default Object evalOnSelector(String selector, String expression) { * * @param selector A selector to query for. See working with selectors for more * details. - * @param expression JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted - * as a function. Otherwise, evaluated as an expression. + * @param expression JavaScript expression to be evaluated in the browser context. If the expresion evaluates to a function, the function is + * automatically invoked. * @param arg Optional argument to pass to {@code expression}. */ Object evalOnSelector(String selector, String expression, Object arg); @@ -1489,8 +1489,8 @@ default Object evalOnSelector(String selector, String expression) { * * @param selector A selector to query for. See working with selectors for more * details. - * @param expression JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted - * as a function. Otherwise, evaluated as an expression. + * @param expression JavaScript expression to be evaluated in the browser context. If the expresion evaluates to a function, the function is + * automatically invoked. */ default Object evalOnSelectorAll(String selector, String expression) { return evalOnSelectorAll(selector, expression, null); @@ -1515,8 +1515,8 @@ default Object evalOnSelectorAll(String selector, String expression) { * * @param selector A selector to query for. See working with selectors for more * details. - * @param expression JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted - * as a function. Otherwise, evaluated as an expression. + * @param expression JavaScript expression to be evaluated in the browser context. If the expresion evaluates to a function, the function is + * automatically invoked. * @param arg Optional argument to pass to {@code expression}. */ Object evalOnSelectorAll(String selector, String expression, Object arg); diff --git a/playwright/src/main/java/com/microsoft/playwright/FileChooser.java b/playwright/src/main/java/com/microsoft/playwright/FileChooser.java index 2447b7aac..a85a4f6e8 100644 --- a/playwright/src/main/java/com/microsoft/playwright/FileChooser.java +++ b/playwright/src/main/java/com/microsoft/playwright/FileChooser.java @@ -22,7 +22,7 @@ /** * {@code FileChooser} objects are dispatched by the page in the {@link Page#onFileChooser Page.onFileChooser()} event. *
{@code
- * FileChooser fileChooser = page.waitForFileChooser(() -> page.locator("upload").click());
+ * FileChooser fileChooser = page.waitForFileChooser(() -> page.getByText("Upload").click());
  * fileChooser.setFiles(Paths.get("myfile.pdf"));
  * }
*/ diff --git a/playwright/src/main/java/com/microsoft/playwright/Frame.java b/playwright/src/main/java/com/microsoft/playwright/Frame.java index 2336eea60..8ef8be146 100644 --- a/playwright/src/main/java/com/microsoft/playwright/Frame.java +++ b/playwright/src/main/java/com/microsoft/playwright/Frame.java @@ -794,6 +794,216 @@ public GetAttributeOptions setTimeout(double timeout) { return this; } } + class GetByAltTextOptions { + /** + * Whether to find an exact match: case-sensitive and whole-string. Default to false. + */ + public Boolean exact; + + /** + * Whether to find an exact match: case-sensitive and whole-string. Default to false. + */ + public GetByAltTextOptions setExact(boolean exact) { + this.exact = exact; + return this; + } + } + class GetByLabelOptions { + /** + * Whether to find an exact match: case-sensitive and whole-string. Default to false. + */ + public Boolean exact; + + /** + * Whether to find an exact match: case-sensitive and whole-string. Default to false. + */ + public GetByLabelOptions setExact(boolean exact) { + this.exact = exact; + return this; + } + } + class GetByPlaceholderOptions { + /** + * Whether to find an exact match: case-sensitive and whole-string. Default to false. + */ + public Boolean exact; + + /** + * Whether to find an exact match: case-sensitive and whole-string. Default to false. + */ + public GetByPlaceholderOptions setExact(boolean exact) { + this.exact = exact; + return this; + } + } + class GetByRoleOptions { + /** + * An attribute that is usually set by {@code aria-checked} or native {@code } controls. Available values for + * checked are {@code true}, {@code false} and {@code "mixed"}. + * + *

Learn more about {@code aria-checked}. + */ + public Boolean checked; + /** + * A boolean attribute that is usually set by {@code aria-disabled} or {@code disabled}. + * + *

NOTE: Unlike most other attributes, {@code disabled} is inherited through the DOM hierarchy. Learn more about {@code aria-disabled}. + */ + public Boolean disabled; + /** + * A boolean attribute that is usually set by {@code aria-expanded}. + * + *

Learn more about {@code aria-expanded}. + */ + public Boolean expanded; + /** + * A boolean attribute that controls whether hidden elements are matched. By default, only non-hidden elements, as defined by ARIA, are matched by role selector. + * + *

Learn more about {@code aria-hidden}. + */ + public Boolean includeHidden; + /** + * A number attribute that is usually present for roles {@code heading}, {@code listitem}, {@code row}, {@code treeitem}, with default values for + * {@code

-

} elements. + * + *

Learn more about {@code aria-level}. + */ + public Integer level; + /** + * A string attribute that matches accessible name. + * + *

Learn more about accessible name. + */ + public Object name; + /** + * An attribute that is usually set by {@code aria-pressed}. Available values for pressed are {@code true}, {@code false} and {@code "mixed"}. + * + *

Learn more about {@code aria-pressed}. + */ + public Boolean pressed; + /** + * A boolean attribute that is usually set by {@code aria-selected}. + * + *

Learn more about {@code aria-selected}. + */ + public Boolean selected; + + /** + * An attribute that is usually set by {@code aria-checked} or native {@code } controls. Available values for + * checked are {@code true}, {@code false} and {@code "mixed"}. + * + *

Learn more about {@code aria-checked}. + */ + public GetByRoleOptions setChecked(boolean checked) { + this.checked = checked; + return this; + } + /** + * A boolean attribute that is usually set by {@code aria-disabled} or {@code disabled}. + * + *

NOTE: Unlike most other attributes, {@code disabled} is inherited through the DOM hierarchy. Learn more about {@code aria-disabled}. + */ + public GetByRoleOptions setDisabled(boolean disabled) { + this.disabled = disabled; + return this; + } + /** + * A boolean attribute that is usually set by {@code aria-expanded}. + * + *

Learn more about {@code aria-expanded}. + */ + public GetByRoleOptions setExpanded(boolean expanded) { + this.expanded = expanded; + return this; + } + /** + * A boolean attribute that controls whether hidden elements are matched. By default, only non-hidden elements, as defined by ARIA, are matched by role selector. + * + *

Learn more about {@code aria-hidden}. + */ + public GetByRoleOptions setIncludeHidden(boolean includeHidden) { + this.includeHidden = includeHidden; + return this; + } + /** + * A number attribute that is usually present for roles {@code heading}, {@code listitem}, {@code row}, {@code treeitem}, with default values for + * {@code

-

} elements. + * + *

Learn more about {@code aria-level}. + */ + public GetByRoleOptions setLevel(int level) { + this.level = level; + return this; + } + /** + * A string attribute that matches accessible name. + * + *

Learn more about accessible name. + */ + public GetByRoleOptions setName(String name) { + this.name = name; + return this; + } + /** + * A string attribute that matches accessible name. + * + *

Learn more about accessible name. + */ + public GetByRoleOptions setName(Pattern name) { + this.name = name; + return this; + } + /** + * An attribute that is usually set by {@code aria-pressed}. Available values for pressed are {@code true}, {@code false} and {@code "mixed"}. + * + *

Learn more about {@code aria-pressed}. + */ + public GetByRoleOptions setPressed(boolean pressed) { + this.pressed = pressed; + return this; + } + /** + * A boolean attribute that is usually set by {@code aria-selected}. + * + *

Learn more about {@code aria-selected}. + */ + public GetByRoleOptions setSelected(boolean selected) { + this.selected = selected; + return this; + } + } + class GetByTextOptions { + /** + * Whether to find an exact match: case-sensitive and whole-string. Default to false. + */ + public Boolean exact; + + /** + * Whether to find an exact match: case-sensitive and whole-string. Default to false. + */ + public GetByTextOptions setExact(boolean exact) { + this.exact = exact; + return this; + } + } + class GetByTitleOptions { + /** + * Whether to find an exact match: case-sensitive and whole-string. Default to false. + */ + public Boolean exact; + + /** + * Whether to find an exact match: case-sensitive and whole-string. Default to false. + */ + public GetByTitleOptions setExact(boolean exact) { + this.exact = exact; + return this; + } + } class NavigateOptions { /** * Referer header value. If provided it will take preference over the referer header value set by {@link @@ -2409,8 +2619,8 @@ default void dragAndDrop(String source, String target) { * * @param selector A selector to query for. See working with selectors for more * details. - * @param expression JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted - * as a function. Otherwise, evaluated as an expression. + * @param expression JavaScript expression to be evaluated in the browser context. If the expresion evaluates to a function, the function is + * automatically invoked. * @param arg Optional argument to pass to {@code expression}. */ default Object evalOnSelector(String selector, String expression, Object arg) { @@ -2439,8 +2649,8 @@ default Object evalOnSelector(String selector, String expression, Object arg) { * * @param selector A selector to query for. See working with selectors for more * details. - * @param expression JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted - * as a function. Otherwise, evaluated as an expression. + * @param expression JavaScript expression to be evaluated in the browser context. If the expresion evaluates to a function, the function is + * automatically invoked. */ default Object evalOnSelector(String selector, String expression) { return evalOnSelector(selector, expression, null); @@ -2468,8 +2678,8 @@ default Object evalOnSelector(String selector, String expression) { * * @param selector A selector to query for. See working with selectors for more * details. - * @param expression JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted - * as a function. Otherwise, evaluated as an expression. + * @param expression JavaScript expression to be evaluated in the browser context. If the expresion evaluates to a function, the function is + * automatically invoked. * @param arg Optional argument to pass to {@code expression}. */ Object evalOnSelector(String selector, String expression, Object arg, EvalOnSelectorOptions options); @@ -2494,8 +2704,8 @@ default Object evalOnSelector(String selector, String expression) { * * @param selector A selector to query for. See working with selectors for more * details. - * @param expression JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted - * as a function. Otherwise, evaluated as an expression. + * @param expression JavaScript expression to be evaluated in the browser context. If the expresion evaluates to a function, the function is + * automatically invoked. */ default Object evalOnSelectorAll(String selector, String expression) { return evalOnSelectorAll(selector, expression, null); @@ -2521,8 +2731,8 @@ default Object evalOnSelectorAll(String selector, String expression) { * * @param selector A selector to query for. See working with selectors for more * details. - * @param expression JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted - * as a function. Otherwise, evaluated as an expression. + * @param expression JavaScript expression to be evaluated in the browser context. If the expresion evaluates to a function, the function is + * automatically invoked. * @param arg Optional argument to pass to {@code expression}. */ Object evalOnSelectorAll(String selector, String expression, Object arg); @@ -2555,8 +2765,8 @@ default Object evalOnSelectorAll(String selector, String expression) { * bodyHandle.dispose(); * }

* - * @param expression JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted - * as a function. Otherwise, evaluated as an expression. + * @param expression JavaScript expression to be evaluated in the browser context. If the expresion evaluates to a function, the function is + * automatically invoked. */ default Object evaluate(String expression) { return evaluate(expression, null); @@ -2590,8 +2800,8 @@ default Object evaluate(String expression) { * bodyHandle.dispose(); * } * - * @param expression JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted - * as a function. Otherwise, evaluated as an expression. + * @param expression JavaScript expression to be evaluated in the browser context. If the expresion evaluates to a function, the function is + * automatically invoked. * @param arg Optional argument to pass to {@code expression}. */ Object evaluate(String expression, Object arg); @@ -2622,8 +2832,8 @@ default Object evaluate(String expression) { * resultHandle.dispose(); * } * - * @param expression JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted - * as a function. Otherwise, evaluated as an expression. + * @param expression JavaScript expression to be evaluated in the browser context. If the expresion evaluates to a function, the function is + * automatically invoked. */ default JSHandle evaluateHandle(String expression) { return evaluateHandle(expression, null); @@ -2655,8 +2865,8 @@ default JSHandle evaluateHandle(String expression) { * resultHandle.dispose(); * } * - * @param expression JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted - * as a function. Otherwise, evaluated as an expression. + * @param expression JavaScript expression to be evaluated in the browser context. If the expresion evaluates to a function, the function is + * automatically invoked. * @param arg Optional argument to pass to {@code expression}. */ JSHandle evaluateHandle(String expression, Object arg); @@ -2733,7 +2943,7 @@ default void focus(String selector) { * that iframe. Following snippet locates element with text "Submit" in the iframe with id {@code my-frame}, like {@code ").setContentType("text/html"))); page.route("**/iframe.html", route -> { route.fulfill(new Route.FulfillOptions().setBody("\n" + - "
\n" + - " \n" + - " \n" + - "
\n" + - " 1\n" + - " 2\n" + - " ").setContentType("text/html")); + "
\n" + + " \n" + + " \n" + + "
\n" + + " 1\n" + + " 2\n" + + " \n" + + "").setContentType("text/html")); }); page.route("**/iframe-2.html", route -> { route.fulfill(new Route.FulfillOptions().setBody("").setContentType("text/html")); @@ -241,4 +243,24 @@ void locatorFrameLocatorShouldNotThrowOnFirstLastNth() { assertThat(button3).hasText("Hello from iframe-3.html"); } + @Test + void getByCoverage() { + routeIframe(page); + page.navigate(server.EMPTY_PAGE); + Locator button1 = page.frameLocator("iframe").getByRole(AriaRole.BUTTON); + Locator button2 = page.frameLocator("iframe").getByText("Hello"); + Locator button3 = page.frameLocator("iframe").getByTestId("buttonId"); + assertThat(button1).hasText("Hello iframe"); + assertThat(button2).hasText("Hello iframe"); + assertThat(button3).hasText("Hello iframe"); + Locator input1 = page.frameLocator("iframe").getByLabel("Name"); + assertThat(input1).hasValue(""); + Locator input2 = page.frameLocator("iframe").getByPlaceholder("Placeholder"); + assertThat(input2).hasValue(""); + Locator input3 = page.frameLocator("iframe").getByAltText("Alternative"); + assertThat(input3).hasValue(""); + Locator input4 = page.frameLocator("iframe").getByTitle("Title"); + assertThat(input4).hasValue(""); + } + } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestSelectorsGetBy.java b/playwright/src/test/java/com/microsoft/playwright/TestSelectorsGetBy.java new file mode 100644 index 000000000..87a928a8a --- /dev/null +++ b/playwright/src/test/java/com/microsoft/playwright/TestSelectorsGetBy.java @@ -0,0 +1,142 @@ +package com.microsoft.playwright; + +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.regex.Pattern; + +import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class TestSelectorsGetBy extends TestBase { + @Test + void getByTestIdShouldWork() { + page.setContent("
Hello world
"); + assertThat(page.getByTestId("Hello")).hasText("Hello world"); + assertThat(page.mainFrame().getByTestId("Hello")).hasText("Hello world"); + assertThat(page.locator("div").getByTestId("Hello")).hasText("Hello world"); + } + + @Test + void getByTestIdShouldEscapeId() { + page.setContent("
Hello world
"); + assertThat(page.getByTestId("He\"llo")).hasText("Hello world"); + } + + @Test + void getByTextShouldWork() { + page.setContent("
yo
ya
\nye
"); + assertTrue(((String) page.getByText("ye").evaluate("e => e.outerHTML")).contains(">\nye ")); + assertTrue(((String) page.getByText(Pattern.compile("ye")).evaluate("e => e.outerHTML")).contains(">\nye ")); + assertTrue(((String) page.getByText(Pattern.compile("e")).evaluate("e => e.outerHTML")).contains(">\nye ")); + + page.setContent("
ye
ye
"); + assertTrue(((String) page.getByText("ye", new Page.GetByTextOptions().setExact(true)).first().evaluate("e => e.outerHTML")).contains("> ye ")); + + page.setContent("
Hello world
Hello
"); + assertEquals("
Hello
", page.getByText("Hello", new Page.GetByTextOptions().setExact(true)).evaluate("e => e.outerHTML")); + } + + @Test + void getByLabelShouldWork() { + page.setContent("
"); + assertEquals("LABEL", page.getByText("Name").evaluate("e => e.nodeName")); + assertEquals("INPUT", page.getByLabel("Name").evaluate("e => e.nodeName")); + assertEquals("INPUT", page.mainFrame().getByLabel("Name").evaluate("e => e.nodeName")); + assertEquals("INPUT", page.locator("div").getByLabel("Name").evaluate("e => e.nodeName")); + } + + @Test + void getByLabelShouldWorkWithNestedElements() { + page.setContent(""); + + assertThat(page.getByLabel("last name")).hasAttribute("id", "target"); + assertThat(page.getByLabel("st na")).hasAttribute("id", "target"); + assertThat(page.getByLabel("Name")).hasAttribute("id", "target"); + assertThat(page.getByLabel("Last Name", new Page.GetByLabelOptions().setExact(true))).hasAttribute("id", "target"); + assertThat(page.getByLabel(Pattern.compile("Last\\s+name", Pattern.CASE_INSENSITIVE))).hasAttribute("id", "target"); + + assertEquals(Collections.emptyList(), page.getByLabel("Last", new Page.GetByLabelOptions().setExact(true)).elementHandles()); + assertEquals(Collections.emptyList(), page.getByLabel("last name", new Page.GetByLabelOptions().setExact(true)).elementHandles()); + assertEquals(Collections.emptyList(), page.getByLabel("Name", new Page.GetByLabelOptions().setExact(true)).elementHandles()); + assertEquals(Collections.emptyList(), page.getByLabel("what?").elementHandles()); + assertEquals(Collections.emptyList(), page.getByLabel(Pattern.compile("last name")).elementHandles()); + } + + @Test + void getByPlaceholderShouldWork() { + page.setContent("
\n" + + " \n" + + " \n" + + "
"); + assertThat(page.getByPlaceholder("hello")).hasCount(2); + assertThat(page.getByPlaceholder("Hello", new Page.GetByPlaceholderOptions().setExact(true))).hasCount(1); + assertThat(page.getByPlaceholder(Pattern.compile("wor", Pattern.CASE_INSENSITIVE))).hasCount(1); + + // Coverage + assertThat(page.mainFrame().getByPlaceholder("hello")).hasCount(2); + assertThat(page.locator("div").getByPlaceholder("hello")).hasCount(2); + } + + @Test + void getByAltTextShouldWork() { + page.setContent("
\n" + + " \n" + + " \n" + + "
"); + assertThat(page.getByAltText("hello")).hasCount(2); + assertThat(page.getByAltText("Hello", new Page.GetByAltTextOptions().setExact(true))).hasCount(1); + assertThat(page.getByAltText(Pattern.compile("wor", Pattern.CASE_INSENSITIVE))).hasCount(1); + + // Coverage + assertThat(page.mainFrame().getByAltText("hello")).hasCount(2); + assertThat(page.locator("div").getByAltText("hello")).hasCount(2); + } + + @Test + void getByTitleShouldWork() { + page.setContent("
\n" + + " \n" + + " \n" + + "
"); + assertThat(page.getByTitle("hello")).hasCount(2); + assertThat(page.getByTitle("Hello", new Page.GetByTitleOptions().setExact(true))).hasCount(1); + assertThat(page.getByTitle(Pattern.compile("wor", Pattern.CASE_INSENSITIVE))).hasCount(1); + + // Coverage + assertThat(page.mainFrame().getByTitle("hello")).hasCount(2); + assertThat(page.locator("div").getByTitle("hello")).hasCount(2); + } + + @Test + void getByEscaping() { + page.setContent(""); + page.evalOnSelector("input", "input => {\n" + + " input.setAttribute('placeholder', 'hello my\\nwo\"rld');\n" + + " input.setAttribute('title', 'hello my\\nwo\"rld');\n" + + " input.setAttribute('alt', 'hello my\\nwo\"rld');\n" + + " }"); + assertThat(page.getByText("hello my\nwo\"rld")).hasAttribute("id", "label"); + assertThat(page.getByText("hello my wo\"rld")).hasAttribute("id", "label"); + assertThat(page.getByLabel("hello my\nwo\"rld")).hasAttribute("id", "control"); + assertThat(page.getByPlaceholder("hello my\nwo\"rld")).hasAttribute("id", "control"); + assertThat(page.getByAltText("hello my\nwo\"rld")).hasAttribute("id", "control"); + assertThat(page.getByTitle("hello my\nwo\"rld")).hasAttribute("id", "control"); + + page.setContent(""); + page.evalOnSelector("input", "input => {\n" + + " input.setAttribute('placeholder', 'hello my\\nworld');\n" + + " input.setAttribute('title', 'hello my\\nworld');\n" + + " input.setAttribute('alt', 'hello my\\nworld');\n" + + " }"); + assertThat(page.getByText("hello my\nworld")).hasAttribute("id", "label"); + assertThat(page.getByText("hello my world")).hasAttribute("id", "label"); + assertThat(page.getByLabel("hello my\nworld")).hasAttribute("id", "control"); + assertThat(page.getByPlaceholder("hello my\nworld")).hasAttribute("id", "control"); + assertThat(page.getByAltText("hello my\nworld")).hasAttribute("id", "control"); + assertThat(page.getByTitle("hello my\nworld")).hasAttribute("id", "control"); + } +} diff --git a/playwright/src/test/java/com/microsoft/playwright/TestSelectorsRole.java b/playwright/src/test/java/com/microsoft/playwright/TestSelectorsRole.java new file mode 100644 index 000000000..2e3fa404f --- /dev/null +++ b/playwright/src/test/java/com/microsoft/playwright/TestSelectorsRole.java @@ -0,0 +1,385 @@ +package com.microsoft.playwright; + +import com.microsoft.playwright.options.AriaRole; +import org.junit.jupiter.api.Test; + +import java.util.regex.Pattern; + +import static java.util.Arrays.asList; +import static java.util.Collections.emptyList; +import static org.junit.jupiter.api.Assertions.*; + +public class TestSelectorsRole extends TestBase { + @Test + void shouldDetectRoles() { + page.setContent("\n" + + " \n" + + " \n" + + "

Heading

\n" + + "
Hello
\n" + + "
I am a dialog
"); + assertEquals(asList(""), page.locator("role=button").evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(asList(""), page.locator("role=listbox").evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(asList(""), page.locator("role=combobox").evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(asList("

Heading

"), page.locator("role=heading").evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(asList("
Hello
"), page.locator("role=group").evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(asList("
I am a dialog
"), page.locator("role=dialog").evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(emptyList(), page.locator("role=menuitem").evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(emptyList(), page.getByRole(AriaRole.MENUITEM).evaluateAll("els => els.map(e => e.outerHTML)")); + } + + @Test + void shouldSupportSelected() { + page.setContent("\n" + + "
\n" + + "
Hi
\n" + + "
Hello
\n" + + "
"); + assertEquals(asList( + "", + "
Hi
" + ), page.locator("role=option[selected]").evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(asList( + "", + "
Hi
" + ), page.locator("role=option[selected=true]").evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(asList( + "", + "
Hi
" + ), page.getByRole(AriaRole.OPTION, new Page.GetByRoleOptions().setSelected(true)).evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(asList( + "", + "
Hello
" + ), page.locator("role=option[selected=false]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "
Hello
" + ), page.getByRole(AriaRole.OPTION, new Page.GetByRoleOptions().setSelected(false)).evaluateAll("els => els.map(e => e.outerHTML)")); + } + + @Test + void shouldSupportChecked() { + page.setContent("\n" + + " \n" + + " \n" + + "
Hi
\n" + + "
Hello
\n" + + "
Unknown
"); + page.evalOnSelector("[indeterminate]", "input => input.indeterminate = true"); + + assertEquals(asList( + "", + "
Hi
" + ), page.locator("role=checkbox[checked]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "
Hi
" + ), page.locator("role=checkbox[checked=true]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "
Hi
" + ), page.getByRole(AriaRole.CHECKBOX, new Page.GetByRoleOptions().setChecked(true)).evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(asList( + "", + "
Hello
", + "
Unknown
" + ), page.locator("role=checkbox[checked=false]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "
Hello
", + "
Unknown
" + ), page.getByRole(AriaRole.CHECKBOX, new Page.GetByRoleOptions().setChecked(false)).evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(asList( + "" + ), page.locator("role=checkbox[checked='mixed']").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "", + "", + "
Hi
", + "
Hello
", + "
Unknown
" + ), page.locator("role=checkbox").evaluateAll("els => els.map(e => e.outerHTML)")); + } + + @Test + void shouldSupportPressed() { + page.setContent("\n" + + " \n" + + " \n" + + " "); + assertEquals(asList( + "" + ), page.locator("role=button[pressed]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "" + ), page.locator("role=button[pressed=true]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "" + ), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setPressed(true)).evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "" + ), page.locator("role=button[pressed=false]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "" + ), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setPressed(false)).evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "" + ), page.locator("role=button[pressed='mixed']").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "", + "", + "" + ), page.locator("role=button").evaluateAll("els => els.map(e => e.outerHTML)")); + } + + @Test + void shouldSupportExpanded() { + page.setContent("\n" + + " \n" + + " "); + assertEquals(asList( + "" + ), page.locator("role=button[expanded]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "" + ), page.locator("role=button[expanded=true]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "" + ), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setExpanded(true)).evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "" + ), page.locator("role=button[expanded=false]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "" + ), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setExpanded(false)).evaluateAll("els => els.map(e => e.outerHTML)")); + } + + @Test + void shouldSupportDisabled() { + page.setContent("\n" + + " \n" + + " \n" + + " \n" + + "
\n" + + " \n" + + "
"); + assertEquals(asList( + "", + "", + "" + ), page.locator("role=button[disabled]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "", + "" + ), page.locator("role=button[disabled=true]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "", + "" + ), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setDisabled(true)).evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "" + ), page.locator("role=button[disabled=false]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "" + ), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setDisabled(false)).evaluateAll("els => els.map(e => e.outerHTML)")); + } + + @Test + void shouldSupportLevel() { + page.setContent("

Hello

\n" + + "

Hi

\n" + + "
Bye
"); + assertEquals(asList( + "

Hello

" + ), page.locator("role=heading[level=1]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "

Hello

" + ), page.getByRole(AriaRole.HEADING, new Page.GetByRoleOptions().setLevel(1)).evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "

Hi

" + ), page.locator("role=heading[level=3]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "

Hi

" + ), page.getByRole(AriaRole.HEADING, new Page.GetByRoleOptions().setLevel(3)).evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "
Bye
" + ), page.locator("role=heading[level=5]").evaluateAll("els => els.map(e => e.outerHTML)")); + } + + @Test + void shouldFilterHiddenUnlessExplicitlyAskedFor() { + page.setContent("\n" + + " \n" + + " \n" + + " \n" + + " \n" + + "
\n" + + " \n" + + "
\n" + + "
\n" + + " \n" + + "
\n" + + " \n" + + "
\n" + + "
\n" + + " "); + assertEquals(asList( + "", + "", + "", + "" + ), page.locator("role=button").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "", + "", + "", + "", + "", + "", + "", + "", + "" + ), page.locator("role=button[include-hidden]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "", + "", + "", + "", + "", + "", + "", + "", + "" + ), page.locator("role=button[include-hidden=true]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "", + "", + "", + "" + ), page.locator("role=button[include-hidden=false]").evaluateAll("els => els.map(e => e.outerHTML)")); + } + + @Test + void shouldSupportName() { + page.setContent("
\n" + + "
\n" + + "
\n" + + "
\n" + + "
"); + assertEquals(asList( + "
" + ), page.locator("role=button[name='Hello']").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "
" + ), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Hello")).evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(asList( + "
" + ), page.locator("role=button[name*='all']").evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(asList( + "
", + "
" + ), page.locator("role=button[name=/^H[ae]llo$/]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "
", + "
" + ), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(Pattern.compile("^H[ae]llo$"))).evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(asList( + "
", + "
" + ), page.locator("role=button[name=/h.*o/i]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "
", + "
" + ), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(Pattern.compile("h.*o", Pattern.CASE_INSENSITIVE))).evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(asList( + "
", + "
" + ), page.locator("role=button[name='Hello'][include-hidden]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "
", + "
" + ), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Hello").setIncludeHidden(true)).evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "
", + "
" + ), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("hello").setIncludeHidden(true)).evaluateAll("els => els.map(e => e.outerHTML)")); + + assertEquals(asList( + "
" + ), page.locator("role=button[name=Hello]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "
" + ), page.locator("role=button[name=123][include-hidden]").evaluateAll("els => els.map(e => e.outerHTML)")); + assertEquals(asList( + "
" + ), page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("123").setIncludeHidden(true)).evaluateAll("els => els.map(e => e.outerHTML)")); + } + + @Test + void errors() { + PlaywrightException e0 = assertThrows(PlaywrightException.class, () -> page.querySelector("role=[bar]")); + assertTrue(e0.getMessage().contains("Role must not be empty"), e0.getMessage()); + + PlaywrightException e1 = assertThrows(PlaywrightException.class, () -> page.querySelector("role=foo[sElected]")); + assertTrue(e1.getMessage().contains("Unknown attribute \"sElected\", must be one of \"checked\", \"disabled\", \"expanded\", \"include-hidden\", \"level\", \"name\", \"pressed\", \"selected\""), e1.getMessage()); + + PlaywrightException e2 = assertThrows(PlaywrightException.class, () -> page.querySelector("role=foo[bar . qux=true]")); + assertTrue(e2.getMessage().contains("Unknown attribute \"bar.qux\""), e2.getMessage()); + + PlaywrightException e3 = assertThrows(PlaywrightException.class, () -> page.querySelector("role=heading[level='bar']")); + assertTrue(e3.getMessage().contains("\"level\" attribute must be compared to a number"), e3.getMessage()); + + PlaywrightException e4 = assertThrows(PlaywrightException.class, () -> page.querySelector("role=checkbox[checked='bar']")); + assertTrue(e4.getMessage().contains("\"checked\" must be one of true, false, \"mixed\""), e4.getMessage()); + + PlaywrightException e5 = assertThrows(PlaywrightException.class, () -> page.querySelector("role=checkbox[checked~=true]")); + assertTrue(e5.getMessage().contains("cannot use ~= in attribute with non-string matching value"), e5.getMessage()); + + PlaywrightException e6 = assertThrows(PlaywrightException.class, () -> page.querySelector("role=button[level=3]")); + assertTrue(e6.getMessage().contains("\"level\" attribute is only supported for roles: \"heading\", \"listitem\", \"row\", \"treeitem\""), e6.getMessage()); + + PlaywrightException e7 = assertThrows(PlaywrightException.class, () -> page.querySelector("role=button[name]")); + assertTrue(e7.getMessage().contains("\"name\" attribute must have a value"), e7.getMessage()); + } + +} diff --git a/scripts/CLI_VERSION b/scripts/CLI_VERSION index 5ff8c4f5d..cd818323c 100644 --- a/scripts/CLI_VERSION +++ b/scripts/CLI_VERSION @@ -1 +1 @@ -1.26.0 +1.27.0-beta-1665092193000 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 da1526048..2a8746824 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 @@ -939,7 +939,7 @@ void writeTo(List output, String offset) { if (methods.stream().anyMatch(m -> "create".equals(m.jsonName))) { output.add("import com.microsoft.playwright.impl." + jsonName + "Impl;"); } - if (asList("Page", "Request", "Response", "APIRequestContext", "APIRequest", "APIResponse", "FileChooser", "Frame", "ElementHandle", "Locator", "Browser", "BrowserContext", "BrowserType", "Mouse", "Keyboard").contains(jsonName)) { + if (asList("Page", "Request", "Response", "APIRequestContext", "APIRequest", "APIResponse", "FileChooser", "Frame", "FrameLocator", "ElementHandle", "Locator", "Browser", "BrowserContext", "BrowserType", "Mouse", "Keyboard").contains(jsonName)) { output.add("import com.microsoft.playwright.options.*;"); } if ("Download".equals(jsonName)) { From 02ac0380a86ce8afaef51a13ddf381840c4e5eae Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Fri, 7 Oct 2022 17:21:15 -0700 Subject: [PATCH 002/420] chore: roll driver to 1.27.0 (#1092) --- .../java/com/microsoft/playwright/Frame.java | 30 ++++++++++++------- .../microsoft/playwright/FrameLocator.java | 30 ++++++++++++------- .../com/microsoft/playwright/Locator.java | 30 ++++++++++++------- .../java/com/microsoft/playwright/Page.java | 30 ++++++++++++------- scripts/CLI_VERSION | 2 +- 5 files changed, 81 insertions(+), 41 deletions(-) diff --git a/playwright/src/main/java/com/microsoft/playwright/Frame.java b/playwright/src/main/java/com/microsoft/playwright/Frame.java index 8ef8be146..2e0b4be36 100644 --- a/playwright/src/main/java/com/microsoft/playwright/Frame.java +++ b/playwright/src/main/java/com/microsoft/playwright/Frame.java @@ -796,12 +796,14 @@ public GetAttributeOptions setTimeout(double timeout) { } class GetByAltTextOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByAltTextOptions setExact(boolean exact) { this.exact = exact; @@ -810,12 +812,14 @@ public GetByAltTextOptions setExact(boolean exact) { } class GetByLabelOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByLabelOptions setExact(boolean exact) { this.exact = exact; @@ -824,12 +828,14 @@ public GetByLabelOptions setExact(boolean exact) { } class GetByPlaceholderOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByPlaceholderOptions setExact(boolean exact) { this.exact = exact; @@ -978,12 +984,14 @@ public GetByRoleOptions setSelected(boolean selected) { } class GetByTextOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByTextOptions setExact(boolean exact) { this.exact = exact; @@ -992,12 +1000,14 @@ public GetByTextOptions setExact(boolean exact) { } class GetByTitleOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByTitleOptions setExact(boolean exact) { this.exact = exact; diff --git a/playwright/src/main/java/com/microsoft/playwright/FrameLocator.java b/playwright/src/main/java/com/microsoft/playwright/FrameLocator.java index 37f914ef1..19f22039e 100644 --- a/playwright/src/main/java/com/microsoft/playwright/FrameLocator.java +++ b/playwright/src/main/java/com/microsoft/playwright/FrameLocator.java @@ -51,12 +51,14 @@ public interface FrameLocator { class GetByAltTextOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByAltTextOptions setExact(boolean exact) { this.exact = exact; @@ -65,12 +67,14 @@ public GetByAltTextOptions setExact(boolean exact) { } class GetByLabelOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByLabelOptions setExact(boolean exact) { this.exact = exact; @@ -79,12 +83,14 @@ public GetByLabelOptions setExact(boolean exact) { } class GetByPlaceholderOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByPlaceholderOptions setExact(boolean exact) { this.exact = exact; @@ -233,12 +239,14 @@ public GetByRoleOptions setSelected(boolean selected) { } class GetByTextOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByTextOptions setExact(boolean exact) { this.exact = exact; @@ -247,12 +255,14 @@ public GetByTextOptions setExact(boolean exact) { } class GetByTitleOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByTitleOptions setExact(boolean exact) { this.exact = exact; diff --git a/playwright/src/main/java/com/microsoft/playwright/Locator.java b/playwright/src/main/java/com/microsoft/playwright/Locator.java index 8a3d382fd..f616b5142 100644 --- a/playwright/src/main/java/com/microsoft/playwright/Locator.java +++ b/playwright/src/main/java/com/microsoft/playwright/Locator.java @@ -672,12 +672,14 @@ public GetAttributeOptions setTimeout(double timeout) { } class GetByAltTextOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByAltTextOptions setExact(boolean exact) { this.exact = exact; @@ -686,12 +688,14 @@ public GetByAltTextOptions setExact(boolean exact) { } class GetByLabelOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByLabelOptions setExact(boolean exact) { this.exact = exact; @@ -700,12 +704,14 @@ public GetByLabelOptions setExact(boolean exact) { } class GetByPlaceholderOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByPlaceholderOptions setExact(boolean exact) { this.exact = exact; @@ -854,12 +860,14 @@ public GetByRoleOptions setSelected(boolean selected) { } class GetByTextOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByTextOptions setExact(boolean exact) { this.exact = exact; @@ -868,12 +876,14 @@ public GetByTextOptions setExact(boolean exact) { } class GetByTitleOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByTitleOptions setExact(boolean exact) { this.exact = exact; diff --git a/playwright/src/main/java/com/microsoft/playwright/Page.java b/playwright/src/main/java/com/microsoft/playwright/Page.java index 22d923362..54b699f27 100644 --- a/playwright/src/main/java/com/microsoft/playwright/Page.java +++ b/playwright/src/main/java/com/microsoft/playwright/Page.java @@ -1144,12 +1144,14 @@ public GetAttributeOptions setTimeout(double timeout) { } class GetByAltTextOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByAltTextOptions setExact(boolean exact) { this.exact = exact; @@ -1158,12 +1160,14 @@ public GetByAltTextOptions setExact(boolean exact) { } class GetByLabelOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByLabelOptions setExact(boolean exact) { this.exact = exact; @@ -1172,12 +1176,14 @@ public GetByLabelOptions setExact(boolean exact) { } class GetByPlaceholderOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByPlaceholderOptions setExact(boolean exact) { this.exact = exact; @@ -1326,12 +1332,14 @@ public GetByRoleOptions setSelected(boolean selected) { } class GetByTextOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByTextOptions setExact(boolean exact) { this.exact = exact; @@ -1340,12 +1348,14 @@ public GetByTextOptions setExact(boolean exact) { } class GetByTitleOptions { /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public Boolean exact; /** - * Whether to find an exact match: case-sensitive and whole-string. Default to false. + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular + * expression. */ public GetByTitleOptions setExact(boolean exact) { this.exact = exact; diff --git a/scripts/CLI_VERSION b/scripts/CLI_VERSION index cd818323c..5db08bf2d 100644 --- a/scripts/CLI_VERSION +++ b/scripts/CLI_VERSION @@ -1 +1 @@ -1.27.0-beta-1665092193000 +1.27.0 From 9ac9347dc554b1c71d4c58eb1c2bf5c5820947b5 Mon Sep 17 00:00:00 2001 From: Jonathan Leitschuh Date: Fri, 7 Oct 2022 20:21:37 -0400 Subject: [PATCH 003/420] [SECURITY] Fix Zip Slip Vulnerability (#1078) --- playwright/src/test/java/com/microsoft/playwright/Utils.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/playwright/src/test/java/com/microsoft/playwright/Utils.java b/playwright/src/test/java/com/microsoft/playwright/Utils.java index 64164a124..ce8114bf0 100644 --- a/playwright/src/test/java/com/microsoft/playwright/Utils.java +++ b/playwright/src/test/java/com/microsoft/playwright/Utils.java @@ -114,6 +114,9 @@ static Map extractZip(Path zipPath, Path toDir) throws IOExcepti try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipPath.toFile()))) { for (ZipEntry zipEntry = zis.getNextEntry(); zipEntry != null; zipEntry = zis.getNextEntry()) { Path toPath = toDir.resolve(zipEntry.getName()); + if (!toPath.normalize().startsWith(toDir.normalize())) { + throw new IOException("Bad zip entry"); + } if (zipEntry.isDirectory()) { Files.createDirectories(toPath); } else { From 261160e4cfee92b2680b2e113d71317bd12d3ce7 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Fri, 7 Oct 2022 17:29:18 -0700 Subject: [PATCH 004/420] chore: bump dev version to 1.28.0-SNAPSHOT (#1094) --- driver-bundle/pom.xml | 2 +- driver/pom.xml | 2 +- examples/pom.xml | 2 +- playwright/pom.xml | 2 +- pom.xml | 2 +- tools/api-generator/pom.xml | 2 +- tools/test-cli-version/pom.xml | 2 +- tools/test-local-installation/pom.xml | 2 +- tools/test-spring-boot-starter/pom.xml | 2 +- tools/update-docs-version/pom.xml | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/driver-bundle/pom.xml b/driver-bundle/pom.xml index 9cd6c1f7e..3bd362fcd 100644 --- a/driver-bundle/pom.xml +++ b/driver-bundle/pom.xml @@ -6,7 +6,7 @@ com.microsoft.playwright parent-pom - 1.27.0-SNAPSHOT + 1.28.0-SNAPSHOT driver-bundle diff --git a/driver/pom.xml b/driver/pom.xml index cd99bc046..001f0df74 100644 --- a/driver/pom.xml +++ b/driver/pom.xml @@ -6,7 +6,7 @@ com.microsoft.playwright parent-pom - 1.27.0-SNAPSHOT + 1.28.0-SNAPSHOT driver diff --git a/examples/pom.xml b/examples/pom.xml index c28574d85..c3e18e8b0 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -6,7 +6,7 @@ org.example examples - 1.27.0-SNAPSHOT + 1.28.0-SNAPSHOT Playwright Client Examples UTF-8 diff --git a/playwright/pom.xml b/playwright/pom.xml index e52d09523..0df3542bc 100644 --- a/playwright/pom.xml +++ b/playwright/pom.xml @@ -7,7 +7,7 @@ com.microsoft.playwright parent-pom - 1.27.0-SNAPSHOT + 1.28.0-SNAPSHOT playwright diff --git a/pom.xml b/pom.xml index a716a2441..fc8c86be3 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.microsoft.playwright parent-pom - 1.27.0-SNAPSHOT + 1.28.0-SNAPSHOT pom Playwright Parent Project Java library to automate Chromium, Firefox and WebKit with a single API. diff --git a/tools/api-generator/pom.xml b/tools/api-generator/pom.xml index 1c3d0ae33..893d4fd41 100644 --- a/tools/api-generator/pom.xml +++ b/tools/api-generator/pom.xml @@ -6,7 +6,7 @@ com.microsoft.playwright api-generator - 1.27.0-SNAPSHOT + 1.28.0-SNAPSHOT Playwright - API Generator This is an internal module used to generate Java API from the upstream Playwright diff --git a/tools/test-cli-version/pom.xml b/tools/test-cli-version/pom.xml index 5d5f31f3a..87ddfd261 100644 --- a/tools/test-cli-version/pom.xml +++ b/tools/test-cli-version/pom.xml @@ -4,7 +4,7 @@ 4.0.0 com.microsoft.playwright test-cli-version - 1.27.0-SNAPSHOT + 1.28.0-SNAPSHOT Test Playwright Command Line Version 1.8 diff --git a/tools/test-local-installation/pom.xml b/tools/test-local-installation/pom.xml index 40e75d14d..390380464 100644 --- a/tools/test-local-installation/pom.xml +++ b/tools/test-local-installation/pom.xml @@ -4,7 +4,7 @@ 4.0.0 com.microsoft.playwright test-local-installation - 1.27.0-SNAPSHOT + 1.28.0-SNAPSHOT Test local installation Runs Playwright test suite (copied from playwright module) against locally cached Playwright diff --git a/tools/test-spring-boot-starter/pom.xml b/tools/test-spring-boot-starter/pom.xml index ee6bb9359..96ebc559f 100644 --- a/tools/test-spring-boot-starter/pom.xml +++ b/tools/test-spring-boot-starter/pom.xml @@ -9,7 +9,7 @@ com.microsoft.playwright test-spring-boot-starter - 1.27.0-SNAPSHOT + 1.28.0-SNAPSHOT Test Playwright With Spring Boot 2.4.3 diff --git a/tools/update-docs-version/pom.xml b/tools/update-docs-version/pom.xml index 393b76612..56211bbae 100644 --- a/tools/update-docs-version/pom.xml +++ b/tools/update-docs-version/pom.xml @@ -6,7 +6,7 @@ com.microsoft.playwright update-version - 1.27.0-SNAPSHOT + 1.28.0-SNAPSHOT Playwright - Update Version in Documentation This is an internal module used to update versions in the documentation based on From 69f81ea8e99b491950c9bc430d92882e5c42da66 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Mon, 10 Oct 2022 12:20:58 -0700 Subject: [PATCH 005/420] docs: update version in readme --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6413d8b0f..0ce5eaa8a 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ To run Playwright simply add following dependency to your Maven project: com.microsoft.playwright playwright - 1.26.0 + 1.27.0 ``` @@ -51,7 +51,7 @@ To run Playwright using Gradle add following dependency to your build.gradle fil ```gradle dependencies { - implementation group: 'com.microsoft.playwright', name: 'playwright', version: '1.26.0' + implementation group: 'com.microsoft.playwright', name: 'playwright', version: '1.27.0' } ``` From 4275ee34553b1f80ef027e6adce979bf05e9ad7c Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 25 Oct 2022 10:38:11 -0700 Subject: [PATCH 006/420] feat(docker): set JAVA_HOME to openjdk 17 (#1105) --- utils/docker/Dockerfile.focal | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/utils/docker/Dockerfile.focal b/utils/docker/Dockerfile.focal index cc28857d7..96b48d053 100644 --- a/utils/docker/Dockerfile.focal +++ b/utils/docker/Dockerfile.focal @@ -5,8 +5,13 @@ ARG DOCKER_IMAGE_NAME_TEMPLATE="mcr.microsoft.com/playwright/java:v%version%-foc # === INSTALL JDK and Maven === RUN apt-get update && \ + # Install install jdk 17 in a separate apt-get command so that + # installing maven doesn't bring in jdk 11 + apt-get install -y --no-install-recommends openjdk-17-jdk && \ apt-get install -y --no-install-recommends \ - openjdk-17-jdk maven \ + # Ubuntu 22.04 and earlier come with Maven 3.6.3 which fails with + # Java 17, so we install latest Maven from Apache instead. + # maven \ # Install utilities required for downloading browsers curl \ # Install utilities required for downloading driver @@ -17,8 +22,12 @@ RUN apt-get update && \ # Create the pwuser adduser pwuser +RUN VERSION=3.8.6 && \ + curl -o - https://dlcdn.apache.org/maven/maven-3/$VERSION/binaries/apache-maven-$VERSION-bin.tar.gz | tar zxfv - -C /opt/ && \ + ln -s /opt/apache-maven-$VERSION/bin/mvn /usr/local/bin/ + ARG PW_TARGET_ARCH -ENV JAVA_HOME=/usr/lib/jvm/java-11-openjdk-${PW_TARGET_ARCH} +ENV JAVA_HOME=/usr/lib/jvm/java-17-openjdk-${PW_TARGET_ARCH} # === BAKE BROWSERS INTO IMAGE === From 48d9528675cb08b208b5e19a4e1b1f652a6bfe46 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Wed, 26 Oct 2022 10:34:05 -0700 Subject: [PATCH 007/420] chore: roll driver to 1.28.0-alpha-oct-26-2022 (#1106) --- README.md | 4 +- .../impl/driver/jar/TestInstall.java | 2 - .../microsoft/playwright/BrowserContext.java | 6 +- .../microsoft/playwright/ElementHandle.java | 95 ++++++++++- .../java/com/microsoft/playwright/Frame.java | 144 +++++++++++++--- .../microsoft/playwright/FrameLocator.java | 16 +- .../com/microsoft/playwright/JSHandle.java | 8 +- .../com/microsoft/playwright/Keyboard.java | 2 +- .../com/microsoft/playwright/Locator.java | 147 +++++++++++++++-- .../java/com/microsoft/playwright/Page.java | 154 +++++++++++++++--- .../com/microsoft/playwright/Request.java | 2 +- .../java/com/microsoft/playwright/Worker.java | 8 +- .../playwright/impl/ElementHandleImpl.java | 5 + .../microsoft/playwright/impl/FrameImpl.java | 9 + .../playwright/impl/LocatorImpl.java | 20 +++ .../microsoft/playwright/impl/PageImpl.java | 6 + .../playwright/options/AriaRole.java | 2 +- .../playwright/TestElementHandleMisc.java | 10 ++ .../microsoft/playwright/TestLocatorMisc.java | 36 ++++ .../microsoft/playwright/TestPageFill.java | 35 ++++ .../com/microsoft/playwright/TestPopup.java | 10 +- scripts/CLI_VERSION | 2 +- 22 files changed, 628 insertions(+), 95 deletions(-) diff --git a/README.md b/README.md index 0ce5eaa8a..0f1c0e545 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 107.0.5304.18 | :white_check_mark: | :white_check_mark: | :white_check_mark: | +| Chromium 107.0.5304.62 | :white_check_mark: | :white_check_mark: | :white_check_mark: | | WebKit 16.0 | ✅ | ✅ | ✅ | -| Firefox 105.0.1 | :white_check_mark: | :white_check_mark: | :white_check_mark: | +| Firefox 106.0 | :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/next/intro/#system-requirements) for details. diff --git a/driver-bundle/src/test/java/com/microsoft/playwright/impl/driver/jar/TestInstall.java b/driver-bundle/src/test/java/com/microsoft/playwright/impl/driver/jar/TestInstall.java index 671284eba..f68416479 100644 --- a/driver-bundle/src/test/java/com/microsoft/playwright/impl/driver/jar/TestInstall.java +++ b/driver-bundle/src/test/java/com/microsoft/playwright/impl/driver/jar/TestInstall.java @@ -17,13 +17,11 @@ package com.microsoft.playwright.impl.driver.jar; import com.microsoft.playwright.impl.driver.Driver; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import java.io.IOException; -import java.lang.reflect.Field; import java.net.ServerSocket; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; diff --git a/playwright/src/main/java/com/microsoft/playwright/BrowserContext.java b/playwright/src/main/java/com/microsoft/playwright/BrowserContext.java index 8f4f54b86..193b29228 100644 --- a/playwright/src/main/java/com/microsoft/playwright/BrowserContext.java +++ b/playwright/src/main/java/com/microsoft/playwright/BrowserContext.java @@ -185,7 +185,8 @@ class RouteFromHAROptions { */ public HarNotFound notFound; /** - * If specified, updates the given HAR with the actual network information instead of serving from file. + * If specified, updates the given HAR with the actual network information instead of serving from file. The file is + * written to disk when {@link BrowserContext#close BrowserContext.close()} is called. */ public Boolean update; /** @@ -207,7 +208,8 @@ public RouteFromHAROptions setNotFound(HarNotFound notFound) { return this; } /** - * If specified, updates the given HAR with the actual network information instead of serving from file. + * If specified, updates the given HAR with the actual network information instead of serving from file. The file is + * written to disk when {@link BrowserContext#close BrowserContext.close()} is called. */ public RouteFromHAROptions setUpdate(boolean update) { this.update = update; diff --git a/playwright/src/main/java/com/microsoft/playwright/ElementHandle.java b/playwright/src/main/java/com/microsoft/playwright/ElementHandle.java index 2e6ed98b3..d8ed26bfa 100644 --- a/playwright/src/main/java/com/microsoft/playwright/ElementHandle.java +++ b/playwright/src/main/java/com/microsoft/playwright/ElementHandle.java @@ -138,6 +138,52 @@ public CheckOptions setTrial(boolean trial) { return this; } } + class ClearOptions { + /** + * Whether to bypass the actionability checks. Defaults to + * {@code false}. + */ + public Boolean force; + /** + * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can + * opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to + * inaccessible pages. Defaults to {@code false}. + */ + public Boolean noWaitAfter; + /** + * Maximum time in milliseconds, defaults to 30 seconds, pass {@code 0} to disable timeout. The default value can be changed by + * using the {@link BrowserContext#setDefaultTimeout BrowserContext.setDefaultTimeout()} or {@link Page#setDefaultTimeout + * Page.setDefaultTimeout()} methods. + */ + public Double timeout; + + /** + * Whether to bypass the actionability checks. Defaults to + * {@code false}. + */ + public ClearOptions setForce(boolean force) { + this.force = force; + return this; + } + /** + * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can + * opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to + * inaccessible pages. Defaults to {@code false}. + */ + public ClearOptions setNoWaitAfter(boolean noWaitAfter) { + this.noWaitAfter = noWaitAfter; + return this; + } + /** + * Maximum time in milliseconds, defaults to 30 seconds, pass {@code 0} to disable timeout. The default value can be changed by + * using the {@link BrowserContext#setDefaultTimeout BrowserContext.setDefaultTimeout()} or {@link Page#setDefaultTimeout + * Page.setDefaultTimeout()} methods. + */ + public ClearOptions setTimeout(double timeout) { + this.timeout = timeout; + return this; + } + } class ClickOptions { /** * Defaults to {@code left}. @@ -438,6 +484,12 @@ class HoverOptions { * modifiers back. If not specified, currently pressed modifiers are used. */ public List modifiers; + /** + * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can + * opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to + * inaccessible pages. Defaults to {@code false}. + */ + public Boolean noWaitAfter; /** * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the * element. @@ -472,6 +524,15 @@ public HoverOptions setModifiers(List modifiers) { this.modifiers = modifiers; return this; } + /** + * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can + * opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to + * inaccessible pages. Defaults to {@code false}. + */ + public HoverOptions setNoWaitAfter(boolean noWaitAfter) { + this.noWaitAfter = noWaitAfter; + return this; + } /** * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the * element. @@ -607,7 +668,7 @@ class ScreenshotOptions { public Integer quality; /** * When set to {@code "css"}, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this will - * keep screenshots small. Using {@code "device"} option will produce a single pixel per each device pixel, so screenhots of + * keep screenshots small. Using {@code "device"} option will produce a single pixel per each device pixel, so screenshots of * high-dpi devices will be twice as large or even larger. * *

Defaults to {@code "device"}. @@ -680,7 +741,7 @@ public ScreenshotOptions setQuality(int quality) { } /** * When set to {@code "css"}, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this will - * keep screenshots small. Using {@code "device"} option will produce a single pixel per each device pixel, so screenhots of + * keep screenshots small. Using {@code "device"} option will produce a single pixel per each device pixel, so screenshots of * high-dpi devices will be twice as large or even larger. * *

Defaults to {@code "device"}. @@ -1269,6 +1330,28 @@ default void check() { * zero timeout disables this. */ void check(CheckOptions options); + /** + * This method waits for actionability checks, focuses the + * element, clears it and triggers an {@code input} event after clearing. + * + *

If the target element is not an {@code }, {@code "); + checkAndMatchSnapshot(page.locator("body"), "- textbox: Before"); + page.evaluate("document.querySelector('textarea').value = 'After'"); + checkAndMatchSnapshot(page.locator("body"), "- textbox: After"); + } + + @Test + void shouldNotShowVisibleChildrenOfHiddenElements(Page page) { + page.setContent( + "

" + + "
" + + "
"); + assertEquals("", page.locator("body").ariaSnapshot()); + } + + @Test + void shouldNotShowUnhiddenChildrenOfAriaHiddenElements(Page page) { + page.setContent( + "
" + + "
" + + "
"); + assertEquals("", page.locator("body").ariaSnapshot()); + } + + @Test + void shouldSnapshotPlaceholderWhenDifferentFromName(Page page) { + page.setContent(""); + assertThat(page.locator("body")).matchesAriaSnapshot("- textbox \"Placeholder\""); + + page.setContent(""); + assertThat(page.locator("body")).matchesAriaSnapshot( + "- textbox \"Label\":\n" + + " - /placeholder: Placeholder"); + } + } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestPageAriaSnapshotAI.java b/playwright/src/test/java/com/microsoft/playwright/TestPageAriaSnapshotAI.java new file mode 100644 index 000000000..b29813211 --- /dev/null +++ b/playwright/src/test/java/com/microsoft/playwright/TestPageAriaSnapshotAI.java @@ -0,0 +1,191 @@ +package com.microsoft.playwright; + +import com.microsoft.playwright.junit.FixtureTest; +import com.microsoft.playwright.junit.UsePlaywright; +import com.microsoft.playwright.options.AriaSnapshotMode; +import org.junit.jupiter.api.Test; + +import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +@FixtureTest +@UsePlaywright +public class TestPageAriaSnapshotAI { + private static String aiSnapshot(Page page) { + return page.ariaSnapshot(new Page.AriaSnapshotOptions().setMode(AriaSnapshotMode.AI)); + } + + @Test + void shouldGenerateRefs(Page page) { + page.setContent(""); + + String snapshot1 = aiSnapshot(page); + assertTrue(snapshot1.contains("button \"One\" [ref=e2]"), snapshot1); + assertTrue(snapshot1.contains("button \"Two\" [ref=e3]"), snapshot1); + assertTrue(snapshot1.contains("button \"Three\" [ref=e4]"), snapshot1); + assertThat(page.locator("aria-ref=e2")).hasText("One"); + assertThat(page.locator("aria-ref=e3")).hasText("Two"); + assertThat(page.locator("aria-ref=e4")).hasText("Three"); + + page.locator("aria-ref=e3").evaluate("e => e.textContent = 'Not Two'"); + + String snapshot2 = aiSnapshot(page); + assertTrue(snapshot2.contains("button \"One\" [ref=e2]"), snapshot2); + assertTrue(snapshot2.contains("button \"Not Two\" [ref=e5]"), snapshot2); + assertTrue(snapshot2.contains("button \"Three\" [ref=e4]"), snapshot2); + } + + @Test + void shouldListIframes(Page page) { + page.setContent( + "

Hello

" + + ""); + + Locator list = page.frames().get(1).locator("ul"); + String snapshot = list.ariaSnapshot(new Locator.AriaSnapshotOptions().setMode(AriaSnapshotMode.AI)); + assertTrue(snapshot.contains("list [ref=f1e1]"), snapshot); + assertTrue(snapshot.contains("listitem [ref=f1e2]: Item 1"), snapshot); + assertTrue(snapshot.contains("listitem [ref=f1e3]: Item 2"), snapshot); + } + + @Test + void shouldCollapseGenericNodes(Page page) { + page.setContent("
"); + String snapshot = aiSnapshot(page); + assertTrue(snapshot.contains("button \"Button\" [ref=e5]"), snapshot); + } + + @Test + void shouldIncludeCursorPointerHint(Page page) { + page.setContent(""); + String snapshot = aiSnapshot(page); + assertTrue(snapshot.contains("button \"Button\" [ref=e2] [cursor=pointer]"), snapshot); + } + + @Test + void shouldNotNestCursorPointerHints(Page page) { + page.setContent( + "" + + "Link with a button " + + ""); + String snapshot = aiSnapshot(page); + assertTrue(snapshot.contains("link \"Link with a button Button\" [ref=e2] [cursor=pointer]"), snapshot); + // The button inside a cursor-pointer link should not get a redundant [cursor=pointer] + assertTrue(snapshot.contains("button \"Button\" [ref=e3]"), snapshot); + assertFalse(snapshot.contains("button \"Button\" [ref=e3] [cursor=pointer]"), snapshot); + } + + @Test + void shouldShowVisibleChildrenOfHiddenElements(Page page) { + page.setContent( + "
" + + "
" + + "
" + + "
" + + "
" + + " " + + "
" + + "
"); + String snapshot = aiSnapshot(page); + assertEquals( + "- generic [active] [ref=e1]:\n" + + " - button \"Visible\" [ref=e3]\n" + + " - button \"Visible\" [ref=e4]", + snapshot); + } + + @Test + void shouldIncludeActiveElementInformation(Page page) { + page.setContent( + "" + + "" + + "
Not focusable
"); + page.waitForFunction("document.activeElement?.id === 'btn2'"); + + String snapshot = aiSnapshot(page); + assertTrue(snapshot.contains("button \"Button 2\" [active] [ref=e3]"), snapshot); + assertFalse(snapshot.contains("button \"Button 1\" [active]"), snapshot); + } + + @Test + void shouldUpdateActiveElementOnFocus(Page page) { + page.setContent( + "" + + ""); + + String initialSnapshot = aiSnapshot(page); + assertTrue(initialSnapshot.contains("textbox \"First input\" [ref=e2]"), initialSnapshot); + assertTrue(initialSnapshot.contains("textbox \"Second input\" [ref=e3]"), initialSnapshot); + assertFalse(initialSnapshot.contains("textbox \"First input\" [active]"), initialSnapshot); + assertFalse(initialSnapshot.contains("textbox \"Second input\" [active]"), initialSnapshot); + + page.locator("#input2").focus(); + + String afterFocusSnapshot = aiSnapshot(page); + assertTrue(afterFocusSnapshot.contains("textbox \"Second input\" [active] [ref=e3]"), afterFocusSnapshot); + assertFalse(afterFocusSnapshot.contains("textbox \"First input\" [active]"), afterFocusSnapshot); + } + + @Test + void shouldCollapseInlineGenericNodes(Page page) { + page.setContent( + "
    " + + "
  • 3 bds
  • " + + "
  • 2 ba
  • " + + "
  • 1,200 sqft
  • " + + "
"); + String snapshot = aiSnapshot(page); + assertTrue(snapshot.contains("listitem [ref=e3]: 3 bds"), snapshot); + assertTrue(snapshot.contains("listitem [ref=e4]: 2 ba"), snapshot); + assertTrue(snapshot.contains("listitem [ref=e5]: 1,200 sqft"), snapshot); + } + + @Test + void shouldNotRemoveGenericNodesWithTitle(Page page) { + page.setContent("
Element content
"); + String snapshot = aiSnapshot(page); + assertTrue(snapshot.contains("generic \"Element title\" [ref=e2]"), snapshot); + } + + @Test + void shouldLimitDepth(Page page) { + page.setContent( + "
    " + + "
  • item1
  • " + + "link" + + "
    • item2
      • item3
  • " + + "
"); + + String snapshot1 = page.ariaSnapshot(new Page.AriaSnapshotOptions().setMode(AriaSnapshotMode.AI).setDepth(1)); + assertTrue(snapshot1.contains("listitem [ref=e3]: item1"), snapshot1); + assertFalse(snapshot1.contains("item2"), snapshot1); + assertFalse(snapshot1.contains("item3"), snapshot1); + + String snapshot2 = page.ariaSnapshot(new Page.AriaSnapshotOptions().setMode(AriaSnapshotMode.AI).setDepth(3)); + assertTrue(snapshot2.contains("item1"), snapshot2); + assertTrue(snapshot2.contains("item2"), snapshot2); + assertFalse(snapshot2.contains("item3"), snapshot2); + + String snapshot3 = page.ariaSnapshot(new Page.AriaSnapshotOptions().setMode(AriaSnapshotMode.AI).setDepth(100)); + assertTrue(snapshot3.contains("item1"), snapshot3); + assertTrue(snapshot3.contains("item2"), snapshot3); + assertTrue(snapshot3.contains("item3"), snapshot3); + + String snapshot4 = page.locator("#target").ariaSnapshot(new Locator.AriaSnapshotOptions().setMode(AriaSnapshotMode.AI).setDepth(1)); + assertTrue(snapshot4.contains("listitem [ref=e7]: item2"), snapshot4); + assertFalse(snapshot4.contains("item3"), snapshot4); + } +} diff --git a/playwright/src/test/java/com/microsoft/playwright/TestPageEventConsole.java b/playwright/src/test/java/com/microsoft/playwright/TestPageEventConsole.java index f3c5b6766..8b4b0b2fc 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestPageEventConsole.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestPageEventConsole.java @@ -16,6 +16,7 @@ package com.microsoft.playwright; +import com.microsoft.playwright.options.ConsoleMessagesFilter; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledIf; @@ -26,8 +27,7 @@ import static com.microsoft.playwright.Utils.mapOf; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class TestPageEventConsole extends TestBase { @Test @@ -149,4 +149,60 @@ void consoleMessagesShouldWork() { assertEquals(page, message.page()); } } + + @Test + void shouldHaveTimestamp() { + double before = (double) System.currentTimeMillis() - 1; + ConsoleMessage message = page.waitForConsoleMessage( + () -> page.evaluate("() => console.log('timestamp test')")); + double after = (double) System.currentTimeMillis() + 1; + assertTrue(message.timestamp() >= before, + "timestamp " + message.timestamp() + " should be >= " + before); + assertTrue(message.timestamp() <= after, + "timestamp " + message.timestamp() + " should be <= " + after); + } + + @Test + void shouldHaveIncreasingTimestamps() { + List messages = new ArrayList<>(); + page.onConsoleMessage(messages::add); + page.evaluate("() => { console.log('first'); console.log('second'); console.log('third'); }"); + assertEquals(3, messages.size()); + for (int i = 1; i < messages.size(); i++) + assertTrue(messages.get(i).timestamp() >= messages.get(i - 1).timestamp()); + } + + @Test + void clearConsoleMessagesShouldWork() { + page.evaluate("() => { console.log('message1'); console.log('message2'); }"); + List messages = page.consoleMessages(); + assertTrue(messages.stream().anyMatch(m -> "message1".equals(m.text()))); + assertTrue(messages.stream().anyMatch(m -> "message2".equals(m.text()))); + + page.clearConsoleMessages(); + messages = page.consoleMessages(); + assertEquals(0, messages.size()); + + page.waitForConsoleMessage(() -> page.evaluate("() => console.log('message3')")); + messages = page.consoleMessages(); + assertEquals(1, messages.size()); + assertEquals("message3", messages.get(0).text()); + } + + @Test + void consoleMessagesSinceNavigationFilterShouldWork() { + page.evaluate("() => console.log('before navigation')"); + page.navigate(server.EMPTY_PAGE); + page.evaluate("() => console.log('after navigation')"); + + List all = page.consoleMessages( + new Page.ConsoleMessagesOptions().setFilter(ConsoleMessagesFilter.ALL)); + assertTrue(all.stream().anyMatch(m -> "before navigation".equals(m.text()))); + assertTrue(all.stream().anyMatch(m -> "after navigation".equals(m.text()))); + + // sinceNavigation is the default + List sinceNav = page.consoleMessages(); + assertFalse(sinceNav.stream().anyMatch(m -> "before navigation".equals(m.text()))); + assertTrue(sinceNav.stream().anyMatch(m -> "after navigation".equals(m.text()))); + } } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestPageEventPageError.java b/playwright/src/test/java/com/microsoft/playwright/TestPageEventPageError.java index a994102ef..f70e2cbd5 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestPageEventPageError.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestPageEventPageError.java @@ -18,7 +18,6 @@ import org.junit.jupiter.api.Test; -import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -44,4 +43,28 @@ void pageErrorsShouldWork() { assertTrue(error.startsWith("Error: error" + (201 + i)), error); } } + + @Test + void clearPageErrorsShouldWork() { + page.navigate(server.EMPTY_PAGE); + page.evaluate("async () => {\n" + + " window.setTimeout(() => { throw new Error('error1'); }, 0);\n" + + " await new Promise(f => window.setTimeout(f, 100));\n" + + "}"); + + List errors = page.pageErrors(); + assertTrue(errors.stream().anyMatch(e -> e.contains("error1"))); + + page.clearPageErrors(); + errors = page.pageErrors(); + assertEquals(0, errors.size()); + + page.evaluate("async () => {\n" + + " window.setTimeout(() => { throw new Error('error2'); }, 0);\n" + + " await new Promise(f => window.setTimeout(f, 100));\n" + + "}"); + errors = page.pageErrors(); + assertEquals(1, errors.size()); + assertTrue(errors.get(0).contains("error2")); + } } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestPopup.java b/playwright/src/test/java/com/microsoft/playwright/TestPopup.java index c8bd17d00..5e0f36715 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestPopup.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestPopup.java @@ -17,6 +17,7 @@ package com.microsoft.playwright; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Assumptions; import java.util.ArrayList; import java.util.Arrays; @@ -107,6 +108,8 @@ void shouldInheritHttpCredentialsFromBrowserContext() { @Test void shouldInheritTouchSupportFromBrowserContext() { + // https://bugzilla.mozilla.org/show_bug.cgi?id=2014330 + Assumptions.assumeFalse(isFirefox() && Integer.parseInt(browser.version().split("\\.")[0]) >= 148); BrowserContext context = browser.newContext(new Browser.NewContextOptions() .setViewportSize(400, 500) .setHasTouch(true)); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestScreencast.java b/playwright/src/test/java/com/microsoft/playwright/TestScreencast.java index 94847f337..53c1724b1 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestScreencast.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestScreencast.java @@ -58,32 +58,6 @@ void shouldSaveAsVideo(@TempDir Path videosDir) { assertTrue(Files.exists(saveAsPath)); } - @Test - void saveAsShouldThrowWhenNoVideoFrames(@TempDir Path videosDir) { - try (BrowserContext context = browser.newContext( - new Browser.NewContextOptions() - .setRecordVideoDir(videosDir) - .setRecordVideoSize(320, 240) - .setViewportSize(320, 240))) { - - Page page = context.newPage(); - Page popup = context.waitForPage(() -> { - page.evaluate("() => {\n" + - " const win = window.open('about:blank');\n" + - " win.close();\n" + - "}"); - }); - page.close(); - - Path saveAsPath = videosDir.resolve("my-video.webm"); - if (!popup.isClosed()) { - popup.waitForClose(() -> {}); - } - PlaywrightException e = assertThrows(PlaywrightException.class, () -> popup.video().saveAs(saveAsPath)); - assertTrue(e.getMessage().contains("Page did not produce any video frames"), e.getMessage()); - } - } - @Test void shouldDeleteVideo(@TempDir Path videosDir) { try (BrowserContext context = browser.newContext( @@ -123,16 +97,4 @@ void shouldWaitForVideoFinishWhenPageIsClosed(@TempDir Path videosDir) throws IO assertTrue(Files.size(files.get(0)) > 0); } - @Test - void shouldErrorIfPageNotClosedBeforeSaveAs(@TempDir Path tmpDir) { - try (Page page = browser.newPage(new Browser.NewPageOptions().setRecordVideoDir(tmpDir))) { - page.navigate(server.PREFIX + "/grid.html"); - Path outPath = tmpDir.resolve("some-video.webm"); - Video video = page.video(); - PlaywrightException exception = assertThrows(PlaywrightException.class, () -> video.saveAs(outPath)); - assertTrue( - exception.getMessage().contains("Page is not yet closed. Close the page prior to calling saveAs"), - exception.getMessage()); - } - } } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestVideo.java b/playwright/src/test/java/com/microsoft/playwright/TestVideo.java index 6d6606590..24b80fae7 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestVideo.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestVideo.java @@ -16,6 +16,7 @@ package com.microsoft.playwright; +import com.microsoft.playwright.options.Size; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -23,7 +24,7 @@ import java.nio.file.Path; import static com.microsoft.playwright.Utils.relativePathOrSkipTest; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class TestVideo extends TestBase { @Test @@ -37,4 +38,50 @@ void shouldWorkWithRelativePathForRecordVideoDir(@TempDir Path tmpDir) { assertTrue(videoPath.isAbsolute(), "videosPath = " + videoPath); assertTrue(Files.exists(videoPath), "videosPath = " + videoPath); } + + @Test + void videoStartShouldFailWhenRecordVideoIsSet(@TempDir Path tmpDir) { + BrowserContext ctx = browser.newContext(new Browser.NewContextOptions() + .setRecordVideoSize(320, 240).setRecordVideoDir(tmpDir)); + Page pg = ctx.newPage(); + try { + PlaywrightException e = assertThrows(PlaywrightException.class, + () -> pg.video().start()); + assertTrue(e.getMessage().contains("Video is already being recorded"), e.getMessage()); + // stop should still work + pg.video().stop(); + } finally { + ctx.close(); + } + } + + @Test + void videoStopShouldFailWhenNoRecordingIsInProgress() { + BrowserContext ctx = browser.newContext(); + Page pg = ctx.newPage(); + try { + PlaywrightException e = assertThrows(PlaywrightException.class, + () -> pg.video().stop()); + assertTrue(e.getMessage().contains("Video is not being recorded"), e.getMessage()); + } finally { + ctx.close(); + } + } + + @Test + void videoStartAndStopShouldProduceVideoFile(@TempDir Path tmpDir) throws Exception { + BrowserContext ctx = browser.newContext(new Browser.NewContextOptions() + .setViewportSize(800, 800)); + Page pg = ctx.newPage(); + try { + Size size = new Size(800, 800); + pg.video().start(new Video.StartOptions().setSize(size)); + pg.video().stop(); + Path videoPath = pg.video().path(); + assertNotNull(videoPath); + assertTrue(Files.exists(videoPath), "video file should exist: " + videoPath); + } finally { + ctx.close(); + } + } } diff --git a/scripts/DRIVER_VERSION b/scripts/DRIVER_VERSION index 79f82f6b8..47f0c6e34 100644 --- a/scripts/DRIVER_VERSION +++ b/scripts/DRIVER_VERSION @@ -1 +1 @@ -1.58.0 +1.59.0-alpha-1774287265000 diff --git a/scripts/roll_driver.sh b/scripts/roll_driver.sh index 243bdebd4..f8535e57f 100755 --- a/scripts/roll_driver.sh +++ b/scripts/roll_driver.sh @@ -6,15 +6,23 @@ set +x trap "cd $(pwd -P)" EXIT cd "$(dirname $0)" -if [ "$#" -ne 1 ]; then +if [ "$#" -gt 1 ]; then echo "" - echo "Usage: scripts/roll_driver.sh [new version]" + echo "Usage: scripts/roll_driver.sh [next|beta|]" echo "" exit 1 fi -NEW_VERSION=$1 +ARG=${1:-next} +if [[ "$ARG" == "next" ]]; then + NEW_VERSION=$(npm view playwright@next version) +elif [[ "$ARG" == "beta" ]]; then + NEW_VERSION=$(npm view playwright@beta version) +else + NEW_VERSION=$ARG +fi CURRENT_VERSION=$(head -1 ./DRIVER_VERSION) +echo "Rolling driver from $CURRENT_VERSION to $NEW_VERSION" if [[ "$CURRENT_VERSION" == "$NEW_VERSION" ]]; then echo "Current version is up to date. Skipping driver download."; 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 9efde32a6..48a185bad 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 @@ -500,6 +500,9 @@ private String convertBuiltinType(JsonObject jsonType) { if ("Buffer".equals(name)) { return "byte[]"; } + if ("Disposable".equals(name)) { + return "AutoCloseable"; + } if ("URL".equals(name)) { return "String"; } @@ -639,7 +642,7 @@ void writeListenerMethods(List output, String offset) { writeJavadoc(output, offset, comment()); String name = toTitle(jsonName); String paramType = type.toJava(); - String listenerType = "Consumer<" + paramType + ">"; + String listenerType = "void".equals(paramType) ? "Runnable" : "Consumer<" + paramType + ">"; output.add(offset + "void on" + name + "(" + listenerType + " handler);"); writeJavadoc(output, offset, "Removes handler that was previously added with {@link #on" + name + " on" + name + "(handler)}."); output.add(offset + "void off" + name + "(" + listenerType + " handler);"); @@ -986,7 +989,7 @@ void writeTo(List output, String offset) { if (methods.stream().anyMatch(m -> "create".equals(m.jsonName))) { output.add("import com.microsoft.playwright.impl." + jsonName + "Impl;"); } - if (asList("Page", "Request", "Response", "APIRequestContext", "APIRequest", "APIResponse", "FileChooser", "Frame", "FrameLocator", "ElementHandle", "Locator", "Browser", "BrowserContext", "BrowserType", "Mouse", "Keyboard", "Tracing").contains(jsonName)) { + if (asList("Page", "Request", "Response", "APIRequestContext", "APIRequest", "APIResponse", "FileChooser", "Frame", "FrameLocator", "ElementHandle", "Locator", "Browser", "BrowserContext", "BrowserType", "Mouse", "Keyboard", "Tracing", "Video", "Debugger").contains(jsonName)) { output.add("import com.microsoft.playwright.options.*;"); } if ("Download".equals(jsonName)) { @@ -998,7 +1001,7 @@ void writeTo(List output, String offset) { if ("Clock".equals(jsonName)) { output.add("import java.util.Date;"); } - if (asList("Page", "Frame", "ElementHandle", "Locator", "LocatorAssertions", "APIRequest", "Browser", "BrowserContext", "BrowserType", "Route", "Request", "Response", "JSHandle", "ConsoleMessage", "APIResponse", "Playwright").contains(jsonName)) { + if (asList("Page", "Frame", "ElementHandle", "Locator", "LocatorAssertions", "APIRequest", "Browser", "BrowserContext", "BrowserType", "Route", "Request", "Response", "JSHandle", "ConsoleMessage", "APIResponse", "Playwright", "Debugger").contains(jsonName)) { output.add("import java.util.*;"); } if (asList("WebSocketRoute").contains(jsonName)) { From 5ccdd3e4b919515974860cd658976df9a5c77c36 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Fri, 27 Mar 2026 12:31:06 -0700 Subject: [PATCH 321/420] chore: roll to 1.59.0-alpha-1774622285000 (#1901) --- README.md | 2 +- .../com/microsoft/playwright/Debugger.java | 12 +- .../com/microsoft/playwright/Locator.java | 20 +++- .../com/microsoft/playwright/Overlay.java | 109 ++++++++++++++++++ .../java/com/microsoft/playwright/Page.java | 14 ++- .../playwright/impl/BrowserContextImpl.java | 1 - .../playwright/impl/DebuggerImpl.java | 17 +-- .../microsoft/playwright/impl/DialogImpl.java | 6 +- .../microsoft/playwright/impl/HARRouter.java | 23 +++- .../microsoft/playwright/impl/LocalUtils.java | 9 +- .../playwright/impl/LocatorImpl.java | 4 +- .../playwright/impl/OverlayImpl.java | 68 +++++++++++ .../microsoft/playwright/impl/PageImpl.java | 7 ++ .../playwright/impl/ResponseImpl.java | 7 +- .../playwright/impl/Serialization.java | 2 +- .../playwright/impl/TracingImpl.java | 15 ++- .../microsoft/playwright/impl/VideoImpl.java | 13 ++- .../playwright/options/Annotate.java | 28 ++++- .../playwright/options/AnnotatePosition.java | 26 +++++ .../microsoft/playwright/TestDebugger.java | 64 ++++++---- .../com/microsoft/playwright/TestOverlay.java | 99 ++++++++++++++++ .../playwright/TestPageNetworkResponse.java | 29 +++++ scripts/DRIVER_VERSION | 2 +- 23 files changed, 515 insertions(+), 62 deletions(-) create mode 100644 playwright/src/main/java/com/microsoft/playwright/Overlay.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/OverlayImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/options/AnnotatePosition.java create mode 100644 playwright/src/test/java/com/microsoft/playwright/TestOverlay.java diff --git a/README.md b/README.md index 07a7206b0..c93f7ed29 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Playwright is a Java library to automate [Chromium](https://www.chromium.org/Hom | | Linux | macOS | Windows | | :--- | :---: | :---: | :---: | -| Chromium 146.0.7680.31 | :white_check_mark: | :white_check_mark: | :white_check_mark: | +| Chromium 147.0.7727.15 | :white_check_mark: | :white_check_mark: | :white_check_mark: | | WebKit 26.0 | ✅ | ✅ | ✅ | | Firefox 148.0.2 | :white_check_mark: | :white_check_mark: | :white_check_mark: | diff --git a/playwright/src/main/java/com/microsoft/playwright/Debugger.java b/playwright/src/main/java/com/microsoft/playwright/Debugger.java index 4b50975de..633f9518c 100644 --- a/playwright/src/main/java/com/microsoft/playwright/Debugger.java +++ b/playwright/src/main/java/com/microsoft/playwright/Debugger.java @@ -35,11 +35,11 @@ public interface Debugger { void offPausedStateChanged(Runnable handler); /** - * Returns details about the currently paused calls. Returns an empty array if the debugger is not paused. + * Returns details about the currently paused call. Returns {@code null} if the debugger is not paused. * * @since v1.59 */ - List pausedDetails(); + PausedDetails pausedDetails(); /** * Configures the debugger to pause before the next action is executed. * @@ -47,13 +47,13 @@ public interface Debugger { * com.microsoft.playwright.Debugger#runTo Debugger.runTo()} to step while paused. * *

Note that {@link com.microsoft.playwright.Page#pause Page.pause()} is equivalent to a "debugger" statement — it pauses - * execution at the call site immediately. On the contrary, {@link com.microsoft.playwright.Debugger#pause - * Debugger.pause()} is equivalent to "pause on next statement" — it configures the debugger to pause before the next - * action is executed. + * execution at the call site immediately. On the contrary, {@link com.microsoft.playwright.Debugger#requestPause + * Debugger.requestPause()} is equivalent to "pause on next statement" — it configures the debugger to pause before the + * next action is executed. * * @since v1.59 */ - void pause(); + void requestPause(); /** * Resumes script execution. Throws if the debugger is not paused. * diff --git a/playwright/src/main/java/com/microsoft/playwright/Locator.java b/playwright/src/main/java/com/microsoft/playwright/Locator.java index e05d86c9f..f4fe34399 100644 --- a/playwright/src/main/java/com/microsoft/playwright/Locator.java +++ b/playwright/src/main/java/com/microsoft/playwright/Locator.java @@ -35,8 +35,8 @@ class AriaSnapshotOptions { */ public Integer depth; /** - * When set to {@code "ai"}, returns a snapshot optimized for AI consumption with element references. Defaults to {@code - * "default"}. + * When set to {@code "ai"}, returns a snapshot optimized for AI consumption. Defaults to {@code "default"}. See details + * for more information. */ public AriaSnapshotMode mode; /** @@ -55,8 +55,8 @@ public AriaSnapshotOptions setDepth(int depth) { return this; } /** - * When set to {@code "ai"}, returns a snapshot optimized for AI consumption with element references. Defaults to {@code - * "default"}. + * When set to {@code "ai"}, returns a snapshot optimized for AI consumption. Defaults to {@code "default"}. See details + * for more information. */ public AriaSnapshotOptions setMode(AriaSnapshotMode mode) { this.mode = mode; @@ -2322,6 +2322,12 @@ public WaitForOptions setTimeout(double timeout) { * *

Below is the HTML markup and the respective ARIA snapshot: * + *

An AI-optimized snapshot, controlled by {@code mode}, is different from a default snapshot: + *

    + *
  1. Includes element references {@code [ref=e2]}. 2. Does not wait for an element matching the locator, and throws when no + * elements match. 3. Includes snapshots of {@code "); + routePage(page, "a.html", ""); + page.navigate(server.EMPTY_PAGE); + page.frameLocator().getByRole(AriaRole.BUTTON, new FrameLocator.GetByRoleOptions().setName("Click me")).click(); + assertEquals(true, page.frames().get(1).evaluate("() => window.__clicked")); + } + + @Test + void shouldClickAButtonInTheMainFrame() { + routePage(page, "empty.html", ""); + routePage(page, "a.html", "
    No buttons here
    "); + page.navigate(server.EMPTY_PAGE); + page.frameLocator().locator("button").click(); + assertEquals(true, page.evaluate("() => window.__clicked")); + } + + @Test + void shouldFailClickWhenElementsMatchInMultipleFrames() { + routePage(page, "empty.html", ""); + routePage(page, "a.html", ""); + routePage(page, "b.html", ""); + page.navigate(server.EMPTY_PAGE); + waitForAllFrames(page, 3, "button"); + PlaywrightException e = assertThrows(PlaywrightException.class, + () -> page.frameLocator().locator("button").click(new Locator.ClickOptions().setTimeout(3000))); + assertTrue(e.getMessage().contains("frameLocator() matched elements in multiple frames"), e.getMessage()); + } + + @Test + void shouldFailClickUponStrictModeViolationInsideASingleFrame() { + routePage(page, "empty.html", ""); + routePage(page, "a.html", ""); + page.navigate(server.EMPTY_PAGE); + waitForAllFrames(page, 2, "button"); + PlaywrightException e = assertThrows(PlaywrightException.class, + () -> page.frameLocator().locator("button").click(new Locator.ClickOptions().setTimeout(3000))); + assertTrue(e.getMessage().contains("strict mode violation"), e.getMessage()); + } + + @Test + void shouldTimeOutOnClickWhenThereAreNoMatches() { + routePage(page, "empty.html", ""); + routePage(page, "a.html", "
    Nothing here
    "); + page.navigate(server.EMPTY_PAGE); + PlaywrightException e = assertThrows(PlaywrightException.class, + () -> page.frameLocator().locator("button").click(new Locator.ClickOptions().setTimeout(1000))); + assertTrue(e.getMessage().contains("Timeout 1000ms exceeded"), e.getMessage()); + } + + @Test + void shouldCountElementsInASingleFrame() { + routePage(page, "empty.html", ""); + routePage(page, "a.html", "
    1
    2
    3
    "); + page.navigate(server.EMPTY_PAGE); + waitForAllFrames(page, 2, "div"); + assertEquals(3, page.frameLocator().locator("div").count()); + assertEquals(0, page.frameLocator().locator("button").count()); + } + + @Test + void shouldFailCountWhenElementsMatchInMultipleFrames() { + routePage(page, "empty.html", "
    main
    "); + routePage(page, "a.html", "
    child
    "); + page.navigate(server.EMPTY_PAGE); + waitForAllFrames(page, 2, "div"); + PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.frameLocator().locator("div").count()); + assertTrue(e.getMessage().contains("frameLocator() matched elements in multiple frames"), e.getMessage()); + } + + @Test + void shouldSupportHasCount() { + routePage(page, "empty.html", ""); + routePage(page, "a.html", "onetwo"); + page.navigate(server.EMPTY_PAGE); + assertThat(page.frameLocator().locator("span")).hasCount(2); + assertThat(page.frameLocator().locator("button")).hasCount(0); + } + + @Test + void shouldWaitForAFrameToAppearWithHasCount() { + routePage(page, "empty.html", "
    No frames yet
    "); + routePage(page, "a.html", "onetwo"); + page.navigate(server.EMPTY_PAGE); + page.evaluate("() => {\n" + + " setTimeout(() => {\n" + + " const iframe = document.createElement('iframe');\n" + + " iframe.src = 'a.html';\n" + + " document.body.appendChild(iframe);\n" + + " }, 500);\n" + + "}"); + assertThat(page.frameLocator().locator("span")).hasCount(2); + } + + @Test + void shouldFailHasCountWhenElementsMatchInMultipleFrames() { + routePage(page, "empty.html", ""); + routePage(page, "a.html", "one"); + routePage(page, "b.html", "two"); + page.navigate(server.EMPTY_PAGE); + waitForAllFrames(page, 3, "span"); + AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(page.frameLocator().locator("span")) + .hasCount(2, new LocatorAssertions.HasCountOptions().setTimeout(3000))); + assertTrue(e.getMessage().contains("frameLocator() matched elements in multiple frames"), e.getMessage()); + } + + @Test + void shouldSupportHasText() { + routePage(page, "empty.html", ""); + routePage(page, "a.html", "
    Hello iframe
    "); + page.navigate(server.EMPTY_PAGE); + assertThat(page.frameLocator().locator("div")).hasText("Hello iframe"); + } + + @Test + void shouldSupportEvaluate() { + routePage(page, "empty.html", ""); + routePage(page, "a.html", ""); + page.navigate(server.EMPTY_PAGE); + assertEquals("one", page.frameLocator().locator("button").evaluate("e => e.textContent")); + } + + @Test + void shouldSupportFirstLastNth() { + routePage(page, "empty.html", ""); + routePage(page, "a.html", "onetwothree"); + page.navigate(server.EMPTY_PAGE); + assertThat(page.frameLocator().locator("span").first()).hasText("one"); + assertThat(page.frameLocator().locator("span").last()).hasText("three"); + assertThat(page.frameLocator().locator("span").nth(1)).hasText("two"); + } + + @Test + void shouldNotAllowNthFrameOnAnyFrameLocator() { + PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.frameLocator().first()); + assertTrue(e.getMessage().contains("Selecting the nth frame is not allowed on frameLocator()"), e.getMessage()); + assertThrows(PlaywrightException.class, () -> page.frameLocator().last()); + assertThrows(PlaywrightException.class, () -> page.frameLocator().nth(1)); + } + + @Test + void shouldSupportTwoFrameLocators() { + routePage(page, "empty.html", ""); + routePage(page, "a.html", ""); + routePage(page, "b.html", ""); + routePage(page, "c.html", ""); + page.navigate(server.EMPTY_PAGE); + assertThat(page.frameLocator().frameLocator("#x").frameLocator("#y").locator("button")).hasText("bottom"); + } + + @Test + void shouldSupportLocatorBeforeFrameLocator() { + routePage(page, "empty.html", ""); + routePage(page, "a.html", "
    "); + routePage(page, "b.html", ""); + routePage(page, "c.html", ""); + page.navigate(server.EMPTY_PAGE); + assertThat(page.frameLocator().locator("section").frameLocator("iframe").locator("button")).hasText("in-section"); + } + + @Test + void shouldSupportOwnerOfAFrameLocator() { + routePage(page, "empty.html", ""); + routePage(page, "a.html", ""); + routePage(page, "b.html", ""); + page.navigate(server.EMPTY_PAGE); + assertEquals("target", page.frameLocator().frameLocator("#target").owner().getAttribute("id")); + } + + @Test + void shouldSupportContentFrameAfterAnyFrameLocator() { + routePage(page, "empty.html", ""); + routePage(page, "a.html", ""); + routePage(page, "b.html", ""); + page.navigate(server.EMPTY_PAGE); + assertThat(page.frameLocator().locator("#my-frame").contentFrame().getByRole(AriaRole.BUTTON)).hasText("inside"); + } + + @Test + void shouldWorkOnFrame() { + routePage(page, "empty.html", ""); + routePage(page, "a.html", ""); + routePage(page, "b.html", ""); + page.navigate(server.EMPTY_PAGE); + page.waitForCondition(() -> page.frames().size() == 3); + assertThat(page.frames().get(1).frameLocator().locator("button")).hasText("deep"); + } +} diff --git a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java index cc87d6673..27fa7dc2f 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java @@ -1070,7 +1070,7 @@ void defaultTimeoutHasTextFail() { Locator locator = page.locator("div"); PlaywrightAssertions.setDefaultAssertionTimeout(1000); AssertionFailedError exception = assertThrows(AssertionFailedError.class, () -> assertThat(locator).hasText("foo")); - assertTrue(exception.getMessage().contains("Assert \"hasText\" with timeout 1000ms"), exception.getMessage()); + assertTrue(exception.getMessage().contains("Assert \"hasText\" locator(\"div\") with timeout 1000ms"), exception.getMessage()); // Restore default. PlaywrightAssertions.setDefaultAssertionTimeout(5_000); } @@ -1119,7 +1119,7 @@ void containsClassFail() { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(page.locator("div")).containsClass("does-not-exist", new ContainsClassOptions().setTimeout(1000)); }); - assertTrue(e.getMessage().contains("Assert \"containsClass\" with timeout 1000ms"), e.getMessage()); + assertTrue(e.getMessage().contains("Assert \"containsClass\" locator(\"div\") with timeout 1000ms"), e.getMessage()); } @Test @@ -1137,6 +1137,6 @@ void containsClassFailWithArray() { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(page.locator("div")).containsClass(asList("foo", "bar", "baz"), new ContainsClassOptions().setTimeout(1000)); }); - assertTrue(e.getMessage().contains("Assert \"containsClass\" with timeout 1000ms"), e.getMessage()); + assertTrue(e.getMessage().contains("Assert \"containsClass\" locator(\"div\") with timeout 1000ms"), e.getMessage()); } } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions2.java b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions2.java index b8009bdf4..9f2a5b266 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions2.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions2.java @@ -218,7 +218,7 @@ void toBeEditableFailWithIndeterminateTrue() { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(locator).isChecked(new LocatorAssertions.IsCheckedOptions().setIndeterminate(true).setTimeout(1000))); // TODO: should be "assertThat().isChecked() with timeout 1000ms" - assertTrue(e.getMessage().contains("Assert \"isChecked\" with timeout 1000ms"), e.getMessage()); + assertTrue(e.getMessage().contains("Assert \"isChecked\" locator(\"input\") with timeout 1000ms"), e.getMessage()); } } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestLocatorMisc.java b/playwright/src/test/java/com/microsoft/playwright/TestLocatorMisc.java index 43cca0091..cdc039dda 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestLocatorMisc.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestLocatorMisc.java @@ -185,4 +185,20 @@ void waitForFunctionShouldRespectTimeout() { new Locator.WaitForFunctionOptions().setTimeout(500))); assertTrue(e.getMessage().contains("Timeout 500ms exceeded"), e.getMessage()); } + + @Test + public void shouldSupportVisible() { + page.setContent("
    \n" + + "
    Hidden data0
    \n" + + "
    visible data1
    \n" + + "
    Hidden data1
    \n" + + "
    visible data2
    \n" + + "
    Hidden data2
    \n" + + "
    visible data3
    \n" + + "
    "); + Locator locator = page.locator(".item").visible().nth(1); + assertThat(locator).hasText("visible data2"); + assertThat(page.locator(".item").visible().getByText("data3")).hasText("visible data3"); + assertThat(page.locator(".item").visible()).hasCount(3); + } } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestPageDialog.java b/playwright/src/test/java/com/microsoft/playwright/TestPageDialog.java index 2ec8d60e7..975dbed37 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestPageDialog.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestPageDialog.java @@ -18,6 +18,9 @@ import org.junit.jupiter.api.Test; +import java.util.ArrayList; +import java.util.List; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @@ -124,4 +127,41 @@ void shouldAutoDismissTheAlertWithoutListeners() { assertEquals(true, page.evaluate("window._clicked")); } + @Test + void shouldFireDialogClosedWhenDialogIsAccepted() { + List closed = new ArrayList<>(); + page.onDialogClosed(closed::add); + Dialog[] opened = {null}; + page.onDialog(dialog -> { + opened[0] = dialog; + dialog.accept(); + }); + page.evaluate("alert('yo')"); + page.waitForCondition(() -> closed.size() == 1); + assertEquals(opened[0], closed.get(0)); + // Perform some roundtrips to ensure the event does not fire twice. + page.evaluate("1"); + page.evaluate("1"); + assertEquals(1, closed.size()); + } + + @Test + void shouldFireDialogClosedWhenDialogIsDismissed() { + Dialog[] closed = {null}; + page.onDialogClosed(dialog -> closed[0] = dialog); + page.onDialog(Dialog::dismiss); + page.evaluate("confirm('boolean?')"); + page.waitForCondition(() -> closed[0] != null); + assertEquals("confirm", closed[0].type()); + assertEquals("boolean?", closed[0].message()); + } + + @Test + void shouldFireDialogClosedForAutoDismissedDialogs() { + Dialog[] closed = {null}; + page.onDialogClosed(dialog -> closed[0] = dialog); + page.evaluate("alert('yo')"); + page.waitForCondition(() -> closed[0] != null); + assertEquals("yo", closed[0].message()); + } } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestTracing.java b/playwright/src/test/java/com/microsoft/playwright/TestTracing.java index 0dd42048a..c0a53e918 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestTracing.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestTracing.java @@ -16,6 +16,8 @@ package com.microsoft.playwright; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import com.microsoft.playwright.options.AriaRole; import com.microsoft.playwright.options.Location; import com.microsoft.playwright.options.MouseButton; @@ -26,11 +28,18 @@ import org.junit.jupiter.api.io.TempDir; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; import java.util.regex.Pattern; +import java.util.stream.Collectors; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; +import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.*; public class TestTracing extends TestBase { @@ -62,7 +71,7 @@ void shouldCollectTrace1(@TempDir Path tempDir) throws Exception { assertTrue(Files.exists(traceFile)); TraceViewerPage.showTraceViewer(this.browserType, traceFile, traceViewer -> { assertThat(traceViewer.actionTitles()).hasText(new Pattern[] { - Pattern.compile("Navigate to \"/empty.html\""), + Pattern.compile("Navigate.*/empty.html"), Pattern.compile("Set content"), Pattern.compile("Click"), Pattern.compile("Close") @@ -92,7 +101,7 @@ void shouldCollectTwoTraces(@TempDir Path tempDir) throws Exception { TraceViewerPage.showTraceViewer(this.browserType, traceFile1, traceViewer -> { assertThat(traceViewer.actionTitles()).hasText(new Pattern[] { - Pattern.compile("Navigate to \"/empty.html\""), + Pattern.compile("Navigate.*/empty.html"), Pattern.compile("Set content"), Pattern.compile("Click") }); @@ -154,7 +163,7 @@ void shouldCollectSources(@TempDir Path tmpDir) throws Exception { TraceViewerPage.showTraceViewer(this.browserType, trace, traceViewer -> { assertThat(traceViewer.actionTitles()).hasText(new Pattern[] { - Pattern.compile("Navigate to \"/empty.html\""), + Pattern.compile("Navigate.*/empty.html"), Pattern.compile("Set content"), Pattern.compile("Click") }); @@ -210,7 +219,7 @@ void shouldRespectTracesDirAndName(@TempDir Path tempDir) throws Exception { TraceViewerPage.showTraceViewer(this.browserType, tempDir.resolve("trace1.zip"), traceViewer -> { assertThat(traceViewer.actionTitles()).hasText(new Pattern[] { - Pattern.compile("Navigate to \"/one-style.html\"") + Pattern.compile("Navigate.*/one-style.html") }); FrameLocator frame = traceViewer.snapshotFrame("Navigate", 0, false); assertThat(frame.locator("body")).hasCSS("background-color", "rgb(255, 192, 203)"); @@ -219,7 +228,7 @@ void shouldRespectTracesDirAndName(@TempDir Path tempDir) throws Exception { TraceViewerPage.showTraceViewer(this.browserType, tempDir.resolve("trace2.zip"), traceViewer -> { assertThat(traceViewer.actionTitles()).hasText(new Pattern[] { - Pattern.compile("Navigate to \"/har.html\"") + Pattern.compile("Navigate.*/har.html") }); FrameLocator frame = traceViewer.snapshotFrame("Navigate", 0, false); assertThat(frame.locator("body")).hasCSS("background-color", "rgb(255, 192, 203)"); @@ -246,7 +255,7 @@ void canCallTracingGroupGroupEndAtAnyTimeAndAutoClose(@TempDir Path tempDir) thr context.tracing().groupEnd(); TraceViewerPage.showTraceViewer(this.browserType, traceFile1, traceViewer -> { - assertThat(traceViewer.actionTitles()).containsText(new String[] {"actual", "Navigate to \"/empty.html\""}); + assertThat(traceViewer.actionTitles()).containsText(new Pattern[] {Pattern.compile("actual"), Pattern.compile("Navigate.*/empty.html")}); }); } @@ -270,7 +279,7 @@ void traceGroupGroupEnd(@TempDir Path tempDir) throws Exception { traceViewer.expandAction("inner group 1"); assertThat(traceViewer.actionTitles()).hasText(new Pattern[] { Pattern.compile("outer group"), - Pattern.compile("Navigate to \"data:"), + Pattern.compile("Navigate.*data:"), Pattern.compile("inner group 1"), Pattern.compile("Click"), Pattern.compile("inner group 2"), @@ -356,7 +365,7 @@ public void shouldNotRecordNetworkActions(@TempDir Path tempDir) throws Exceptio TraceViewerPage.showTraceViewer(this.browserType, traceFile1, traceViewer -> { assertThat(traceViewer.actionTitles()).hasText(new Pattern[] { - Pattern.compile("Navigate to \"/empty.html\"") + Pattern.compile("Navigate.*/empty.html") }); }); } @@ -375,7 +384,7 @@ public void shouldShowWaitForLoadState(@TempDir Path tempDir) throws Exception { TraceViewerPage.showTraceViewer(this.browserType, traceFile1, traceViewer -> { assertThat(traceViewer.actionTitles()).hasText(new Pattern[] { - Pattern.compile("Navigate to \"/empty.html\""), + Pattern.compile("Navigate.*/empty.html"), Pattern.compile("Wait for load state \"load\""), }); }); @@ -391,4 +400,83 @@ public void shouldRecordHarWithStartHarStopHar(@TempDir Path tempDir) throws Exc assertTrue(content.contains("\"log\""), content); assertTrue(content.contains("/one-style.html"), content); } + + @Test + void shouldRecoverTracingAfterAFailedStop(@TempDir Path tempDir) throws Exception { + // https://github.com/microsoft/playwright/issues/42423 + context.tracing().start(); + // Saving fails: a parent of the destination is a file, not a directory. + Path blocker = tempDir.resolve("blocker"); + Files.write(blocker, new byte[0]); + assertThrows(PlaywrightException.class, () -> context.tracing().stop( + new Tracing.StopOptions().setPath(blocker.resolve("trace1.zip")))); + + // The failed stop must not wedge tracing for the rest of the context lifetime. + context.tracing().start(); + page.navigate(server.PREFIX + "/input/button.html"); + page.click("button"); + Path trace = tempDir.resolve("trace2.zip"); + context.tracing().stop(new Tracing.StopOptions().setPath(trace)); + + List events = traceEvents(Utils.parseZip(trace)); + assertEquals("context-options", events.get(0).get("type").getAsString()); + assertTrue(events.stream().anyMatch(e -> "before".equals(e.get("type").getAsString()) + && "click".equals(e.get("method").getAsString()))); + } + + @Test + void shouldCollectActionScreenshots(@TempDir Path tempDir) throws Exception { + context.tracing().start(new Tracing.StartOptions().setScreenSnapshots(true)); + checkClickArtifacts(tempDir, "screenshot", "screenshots/", ".png", + content -> assertTrue(content.length > 0)); + } + + @Test + void shouldCollectAriaSnapshots(@TempDir Path tempDir) throws Exception { + context.tracing().start(new Tracing.StartOptions().setAriaSnapshots(true)); + checkClickArtifacts(tempDir, "aria-snapshot", "aria/", ".json", + content -> assertTrue(new String(content, StandardCharsets.UTF_8).contains("Click target"))); + } + + // Clicks a button while tracing and checks that before/action/after artifacts of the given type were recorded. + private void checkClickArtifacts(Path tempDir, String eventType, String dir, String extension, Consumer checkContent) throws Exception { + page.navigate(server.PREFIX + "/input/button.html"); + page.click("button"); + Path trace = tempDir.resolve("trace.zip"); + context.tracing().stop(new Tracing.StopOptions().setPath(trace)); + + Map resources = Utils.parseZip(trace); + List events = traceEvents(resources); + String clickCallId = findCallId(events, "click"); + List artifacts = events.stream().filter(e -> eventType.equals(e.get("type").getAsString()) + && clickCallId.equals(e.get("callId").getAsString())).collect(Collectors.toList()); + assertEquals(asList("before", "action", "after"), + artifacts.stream().map(e -> e.get("phase").getAsString()).collect(Collectors.toList())); + for (JsonObject artifact : artifacts) { + String file = artifact.get("file").getAsString(); + assertEquals(dir + clickCallId + "-" + artifact.get("phase").getAsString() + extension, file); + assertTrue(resources.containsKey(file), file); + checkContent.accept(resources.get(file)); + } + } + + private static List traceEvents(Map resources) { + List events = new ArrayList<>(); + for (Map.Entry entry : resources.entrySet()) { + if (!entry.getKey().endsWith(".trace")) { + continue; + } + for (String line : new String(entry.getValue(), StandardCharsets.UTF_8).split("\n")) { + if (!line.trim().isEmpty()) { + events.add(JsonParser.parseString(line).getAsJsonObject()); + } + } + } + return events; + } + + private static String findCallId(List events, String method) { + return events.stream().filter(e -> "before".equals(e.get("type").getAsString()) + && method.equals(e.get("method").getAsString())).findFirst().get().get("callId").getAsString(); + } } diff --git a/scripts/DRIVER_VERSION b/scripts/DRIVER_VERSION index b77a81dcb..1e6b0f21d 100644 --- a/scripts/DRIVER_VERSION +++ b/scripts/DRIVER_VERSION @@ -1 +1 @@ -1.62.1 +1.63.0-alpha-1788460676000 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 a41df3f87..e4847362f 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 @@ -406,6 +406,29 @@ int unionSize() { return supportedUnionTypes().size(); } + // True for Object|Array unions where both refer to the same custom class. + boolean isCustomClassOrListUnion() { + if (customType == null || !isTypeUnion()) { + return false; + } + List types = supportedUnionTypes(); + if (types.size() != 2) { + return false; + } + boolean hasObject = false; + boolean hasList = false; + for (JsonObject o : types) { + String name = o.get("name").getAsString(); + if ("Object".equals(name)) { + hasObject = true; + } else if ("Array".equals(name) && o.has("templates") && o.getAsJsonArray("templates").size() == 1 + && "Object".equals(o.getAsJsonArray("templates").get(0).getAsJsonObject().get("name").getAsString())) { + hasList = true; + } + } + return hasObject && hasList; + } + String formatTypeFromUnion(int i) { JsonElement overloadedType = supportedUnionTypes().get(i); return convertBuiltinType(overloadedType.getAsJsonObject()); @@ -898,32 +921,19 @@ void writeTo(List output, String offset) { } void writeBuilderMethod(List output, String offset, String parentClass) { - if (type.customType == null && type.isTypeUnion()) { + if (type.isTypeUnion() && (type.customType == null || type.isCustomClassOrListUnion())) { + // Union of a custom class and its list, e.g. Object|Array for httpCredentials, + // gets the convenience setter with the required fields in addition to the overloads. + if (type.customType != null) { + writeRequiredFieldsBuilderMethod(output, offset, parentClass); + } for (int i = 0; i < type.unionSize(); i++) { writeGenericBuilderMethod(output, offset, parentClass, type.formatTypeFromUnion(i)); } return; } if (type.isCustomClass()) { - TypeDefinition customType = topLevelTypes().get(type.customType); - if (customType instanceof CustomClass) { - CustomClass clazz = (CustomClass) customType; - List params = new ArrayList<>(); - List args = new ArrayList<>(); - for (Field f : clazz.fields) { - if (!f.isRequired()) { - continue; - } - params.add(f.type.toJava() + " " + f.name); - args.add(f.name); - } - if (!params.isEmpty()) { - writeJavadoc(output, offset, comment()); - output.add(offset + "public " + parentClass + " set" + toTitle(name) + "(" + String.join(", ", params) + ") {"); - output.add(offset + " return set" + toTitle(name) + "(new " + type.toJava() + "(" + String.join(", ", args) + "));"); - output.add(offset + "}"); - } - } + writeRequiredFieldsBuilderMethod(output, offset, parentClass); } if (isBrowserChannelOption()) { @@ -934,6 +944,31 @@ void writeBuilderMethod(List output, String offset, String parentClass) writeGenericBuilderMethod(output, offset, parentClass, type.toJava()); } + // Convenience setter taking the required fields of the custom class, e.g. setHttpCredentials(username, password). + private void writeRequiredFieldsBuilderMethod(List output, String offset, String parentClass) { + TypeDefinition customType = topLevelTypes().get(type.customType); + if (!(customType instanceof CustomClass)) { + return; + } + CustomClass clazz = (CustomClass) customType; + List params = new ArrayList<>(); + List args = new ArrayList<>(); + for (Field f : clazz.fields) { + if (!f.isRequired()) { + continue; + } + params.add(f.type.toJava() + " " + f.name); + args.add(f.name); + } + if (params.isEmpty()) { + return; + } + writeJavadoc(output, offset, comment()); + output.add(offset + "public " + parentClass + " set" + toTitle(name) + "(" + String.join(", ", params) + ") {"); + output.add(offset + " return set" + toTitle(name) + "(new " + type.customType + "(" + String.join(", ", args) + "));"); + output.add(offset + "}"); + } + private void writeGenericBuilderMethod(List output, String offset, String parentClass, String paramType) { writeJavadoc(output, offset, comment()); output.add(offset + "public " + parentClass + " set" + toTitle(name) + "(" + paramType + " " + name + ") {"); From 11152a2dc811254f744bbb0b86c1ee4df2008fa4 Mon Sep 17 00:00:00 2001 From: Dan Fiedler <151573964+danfiedler-msft@users.noreply.github.com> Date: Fri, 4 Sep 2026 15:57:26 -0400 Subject: [PATCH 357/420] Pin GitHub Actions to full-length commit SHAs (#1964) --- .github/dependabot.yml | 2 ++ .github/workflows/publish_docker.yml | 8 ++++---- .github/workflows/test.yml | 12 ++++++------ .github/workflows/test_cli.yml | 4 ++-- .github/workflows/test_docker.yml | 2 +- .github/workflows/verify_api.yml | 2 +- 6 files changed, 16 insertions(+), 14 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index a964f2f3c..cffb917d3 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -25,3 +25,5 @@ updates: actions: patterns: - "*" + cooldown: + default-days: 7 diff --git a/.github/workflows/publish_docker.yml b/.github/workflows/publish_docker.yml index d0a35182b..bf1fd3338 100644 --- a/.github/workflows/publish_docker.yml +++ b/.github/workflows/publish_docker.yml @@ -13,9 +13,9 @@ jobs: environment: Docker if: github.repository == 'microsoft/playwright-java' steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Azure login - uses: azure/login@v3 + uses: azure/login@f5d393ae46f8fde4be8b75f32e3fc50e654ad0ca # v3.0.1 with: client-id: ${{ secrets.AZURE_DOCKER_CLIENT_ID }} tenant-id: ${{ secrets.AZURE_DOCKER_TENANT_ID }} @@ -23,8 +23,8 @@ jobs: - name: Login to ACR via OIDC run: az acr login --name playwright - name: Set up Docker QEMU for arm64 docker builds - uses: docker/setup-qemu-action@v4 + uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0 with: platforms: arm64 - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - run: ./utils/docker/publish_docker.sh stable diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2b6878985..b15c361d0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -28,9 +28,9 @@ jobs: browser: webkit runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Set up JDK 1.8 - uses: actions/setup-java@v5.6.0 + uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 with: distribution: zulu java-version: 8 @@ -73,13 +73,13 @@ jobs: browser-channel: msedge runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install Media Pack if: matrix.os == 'windows-latest' shell: powershell run: Install-WindowsFeature Server-Media-Foundation - name: Set up JDK 1.8 - uses: actions/setup-java@v5.6.0 + uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 with: distribution: zulu java-version: 8 @@ -108,9 +108,9 @@ jobs: browser: [chromium, firefox, webkit] runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Set up JDK 21 - uses: actions/setup-java@v5.6.0 + uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 with: distribution: adopt java-version: 21 diff --git a/.github/workflows/test_cli.yml b/.github/workflows/test_cli.yml index 8d6c0cb11..9f61bdd4c 100644 --- a/.github/workflows/test_cli.yml +++ b/.github/workflows/test_cli.yml @@ -13,9 +13,9 @@ jobs: timeout-minutes: 30 runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Cache Maven packages - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.m2 key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} diff --git a/.github/workflows/test_docker.yml b/.github/workflows/test_docker.yml index 7512941d6..36b07f466 100644 --- a/.github/workflows/test_docker.yml +++ b/.github/workflows/test_docker.yml @@ -34,7 +34,7 @@ jobs: - runs-on: ubuntu-24.04-arm arch: arm64 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Build Docker image run: | bash utils/docker/build.sh --${{ matrix.arch }} ${{ matrix.flavor }} playwright-java:localbuild-${{ matrix.flavor }} diff --git a/.github/workflows/verify_api.yml b/.github/workflows/verify_api.yml index a67da2807..8cedfb20f 100644 --- a/.github/workflows/verify_api.yml +++ b/.github/workflows/verify_api.yml @@ -19,7 +19,7 @@ jobs: timeout-minutes: 30 runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Download drivers run: scripts/download_driver.sh - name: Regenerate APIs From 045d72f59f4f106ddd311b3b8ee60b29087df6ab Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Mon, 14 Sep 2026 09:10:34 -0700 Subject: [PATCH 358/420] feat(api): add JSpecify nullability annotations (#1970) --- playwright/pom.xml | 65 ++ .../com/microsoft/playwright/APIRequest.java | 27 +- .../playwright/APIRequestContext.java | 29 +- .../com/microsoft/playwright/APIResponse.java | 5 +- .../com/microsoft/playwright/Browser.java | 187 ++--- .../microsoft/playwright/BrowserContext.java | 77 +- .../com/microsoft/playwright/BrowserType.java | 175 ++--- .../com/microsoft/playwright/CDPSession.java | 3 +- .../java/com/microsoft/playwright/Clock.java | 5 +- .../microsoft/playwright/ConsoleMessage.java | 5 +- .../com/microsoft/playwright/Credentials.java | 17 +- .../com/microsoft/playwright/Debugger.java | 3 +- .../java/com/microsoft/playwright/Dialog.java | 5 +- .../com/microsoft/playwright/Download.java | 3 +- .../microsoft/playwright/ElementHandle.java | 249 ++++--- .../com/microsoft/playwright/FileChooser.java | 13 +- .../java/com/microsoft/playwright/Frame.java | 467 ++++++------ .../microsoft/playwright/FrameLocator.java | 65 +- .../com/microsoft/playwright/JSHandle.java | 11 +- .../com/microsoft/playwright/Keyboard.java | 9 +- .../com/microsoft/playwright/Locator.java | 443 +++++------ .../java/com/microsoft/playwright/Mouse.java | 31 +- .../java/com/microsoft/playwright/Page.java | 703 +++++++++--------- .../com/microsoft/playwright/Playwright.java | 5 +- .../com/microsoft/playwright/Request.java | 17 +- .../com/microsoft/playwright/Response.java | 9 +- .../java/com/microsoft/playwright/Route.java | 55 +- .../com/microsoft/playwright/Screencast.java | 31 +- .../com/microsoft/playwright/Selectors.java | 7 +- .../com/microsoft/playwright/Tracing.java | 45 +- .../com/microsoft/playwright/WebError.java | 3 +- .../com/microsoft/playwright/WebSocket.java | 13 +- .../microsoft/playwright/WebSocketFrame.java | 5 +- .../microsoft/playwright/WebSocketRoute.java | 7 +- .../com/microsoft/playwright/WebStorage.java | 3 +- .../java/com/microsoft/playwright/Worker.java | 17 +- .../assertions/LocatorAssertions.java | 173 ++--- .../playwright/assertions/PageAssertions.java | 19 +- .../playwright/assertions/package-info.java | 20 + .../playwright/options/ClientCertificate.java | 15 +- .../microsoft/playwright/options/Cookie.java | 18 +- .../playwright/options/DropPayload.java | 5 +- .../playwright/options/Geolocation.java | 4 +- .../playwright/options/HttpCredentials.java | 6 +- .../playwright/options/Location.java | 6 +- .../microsoft/playwright/options/Margin.java | 10 +- .../microsoft/playwright/options/Proxy.java | 8 +- .../playwright/options/SecurityDetails.java | 12 +- .../playwright/options/SelectOption.java | 8 +- .../playwright/options/package-info.java | 20 + .../microsoft/playwright/package-info.java | 20 + .../playwright/TestJSpecifyAnnotations.java | 36 + .../nullability/JSpecifyApiConsumer.java | 42 ++ pom.xml | 8 + .../playwright/tools/ApiGenerator.java | 115 ++- 55 files changed, 1829 insertions(+), 1530 deletions(-) create mode 100644 playwright/src/main/java/com/microsoft/playwright/assertions/package-info.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/options/package-info.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/package-info.java create mode 100644 playwright/src/test/java/com/microsoft/playwright/TestJSpecifyAnnotations.java create mode 100644 playwright/src/test/java/com/microsoft/playwright/nullability/JSpecifyApiConsumer.java diff --git a/playwright/pom.xml b/playwright/pom.xml index 2c927d88c..05c3a6a5b 100644 --- a/playwright/pom.xml +++ b/playwright/pom.xml @@ -65,6 +65,10 @@ com.google.code.gson gson + + org.jspecify + jspecify + org.java-websocket Java-WebSocket @@ -99,4 +103,65 @@ driver-bundle + + + nullaway + + [21,) + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + nullaway-testCompile + test-compile + + testCompile + + + true + + ${project.build.directory}/nullaway-test-classes + + com/microsoft/playwright/nullability/JSpecifyApiConsumer.java + + + -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED + -XDcompilePolicy=simple + --should-stop=ifError=FLOW + -XDaddTypeAnnotationsToSymbol=true + -Xplugin:ErrorProne -XepDisableAllChecks -Xep:NullAway:ERROR -XepOpt:NullAway:OnlyNullMarked=true -XepOpt:NullAway:JSpecifyMode=true + + + + com.google.errorprone + error_prone_core + ${error-prone.version} + + + com.uber.nullaway + nullaway + ${nullaway.version} + + + + + + + + + + diff --git a/playwright/src/main/java/com/microsoft/playwright/APIRequest.java b/playwright/src/main/java/com/microsoft/playwright/APIRequest.java index 0ecd5d225..20bd60abb 100644 --- a/playwright/src/main/java/com/microsoft/playwright/APIRequest.java +++ b/playwright/src/main/java/com/microsoft/playwright/APIRequest.java @@ -16,6 +16,7 @@ package com.microsoft.playwright; +import org.jspecify.annotations.Nullable; import com.microsoft.playwright.options.*; import java.nio.file.Path; import java.util.*; @@ -40,7 +41,7 @@ class NewContextOptions { * {@code http://localhost:3000/bar.html} * */ - public String baseURL; + public @Nullable String baseURL; /** * TLS Client Authentication allows the server to request a client certificate and verify it. * @@ -58,15 +59,15 @@ class NewContextOptions { *

    NOTE: When using WebKit on macOS, accessing {@code localhost} will not pick up client certificates. You can make it work by * replacing {@code localhost} with {@code local.playwright}. */ - public List clientCertificates; + public @Nullable List clientCertificates; /** * An object containing additional HTTP headers to be sent with every request. Defaults to none. */ - public Map extraHTTPHeaders; + public @Nullable Map extraHTTPHeaders; /** * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes. */ - public Boolean failOnStatusCode; + public @Nullable Boolean failOnStatusCode; /** * Credentials for HTTP authentication. If * no origin is specified, the username and password are sent to any servers upon unauthorized responses. @@ -74,21 +75,21 @@ class NewContextOptions { *

    Pass an array to use different credentials for different origins. The first entry that matches the request origin is * used, and entries with no origin match any request. */ - public Object httpCredentials; + public @Nullable Object httpCredentials; /** * Whether to ignore HTTPS errors when sending network requests. Defaults to {@code false}. */ - public Boolean ignoreHTTPSErrors; + public @Nullable Boolean ignoreHTTPSErrors; /** * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is * exceeded. Defaults to {@code 20}. Pass {@code 0} to not follow redirects. This can be overwritten for each request * individually. */ - public Integer maxRedirects; + public @Nullable Integer maxRedirects; /** * Network proxy settings. */ - public Proxy proxy; + public @Nullable Proxy proxy; /** * Populates context with given storage state. This option can be used to initialize context with logged-in information * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()} or {@link @@ -97,22 +98,22 @@ class NewContextOptions { * BrowserContext.storageState()} or {@link com.microsoft.playwright.APIRequestContext#storageState * APIRequestContext.storageState()} methods. */ - public String storageState; + public @Nullable String storageState; /** * Populates context with given storage state. This option can be used to initialize context with logged-in information * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()}. Path to the * file with saved storage state. */ - public Path storageStatePath; + public @Nullable Path storageStatePath; /** * Maximum time in milliseconds to wait for the response. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable * timeout. */ - public Double timeout; + public @Nullable Double timeout; /** * Specific user agent to use in this context. */ - public String userAgent; + public @Nullable String userAgent; /** * Methods like {@link com.microsoft.playwright.APIRequestContext#get APIRequestContext.get()} take the base URL into @@ -277,6 +278,6 @@ default APIRequestContext newContext() { * * @since v1.16 */ - APIRequestContext newContext(NewContextOptions options); + APIRequestContext newContext(@Nullable NewContextOptions options); } diff --git a/playwright/src/main/java/com/microsoft/playwright/APIRequestContext.java b/playwright/src/main/java/com/microsoft/playwright/APIRequestContext.java index 32d8fae6e..1372d5265 100644 --- a/playwright/src/main/java/com/microsoft/playwright/APIRequestContext.java +++ b/playwright/src/main/java/com/microsoft/playwright/APIRequestContext.java @@ -16,6 +16,7 @@ package com.microsoft.playwright; +import org.jspecify.annotations.Nullable; import com.microsoft.playwright.options.*; import java.nio.file.Path; @@ -46,7 +47,7 @@ class DisposeOptions { /** * The reason to be reported to the operations interrupted by the context disposal. */ - public String reason; + public @Nullable String reason; /** * The reason to be reported to the operations interrupted by the context disposal. @@ -60,16 +61,16 @@ class StorageStateOptions { /** * Set to {@code true} to include IndexedDB in the storage state snapshot. */ - public Boolean indexedDB; + public @Nullable Boolean indexedDB; /** * Set to {@code true} to include the origin private file system in the storage state snapshot. */ - public Boolean opfs; + public @Nullable Boolean opfs; /** * The file path to save the storage state to. If {@code path} is a relative path, then it is resolved relative to current * working directory. If no path is provided, storage state is still returned, but won't be saved to the disk. */ - public Path path; + public @Nullable Path path; /** * Set to {@code true} to include IndexedDB in the storage state snapshot. @@ -114,7 +115,7 @@ default APIResponse delete(String url) { * @param params Optional request parameters. * @since v1.16 */ - APIResponse delete(String url, RequestOptions params); + APIResponse delete(String url, @Nullable RequestOptions params); /** * All responses returned by {@link com.microsoft.playwright.APIRequestContext#get APIRequestContext.get()} and similar * methods are stored in the memory, so that you can later call {@link com.microsoft.playwright.APIResponse#body @@ -134,7 +135,7 @@ default void dispose() { * * @since v1.16 */ - void dispose(DisposeOptions options); + void dispose(@Nullable DisposeOptions options); /** * 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. @@ -207,7 +208,7 @@ default APIResponse fetch(String urlOrRequest) { * @param params Optional request parameters. * @since v1.16 */ - APIResponse fetch(String urlOrRequest, RequestOptions params); + APIResponse fetch(String urlOrRequest, @Nullable 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. @@ -280,7 +281,7 @@ default APIResponse fetch(Request urlOrRequest) { * @param params Optional request parameters. * @since v1.16 */ - APIResponse fetch(Request urlOrRequest, RequestOptions params); + APIResponse fetch(Request urlOrRequest, @Nullable RequestOptions params); /** * Sends HTTP(S) GET request and returns its * response. The method will populate request cookies from the context and update context cookies from the response. The @@ -319,7 +320,7 @@ default APIResponse get(String url) { * @param params Optional request parameters. * @since v1.16 */ - APIResponse get(String url, RequestOptions params); + APIResponse get(String url, @Nullable RequestOptions params); /** * Sends HTTP(S) HEAD request and returns its * response. The method will populate request cookies from the context and update context cookies from the response. The @@ -340,7 +341,7 @@ default APIResponse head(String url) { * @param params Optional request parameters. * @since v1.16 */ - APIResponse head(String url, RequestOptions params); + APIResponse head(String url, @Nullable RequestOptions params); /** * Sends HTTP(S) PATCH request and returns * its response. The method will populate request cookies from the context and update context cookies from the response. @@ -361,7 +362,7 @@ default APIResponse patch(String url) { * @param params Optional request parameters. * @since v1.16 */ - APIResponse patch(String url, RequestOptions params); + APIResponse patch(String url, @Nullable RequestOptions params); /** * Sends HTTP(S) POST request and returns its * response. The method will populate request cookies from the context and update context cookies from the response. The @@ -456,7 +457,7 @@ default APIResponse post(String url) { * @param params Optional request parameters. * @since v1.16 */ - APIResponse post(String url, RequestOptions params); + APIResponse post(String url, @Nullable RequestOptions params); /** * Sends HTTP(S) PUT request and returns its * response. The method will populate request cookies from the context and update context cookies from the response. The @@ -477,7 +478,7 @@ default APIResponse put(String url) { * @param params Optional request parameters. * @since v1.16 */ - APIResponse put(String url, RequestOptions params); + APIResponse put(String url, @Nullable RequestOptions params); /** * Returns storage state for this request context, contains current cookies and local storage snapshot if it was passed to * the constructor. @@ -493,7 +494,7 @@ default String storageState() { * * @since v1.16 */ - String storageState(StorageStateOptions options); + String storageState(@Nullable StorageStateOptions options); /** * Tracing recorder for requests made through this API request context. * diff --git a/playwright/src/main/java/com/microsoft/playwright/APIResponse.java b/playwright/src/main/java/com/microsoft/playwright/APIResponse.java index c52f1d31e..e72069b6a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/APIResponse.java +++ b/playwright/src/main/java/com/microsoft/playwright/APIResponse.java @@ -16,6 +16,7 @@ package com.microsoft.playwright; +import org.jspecify.annotations.Nullable; import com.microsoft.playwright.options.*; import java.util.*; @@ -61,14 +62,14 @@ public interface APIResponse { * * @since v1.61 */ - SecurityDetails securityDetails(); + @Nullable SecurityDetails securityDetails(); /** * Returns the IP address and port of the server. Resolves to {@code null} if the server address is not available. For * redirected requests, returns the information for the last request in the redirect chain. * * @since v1.61 */ - ServerAddr serverAddr(); + @Nullable ServerAddr serverAddr(); /** * Contains the status code of the response (e.g., 200 for a success). * diff --git a/playwright/src/main/java/com/microsoft/playwright/Browser.java b/playwright/src/main/java/com/microsoft/playwright/Browser.java index 06bd96f8a..6c7f1178a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/Browser.java +++ b/playwright/src/main/java/com/microsoft/playwright/Browser.java @@ -16,6 +16,7 @@ package com.microsoft.playwright; +import org.jspecify.annotations.Nullable; import com.microsoft.playwright.options.*; import java.nio.file.Path; import java.util.*; @@ -69,7 +70,7 @@ class CloseOptions { /** * The reason to be reported to the operations interrupted by the browser closure. */ - public String reason; + public @Nullable String reason; /** * The reason to be reported to the operations interrupted by the browser closure. @@ -83,7 +84,7 @@ class NewContextOptions { /** * Whether to automatically download all the attachments. Defaults to {@code true} where all the downloads are accepted. */ - public Boolean acceptDownloads; + public @Nullable Boolean acceptDownloads; /** * When using {@link com.microsoft.playwright.Page#navigate Page.navigate()}, {@link com.microsoft.playwright.Page#route * Page.route()}, {@link com.microsoft.playwright.Page#waitForURL Page.waitForURL()}, {@link @@ -100,11 +101,11 @@ class NewContextOptions { * {@code http://localhost:3000/bar.html} * */ - public String baseURL; + public @Nullable String baseURL; /** * Toggles bypassing page's Content-Security-Policy. Defaults to {@code false}. */ - public Boolean bypassCSP; + public @Nullable Boolean bypassCSP; /** * TLS Client Authentication allows the server to request a client certificate and verify it. * @@ -122,7 +123,7 @@ class NewContextOptions { *

    NOTE: When using WebKit on macOS, accessing {@code localhost} will not pick up client certificates. You can make it work by * replacing {@code localhost} with {@code local.playwright}. */ - public List clientCertificates; + public @Nullable List clientCertificates; /** * Emulates prefers-colors-scheme media @@ -130,34 +131,34 @@ class NewContextOptions { * Page.emulateMedia()} for more details. Passing {@code null} resets emulation to system defaults. Defaults to {@code * "light"}. */ - public Optional colorScheme; + public @Nullable Optional colorScheme; /** * Emulates {@code "prefers-contrast"} media feature, supported values are {@code "no-preference"}, {@code "more"}. See * {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets * emulation to system defaults. Defaults to {@code "no-preference"}. */ - public Optional contrast; + public @Nullable Optional contrast; /** * Specify device scale factor (can be thought of as dpr). Defaults to {@code 1}. Learn more about emulating devices with device scale factor. */ - public Double deviceScaleFactor; + public @Nullable Double deviceScaleFactor; /** * An object containing additional HTTP headers to be sent with every request. Defaults to none. */ - public Map extraHTTPHeaders; + public @Nullable Map extraHTTPHeaders; /** * Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link * com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets emulation * to system defaults. Defaults to {@code "none"}. */ - public Optional forcedColors; - public Geolocation geolocation; + public @Nullable Optional forcedColors; + public @Nullable Geolocation geolocation; /** * Specifies if viewport supports touch events. Defaults to false. Learn more about mobile emulation. */ - public Boolean hasTouch; + public @Nullable Boolean hasTouch; /** * Credentials for HTTP authentication. If * no origin is specified, the username and password are sent to any servers upon unauthorized responses. @@ -165,89 +166,89 @@ class NewContextOptions { *

    Pass an array to use different credentials for different origins. The first entry that matches the request origin is * used, and entries with no origin match any request. */ - public Object httpCredentials; + public @Nullable Object httpCredentials; /** * Whether to ignore HTTPS errors when sending network requests. Defaults to {@code false}. */ - public Boolean ignoreHTTPSErrors; + public @Nullable Boolean ignoreHTTPSErrors; /** * Whether the {@code meta viewport} tag is taken into account and touch events are enabled. isMobile is a part of device, * so you don't actually need to set it manually. Defaults to {@code false} and is not supported in Firefox. Learn more * about mobile emulation. */ - public Boolean isMobile; + public @Nullable Boolean isMobile; /** * Whether or not to enable JavaScript in the context. Defaults to {@code true}. Learn more about disabling JavaScript. */ - public Boolean javaScriptEnabled; + public @Nullable Boolean javaScriptEnabled; /** * Specify user locale, for example {@code en-GB}, {@code de-DE}, etc. Locale will affect {@code navigator.language} value, * {@code Accept-Language} request header value as well as number and date formatting rules. Defaults to the system default * locale. Learn more about emulation in our emulation guide. */ - public String locale; + public @Nullable String locale; /** * Whether to emulate network being offline. Defaults to {@code false}. Learn more about network emulation. */ - public Boolean offline; + public @Nullable Boolean offline; /** * A list of permissions to grant to all pages in this context. See {@link * com.microsoft.playwright.BrowserContext#grantPermissions BrowserContext.grantPermissions()} for more details. Defaults * to none. */ - public List permissions; + public @Nullable List permissions; /** * Network proxy settings to use with this context. Defaults to none. */ - public Proxy proxy; + public @Nullable Proxy proxy; /** * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If * {@code attach} is specified, resources are persisted as separate files and all of these files are archived along with * the HAR file. Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification. */ - public HarContentPolicy recordHarContent; + public @Nullable HarContentPolicy recordHarContent; /** * When set to {@code minimal}, only record information necessary for routing from HAR. This omits sizes, timing, page, * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to {@code * full}. */ - public HarMode recordHarMode; + public @Nullable HarMode recordHarMode; /** * Optional setting to control whether to omit request content from the HAR. Defaults to {@code false}. */ - public Boolean recordHarOmitContent; + public @Nullable Boolean recordHarOmitContent; /** * Enables HAR recording for all pages into the specified HAR * file on the filesystem. If not specified, the HAR is not recorded. Make sure to call {@link * com.microsoft.playwright.BrowserContext#close BrowserContext.close()} for the HAR to be saved. */ - public Path recordHarPath; - public Object recordHarUrlFilter; + public @Nullable Path recordHarPath; + public @Nullable Object recordHarUrlFilter; /** * Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make sure * to call {@link com.microsoft.playwright.BrowserContext#close BrowserContext.close()} for videos to be saved. */ - public Path recordVideoDir; + public @Nullable Path recordVideoDir; /** * Dimensions of the recorded videos. If not specified the size will be equal to {@code viewport} scaled down to fit into * 800x800. If {@code viewport} is not configured explicitly the video size defaults to 800x450. Actual picture of each * page will be scaled down if necessary to fit the specified size. */ - public RecordVideoSize recordVideoSize; + public @Nullable RecordVideoSize recordVideoSize; /** * Emulates {@code "prefers-reduced-motion"} media feature, supported values are {@code "reduce"}, {@code "no-preference"}. * See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets * emulation to system defaults. Defaults to {@code "no-preference"}. */ - public Optional reducedMotion; + public @Nullable Optional reducedMotion; /** * Emulates consistent window screen size available inside web page via {@code window.screen}. Is only used when the {@code * viewport} is set. */ - public ScreenSize screenSize; + public @Nullable ScreenSize screenSize; /** * Whether to allow sites to register Service workers. Defaults to {@code "allow"}. *

      @@ -256,35 +257,35 @@ class NewContextOptions { *
    • {@code "block"}: Playwright will block all registration of Service Workers.
    • *
    */ - public ServiceWorkerPolicy serviceWorkers; + public @Nullable ServiceWorkerPolicy serviceWorkers; /** * Populates context with given storage state. This option can be used to initialize context with logged-in information * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()}. */ - public String storageState; + public @Nullable String storageState; /** * Populates context with given storage state. This option can be used to initialize context with logged-in information * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()}. Path to the * file with saved storage state. */ - public Path storageStatePath; + public @Nullable Path storageStatePath; /** * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors * that imply single target DOM element will throw when more than one element matches the selector. This option does not * affect any Locator APIs (Locators are always strict). Defaults to {@code false}. See {@code Locator} to learn more about * the strict mode. */ - public Boolean strictSelectors; + public @Nullable Boolean strictSelectors; /** * Changes the timezone of the context. See ICU's * metaZones.txt for a list of supported timezone IDs. Defaults to the system timezone. */ - public String timezoneId; + public @Nullable String timezoneId; /** * Specific user agent to use in this context. */ - public String userAgent; + public @Nullable String userAgent; /** * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use {@code null} to disable the consistent * viewport emulation. Learn more about viewport @@ -293,7 +294,7 @@ class NewContextOptions { *

    NOTE: The {@code null} value opts out from the default presets, makes viewport depend on the host window size defined by the * operating system. It makes the execution of the tests non-deterministic. */ - public Optional viewportSize; + public @Nullable Optional viewportSize; /** * Whether to automatically download all the attachments. Defaults to {@code true} where all the downloads are accepted. @@ -357,7 +358,7 @@ public NewContextOptions setClientCertificates(List clientCer * Page.emulateMedia()} for more details. Passing {@code null} resets emulation to system defaults. Defaults to {@code * "light"}. */ - public NewContextOptions setColorScheme(ColorScheme colorScheme) { + public NewContextOptions setColorScheme(@Nullable ColorScheme colorScheme) { this.colorScheme = Optional.ofNullable(colorScheme); return this; } @@ -366,7 +367,7 @@ public NewContextOptions setColorScheme(ColorScheme colorScheme) { * {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets * emulation to system defaults. Defaults to {@code "no-preference"}. */ - public NewContextOptions setContrast(Contrast contrast) { + public NewContextOptions setContrast(@Nullable Contrast contrast) { this.contrast = Optional.ofNullable(contrast); return this; } @@ -390,7 +391,7 @@ public NewContextOptions setExtraHTTPHeaders(Map extraHTTPHeader * com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets emulation * to system defaults. Defaults to {@code "none"}. */ - public NewContextOptions setForcedColors(ForcedColors forcedColors) { + public NewContextOptions setForcedColors(@Nullable ForcedColors forcedColors) { this.forcedColors = Optional.ofNullable(forcedColors); return this; } @@ -577,7 +578,7 @@ public NewContextOptions setRecordVideoSize(RecordVideoSize recordVideoSize) { * See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets * emulation to system defaults. Defaults to {@code "no-preference"}. */ - public NewContextOptions setReducedMotion(ReducedMotion reducedMotion) { + public NewContextOptions setReducedMotion(@Nullable ReducedMotion reducedMotion) { this.reducedMotion = Optional.ofNullable(reducedMotion); return this; } @@ -670,7 +671,7 @@ public NewContextOptions setViewportSize(int width, int height) { *

    NOTE: The {@code null} value opts out from the default presets, makes viewport depend on the host window size defined by the * operating system. It makes the execution of the tests non-deterministic. */ - public NewContextOptions setViewportSize(ViewportSize viewportSize) { + public NewContextOptions setViewportSize(@Nullable ViewportSize viewportSize) { this.viewportSize = Optional.ofNullable(viewportSize); return this; } @@ -679,7 +680,7 @@ class NewPageOptions { /** * Whether to automatically download all the attachments. Defaults to {@code true} where all the downloads are accepted. */ - public Boolean acceptDownloads; + public @Nullable Boolean acceptDownloads; /** * When using {@link com.microsoft.playwright.Page#navigate Page.navigate()}, {@link com.microsoft.playwright.Page#route * Page.route()}, {@link com.microsoft.playwright.Page#waitForURL Page.waitForURL()}, {@link @@ -696,11 +697,11 @@ class NewPageOptions { * {@code http://localhost:3000/bar.html} * */ - public String baseURL; + public @Nullable String baseURL; /** * Toggles bypassing page's Content-Security-Policy. Defaults to {@code false}. */ - public Boolean bypassCSP; + public @Nullable Boolean bypassCSP; /** * TLS Client Authentication allows the server to request a client certificate and verify it. * @@ -718,7 +719,7 @@ class NewPageOptions { *

    NOTE: When using WebKit on macOS, accessing {@code localhost} will not pick up client certificates. You can make it work by * replacing {@code localhost} with {@code local.playwright}. */ - public List clientCertificates; + public @Nullable List clientCertificates; /** * Emulates prefers-colors-scheme media @@ -726,34 +727,34 @@ class NewPageOptions { * Page.emulateMedia()} for more details. Passing {@code null} resets emulation to system defaults. Defaults to {@code * "light"}. */ - public Optional colorScheme; + public @Nullable Optional colorScheme; /** * Emulates {@code "prefers-contrast"} media feature, supported values are {@code "no-preference"}, {@code "more"}. See * {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets * emulation to system defaults. Defaults to {@code "no-preference"}. */ - public Optional contrast; + public @Nullable Optional contrast; /** * Specify device scale factor (can be thought of as dpr). Defaults to {@code 1}. Learn more about emulating devices with device scale factor. */ - public Double deviceScaleFactor; + public @Nullable Double deviceScaleFactor; /** * An object containing additional HTTP headers to be sent with every request. Defaults to none. */ - public Map extraHTTPHeaders; + public @Nullable Map extraHTTPHeaders; /** * Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link * com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets emulation * to system defaults. Defaults to {@code "none"}. */ - public Optional forcedColors; - public Geolocation geolocation; + public @Nullable Optional forcedColors; + public @Nullable Geolocation geolocation; /** * Specifies if viewport supports touch events. Defaults to false. Learn more about mobile emulation. */ - public Boolean hasTouch; + public @Nullable Boolean hasTouch; /** * Credentials for HTTP authentication. If * no origin is specified, the username and password are sent to any servers upon unauthorized responses. @@ -761,89 +762,89 @@ class NewPageOptions { *

    Pass an array to use different credentials for different origins. The first entry that matches the request origin is * used, and entries with no origin match any request. */ - public Object httpCredentials; + public @Nullable Object httpCredentials; /** * Whether to ignore HTTPS errors when sending network requests. Defaults to {@code false}. */ - public Boolean ignoreHTTPSErrors; + public @Nullable Boolean ignoreHTTPSErrors; /** * Whether the {@code meta viewport} tag is taken into account and touch events are enabled. isMobile is a part of device, * so you don't actually need to set it manually. Defaults to {@code false} and is not supported in Firefox. Learn more * about mobile emulation. */ - public Boolean isMobile; + public @Nullable Boolean isMobile; /** * Whether or not to enable JavaScript in the context. Defaults to {@code true}. Learn more about disabling JavaScript. */ - public Boolean javaScriptEnabled; + public @Nullable Boolean javaScriptEnabled; /** * Specify user locale, for example {@code en-GB}, {@code de-DE}, etc. Locale will affect {@code navigator.language} value, * {@code Accept-Language} request header value as well as number and date formatting rules. Defaults to the system default * locale. Learn more about emulation in our emulation guide. */ - public String locale; + public @Nullable String locale; /** * Whether to emulate network being offline. Defaults to {@code false}. Learn more about network emulation. */ - public Boolean offline; + public @Nullable Boolean offline; /** * A list of permissions to grant to all pages in this context. See {@link * com.microsoft.playwright.BrowserContext#grantPermissions BrowserContext.grantPermissions()} for more details. Defaults * to none. */ - public List permissions; + public @Nullable List permissions; /** * Network proxy settings to use with this context. Defaults to none. */ - public Proxy proxy; + public @Nullable Proxy proxy; /** * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If * {@code attach} is specified, resources are persisted as separate files and all of these files are archived along with * the HAR file. Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification. */ - public HarContentPolicy recordHarContent; + public @Nullable HarContentPolicy recordHarContent; /** * When set to {@code minimal}, only record information necessary for routing from HAR. This omits sizes, timing, page, * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to {@code * full}. */ - public HarMode recordHarMode; + public @Nullable HarMode recordHarMode; /** * Optional setting to control whether to omit request content from the HAR. Defaults to {@code false}. */ - public Boolean recordHarOmitContent; + public @Nullable Boolean recordHarOmitContent; /** * Enables HAR recording for all pages into the specified HAR * file on the filesystem. If not specified, the HAR is not recorded. Make sure to call {@link * com.microsoft.playwright.BrowserContext#close BrowserContext.close()} for the HAR to be saved. */ - public Path recordHarPath; - public Object recordHarUrlFilter; + public @Nullable Path recordHarPath; + public @Nullable Object recordHarUrlFilter; /** * Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make sure * to call {@link com.microsoft.playwright.BrowserContext#close BrowserContext.close()} for videos to be saved. */ - public Path recordVideoDir; + public @Nullable Path recordVideoDir; /** * Dimensions of the recorded videos. If not specified the size will be equal to {@code viewport} scaled down to fit into * 800x800. If {@code viewport} is not configured explicitly the video size defaults to 800x450. Actual picture of each * page will be scaled down if necessary to fit the specified size. */ - public RecordVideoSize recordVideoSize; + public @Nullable RecordVideoSize recordVideoSize; /** * Emulates {@code "prefers-reduced-motion"} media feature, supported values are {@code "reduce"}, {@code "no-preference"}. * See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets * emulation to system defaults. Defaults to {@code "no-preference"}. */ - public Optional reducedMotion; + public @Nullable Optional reducedMotion; /** * Emulates consistent window screen size available inside web page via {@code window.screen}. Is only used when the {@code * viewport} is set. */ - public ScreenSize screenSize; + public @Nullable ScreenSize screenSize; /** * Whether to allow sites to register Service workers. Defaults to {@code "allow"}. *

      @@ -852,35 +853,35 @@ class NewPageOptions { *
    • {@code "block"}: Playwright will block all registration of Service Workers.
    • *
    */ - public ServiceWorkerPolicy serviceWorkers; + public @Nullable ServiceWorkerPolicy serviceWorkers; /** * Populates context with given storage state. This option can be used to initialize context with logged-in information * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()}. */ - public String storageState; + public @Nullable String storageState; /** * Populates context with given storage state. This option can be used to initialize context with logged-in information * obtained via {@link com.microsoft.playwright.BrowserContext#storageState BrowserContext.storageState()}. Path to the * file with saved storage state. */ - public Path storageStatePath; + public @Nullable Path storageStatePath; /** * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors * that imply single target DOM element will throw when more than one element matches the selector. This option does not * affect any Locator APIs (Locators are always strict). Defaults to {@code false}. See {@code Locator} to learn more about * the strict mode. */ - public Boolean strictSelectors; + public @Nullable Boolean strictSelectors; /** * Changes the timezone of the context. See ICU's * metaZones.txt for a list of supported timezone IDs. Defaults to the system timezone. */ - public String timezoneId; + public @Nullable String timezoneId; /** * Specific user agent to use in this context. */ - public String userAgent; + public @Nullable String userAgent; /** * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use {@code null} to disable the consistent * viewport emulation. Learn more about viewport @@ -889,7 +890,7 @@ class NewPageOptions { *

    NOTE: The {@code null} value opts out from the default presets, makes viewport depend on the host window size defined by the * operating system. It makes the execution of the tests non-deterministic. */ - public Optional viewportSize; + public @Nullable Optional viewportSize; /** * Whether to automatically download all the attachments. Defaults to {@code true} where all the downloads are accepted. @@ -953,7 +954,7 @@ public NewPageOptions setClientCertificates(List clientCertif * Page.emulateMedia()} for more details. Passing {@code null} resets emulation to system defaults. Defaults to {@code * "light"}. */ - public NewPageOptions setColorScheme(ColorScheme colorScheme) { + public NewPageOptions setColorScheme(@Nullable ColorScheme colorScheme) { this.colorScheme = Optional.ofNullable(colorScheme); return this; } @@ -962,7 +963,7 @@ public NewPageOptions setColorScheme(ColorScheme colorScheme) { * {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets * emulation to system defaults. Defaults to {@code "no-preference"}. */ - public NewPageOptions setContrast(Contrast contrast) { + public NewPageOptions setContrast(@Nullable Contrast contrast) { this.contrast = Optional.ofNullable(contrast); return this; } @@ -986,7 +987,7 @@ public NewPageOptions setExtraHTTPHeaders(Map extraHTTPHeaders) * com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets emulation * to system defaults. Defaults to {@code "none"}. */ - public NewPageOptions setForcedColors(ForcedColors forcedColors) { + public NewPageOptions setForcedColors(@Nullable ForcedColors forcedColors) { this.forcedColors = Optional.ofNullable(forcedColors); return this; } @@ -1173,7 +1174,7 @@ public NewPageOptions setRecordVideoSize(RecordVideoSize recordVideoSize) { * See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets * emulation to system defaults. Defaults to {@code "no-preference"}. */ - public NewPageOptions setReducedMotion(ReducedMotion reducedMotion) { + public NewPageOptions setReducedMotion(@Nullable ReducedMotion reducedMotion) { this.reducedMotion = Optional.ofNullable(reducedMotion); return this; } @@ -1266,7 +1267,7 @@ public NewPageOptions setViewportSize(int width, int height) { *

    NOTE: The {@code null} value opts out from the default presets, makes viewport depend on the host window size defined by the * operating system. It makes the execution of the tests non-deterministic. */ - public NewPageOptions setViewportSize(ViewportSize viewportSize) { + public NewPageOptions setViewportSize(@Nullable ViewportSize viewportSize) { this.viewportSize = Optional.ofNullable(viewportSize); return this; } @@ -1275,16 +1276,16 @@ class BindOptions { /** * Host to bind the web socket server to. When specified, a web socket server is created instead of a named pipe. */ - public String host; + public @Nullable String host; /** * Port to bind the web socket server to. When specified, a web socket server is created instead of a named pipe. Use * {@code 0} to let the OS pick an available port. */ - public Integer port; + public @Nullable Integer port; /** * Working directory associated with this browser server. */ - public String workspaceDir; + public @Nullable String workspaceDir; /** * Host to bind the web socket server to. When specified, a web socket server is created instead of a named pipe. @@ -1313,15 +1314,15 @@ class StartTracingOptions { /** * specify custom categories to use instead of default. */ - public List categories; + public @Nullable List categories; /** * A path to write the trace file to. */ - public Path path; + public @Nullable Path path; /** * captures screenshots in the trace. */ - public Boolean screenshots; + public @Nullable Boolean screenshots; /** * specify custom categories to use instead of default. @@ -1386,7 +1387,7 @@ default void close() { * * @since v1.8 */ - void close(CloseOptions options); + void close(@Nullable CloseOptions options); /** * Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts. * @@ -1466,7 +1467,7 @@ default BrowserContext newContext() { * * @since v1.8 */ - BrowserContext newContext(NewContextOptions options); + BrowserContext newContext(@Nullable NewContextOptions options); /** * Creates a new page in a new browser context. Closing this page will close the context as well. * @@ -1490,7 +1491,7 @@ default Page newPage() { * * @since v1.8 */ - Page newPage(NewPageOptions options); + Page newPage(@Nullable NewPageOptions options); /** * Binds the browser to a named pipe or web socket, making it available for other clients to connect to. * @@ -1506,7 +1507,7 @@ default BindResult bind(String title) { * @param title Title of the browser server, used for identification. * @since v1.59 */ - BindResult bind(String title, BindOptions options); + BindResult bind(String title, @Nullable BindOptions options); /** * NOTE: This API controls Chromium Tracing * which is a low-level chromium-specific debugging tool. API to control NOTE: This API controls Chromium Tracing * which is a low-level chromium-specific debugging tool. API to control Defaults to abort. */ - public HarNotFound notFound; + public @Nullable HarNotFound notFound; /** * If specified, updates the given HAR with the actual network information instead of serving from file. The file is * written to disk when {@link com.microsoft.playwright.BrowserContext#close BrowserContext.close()} is called. */ - public Boolean update; + public @Nullable Boolean update; /** * Optional setting to control resource content management. If {@code attach} is specified, resources are persisted as * separate files or entries in the ZIP archive. If {@code embed} is specified, content is stored inline the HAR file. */ - public RouteFromHarUpdateContentPolicy updateContent; + public @Nullable RouteFromHarUpdateContentPolicy updateContent; /** * When set to {@code minimal}, only record information necessary for routing from HAR. This omits sizes, timing, page, * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to {@code * minimal}. */ - public HarMode updateMode; + public @Nullable HarMode updateMode; /** * A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the pattern * will be served from the HAR file. If not specified, all requests are served from the HAR file. */ - public Object url; + public @Nullable Object url; /** *

    * @since v1.8 */ - void grantPermissions(List permissions, GrantPermissionsOptions options); + void grantPermissions(List permissions, @Nullable GrantPermissionsOptions options); /** * Indicates that the browser context is in the process of closing or has already been closed. * @@ -1126,7 +1127,7 @@ default AutoCloseable route(String url, Consumer handler) { * @param handler handler function to route the request. * @since v1.8 */ - AutoCloseable route(String url, Consumer handler, RouteOptions options); + AutoCloseable route(String url, Consumer handler, @Nullable RouteOptions options); /** * Routing provides the capability to modify network requests that are made by any page in the browser context. Once route * is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted. @@ -1236,7 +1237,7 @@ default AutoCloseable route(Pattern url, Consumer handler) { * @param handler handler function to route the request. * @since v1.8 */ - AutoCloseable route(Pattern url, Consumer handler, RouteOptions options); + AutoCloseable route(Pattern url, Consumer handler, @Nullable RouteOptions options); /** * Routing provides the capability to modify network requests that are made by any page in the browser context. Once route * is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted. @@ -1346,7 +1347,7 @@ default AutoCloseable route(Predicate url, Consumer handler) { * @param handler handler function to route the request. * @since v1.8 */ - AutoCloseable route(Predicate url, Consumer handler, RouteOptions options); + AutoCloseable route(Predicate url, Consumer handler, @Nullable RouteOptions options); /** * If specified the network requests that are made in the context will be served from the HAR file. Read more about Replaying from HAR. @@ -1374,7 +1375,7 @@ default void routeFromHAR(Path har) { * path} is a relative path, then it is resolved relative to the current working directory. * @since v1.23 */ - void routeFromHAR(Path har, RouteFromHAROptions options); + void routeFromHAR(Path har, @Nullable RouteFromHAROptions options); /** * This method allows to modify websocket connections that are made by any page in the browser context. * @@ -1513,7 +1514,7 @@ default void routeFromHAR(Path har) { * * @since v1.8 */ - void setGeolocation(Geolocation geolocation); + void setGeolocation(@Nullable Geolocation geolocation); /** * * @@ -1536,7 +1537,7 @@ default String storageState() { * * @since v1.8 */ - String storageState(StorageStateOptions options); + String storageState(@Nullable StorageStateOptions options); /** * Clears the existing cookies, local storage, IndexedDB entries, origin private file system entries and virtual WebAuthn * credentials, and sets the new storage state. When the storage state contains credentials, the virtual WebAuthn @@ -1589,7 +1590,7 @@ default void unroute(String url) { * BrowserContext.route()}. * @since v1.8 */ - void unroute(String url, Consumer handler); + void unroute(String url, @Nullable Consumer handler); /** * Removes a route created with {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()}. When {@code * handler} is not specified, removes all routes for the {@code url}. @@ -1611,7 +1612,7 @@ default void unroute(Pattern url) { * BrowserContext.route()}. * @since v1.8 */ - void unroute(Pattern url, Consumer handler); + void unroute(Pattern url, @Nullable Consumer handler); /** * Removes a route created with {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()}. When {@code * handler} is not specified, removes all routes for the {@code url}. @@ -1633,7 +1634,7 @@ default void unroute(Predicate url) { * BrowserContext.route()}. * @since v1.8 */ - void unroute(Predicate url, Consumer handler); + void unroute(Predicate url, @Nullable Consumer handler); /** * The method will block until the condition returns true. All Playwright events will be dispatched while the method is * waiting for the condition. @@ -1681,7 +1682,7 @@ default void waitForCondition(BooleanSupplier condition) { * @param condition Condition to wait for. * @since v1.32 */ - void waitForCondition(BooleanSupplier condition, WaitForConditionOptions options); + void waitForCondition(BooleanSupplier condition, @Nullable WaitForConditionOptions options); /** * Performs action and waits for a {@code ConsoleMessage} to be logged by in the pages in the context. If predicate is * provided, it passes {@code ConsoleMessage} value into the {@code predicate} function and waits for {@code @@ -1703,7 +1704,7 @@ default ConsoleMessage waitForConsoleMessage(Runnable callback) { * @param callback Callback that performs the action triggering the event. * @since v1.34 */ - ConsoleMessage waitForConsoleMessage(WaitForConsoleMessageOptions options, Runnable callback); + ConsoleMessage waitForConsoleMessage(@Nullable WaitForConsoleMessageOptions options, Runnable callback); /** * Performs action and waits for a new {@code Page} to be created in the context. If predicate is provided, it passes * {@code Page} value into the {@code predicate} function and waits for {@code predicate(event)} to return a truthy value. @@ -1723,6 +1724,6 @@ default Page waitForPage(Runnable callback) { * @param callback Callback that performs the action triggering the event. * @since v1.9 */ - Page waitForPage(WaitForPageOptions options, Runnable callback); + Page waitForPage(@Nullable WaitForPageOptions options, Runnable callback); } diff --git a/playwright/src/main/java/com/microsoft/playwright/BrowserType.java b/playwright/src/main/java/com/microsoft/playwright/BrowserType.java index d550f098b..5c38b2814 100644 --- a/playwright/src/main/java/com/microsoft/playwright/BrowserType.java +++ b/playwright/src/main/java/com/microsoft/playwright/BrowserType.java @@ -16,6 +16,7 @@ package com.microsoft.playwright; +import org.jspecify.annotations.Nullable; import com.microsoft.playwright.options.*; import java.nio.file.Path; import java.util.*; @@ -62,20 +63,20 @@ class ConnectOptions { *
  2. {@code "*.test.internal-domain,*.staging.internal-domain,"} to expose test/staging deployments and localhost.
  3. * */ - public String exposeNetwork; + public @Nullable String exposeNetwork; /** * Additional HTTP headers to be sent with web socket connect request. Optional. */ - public Map headers; + public @Nullable Map headers; /** * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. * Defaults to 0. */ - public Double slowMo; + public @Nullable Double slowMo; /** * Maximum time in milliseconds to wait for the connection to be established. Defaults to {@code 0} (no timeout). */ - public Double timeout; + public @Nullable Double timeout; /** * This option exposes network available on the connecting client to the browser being connected to. Consists of a list of @@ -127,16 +128,16 @@ class ConnectOverCDPOptions { /** * If specified, browser artifacts (such as traces and downloads) are saved into this directory. */ - public Path artifactsDir; + public @Nullable Path artifactsDir; /** * Additional HTTP headers to be sent with connect request. Optional. */ - public Map headers; + public @Nullable Map headers; /** * Tells Playwright that it runs on the same host as the CDP server. It will enable certain optimizations that rely upon * the file system being the same between Playwright and the Browser. */ - public Boolean isLocal; + public @Nullable Boolean isLocal; /** * When true, Playwright will not apply its default overrides to the existing default browser context. Specifically, {@code * acceptDownloads} is left at the browser's setting, focus emulation is not enabled, and media emulation options (such as @@ -145,17 +146,17 @@ class ConnectOverCDPOptions { * contexts created via {@link com.microsoft.playwright.Browser#newContext Browser.newContext()} are not affected. Defaults * to {@code false}. */ - public Boolean noDefaults; + public @Nullable Boolean noDefaults; /** * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. * Defaults to 0. */ - public Double slowMo; + public @Nullable Double slowMo; /** * Maximum time in milliseconds to wait for the connection to be established. Defaults to {@code 30000} (30 seconds). Pass * {@code 0} to disable timeout. */ - public Double timeout; + public @Nullable Double timeout; /** * If specified, browser artifacts (such as traces and downloads) are saved into this directory. @@ -215,13 +216,13 @@ class LaunchOptions { *

    Additional arguments to pass to the browser instance. The list of Chromium flags can be found here. */ - public List args; + public @Nullable List args; /** * If specified, artifacts (traces, videos, downloads, HAR files, etc.) are saved into this directory. The directory is not * cleaned up when the browser closes. If not specified, a temporary directory is used and cleaned up when the browser * closes. */ - public Path artifactsDir; + public @Nullable Path artifactsDir; /** * Browser distribution channel. * @@ -232,27 +233,27 @@ class LaunchOptions { * use branded Google Chrome and * Microsoft Edge. */ - public Object channel; + public @Nullable Object channel; /** * Enable Chromium sandboxing. Defaults to {@code false}. */ - public Boolean chromiumSandbox; + public @Nullable Boolean chromiumSandbox; /** * If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is * deleted when browser is closed. In either case, the downloads are deleted when the browser context they were created in * is closed. */ - public Path downloadsPath; + public @Nullable Path downloadsPath; /** * Specify environment variables that will be visible to the browser. Defaults to {@code process.env}. */ - public Map env; + public @Nullable Map env; /** * Path to a browser executable to run instead of the bundled one. If {@code executablePath} is a relative path, then it is * resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium, Firefox * or WebKit, use at your own risk. */ - public Path executablePath; + public @Nullable Path executablePath; /** * Firefox user preferences. Learn more about the Firefox user preferences at {@code about:config}. @@ -260,52 +261,52 @@ class LaunchOptions { *

    You can also provide a path to a custom {@code policies.json} * file via {@code PLAYWRIGHT_FIREFOX_POLICIES_JSON} environment variable. */ - public Map firefoxUserPrefs; + public @Nullable Map firefoxUserPrefs; /** * Close the browser process on SIGHUP. Defaults to {@code true}. */ - public Boolean handleSIGHUP; + public @Nullable Boolean handleSIGHUP; /** * Close the browser process on Ctrl-C. Defaults to {@code true}. */ - public Boolean handleSIGINT; + public @Nullable Boolean handleSIGINT; /** * Close the browser process on SIGTERM. Defaults to {@code true}. */ - public Boolean handleSIGTERM; + public @Nullable Boolean handleSIGTERM; /** * Whether to run browser in headless mode. More details for Chromium and Firefox. Defaults to {@code true}. */ - public Boolean headless; + public @Nullable Boolean headless; /** * If {@code true}, Playwright does not pass its own configurations args and only uses the ones from {@code args}. * Dangerous option; use with care. Defaults to {@code false}. */ - public Boolean ignoreAllDefaultArgs; + public @Nullable Boolean ignoreAllDefaultArgs; /** * If {@code true}, Playwright does not pass its own configurations args and only uses the ones from {@code args}. * Dangerous option; use with care. */ - public List ignoreDefaultArgs; + public @Nullable List ignoreDefaultArgs; /** * Network proxy settings. */ - public Proxy proxy; + public @Nullable Proxy proxy; /** * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. */ - public Double slowMo; + public @Nullable Double slowMo; /** * Maximum time in milliseconds to wait for the browser instance to start. Defaults to {@code 30000} (30 seconds). Pass * {@code 0} to disable timeout. */ - public Double timeout; + public @Nullable Double timeout; /** * If specified, traces are saved into this directory. */ - public Path tracesDir; + public @Nullable Path tracesDir; /** * NOTE: Use custom browser args at your own risk, as some of them may break Playwright functionality. @@ -484,20 +485,20 @@ class LaunchPersistentContextOptions { /** * Whether to automatically download all the attachments. Defaults to {@code true} where all the downloads are accepted. */ - public Boolean acceptDownloads; + public @Nullable Boolean acceptDownloads; /** * NOTE: Use custom browser args at your own risk, as some of them may break Playwright functionality. * *

    Additional arguments to pass to the browser instance. The list of Chromium flags can be found here. */ - public List args; + public @Nullable List args; /** * If specified, artifacts (traces, videos, downloads, HAR files, etc.) are saved into this directory. The directory is not * cleaned up when the browser closes. If not specified, a temporary directory is used and cleaned up when the browser * closes. */ - public Path artifactsDir; + public @Nullable Path artifactsDir; /** * When using {@link com.microsoft.playwright.Page#navigate Page.navigate()}, {@link com.microsoft.playwright.Page#route * Page.route()}, {@link com.microsoft.playwright.Page#waitForURL Page.waitForURL()}, {@link @@ -514,11 +515,11 @@ class LaunchPersistentContextOptions { * {@code http://localhost:3000/bar.html} * */ - public String baseURL; + public @Nullable String baseURL; /** * Toggles bypassing page's Content-Security-Policy. Defaults to {@code false}. */ - public Boolean bypassCSP; + public @Nullable Boolean bypassCSP; /** * Browser distribution channel. * @@ -529,11 +530,11 @@ class LaunchPersistentContextOptions { * use branded Google Chrome and * Microsoft Edge. */ - public Object channel; + public @Nullable Object channel; /** * Enable Chromium sandboxing. Defaults to {@code false}. */ - public Boolean chromiumSandbox; + public @Nullable Boolean chromiumSandbox; /** * TLS Client Authentication allows the server to request a client certificate and verify it. * @@ -551,7 +552,7 @@ class LaunchPersistentContextOptions { *

    NOTE: When using WebKit on macOS, accessing {@code localhost} will not pick up client certificates. You can make it work by * replacing {@code localhost} with {@code local.playwright}. */ - public List clientCertificates; + public @Nullable List clientCertificates; /** * Emulates prefers-colors-scheme media @@ -559,38 +560,38 @@ class LaunchPersistentContextOptions { * Page.emulateMedia()} for more details. Passing {@code null} resets emulation to system defaults. Defaults to {@code * "light"}. */ - public Optional colorScheme; + public @Nullable Optional colorScheme; /** * Emulates {@code "prefers-contrast"} media feature, supported values are {@code "no-preference"}, {@code "more"}. See * {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets * emulation to system defaults. Defaults to {@code "no-preference"}. */ - public Optional contrast; + public @Nullable Optional contrast; /** * Specify device scale factor (can be thought of as dpr). Defaults to {@code 1}. Learn more about emulating devices with device scale factor. */ - public Double deviceScaleFactor; + public @Nullable Double deviceScaleFactor; /** * If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is * deleted when browser is closed. In either case, the downloads are deleted when the browser context they were created in * is closed. */ - public Path downloadsPath; + public @Nullable Path downloadsPath; /** * Specify environment variables that will be visible to the browser. Defaults to {@code process.env}. */ - public Map env; + public @Nullable Map env; /** * Path to a browser executable to run instead of the bundled one. If {@code executablePath} is a relative path, then it is * resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium, Firefox * or WebKit, use at your own risk. */ - public Path executablePath; + public @Nullable Path executablePath; /** * An object containing additional HTTP headers to be sent with every request. Defaults to none. */ - public Map extraHTTPHeaders; + public @Nullable Map extraHTTPHeaders; /** * Firefox user preferences. Learn more about the Firefox user preferences at {@code about:config}. @@ -598,37 +599,37 @@ class LaunchPersistentContextOptions { *

    You can also provide a path to a custom {@code policies.json} * file via {@code PLAYWRIGHT_FIREFOX_POLICIES_JSON} environment variable. */ - public Map firefoxUserPrefs; + public @Nullable Map firefoxUserPrefs; /** * Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link * com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets emulation * to system defaults. Defaults to {@code "none"}. */ - public Optional forcedColors; - public Geolocation geolocation; + public @Nullable Optional forcedColors; + public @Nullable Geolocation geolocation; /** * Close the browser process on SIGHUP. Defaults to {@code true}. */ - public Boolean handleSIGHUP; + public @Nullable Boolean handleSIGHUP; /** * Close the browser process on Ctrl-C. Defaults to {@code true}. */ - public Boolean handleSIGINT; + public @Nullable Boolean handleSIGINT; /** * Close the browser process on SIGTERM. Defaults to {@code true}. */ - public Boolean handleSIGTERM; + public @Nullable Boolean handleSIGTERM; /** * Specifies if viewport supports touch events. Defaults to false. Learn more about mobile emulation. */ - public Boolean hasTouch; + public @Nullable Boolean hasTouch; /** * Whether to run browser in headless mode. More details for Chromium and Firefox. Defaults to {@code true}. */ - public Boolean headless; + public @Nullable Boolean headless; /** * Credentials for HTTP authentication. If * no origin is specified, the username and password are sent to any servers upon unauthorized responses. @@ -636,99 +637,99 @@ class LaunchPersistentContextOptions { *

    Pass an array to use different credentials for different origins. The first entry that matches the request origin is * used, and entries with no origin match any request. */ - public Object httpCredentials; + public @Nullable Object httpCredentials; /** * If {@code true}, Playwright does not pass its own configurations args and only uses the ones from {@code args}. * Dangerous option; use with care. Defaults to {@code false}. */ - public Boolean ignoreAllDefaultArgs; + public @Nullable Boolean ignoreAllDefaultArgs; /** * If {@code true}, Playwright does not pass its own configurations args and only uses the ones from {@code args}. * Dangerous option; use with care. */ - public List ignoreDefaultArgs; + public @Nullable List ignoreDefaultArgs; /** * Whether to ignore HTTPS errors when sending network requests. Defaults to {@code false}. */ - public Boolean ignoreHTTPSErrors; + public @Nullable Boolean ignoreHTTPSErrors; /** * Whether the {@code meta viewport} tag is taken into account and touch events are enabled. isMobile is a part of device, * so you don't actually need to set it manually. Defaults to {@code false} and is not supported in Firefox. Learn more * about mobile emulation. */ - public Boolean isMobile; + public @Nullable Boolean isMobile; /** * Whether or not to enable JavaScript in the context. Defaults to {@code true}. Learn more about disabling JavaScript. */ - public Boolean javaScriptEnabled; + public @Nullable Boolean javaScriptEnabled; /** * Specify user locale, for example {@code en-GB}, {@code de-DE}, etc. Locale will affect {@code navigator.language} value, * {@code Accept-Language} request header value as well as number and date formatting rules. Defaults to the system default * locale. Learn more about emulation in our emulation guide. */ - public String locale; + public @Nullable String locale; /** * Whether to emulate network being offline. Defaults to {@code false}. Learn more about network emulation. */ - public Boolean offline; + public @Nullable Boolean offline; /** * A list of permissions to grant to all pages in this context. See {@link * com.microsoft.playwright.BrowserContext#grantPermissions BrowserContext.grantPermissions()} for more details. Defaults * to none. */ - public List permissions; + public @Nullable List permissions; /** * Network proxy settings. */ - public Proxy proxy; + public @Nullable Proxy proxy; /** * Optional setting to control resource content management. If {@code omit} is specified, content is not persisted. If * {@code attach} is specified, resources are persisted as separate files and all of these files are archived along with * the HAR file. Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification. */ - public HarContentPolicy recordHarContent; + public @Nullable HarContentPolicy recordHarContent; /** * When set to {@code minimal}, only record information necessary for routing from HAR. This omits sizes, timing, page, * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to {@code * full}. */ - public HarMode recordHarMode; + public @Nullable HarMode recordHarMode; /** * Optional setting to control whether to omit request content from the HAR. Defaults to {@code false}. */ - public Boolean recordHarOmitContent; + public @Nullable Boolean recordHarOmitContent; /** * Enables HAR recording for all pages into the specified HAR * file on the filesystem. If not specified, the HAR is not recorded. Make sure to call {@link * com.microsoft.playwright.BrowserContext#close BrowserContext.close()} for the HAR to be saved. */ - public Path recordHarPath; - public Object recordHarUrlFilter; + public @Nullable Path recordHarPath; + public @Nullable Object recordHarUrlFilter; /** * Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make sure * to call {@link com.microsoft.playwright.BrowserContext#close BrowserContext.close()} for videos to be saved. */ - public Path recordVideoDir; + public @Nullable Path recordVideoDir; /** * Dimensions of the recorded videos. If not specified the size will be equal to {@code viewport} scaled down to fit into * 800x800. If {@code viewport} is not configured explicitly the video size defaults to 800x450. Actual picture of each * page will be scaled down if necessary to fit the specified size. */ - public RecordVideoSize recordVideoSize; + public @Nullable RecordVideoSize recordVideoSize; /** * Emulates {@code "prefers-reduced-motion"} media feature, supported values are {@code "reduce"}, {@code "no-preference"}. * See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets * emulation to system defaults. Defaults to {@code "no-preference"}. */ - public Optional reducedMotion; + public @Nullable Optional reducedMotion; /** * Emulates consistent window screen size available inside web page via {@code window.screen}. Is only used when the {@code * viewport} is set. */ - public ScreenSize screenSize; + public @Nullable ScreenSize screenSize; /** * Whether to allow sites to register Service workers. Defaults to {@code "allow"}. *

      @@ -737,37 +738,37 @@ class LaunchPersistentContextOptions { *
    • {@code "block"}: Playwright will block all registration of Service Workers.
    • *
    */ - public ServiceWorkerPolicy serviceWorkers; + public @Nullable ServiceWorkerPolicy serviceWorkers; /** * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. */ - public Double slowMo; + public @Nullable Double slowMo; /** * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors * that imply single target DOM element will throw when more than one element matches the selector. This option does not * affect any Locator APIs (Locators are always strict). Defaults to {@code false}. See {@code Locator} to learn more about * the strict mode. */ - public Boolean strictSelectors; + public @Nullable Boolean strictSelectors; /** * Maximum time in milliseconds to wait for the browser instance to start. Defaults to {@code 30000} (30 seconds). Pass * {@code 0} to disable timeout. */ - public Double timeout; + public @Nullable Double timeout; /** * Changes the timezone of the context. See ICU's * metaZones.txt for a list of supported timezone IDs. Defaults to the system timezone. */ - public String timezoneId; + public @Nullable String timezoneId; /** * If specified, traces are saved into this directory. */ - public Path tracesDir; + public @Nullable Path tracesDir; /** * Specific user agent to use in this context. */ - public String userAgent; + public @Nullable String userAgent; /** * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use {@code null} to disable the consistent * viewport emulation. Learn more about viewport @@ -776,7 +777,7 @@ class LaunchPersistentContextOptions { *

    NOTE: The {@code null} value opts out from the default presets, makes viewport depend on the host window size defined by the * operating system. It makes the execution of the tests non-deterministic. */ - public Optional viewportSize; + public @Nullable Optional viewportSize; /** * Whether to automatically download all the attachments. Defaults to {@code true} where all the downloads are accepted. @@ -895,7 +896,7 @@ public LaunchPersistentContextOptions setClientCertificates(List fi * com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets emulation * to system defaults. Defaults to {@code "none"}. */ - public LaunchPersistentContextOptions setForcedColors(ForcedColors forcedColors) { + public LaunchPersistentContextOptions setForcedColors(@Nullable ForcedColors forcedColors) { this.forcedColors = Optional.ofNullable(forcedColors); return this; } @@ -1197,7 +1198,7 @@ public LaunchPersistentContextOptions setRecordVideoSize(RecordVideoSize recordV * See {@link com.microsoft.playwright.Page#emulateMedia Page.emulateMedia()} for more details. Passing {@code null} resets * emulation to system defaults. Defaults to {@code "no-preference"}. */ - public LaunchPersistentContextOptions setReducedMotion(ReducedMotion reducedMotion) { + public LaunchPersistentContextOptions setReducedMotion(@Nullable ReducedMotion reducedMotion) { this.reducedMotion = Optional.ofNullable(reducedMotion); return this; } @@ -1295,7 +1296,7 @@ public LaunchPersistentContextOptions setViewportSize(int width, int height) { *

    NOTE: The {@code null} value opts out from the default presets, makes viewport depend on the host window size defined by the * operating system. It makes the execution of the tests non-deterministic. */ - public LaunchPersistentContextOptions setViewportSize(ViewportSize viewportSize) { + public LaunchPersistentContextOptions setViewportSize(@Nullable ViewportSize viewportSize) { this.viewportSize = Optional.ofNullable(viewportSize); return this; } @@ -1321,7 +1322,7 @@ default Browser connect(String endpoint) { * @param endpoint A Playwright browser websocket endpoint to connect to. You obtain this endpoint via {@code BrowserServer.wsEndpoint}. * @since v1.8 */ - Browser connect(String endpoint, ConnectOptions options); + Browser connect(String endpoint, @Nullable ConnectOptions options); /** * This method attaches Playwright to an existing browser instance using the Chrome DevTools Protocol. * @@ -1377,7 +1378,7 @@ default Browser connectOverCDP(String endpointURL) { * ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4}. * @since v1.9 */ - Browser connectOverCDP(String endpointURL, ConnectOverCDPOptions options); + Browser connectOverCDP(String endpointURL, @Nullable ConnectOverCDPOptions options); /** * A path where Playwright expects to find a bundled browser executable. * @@ -1453,7 +1454,7 @@ default Browser launch() { * * @since v1.8 */ - Browser launch(LaunchOptions options); + Browser launch(@Nullable LaunchOptions options); /** * Returns the persistent browser context instance. * @@ -1501,7 +1502,7 @@ default BrowserContext launchPersistentContext(Path userDataDir) { * as your automation profile instead. See https://developer.chrome.com/blog/remote-debugging-port for details. * @since v1.8 */ - BrowserContext launchPersistentContext(Path userDataDir, LaunchPersistentContextOptions options); + BrowserContext launchPersistentContext(Path userDataDir, @Nullable LaunchPersistentContextOptions options); /** * Returns browser name. For example: {@code "chromium"}, {@code "webkit"} or {@code "firefox"}. * diff --git a/playwright/src/main/java/com/microsoft/playwright/CDPSession.java b/playwright/src/main/java/com/microsoft/playwright/CDPSession.java index 1c137a4a2..7760ca63d 100644 --- a/playwright/src/main/java/com/microsoft/playwright/CDPSession.java +++ b/playwright/src/main/java/com/microsoft/playwright/CDPSession.java @@ -16,6 +16,7 @@ package com.microsoft.playwright; +import org.jspecify.annotations.Nullable; import java.util.function.Consumer; import com.google.gson.JsonObject; @@ -81,7 +82,7 @@ default JsonObject send(String method) { * @param args Optional method parameters. * @since v1.8 */ - JsonObject send(String method, JsonObject args); + JsonObject send(String method, @Nullable JsonObject args); /** * Register an event handler for events with the specified event name. The given handler will be called for every event * with the given name. diff --git a/playwright/src/main/java/com/microsoft/playwright/Clock.java b/playwright/src/main/java/com/microsoft/playwright/Clock.java index bab0a7f65..c70004e6c 100644 --- a/playwright/src/main/java/com/microsoft/playwright/Clock.java +++ b/playwright/src/main/java/com/microsoft/playwright/Clock.java @@ -16,6 +16,7 @@ package com.microsoft.playwright; +import org.jspecify.annotations.Nullable; import java.util.Date; /** @@ -30,7 +31,7 @@ class InstallOptions { /** * Time to initialize with, current system time by default. */ - public Object time; + public @Nullable Object time; /** * Time to initialize with, current system time by default. @@ -129,7 +130,7 @@ default void install() { * * @since v1.45 */ - void install(InstallOptions options); + void install(@Nullable InstallOptions options); /** * Advance the clock, firing all the time-related callbacks. * diff --git a/playwright/src/main/java/com/microsoft/playwright/ConsoleMessage.java b/playwright/src/main/java/com/microsoft/playwright/ConsoleMessage.java index db548f8be..8d88ddd71 100644 --- a/playwright/src/main/java/com/microsoft/playwright/ConsoleMessage.java +++ b/playwright/src/main/java/com/microsoft/playwright/ConsoleMessage.java @@ -16,6 +16,7 @@ package com.microsoft.playwright; +import org.jspecify.annotations.Nullable; import java.util.*; /** @@ -62,7 +63,7 @@ public interface ConsoleMessage { * * @since v1.34 */ - Page page(); + @Nullable Page page(); /** * The text of the console message. * @@ -90,6 +91,6 @@ public interface ConsoleMessage { * * @since v1.57 */ - Worker worker(); + @Nullable Worker worker(); } diff --git a/playwright/src/main/java/com/microsoft/playwright/Credentials.java b/playwright/src/main/java/com/microsoft/playwright/Credentials.java index 5c3eb6d40..15d2cf098 100644 --- a/playwright/src/main/java/com/microsoft/playwright/Credentials.java +++ b/playwright/src/main/java/com/microsoft/playwright/Credentials.java @@ -16,6 +16,7 @@ package com.microsoft.playwright; +import org.jspecify.annotations.Nullable; import com.microsoft.playwright.options.*; import java.util.*; @@ -87,19 +88,19 @@ class CreateOptions { /** * Base64url-encoded credential id. Auto-generated if omitted. */ - public String id; + public @Nullable String id; /** * Base64url-encoded PKCS#8 (DER) private key. Auto-generated if omitted. */ - public String privateKey; + public @Nullable String privateKey; /** * Base64url-encoded SPKI (DER) public key. Auto-generated if omitted. */ - public String publicKey; + public @Nullable String publicKey; /** * Base64url-encoded user handle. Auto-generated if omitted. */ - public String userHandle; + public @Nullable String userHandle; /** * Base64url-encoded credential id. Auto-generated if omitted. @@ -134,11 +135,11 @@ class GetOptions { /** * Only return the credential with this base64url-encoded id. */ - public String id; + public @Nullable String id; /** * Only return credentials for this relying party id. */ - public String rpId; + public @Nullable String rpId; /** * Only return the credential with this base64url-encoded id. @@ -203,7 +204,7 @@ default VirtualCredential create(String rpId) { * @param rpId Relying party id (typically the site's effective domain). * @since v1.61 */ - VirtualCredential create(String rpId, CreateOptions options); + VirtualCredential create(String rpId, @Nullable CreateOptions options); /** * Removes a credential from the authenticator by its id. Works for any credential currently held — both those seeded with * {@link com.microsoft.playwright.Credentials#create Credentials.create()} and those the page registered itself by calling @@ -238,6 +239,6 @@ default List get() { * * @since v1.61 */ - List get(GetOptions options); + List get(@Nullable GetOptions options); } diff --git a/playwright/src/main/java/com/microsoft/playwright/Debugger.java b/playwright/src/main/java/com/microsoft/playwright/Debugger.java index 9fbe29998..9d043c63b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/Debugger.java +++ b/playwright/src/main/java/com/microsoft/playwright/Debugger.java @@ -16,6 +16,7 @@ package com.microsoft.playwright; +import org.jspecify.annotations.Nullable; import com.microsoft.playwright.options.*; import java.util.*; @@ -39,7 +40,7 @@ public interface Debugger { * * @since v1.59 */ - DebuggerPausedDetails pausedDetails(); + @Nullable DebuggerPausedDetails pausedDetails(); /** * Configures the debugger to pause before the next action is executed. * diff --git a/playwright/src/main/java/com/microsoft/playwright/Dialog.java b/playwright/src/main/java/com/microsoft/playwright/Dialog.java index 3b187d52f..4d7ff391e 100644 --- a/playwright/src/main/java/com/microsoft/playwright/Dialog.java +++ b/playwright/src/main/java/com/microsoft/playwright/Dialog.java @@ -16,6 +16,7 @@ package com.microsoft.playwright; +import org.jspecify.annotations.Nullable; /** * {@code Dialog} objects are dispatched by page via the {@link com.microsoft.playwright.Page#onDialog Page.onDialog()} @@ -63,7 +64,7 @@ default void accept() { * @param promptText A text to enter in prompt. Does not cause any effects if the dialog's {@code type} is not prompt. Optional. * @since v1.8 */ - void accept(String promptText); + void accept(@Nullable String promptText); /** * If dialog is prompt, returns default prompt value. Otherwise, returns empty string. * @@ -87,7 +88,7 @@ default void accept() { * * @since v1.34 */ - Page page(); + @Nullable Page page(); /** * Returns dialog's type, can be one of {@code alert}, {@code beforeunload}, {@code confirm} or {@code prompt}. * diff --git a/playwright/src/main/java/com/microsoft/playwright/Download.java b/playwright/src/main/java/com/microsoft/playwright/Download.java index 490b32096..d76bd1e29 100644 --- a/playwright/src/main/java/com/microsoft/playwright/Download.java +++ b/playwright/src/main/java/com/microsoft/playwright/Download.java @@ -16,6 +16,7 @@ package com.microsoft.playwright; +import org.jspecify.annotations.Nullable; import java.io.InputStream; import java.nio.file.Path; @@ -65,7 +66,7 @@ public interface Download { * * @since v1.8 */ - String failure(); + @Nullable String failure(); /** * Get the page that the download belongs to. * diff --git a/playwright/src/main/java/com/microsoft/playwright/ElementHandle.java b/playwright/src/main/java/com/microsoft/playwright/ElementHandle.java index 9fb77bcfa..53bd72438 100644 --- a/playwright/src/main/java/com/microsoft/playwright/ElementHandle.java +++ b/playwright/src/main/java/com/microsoft/playwright/ElementHandle.java @@ -16,6 +16,7 @@ package com.microsoft.playwright; +import org.jspecify.annotations.Nullable; import com.microsoft.playwright.options.*; import java.nio.file.Path; import java.util.*; @@ -63,36 +64,36 @@ class CheckOptions { * Whether to bypass the actionability checks. Defaults to * {@code false}. */ - public Boolean force; + public @Nullable Boolean force; /** * @deprecated This option has no effect. */ - public Boolean noWaitAfter; + public @Nullable Boolean noWaitAfter; /** * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the * element. */ - public Position position; + public @Nullable Position position; /** * Controls whether Playwright scrolls the element into view before performing the action. Defaults to {@code "auto"}, * which scrolls the element into view when necessary, including scrolling nested scrollable containers. When set to {@code * "none"}, Playwright does not scroll the element and the action fails if the element is not already in the viewport. This * is useful to assert that an element is reachable by the user without additional scrolling. */ - public ScrollMode scroll; + public @Nullable ScrollMode scroll; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default * value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * When set, this method only performs the actionability * checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without * performing it. */ - public Boolean trial; + public @Nullable Boolean trial; /** * Whether to bypass the actionability checks. Defaults to @@ -158,61 +159,61 @@ class ClickOptions { /** * Defaults to {@code left}. */ - public MouseButton button; + public @Nullable MouseButton button; /** * defaults to 1. See [UIEvent.detail]. */ - public Integer clickCount; + public @Nullable Integer clickCount; /** * Time to wait between {@code mousedown} and {@code mouseup} in milliseconds. Defaults to 0. */ - public Double delay; + public @Nullable Double delay; /** * Whether to bypass the actionability checks. Defaults to * {@code false}. */ - public Boolean force; + public @Nullable Boolean force; /** * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current * modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows * and Linux and to "Meta" on macOS. */ - public List modifiers; + public @Nullable List modifiers; /** * @deprecated This option will default to {@code true} in the future. */ - public Boolean noWaitAfter; + public @Nullable Boolean noWaitAfter; /** * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the * element. */ - public Position position; + public @Nullable Position position; /** * Controls whether Playwright scrolls the element into view before performing the action. Defaults to {@code "auto"}, * which scrolls the element into view when necessary, including scrolling nested scrollable containers. When set to {@code * "none"}, Playwright does not scroll the element and the action fails if the element is not already in the viewport. This * is useful to assert that an element is reachable by the user without additional scrolling. */ - public ScrollMode scroll; + public @Nullable ScrollMode scroll; /** * Defaults to 1. Sends {@code n} interpolated {@code mousemove} events to represent travel between Playwright's current * cursor position and the provided destination. When set to 1, emits a single {@code mousemove} event at the destination * location. */ - public Integer steps; + public @Nullable Integer steps; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default * value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * When set, this method only performs the actionability * checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without * performing it. */ - public Boolean trial; + public @Nullable Boolean trial; /** * Defaults to {@code left}. @@ -317,57 +318,57 @@ class DblclickOptions { /** * Defaults to {@code left}. */ - public MouseButton button; + public @Nullable MouseButton button; /** * Time to wait between {@code mousedown} and {@code mouseup} in milliseconds. Defaults to 0. */ - public Double delay; + public @Nullable Double delay; /** * Whether to bypass the actionability checks. Defaults to * {@code false}. */ - public Boolean force; + public @Nullable Boolean force; /** * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current * modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows * and Linux and to "Meta" on macOS. */ - public List modifiers; + public @Nullable List modifiers; /** * @deprecated This option has no effect. */ - public Boolean noWaitAfter; + public @Nullable Boolean noWaitAfter; /** * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the * element. */ - public Position position; + public @Nullable Position position; /** * Controls whether Playwright scrolls the element into view before performing the action. Defaults to {@code "auto"}, * which scrolls the element into view when necessary, including scrolling nested scrollable containers. When set to {@code * "none"}, Playwright does not scroll the element and the action fails if the element is not already in the viewport. This * is useful to assert that an element is reachable by the user without additional scrolling. */ - public ScrollMode scroll; + public @Nullable ScrollMode scroll; /** * Defaults to 1. Sends {@code n} interpolated {@code mousemove} events to represent travel between Playwright's current * cursor position and the provided destination. When set to 1, emits a single {@code mousemove} event at the destination * location. */ - public Integer steps; + public @Nullable Integer steps; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default * value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * When set, this method only performs the actionability * checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without * performing it. */ - public Boolean trial; + public @Nullable Boolean trial; /** * Defaults to {@code left}. @@ -466,18 +467,18 @@ class FillOptions { * Whether to bypass the actionability checks. Defaults to * {@code false}. */ - public Boolean force; + public @Nullable Boolean force; /** * @deprecated This option has no effect. */ - public Boolean noWaitAfter; + public @Nullable Boolean noWaitAfter; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default * value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * Whether to bypass the actionability checks. Defaults to @@ -510,42 +511,42 @@ class HoverOptions { * Whether to bypass the actionability checks. Defaults to * {@code false}. */ - public Boolean force; + public @Nullable Boolean force; /** * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current * modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows * and Linux and to "Meta" on macOS. */ - public List modifiers; + public @Nullable List modifiers; /** * @deprecated This option has no effect. */ - public Boolean noWaitAfter; + public @Nullable Boolean noWaitAfter; /** * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the * element. */ - public Position position; + public @Nullable Position position; /** * Controls whether Playwright scrolls the element into view before performing the action. Defaults to {@code "auto"}, * which scrolls the element into view when necessary, including scrolling nested scrollable containers. When set to {@code * "none"}, Playwright does not scroll the element and the action fails if the element is not already in the viewport. This * is useful to assert that an element is reachable by the user without additional scrolling. */ - public ScrollMode scroll; + public @Nullable ScrollMode scroll; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default * value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * When set, this method only performs the actionability * checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without * performing it. */ - public Boolean trial; + public @Nullable Boolean trial; /** * Whether to bypass the actionability checks. Defaults to @@ -620,7 +621,7 @@ class InputValueOptions { /** * @deprecated This option is ignored. The value is returned immediately. */ - public Double timeout; + public @Nullable Double timeout; /** * @deprecated This option is ignored. The value is returned immediately. @@ -634,18 +635,18 @@ class PressOptions { /** * Time to wait between {@code keydown} and {@code keyup} in milliseconds. Defaults to 0. */ - public Double delay; + public @Nullable Double delay; /** * @deprecated This option will default to {@code true} in the future. */ - public Boolean noWaitAfter; + public @Nullable Boolean noWaitAfter; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default * value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * Time to wait between {@code keydown} and {@code keyup} in milliseconds. Defaults to 0. @@ -683,42 +684,42 @@ class ScreenshotOptions { * *

    Defaults to {@code "allow"} that leaves animations untouched. */ - public ScreenshotAnimations animations; + public @Nullable ScreenshotAnimations animations; /** * When set to {@code "hide"}, screenshot will hide text caret. When set to {@code "initial"}, text caret behavior will not * be changed. Defaults to {@code "hide"}. */ - public ScreenshotCaret caret; + public @Nullable ScreenshotCaret caret; /** * Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink box * {@code #FF00FF} (customized by {@code maskColor}) that completely covers its bounding box. The mask is also applied to * invisible elements, see Matching only * visible elements to disable that. */ - public List mask; + public @Nullable List mask; /** * Specify the color of the overlay box for masked elements, in CSS color format. Default color is pink {@code * #FF00FF}. */ - public String maskColor; + public @Nullable String maskColor; /** * Hides default white background and allows capturing screenshots with transparency. Not applicable to {@code jpeg} * images. Defaults to {@code false}. */ - public Boolean omitBackground; + public @Nullable Boolean omitBackground; /** * The file path to save the image to. The screenshot type will be inferred from file extension. If {@code path} is a * relative path, then it is resolved relative to the current working directory. If no path is provided, the image won't be * saved to the disk. */ - public Path path; + public @Nullable Path path; /** * The quality of the image, between 0-100. Not applicable to {@code png} images. For {@code jpeg} the default is {@code * 80}. For {@code webp}, a quality of {@code 100} (the default) produces a lossless image, while lower values use lossy * compression. */ - public Integer quality; + public @Nullable Integer quality; /** * When set to {@code "css"}, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, * this will keep screenshots small. Using {@code "device"} option will produce a single pixel per each device pixel, so @@ -726,24 +727,24 @@ class ScreenshotOptions { * *

    Defaults to {@code "device"}. */ - public ScreenshotScale scale; + public @Nullable ScreenshotScale scale; /** * Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make elements * invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces the Shadow DOM * and applies to the inner frames. */ - public String style; + public @Nullable String style; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default * value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * Specify screenshot type, defaults to {@code png}. */ - public ScreenshotType type; + public @Nullable ScreenshotType type; /** * When set to {@code "disabled"}, stops CSS animations, CSS transitions and Web Animations. Animations get different @@ -857,7 +858,7 @@ class ScrollIntoViewIfNeededOptions { * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default @@ -875,18 +876,18 @@ class SelectOptionOptions { * Whether to bypass the actionability checks. Defaults to * {@code false}. */ - public Boolean force; + public @Nullable Boolean force; /** * @deprecated This option has no effect. */ - public Boolean noWaitAfter; + public @Nullable Boolean noWaitAfter; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default * value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * Whether to bypass the actionability checks. Defaults to @@ -919,14 +920,14 @@ class SelectTextOptions { * Whether to bypass the actionability checks. Defaults to * {@code false}. */ - public Boolean force; + public @Nullable Boolean force; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default * value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * Whether to bypass the actionability checks. Defaults to @@ -952,36 +953,36 @@ class SetCheckedOptions { * Whether to bypass the actionability checks. Defaults to * {@code false}. */ - public Boolean force; + public @Nullable Boolean force; /** * @deprecated This option has no effect. */ - public Boolean noWaitAfter; + public @Nullable Boolean noWaitAfter; /** * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the * element. */ - public Position position; + public @Nullable Position position; /** * Controls whether Playwright scrolls the element into view before performing the action. Defaults to {@code "auto"}, * which scrolls the element into view when necessary, including scrolling nested scrollable containers. When set to {@code * "none"}, Playwright does not scroll the element and the action fails if the element is not already in the viewport. This * is useful to assert that an element is reachable by the user without additional scrolling. */ - public ScrollMode scroll; + public @Nullable ScrollMode scroll; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default * value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * When set, this method only performs the actionability * checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without * performing it. */ - public Boolean trial; + public @Nullable Boolean trial; /** * Whether to bypass the actionability checks. Defaults to @@ -1047,14 +1048,14 @@ class SetInputFilesOptions { /** * @deprecated This option has no effect. */ - public Boolean noWaitAfter; + public @Nullable Boolean noWaitAfter; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default * value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * @deprecated This option has no effect. @@ -1079,42 +1080,42 @@ class TapOptions { * Whether to bypass the actionability checks. Defaults to * {@code false}. */ - public Boolean force; + public @Nullable Boolean force; /** * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current * modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows * and Linux and to "Meta" on macOS. */ - public List modifiers; + public @Nullable List modifiers; /** * @deprecated This option has no effect. */ - public Boolean noWaitAfter; + public @Nullable Boolean noWaitAfter; /** * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the * element. */ - public Position position; + public @Nullable Position position; /** * Controls whether Playwright scrolls the element into view before performing the action. Defaults to {@code "auto"}, * which scrolls the element into view when necessary, including scrolling nested scrollable containers. When set to {@code * "none"}, Playwright does not scroll the element and the action fails if the element is not already in the viewport. This * is useful to assert that an element is reachable by the user without additional scrolling. */ - public ScrollMode scroll; + public @Nullable ScrollMode scroll; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default * value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * When set, this method only performs the actionability * checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without * performing it. */ - public Boolean trial; + public @Nullable Boolean trial; /** * Whether to bypass the actionability checks. Defaults to @@ -1189,18 +1190,18 @@ class TypeOptions { /** * Time to wait between key presses in milliseconds. Defaults to 0. */ - public Double delay; + public @Nullable Double delay; /** * @deprecated This option has no effect. */ - public Boolean noWaitAfter; + public @Nullable Boolean noWaitAfter; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default * value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * Time to wait between key presses in milliseconds. Defaults to 0. @@ -1232,36 +1233,36 @@ class UncheckOptions { * Whether to bypass the actionability checks. Defaults to * {@code false}. */ - public Boolean force; + public @Nullable Boolean force; /** * @deprecated This option has no effect. */ - public Boolean noWaitAfter; + public @Nullable Boolean noWaitAfter; /** * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the * element. */ - public Position position; + public @Nullable Position position; /** * Controls whether Playwright scrolls the element into view before performing the action. Defaults to {@code "auto"}, * which scrolls the element into view when necessary, including scrolling nested scrollable containers. When set to {@code * "none"}, Playwright does not scroll the element and the action fails if the element is not already in the viewport. This * is useful to assert that an element is reachable by the user without additional scrolling. */ - public ScrollMode scroll; + public @Nullable ScrollMode scroll; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default * value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * When set, this method only performs the actionability * checks and skips the action. Defaults to {@code false}. Useful to wait until the element is ready for the action without * performing it. */ - public Boolean trial; + public @Nullable Boolean trial; /** * Whether to bypass the actionability checks. Defaults to @@ -1330,7 +1331,7 @@ class WaitForElementStateOptions { * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default @@ -1355,19 +1356,19 @@ class WaitForSelectorOptions { * visibility:hidden}. This is opposite to the {@code "visible"} option. * */ - public WaitForSelectorState state; + public @Nullable WaitForSelectorState state; /** * When true, the call requires selector to resolve to a single element. If given selector resolves to more than one * element, the call throws an exception. */ - public Boolean strict; + public @Nullable Boolean strict; /** * Maximum time in milliseconds. Defaults to {@code 30000} (30 seconds). Pass {@code 0} to disable timeout. The default * value can be changed by using the {@link com.microsoft.playwright.BrowserContext#setDefaultTimeout * BrowserContext.setDefaultTimeout()} or {@link com.microsoft.playwright.Page#setDefaultTimeout Page.setDefaultTimeout()} * methods. */ - public Double timeout; + public @Nullable Double timeout; /** * Defaults to {@code "visible"}. Can be either: @@ -1425,7 +1426,7 @@ public WaitForSelectorOptions setTimeout(double timeout) { * * @since v1.8 */ - BoundingBox boundingBox(); + @Nullable BoundingBox boundingBox(); /** * This method checks the element by performing the following steps: *

      @@ -1467,7 +1468,7 @@ default void check() { * * @since v1.8 */ - void check(CheckOptions options); + void check(@Nullable CheckOptions options); /** * This method clicks the element by performing the following steps: *
        @@ -1507,13 +1508,13 @@ default void click() { * * @since v1.8 */ - void click(ClickOptions options); + void click(@Nullable ClickOptions options); /** * Returns the content frame for element handles referencing iframe nodes, or {@code null} otherwise * * @since v1.8 */ - Frame contentFrame(); + @Nullable Frame contentFrame(); /** * This method double clicks the element by performing the following steps: *
          @@ -1555,7 +1556,7 @@ default void dblclick() { * * @since v1.8 */ - void dblclick(DblclickOptions options); + void dblclick(@Nullable DblclickOptions options); /** * The snippet below dispatches the {@code click} event on the element. Regardless of the visibility state of the element, * {@code click} is dispatched. This is equivalent to calling actionability checks, focuses the * element, fills it and triggers an {@code input} event after filling. Note that you can pass an empty string to clear the @@ -1778,7 +1779,7 @@ default void fill(String value) { * @param value Value to set for the {@code }, {@code "); page.evalOnSelector("textarea", "t => t.readOnly = true"); ElementHandle input1 = page.querySelector("#input1"); @@ -256,8 +256,8 @@ void isEditableShouldWork() { assertFalse(page.isEditable("textarea")); } - @Test - void isCheckedShouldWork() { + @PlaywrightTest + void isCheckedShouldWork(Page page) { page.setContent("
          Not a checkbox
          "); ElementHandle handle = page.querySelector("input"); assertTrue(handle.isChecked()); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestElementHandleMisc.java b/playwright/src/test/java/com/microsoft/playwright/TestElementHandleMisc.java index 695da49c2..423a68bdb 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestElementHandleMisc.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestElementHandleMisc.java @@ -16,23 +16,23 @@ package com.microsoft.playwright; -import org.junit.jupiter.api.Test; +import com.microsoft.playwright.fixtures.PlaywrightTest; import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -public class TestElementHandleMisc extends TestBase { - @Test - void shouldHover() { +public class TestElementHandleMisc { + @PlaywrightTest + void shouldHover(Page page, Server server) { page.navigate(server.PREFIX + "/input/scrollable.html"); ElementHandle button = page.querySelector("#button-6"); button.hover(); assertEquals("button-6", page.evaluate("document.querySelector('button:hover').id")); } - @Test - void shouldHoverWhenNodeIsRemoved() { + @PlaywrightTest + void shouldHoverWhenNodeIsRemoved(Page page, Server server) { page.navigate(server.PREFIX + "/input/scrollable.html"); page.evaluate("() => delete window['Node']"); ElementHandle button = page.querySelector("#button-6"); @@ -40,16 +40,16 @@ void shouldHoverWhenNodeIsRemoved() { assertEquals("button-6", page.evaluate("document.querySelector('button:hover').id")); } - @Test - void shouldFillInput() { + @PlaywrightTest + void shouldFillInput(Page page, Server server) { page.navigate(server.PREFIX + "/input/textarea.html"); ElementHandle handle = page.querySelector("input"); handle.fill("some value"); assertEquals("some value", page.evaluate("window['result']")); } - @Test - void shouldFillInputWhenNodeIsRemoved() { + @PlaywrightTest + void shouldFillInputWhenNodeIsRemoved(Page page, Server server) { page.navigate(server.PREFIX + "/input/textarea.html"); page.evaluate("() => delete window['Node']"); ElementHandle handle = page.querySelector("input"); @@ -57,24 +57,24 @@ void shouldFillInputWhenNodeIsRemoved() { assertEquals("some value", page.evaluate("window['result']")); } - @Test - void shouldCheckTheBox() { + @PlaywrightTest + void shouldCheckTheBox(Page page) { page.setContent(""); ElementHandle input = page.querySelector("input"); input.check(); assertEquals(true, page.evaluate("checkbox.checked")); } - @Test - void shouldUncheckTheBox() { + @PlaywrightTest + void shouldUncheckTheBox(Page page) { page.setContent(""); ElementHandle input = page.querySelector("input"); input.uncheck(); assertEquals(false, page.evaluate("checkbox.checked")); } - @Test - void shouldSelectSingleOption() { + @PlaywrightTest + void shouldSelectSingleOption(Page page, Server server) { page.navigate(server.PREFIX + "/input/select.html"); ElementHandle select = page.querySelector("select"); select.selectOption("blue"); @@ -82,8 +82,8 @@ void shouldSelectSingleOption() { assertEquals(asList("blue"), page.evaluate("window['result'].onChange")); } - @Test - void shouldFocusAButton() { + @PlaywrightTest + void shouldFocusAButton(Page page, Server server) { page.navigate(server.PREFIX + "/input/button.html"); ElementHandle button = page.querySelector("button"); assertEquals(false, button.evaluate("button => document.activeElement === button")); @@ -91,8 +91,8 @@ void shouldFocusAButton() { assertEquals(true, button.evaluate("button => document.activeElement === button")); } - @Test - void shouldCheckTheBoxUsingSetChecked() { + @PlaywrightTest + void shouldCheckTheBoxUsingSetChecked(Page page) { page.setContent(""); ElementHandle input = page.querySelector("input"); input.setChecked(true); @@ -101,16 +101,16 @@ void shouldCheckTheBoxUsingSetChecked() { assertEquals(false, page.evaluate("checkbox.checked")); } - @Test - void shouldFallBackToSelectingByLabel() { + @PlaywrightTest + void shouldFallBackToSelectingByLabel(Page page, Server server) { page.navigate(server.PREFIX + "/input/select.html"); page.querySelector("select").selectOption("Blue"); assertEquals(asList("blue"), page.evaluate("() => window['result'].onInput")); assertEquals(asList("blue"), page.evaluate("() => window['result'].onChange")); } - @Test - void shouldAllowDisposingTwice() { + @PlaywrightTest + void shouldAllowDisposingTwice(Page page) { page.setContent("
          39
          "); ElementHandle element = page.querySelector("section"); assertNotNull(element); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestElementHandleOwnerFrame.java b/playwright/src/test/java/com/microsoft/playwright/TestElementHandleOwnerFrame.java index 157202980..9378cd648 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestElementHandleOwnerFrame.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestElementHandleOwnerFrame.java @@ -16,16 +16,16 @@ package com.microsoft.playwright; -import org.junit.jupiter.api.Test; +import com.microsoft.playwright.fixtures.PlaywrightTest; -import static com.microsoft.playwright.options.LoadState.DOMCONTENTLOADED; import static com.microsoft.playwright.Utils.attachFrame; +import static com.microsoft.playwright.options.LoadState.DOMCONTENTLOADED; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -public class TestElementHandleOwnerFrame extends TestBase { - @Test - void shouldWork() { +public class TestElementHandleOwnerFrame { + @PlaywrightTest + void shouldWork(Page page, Server server) { page.navigate(server.EMPTY_PAGE); attachFrame(page, "frame1", server.EMPTY_PAGE); Frame frame = page.frames().get(1); @@ -35,8 +35,8 @@ void shouldWork() { assertEquals(frame, elementHandle.ownerFrame()); } - @Test - void shouldWorkForCrossProcessIframes() { + @PlaywrightTest + void shouldWorkForCrossProcessIframes(Page page, Server server) { page.navigate(server.EMPTY_PAGE); attachFrame(page, "frame1", server.CROSS_PROCESS_PREFIX + "/empty.html"); Frame frame = page.frames().get(1); @@ -46,8 +46,8 @@ void shouldWorkForCrossProcessIframes() { assertEquals(frame, elementHandle.ownerFrame()); } - @Test - void shouldWorkForDocument() { + @PlaywrightTest + void shouldWorkForDocument(Page page, Server server) { // TODO: test.flaky(platform === "win32" && browserName === "webkit"); page.navigate(server.EMPTY_PAGE); attachFrame(page, "frame1", server.EMPTY_PAGE); @@ -58,8 +58,8 @@ void shouldWorkForDocument() { assertEquals(frame, elementHandle.ownerFrame()); } - @Test - void shouldWorkForIframeElements() { + @PlaywrightTest + void shouldWorkForIframeElements(Page page, Server server) { page.navigate(server.EMPTY_PAGE); attachFrame(page, "frame1", server.EMPTY_PAGE); Frame frame = page.mainFrame(); @@ -69,8 +69,8 @@ void shouldWorkForIframeElements() { assertEquals(frame, elementHandle.ownerFrame()); } - @Test - void shouldWorkForCrossFrameEvaluations() { + @PlaywrightTest + void shouldWorkForCrossFrameEvaluations(Page page, Server server) { page.navigate(server.EMPTY_PAGE); attachFrame(page, "frame1", server.EMPTY_PAGE); Frame frame = page.mainFrame(); @@ -78,8 +78,8 @@ void shouldWorkForCrossFrameEvaluations() { assertEquals(frame.childFrames().get(0), elementHandle.asElement().ownerFrame()); } - @Test - void shouldWorkForDetachedElements() { + @PlaywrightTest + void shouldWorkForDetachedElements(Page page, Server server) { page.navigate(server.EMPTY_PAGE); JSHandle divHandle = page.evaluateHandle("() => {\n" + " const div = document.createElement('div');\n" + @@ -94,8 +94,8 @@ void shouldWorkForDetachedElements() { assertEquals(page.mainFrame(), divHandle.asElement().ownerFrame()); } - @Test - void shouldWorkForAdoptedElements() { + @PlaywrightTest + void shouldWorkForAdoptedElements(Page page, Server server) { page.navigate(server.EMPTY_PAGE); Page popup = page.waitForPopup(() -> page.evaluate("url => window['__popup'] = window.open(url)", server.EMPTY_PAGE)); JSHandle divHandle = page.evaluateHandle("() => {\n" + diff --git a/playwright/src/test/java/com/microsoft/playwright/TestElementHandlePress.java b/playwright/src/test/java/com/microsoft/playwright/TestElementHandlePress.java index 46f59fbbd..83eb1786d 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestElementHandlePress.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestElementHandlePress.java @@ -16,28 +16,30 @@ package com.microsoft.playwright; -import org.junit.jupiter.api.Test; +import com.microsoft.playwright.fixtures.BrowserName; +import com.microsoft.playwright.fixtures.PlaywrightTest; +import static com.microsoft.playwright.fixtures.BrowserName.WEBKIT; import static org.junit.jupiter.api.Assertions.assertEquals; -public class TestElementHandlePress extends TestBase { +public class TestElementHandlePress { - @Test - void shouldWork() { + @PlaywrightTest + void shouldWork(Page page) { page.setContent(""); page.press("input", "h"); assertEquals("h", page.evalOnSelector("input", "input => input.value")); } - @Test - void shouldNotSelectExistingValue() { + @PlaywrightTest + void shouldNotSelectExistingValue(Page page) { page.setContent(""); page.press("input", "w"); assertEquals("whello", page.evalOnSelector("input", "input => input.value")); } - @Test - void shouldResetSelectionWhenNotFocused() { + @PlaywrightTest + void shouldResetSelectionWhenNotFocused(Page page) { page.setContent("
          text
          "); page.evalOnSelector("input", "input => {\n" + " input.selectionStart = 2;\n" + @@ -48,8 +50,8 @@ void shouldResetSelectionWhenNotFocused() { assertEquals("whello", page.evalOnSelector("input", "input => input.value")); } - @Test - void shouldNotModifySelectionWhenFocused() { + @PlaywrightTest + void shouldNotModifySelectionWhenFocused(Page page) { page.setContent(""); page.evalOnSelector("input", "input => {\n" + " input.focus();\n" + @@ -60,10 +62,10 @@ void shouldNotModifySelectionWhenFocused() { assertEquals("hewo", page.evalOnSelector("input", "input => input.value")); } - @Test - void shouldWorkWithNumberInput() { + @PlaywrightTest + void shouldWorkWithNumberInput(Page page, BrowserName browserName) { page.setContent(""); page.press("input", "1"); - assertEquals(isWebKit() ? "1" : "12", page.evalOnSelector("input", "input => input.value")); + assertEquals(browserName == WEBKIT ? "1" : "12", page.evalOnSelector("input", "input => input.value")); } } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestElementHandleQuerySelector.java b/playwright/src/test/java/com/microsoft/playwright/TestElementHandleQuerySelector.java index c4604a525..f83af6cab 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestElementHandleQuerySelector.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestElementHandleQuerySelector.java @@ -16,7 +16,7 @@ package com.microsoft.playwright; -import org.junit.jupiter.api.Test; +import com.microsoft.playwright.fixtures.PlaywrightTest; import java.util.ArrayList; import java.util.Arrays; @@ -25,9 +25,9 @@ import static com.microsoft.playwright.options.LoadState.DOMCONTENTLOADED; import static org.junit.jupiter.api.Assertions.*; -public class TestElementHandleQuerySelector extends TestBase { - @Test - void shouldQueryExistingElement() { +public class TestElementHandleQuerySelector { + @PlaywrightTest + void shouldQueryExistingElement(Page page, Server server) { page.navigate(server.PREFIX + "/playground.html"); page.setContent("
          A
          "); ElementHandle html = page.querySelector("html"); @@ -37,16 +37,16 @@ void shouldQueryExistingElement() { assertEquals( "A", content); } - @Test - void shouldReturnNullForNonExistingElement() { + @PlaywrightTest + void shouldReturnNullForNonExistingElement(Page page) { page.setContent("
          B
          "); ElementHandle html = page.querySelector("html"); ElementHandle second = html.querySelector(".third"); assertNull(second); } - @Test - void shouldWorkForAdoptedElements() { + @PlaywrightTest + void shouldWorkForAdoptedElements(Page page, Server server) { page.navigate(server.EMPTY_PAGE); Page popup = page.waitForPopup(() -> page.evaluate( "url => window['__popup'] = window.open(url)", server.EMPTY_PAGE)); @@ -73,8 +73,8 @@ void shouldWorkForAdoptedElements() { assertEquals("hello", popup.querySelector("span").evaluate("e => e.textContent")); } - @Test - void shouldQueryExistingElements() { + @PlaywrightTest + void shouldQueryExistingElements(Page page) { page.setContent("
          A

          B
          "); ElementHandle html = page.querySelector("html"); List elements = html.querySelectorAll("div"); @@ -84,16 +84,16 @@ void shouldQueryExistingElements() { assertTrue(Arrays.asList("A", "B").equals(result)); } - @Test - void shouldReturnEmptyArrayForNonExistingElement() { + @PlaywrightTest + void shouldReturnEmptyArrayForNonExistingElement(Page page) { page.setContent("A
          B"); ElementHandle html = page.querySelector("html"); List elements = html.querySelectorAll("div"); assertEquals(0, elements.size()); } - @Test - void xpathShouldQueryExistingElement() { + @PlaywrightTest + void xpathShouldQueryExistingElement(Page page, Server server) { page.navigate(server.PREFIX + "/playground.html"); page.setContent("
          A
          "); ElementHandle html = page.querySelector("html"); @@ -103,8 +103,8 @@ void xpathShouldQueryExistingElement() { assertEquals("A", content); } - @Test - void xpathShouldReturnNullForNonExistingElement() { + @PlaywrightTest + void xpathShouldReturnNullForNonExistingElement(Page page) { page.setContent("
          B
          "); ElementHandle html = page.querySelector("html"); List second = html.querySelectorAll("xpath=/div[contains(@class, 'third')]"); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestElementHandleSelectText.java b/playwright/src/test/java/com/microsoft/playwright/TestElementHandleSelectText.java index 7972d6771..d69cf67ce 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestElementHandleSelectText.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestElementHandleSelectText.java @@ -16,19 +16,22 @@ package com.microsoft.playwright; +import com.microsoft.playwright.fixtures.BrowserName; +import com.microsoft.playwright.fixtures.PlaywrightTest; import org.junit.jupiter.api.Test; +import static com.microsoft.playwright.fixtures.BrowserName.FIREFOX; import static org.junit.jupiter.api.Assertions.*; -public class TestElementHandleSelectText extends TestBase { +public class TestElementHandleSelectText { - @Test - void shouldSelectTextarea() { + @PlaywrightTest + void shouldSelectTextarea(Page page, Server server, BrowserName browserName) { page.navigate(server.PREFIX + "/input/textarea.html"); ElementHandle textarea = page.querySelector("textarea"); textarea.evaluate("textarea => textarea.value = 'some value'"); textarea.selectText(); - if (isFirefox()) { + if (browserName == FIREFOX) { assertEquals(0, textarea.evaluate("el => el.selectionStart")); assertEquals(10, textarea.evaluate("el => el.selectionEnd")); } else { @@ -36,13 +39,13 @@ void shouldSelectTextarea() { } } - @Test - void shouldSelectInput() { + @PlaywrightTest + void shouldSelectInput(Page page, Server server, BrowserName browserName) { page.navigate(server.PREFIX + "/input/textarea.html"); ElementHandle input = page.querySelector("input"); input.evaluate("input => input.value = 'some value'"); input.selectText(); - if (isFirefox()) { + if (browserName == FIREFOX) { assertEquals(0, input.evaluate("el => el.selectionStart")); assertEquals(10, input.evaluate("el => el.selectionEnd")); } else { @@ -50,16 +53,16 @@ void shouldSelectInput() { } } - @Test - void shouldSelectPlainDiv() { + @PlaywrightTest + void shouldSelectPlainDiv(Page page, Server server) { page.navigate(server.PREFIX + "/input/textarea.html"); ElementHandle div = page.querySelector("div.plain"); div.selectText(); assertEquals("Plain div", page.evaluate("() => window.getSelection().toString()")); } - @Test - void shouldTimeoutWaitingForInvisibleElement() { + @PlaywrightTest + void shouldTimeoutWaitingForInvisibleElement(Page page, Server server) { page.navigate(server.PREFIX + "/input/textarea.html"); ElementHandle textarea = page.querySelector("textarea"); textarea.evaluate("e => e.style.display = 'none'"); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestElementHandleType.java b/playwright/src/test/java/com/microsoft/playwright/TestElementHandleType.java index 9b1f9c0a9..3baeb97a0 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestElementHandleType.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestElementHandleType.java @@ -16,28 +16,30 @@ package com.microsoft.playwright; -import org.junit.jupiter.api.Test; +import com.microsoft.playwright.fixtures.BrowserName; +import com.microsoft.playwright.fixtures.PlaywrightTest; +import static com.microsoft.playwright.fixtures.BrowserName.WEBKIT; import static org.junit.jupiter.api.Assertions.assertEquals; -public class TestElementHandleType extends TestBase { +public class TestElementHandleType { - @Test - void shouldWork() { + @PlaywrightTest + void shouldWork(Page page) { page.setContent(""); page.type("input", "hello"); assertEquals("hello", page.evalOnSelector("input", "input => input.value")); } - @Test - void shouldNotSelectExistingValue() { + @PlaywrightTest + void shouldNotSelectExistingValue(Page page) { page.setContent(""); page.type("input", "world"); assertEquals("worldhello", page.evalOnSelector("input", "input => input.value")); } - @Test - void shouldResetSelectionWhenNotFocus() { + @PlaywrightTest + void shouldResetSelectionWhenNotFocus(Page page) { page.setContent("
          text
          "); page.evalOnSelector("input", "input => {\n" + " input.selectionStart = 2;\n" + @@ -48,8 +50,8 @@ void shouldResetSelectionWhenNotFocus() { assertEquals("worldhello", page.evalOnSelector("input", "input => input.value")); } - @Test - void shouldNotModifySelectionWhenFocus() { + @PlaywrightTest + void shouldNotModifySelectionWhenFocus(Page page) { page.setContent(""); page.evalOnSelector("input", "input => {\n" + " input.focus();\n" + @@ -60,10 +62,10 @@ void shouldNotModifySelectionWhenFocus() { assertEquals("heworldo", page.evalOnSelector("input", "input => input.value")); } - @Test - void shouldWorkWithNumberInput() { + @PlaywrightTest + void shouldWorkWithNumberInput(Page page, BrowserName browserName) { page.setContent(""); page.type("input", "13"); - assertEquals(isWebKit() ? "13" : "132", page.evalOnSelector("input", "input => input.value")); + assertEquals(browserName == WEBKIT ? "13" : "132", page.evalOnSelector("input", "input => input.value")); } } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestElementHandleWaitForElementState.java b/playwright/src/test/java/com/microsoft/playwright/TestElementHandleWaitForElementState.java index a0ed26327..6051c5581 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestElementHandleWaitForElementState.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestElementHandleWaitForElementState.java @@ -16,13 +16,15 @@ package com.microsoft.playwright; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.DisabledIf; +import com.microsoft.playwright.fixtures.DisabledOnBrowser; +import com.microsoft.playwright.fixtures.PlaywrightTest; +import org.junit.jupiter.api.condition.OS; +import static com.microsoft.playwright.fixtures.BrowserName.FIREFOX; import static com.microsoft.playwright.options.ElementState.*; import static org.junit.jupiter.api.Assertions.*; -public class TestElementHandleWaitForElementState extends TestBase { +public class TestElementHandleWaitForElementState { static void giveItAChanceToResolve(Page page) { for (int i = 0; i < 5; i++) { @@ -30,8 +32,8 @@ static void giveItAChanceToResolve(Page page) { } } - @Test - void shouldWaitForVisible() { + @PlaywrightTest + void shouldWaitForVisible(Page page) { page.setContent("
          content
          "); ElementHandle div = page.querySelector("div"); giveItAChanceToResolve(page); @@ -39,15 +41,15 @@ void shouldWaitForVisible() { div.waitForElementState(VISIBLE); } - @Test - void shouldWaitForAlreadyVisible() { + @PlaywrightTest + void shouldWaitForAlreadyVisible(Page page) { page.setContent("
          content
          "); ElementHandle div = page.querySelector("div"); div.waitForElementState(VISIBLE); } - @Test - void shouldTimeoutWaitingForVisible() { + @PlaywrightTest + void shouldTimeoutWaitingForVisible(Page page) { page.setContent("
          content
          "); ElementHandle div = page.querySelector("div"); PlaywrightException e = assertThrows(PlaywrightException.class, () -> { @@ -56,8 +58,8 @@ void shouldTimeoutWaitingForVisible() { assertTrue(e.getMessage().contains("Timeout 1000ms exceeded")); } - @Test - void shouldThrowWaitingForVisibleWhenDetached() { + @PlaywrightTest + void shouldThrowWaitingForVisibleWhenDetached(Page page) { page.setContent("
          content
          "); ElementHandle div = page.querySelector("div"); div.evaluate("div => div.remove()"); @@ -65,8 +67,8 @@ void shouldThrowWaitingForVisibleWhenDetached() { assertTrue(e.getMessage().contains("Element is not attached to the DOM")); } - @Test - void shouldWaitForHidden() { + @PlaywrightTest + void shouldWaitForHidden(Page page) { page.setContent("
          content
          "); ElementHandle div = page.querySelector("div"); giveItAChanceToResolve(page); @@ -74,15 +76,15 @@ void shouldWaitForHidden() { div.waitForElementState(HIDDEN); } - @Test - void shouldWaitForAlreadyHidden() { + @PlaywrightTest + void shouldWaitForAlreadyHidden(Page page) { page.setContent("
          "); ElementHandle div = page.querySelector("div"); div.waitForElementState(HIDDEN); } - @Test - void shouldWaitForHiddenWhenDetached() { + @PlaywrightTest + void shouldWaitForHiddenWhenDetached(Page page) { page.setContent("
          content
          "); ElementHandle div = page.querySelector("div"); giveItAChanceToResolve(page); @@ -90,8 +92,8 @@ void shouldWaitForHiddenWhenDetached() { div.waitForElementState(HIDDEN); } - @Test - void shouldWaitForEnabledButton() { + @PlaywrightTest + void shouldWaitForEnabledButton(Page page) { page.setContent(""); ElementHandle span = page.querySelector("text=Target"); giveItAChanceToResolve(page); @@ -99,8 +101,8 @@ void shouldWaitForEnabledButton() { span.waitForElementState(ENABLED); } - @Test - void shouldThrowWaitingForEnabledWhenDetached() { + @PlaywrightTest + void shouldThrowWaitingForEnabledWhenDetached(Page page) { page.setContent(""); ElementHandle button = page.querySelector("button"); button.evaluate("button => button.remove()"); @@ -108,8 +110,8 @@ void shouldThrowWaitingForEnabledWhenDetached() { assertTrue(e.getMessage().contains("Element is not attached to the DOM")); } - @Test - void shouldWaitForDisabledButton() { + @PlaywrightTest + void shouldWaitForDisabledButton(Page page) { page.setContent(""); ElementHandle span = page.querySelector("text=Target"); giveItAChanceToResolve(page); @@ -117,12 +119,9 @@ void shouldWaitForDisabledButton() { span.waitForElementState(DISABLED); } - static boolean isFirefoxLinux() { - return isFirefox() && Utils.getOS() == Utils.OS.LINUX; - } - @Test - @DisabledIf(value="isFirefoxLinux", disabledReason="fixme") - void shouldWaitForStablePosition() { + @PlaywrightTest + @DisabledOnBrowser(value = FIREFOX, os = OS.LINUX, reason = "fixme") + void shouldWaitForStablePosition(Page page, Server server) { page.navigate(server.PREFIX + "/input/button.html"); ElementHandle button = page.querySelector("button"); page.evalOnSelector("button", "button => {\n" + diff --git a/playwright/src/test/java/com/microsoft/playwright/TestEvalOnSelector.java b/playwright/src/test/java/com/microsoft/playwright/TestEvalOnSelector.java index 380ecb46a..c310c58b7 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestEvalOnSelector.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestEvalOnSelector.java @@ -16,145 +16,145 @@ package com.microsoft.playwright; -import org.junit.jupiter.api.Test; +import com.microsoft.playwright.fixtures.PlaywrightTest; import java.util.Arrays; import java.util.Collections; import static org.junit.jupiter.api.Assertions.*; -public class TestEvalOnSelector extends TestBase { +public class TestEvalOnSelector { - @Test - void shouldWorkWithCssSelector() { + @PlaywrightTest + void shouldWorkWithCssSelector(Page page) { page.setContent("
          43543
          "); Object idAttribute = page.evalOnSelector("css=section", "e => e.id"); assertEquals("testAttribute", idAttribute); } - @Test - void shouldWorkWithIdSelector() { + @PlaywrightTest + void shouldWorkWithIdSelector(Page page) { page.setContent("
          43543
          "); Object idAttribute = page.evalOnSelector("id=testAttribute", "e => e.id"); assertEquals("testAttribute", idAttribute); } - @Test - void shouldWorkWithDataTestSelector() { + @PlaywrightTest + void shouldWorkWithDataTestSelector(Page page) { page.setContent("
          43543
          "); Object idAttribute = page.evalOnSelector("data-test=foo", "e => e.id"); assertEquals("testAttribute", idAttribute); } - @Test - void shouldWorkWithDataTestidSelector() { + @PlaywrightTest + void shouldWorkWithDataTestidSelector(Page page) { page.setContent("
          43543
          "); Object idAttribute = page.evalOnSelector("data-testid=foo", "e => e.id"); assertEquals("testAttribute", idAttribute); } - @Test - void shouldWorkWithDataTestIdSelector() { + @PlaywrightTest + void shouldWorkWithDataTestIdSelector(Page page) { page.setContent("
          43543
          "); Object idAttribute = page.evalOnSelector("data-test-id=foo", "e => e.id"); assertEquals("testAttribute", idAttribute); } - @Test - void shouldWorkWithTextSelector1() { + @PlaywrightTest + void shouldWorkWithTextSelector1(Page page) { page.setContent("
          43543
          "); Object idAttribute = page.evalOnSelector("text='43543'", "e => e.id"); assertEquals("testAttribute", idAttribute); } - @Test - void shouldWorkWithXpathSelector() { + @PlaywrightTest + void shouldWorkWithXpathSelector(Page page) { page.setContent("
          43543
          "); Object idAttribute = page.evalOnSelector("xpath=/html/body/section", "e => e.id"); assertEquals("testAttribute", idAttribute); } - @Test - void shouldWorkWithTextSelector2() { + @PlaywrightTest + void shouldWorkWithTextSelector2(Page page) { page.setContent("
          43543
          "); Object idAttribute = page.evalOnSelector("text=43543", "e => e.id"); assertEquals("testAttribute", idAttribute); } - @Test - void shouldAutoDetectCssSelector() { + @PlaywrightTest + void shouldAutoDetectCssSelector(Page page) { page.setContent("
          43543
          "); Object idAttribute = page.evalOnSelector("section", "e => e.id"); assertEquals("testAttribute", idAttribute); } - @Test - void shouldAutoDetectCssSelectorWithAttributes() { + @PlaywrightTest + void shouldAutoDetectCssSelectorWithAttributes(Page page) { page.setContent("
          43543
          "); Object idAttribute = page.evalOnSelector("section[id='testAttribute']", "e => e.id"); assertEquals("testAttribute", idAttribute); } - @Test - void shouldAutoDetectNestedSelectors() { + @PlaywrightTest + void shouldAutoDetectNestedSelectors(Page page) { page.setContent("
          43543Hello
          "); Object idAttribute = page.evalOnSelector("div[foo=bar] > section >> 'Hello' >> div", "e => e.id"); assertEquals("target", idAttribute); } - @Test - void shouldAcceptArguments() { + @PlaywrightTest + void shouldAcceptArguments(Page page) { page.setContent("
          hello
          "); Object text = page.evalOnSelector("section", "(e, suffix) => e.textContent + suffix", " world!"); assertEquals("hello world!", text); } - @Test - void shouldAcceptElementHandlesAsArguments() { + @PlaywrightTest + void shouldAcceptElementHandlesAsArguments(Page page) { page.setContent("
          hello
          world
          "); ElementHandle divHandle = page.querySelector("div"); Object text = page.evalOnSelector("section", "(e, div) => e.textContent + div.textContent", divHandle); assertEquals("hello world", text); } - @Test - void shouldThrowErrorIfNoElementIsFound() { + @PlaywrightTest + void shouldThrowErrorIfNoElementIsFound(Page page) { PlaywrightException e = assertThrows(PlaywrightException.class, () -> { page.evalOnSelector("section", "e => e.id"); }); assertTrue(e.getMessage().contains("Failed to find element matching selector \"section\""), e.getMessage()); } - @Test - void shouldSupportSyntax() { + @PlaywrightTest + void shouldSupportSyntax(Page page) { page.setContent("
          hello
          "); Object text = page.evalOnSelector("css=section >> css=div", "(e, suffix) => e.textContent + suffix", " world!"); assertEquals("hello world!", text); } - @Test - void shouldSupportSyntaxWithDifferentEngines() { + @PlaywrightTest + void shouldSupportSyntaxWithDifferentEngines(Page page) { page.setContent("
          hello
          "); Object text = page.evalOnSelector("xpath=/html/body/section >> css=div >> text='hello'", "(e, suffix) => e.textContent + suffix", " world!"); assertEquals("hello world!", text); } - @Test - void shouldSupportSpacesWithSyntax() { + @PlaywrightTest + void shouldSupportSpacesWithSyntax(Page page, Server server) { page.navigate(server.PREFIX + "/deep-shadow.html"); Object text = page.evalOnSelector(" css = div >>css=div>>css = span ", "e => e.textContent"); assertEquals("Hello from root2", text); } - @Test - void shouldNotStopAtFirstFailureWithSyntax() { + @PlaywrightTest + void shouldNotStopAtFirstFailureWithSyntax(Page page) { page.setContent("
          Next
          "); Object html = page.evalOnSelector("button >> 'Next'", "e => e.outerHTML"); assertEquals("", html); } - @Test - void shouldSupportCapture() { + @PlaywrightTest + void shouldSupportCapture(Page page) { page.setContent("
          a
          b
          "); assertEquals("
          b
          ", page.evalOnSelector("*css=div >> 'b'", "e => e.outerHTML")); assertEquals("
          b
          ", page.evalOnSelector("section >> *css=div >> 'b'", "e => e.outerHTML")); @@ -162,24 +162,24 @@ void shouldSupportCapture() { assertNotNull(page.querySelector("*")); } - @Test - void shouldThrowOnMultipleCaptures() { + @PlaywrightTest + void shouldThrowOnMultipleCaptures(Page page) { PlaywrightException e = assertThrows(PlaywrightException.class, () -> { page.evalOnSelector("*css=div >> *css=span", "e => e.outerHTML"); }); assertTrue(e.getMessage().contains("Only one of the selectors can capture using * modifier")); } - @Test - void shouldThrowOnMalformedCapture() { + @PlaywrightTest + void shouldThrowOnMalformedCapture(Page page) { PlaywrightException e = assertThrows(PlaywrightException.class, () -> { page.evalOnSelector("*=div", "e => e.outerHTML"); }); assertTrue(e.getMessage().contains("Unknown engine \"\" while parsing selector *=div")); } - @Test - void shouldWorkWithSpacesInCssAttributes() { + @PlaywrightTest + void shouldWorkWithSpacesInCssAttributes(Page page) { page.setContent("
          "); assertNotNull(page.waitForSelector("[placeholder=\"Select date\"]")); assertNotNull(page.waitForSelector("[placeholder='Select date']")); @@ -201,8 +201,8 @@ void shouldWorkWithSpacesInCssAttributes() { assertEquals("", page.evalOnSelector("div >> [placeholder='Select date']", "e => e.outerHTML")); } - @Test - void shouldWorkWithQuotesInCssAttributes() { + @PlaywrightTest + void shouldWorkWithQuotesInCssAttributes(Page page) { page.setContent("
          "); assertNotNull(page.querySelector("[placeholder=\"Select\\\"date\"]")); assertNotNull(page.querySelector("[placeholder='Select\"date']")); @@ -217,22 +217,22 @@ void shouldWorkWithQuotesInCssAttributes() { assertNotNull(page.querySelector("[placeholder='Select \\' date']")); } - @Test - void shouldWorkWithSpacesInCssAttributesWhenMissing() { + @PlaywrightTest + void shouldWorkWithSpacesInCssAttributesWhenMissing(Page page) { assertNull(page.querySelector("[placeholder='Select date']")); page.setContent("
          "); page.waitForSelector("[placeholder='Select date']"); } - @Test - void shouldWorkWithQuotesInCssAttributesWhenMissing() { + @PlaywrightTest + void shouldWorkWithQuotesInCssAttributesWhenMissing(Page page) { assertNull(page.querySelector("[placeholder='Select\\\"date']")); page.setContent("
          "); page.waitForSelector("[placeholder='Select\\\"date']"); } - @Test - void shouldReturnComplexValues() { + @PlaywrightTest + void shouldReturnComplexValues(Page page) { page.setContent("
          43543
          "); Object idAttribute = page.evalOnSelector("css=section", "e => [{ id: e.id }]"); assertEquals(Arrays.asList(Collections.singletonMap("id", "testAttribute")), idAttribute); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestEvalOnSelectorAll.java b/playwright/src/test/java/com/microsoft/playwright/TestEvalOnSelectorAll.java index ff257c9ef..8b1248b28 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestEvalOnSelectorAll.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestEvalOnSelectorAll.java @@ -16,50 +16,50 @@ package com.microsoft.playwright; -import org.junit.jupiter.api.Test; +import com.microsoft.playwright.fixtures.PlaywrightTest; import java.util.Arrays; import static org.junit.jupiter.api.Assertions.assertEquals; -public class TestEvalOnSelectorAll extends TestBase { +public class TestEvalOnSelectorAll { - @Test - void shouldWorkWithCssSelector() { + @PlaywrightTest + void shouldWorkWithCssSelector(Page page) { page.setContent("
          hello
          beautiful
          world!
          "); Object divsCount = page.evalOnSelectorAll("css=div", "divs => divs.length"); assertEquals(3, divsCount); } - @Test - void shouldWorkWithTextSelector() { + @PlaywrightTest + void shouldWorkWithTextSelector(Page page) { page.setContent("
          hello
          beautiful
          beautiful
          world!
          "); Object divsCount = page.evalOnSelectorAll("text='beautiful'", "divs => divs.length"); assertEquals(2, divsCount); } - @Test - void shouldWorkWithXpathSelector() { + @PlaywrightTest + void shouldWorkWithXpathSelector(Page page) { page.setContent("
          hello
          beautiful
          world!
          "); Object divsCount = page.evalOnSelectorAll("xpath=/html/body/div", "divs => divs.length"); assertEquals(3, divsCount); } - @Test - void shouldAutoDetectCssSelector() { + @PlaywrightTest + void shouldAutoDetectCssSelector(Page page) { page.setContent("
          hello
          beautiful
          world!
          "); Object divsCount = page.evalOnSelectorAll("div", "divs => divs.length"); assertEquals(3, divsCount); } - @Test - void shouldSupportSyntax() { + @PlaywrightTest + void shouldSupportSyntax(Page page) { page.setContent("
          hello
          beautiful
          world!
          Not this one"); Object spansCount = page.evalOnSelectorAll("css=div >> css=span", "spans => spans.length"); assertEquals(3, spansCount); } - @Test - void shouldSupportCapture() { + @PlaywrightTest + void shouldSupportCapture(Page page) { page.setContent("
          a
          b
          "); assertEquals(1, page.evalOnSelectorAll("*css=div >> 'b'", "els => els.length")); assertEquals(1, page.evalOnSelectorAll("section >> *css=div >> 'b'", "els => els.length")); @@ -74,16 +74,16 @@ void shouldSupportCapture() { assertEquals(1, page.evalOnSelectorAll("section >> *css=div >> 'a'", "els => els.length")); } - @Test - void shouldSupportCaptureWhenMultiplePathsMatch() { + @PlaywrightTest + void shouldSupportCaptureWhenMultiplePathsMatch(Page page) { page.setContent("
          "); assertEquals(2, page.evalOnSelectorAll("*css=div >> span", "els => els.length")); page.setContent("
          "); assertEquals(2, page.evalOnSelectorAll("*css=div >> span", "els => els.length")); } - @Test - void shouldReturnComplexValues() { + @PlaywrightTest + void shouldReturnComplexValues(Page page) { page.setContent("
          hello
          beautiful
          world!
          "); Object texts = page.evalOnSelectorAll("css=div", "divs => divs.map(div => div.textContent)"); assertEquals(Arrays.asList("hello", "beautiful", "world!"), texts); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestExpectMisc.java b/playwright/src/test/java/com/microsoft/playwright/TestExpectMisc.java index 9c9790101..d348c046b 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestExpectMisc.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestExpectMisc.java @@ -16,7 +16,7 @@ package com.microsoft.playwright; -import org.junit.jupiter.api.Test; +import com.microsoft.playwright.fixtures.PlaywrightTest; import org.opentest4j.AssertionFailedError; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; @@ -24,9 +24,9 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -public class TestExpectMisc extends TestBase { - @Test - void strictModeViolationErrorFormat() { +public class TestExpectMisc { + @PlaywrightTest + void strictModeViolationErrorFormat(Page page) { page.setContent("
          hello
          hi
          "); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("div")).isVisible()); @@ -34,8 +34,8 @@ void strictModeViolationErrorFormat() { assertTrue(error.getMessage().contains("Error: strict mode violation: locator(\"div\") resolved to 2 elements:"), error.getMessage()); } - @Test - void invalidSelectorErrorFormat() { + @PlaywrightTest + void invalidSelectorErrorFormat(Page page) { page.setContent("
          hello
          hi
          "); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("##")).isVisible()); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestFirefoxLauncher.java b/playwright/src/test/java/com/microsoft/playwright/TestFirefoxLauncher.java index b9878ccf3..e685a4e7b 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestFirefoxLauncher.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestFirefoxLauncher.java @@ -16,55 +16,44 @@ package com.microsoft.playwright; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.EnabledIf; +import com.microsoft.playwright.fixtures.EnabledOnBrowser; +import com.microsoft.playwright.fixtures.PlaywrightTest; import org.junit.jupiter.api.io.TempDir; import java.nio.file.Path; import static com.microsoft.playwright.Utils.mapOf; +import static com.microsoft.playwright.fixtures.BrowserName.FIREFOX; import static org.junit.jupiter.api.Assertions.*; -@EnabledIf(value="com.microsoft.playwright.TestBase#isFirefox", disabledReason="skip") -public class TestFirefoxLauncher extends TestBase { - - @Override - @BeforeAll - // Hide base class method to not launch browser. - void launchBrowser() { - } - - @Override - void createContextAndPage() { - // Do nothing - } - - @Test - void shouldPassFirefoxUserPreferences() { +@EnabledOnBrowser(value = FIREFOX, reason = "skip") +public class TestFirefoxLauncher { + @PlaywrightTest + void shouldPassFirefoxUserPreferences(BrowserType browserType) { BrowserType.LaunchOptions options = new BrowserType.LaunchOptions().setFirefoxUserPrefs( mapOf( "network.proxy.type", 1, "network.proxy.http", "127.0.0.1", "network.proxy.http_port", 3333)); - launchBrowser(options); - Page page = browser.newPage(); - PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.navigate("http://example.com")); - assertTrue(e.getMessage().contains("NS_ERROR_PROXY_CONNECTION_REFUSED")); + try (Browser browser = browserType.launch(options)) { + Page page = browser.newPage(); + PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.navigate("http://example.com")); + assertTrue(e.getMessage().contains("NS_ERROR_PROXY_CONNECTION_REFUSED")); + } } - @Test - void shouldPassFirefoxUserPreferencesInPersistent(@TempDir Path tmpDir) { + @PlaywrightTest + void shouldPassFirefoxUserPreferencesInPersistent(BrowserType browserType, @TempDir Path tmpDir) { BrowserType.LaunchPersistentContextOptions options = new BrowserType.LaunchPersistentContextOptions().setFirefoxUserPrefs( mapOf( "network.proxy.type", 1, "network.proxy.http", "127.0.0.1", "network.proxy.http_port", 3333)); - initBrowserType(); - context = browserType.launchPersistentContext(tmpDir.resolve("user-data-dir"), options); - assertNotNull(context); - Page page = context.pages().get(0); - PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.navigate("http://example.com")); - assertTrue(e.getMessage().contains("NS_ERROR_PROXY_CONNECTION_REFUSED")); + try (BrowserContext context = browserType.launchPersistentContext(tmpDir.resolve("user-data-dir"), options)) { + assertNotNull(context); + Page page = context.pages().get(0); + PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.navigate("http://example.com")); + assertTrue(e.getMessage().contains("NS_ERROR_PROXY_CONNECTION_REFUSED")); + } } } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestFrameNavigate.java b/playwright/src/test/java/com/microsoft/playwright/TestFrameNavigate.java index 5a1d00d55..1504d8d62 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestFrameNavigate.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestFrameNavigate.java @@ -16,15 +16,15 @@ package com.microsoft.playwright; -import org.junit.jupiter.api.Test; +import com.microsoft.playwright.fixtures.PlaywrightTest; import static com.microsoft.playwright.options.WaitUntilState.NETWORKIDLE; import static org.junit.jupiter.api.Assertions.*; -public class TestFrameNavigate extends TestBase { +public class TestFrameNavigate { - @Test - void shouldNavigateSubframes() { + @PlaywrightTest + void shouldNavigateSubframes(Page page, Server server) { page.navigate(server.PREFIX + "/frames/one-frame.html"); assertTrue(page.frames().get(0).url().contains("/frames/one-frame.html")); assertTrue(page.frames().get(1).url().contains("/frames/frame.html")); @@ -38,8 +38,8 @@ void shouldNavigateSubframes() { void shouldRejectWhenFrameDetaches() { } - @Test - void shouldContinueAfterClientRedirect() { + @PlaywrightTest + void shouldContinueAfterClientRedirect(Page page, Server server) { server.setRoute("/frames/script.js", (httpExchange) -> {}); String url = server.PREFIX + "/frames/child-redirect.html"; TimeoutError e = assertThrows(TimeoutError.class, () -> { diff --git a/playwright/src/test/java/com/microsoft/playwright/TestGeolocation.java b/playwright/src/test/java/com/microsoft/playwright/TestGeolocation.java index 4b6829f61..ac3930c18 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestGeolocation.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestGeolocation.java @@ -16,8 +16,8 @@ package com.microsoft.playwright; +import com.microsoft.playwright.fixtures.PlaywrightTest; import com.microsoft.playwright.options.Geolocation; -import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; @@ -26,9 +26,9 @@ import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.*; -public class TestGeolocation extends TestBase { - @Test - void shouldWork() { +public class TestGeolocation { + @PlaywrightTest + void shouldWork(Page page, BrowserContext context, Server server) { context.grantPermissions(asList("geolocation")); page.navigate(server.EMPTY_PAGE); context.setGeolocation(new Geolocation(10, 10)); @@ -38,16 +38,16 @@ void shouldWork() { assertEquals(mapOf("latitude", 10, "longitude", 10), geolocation); } - @Test - void shouldThrowWhenInvalidLongitude() { + @PlaywrightTest + void shouldThrowWhenInvalidLongitude(BrowserContext context) { PlaywrightException e = assertThrows(PlaywrightException.class, () -> { context.setGeolocation(new Geolocation(10, 200)); }); assertTrue(e.getMessage().contains("geolocation.longitude: precondition -180 <= LONGITUDE <= 180 failed.")); } - @Test - void shouldIsolateContexts() { + @PlaywrightTest + void shouldIsolateContexts(Page page, BrowserContext context, Browser browser, Server server) { context.grantPermissions(asList("geolocation")); context.setGeolocation(new Geolocation(10, 10)); page.navigate(server.EMPTY_PAGE); @@ -74,8 +74,8 @@ void shouldThrowWithMissingLatitude() { // Not applicable in Java. } - @Test - void shouldNotModifyPassedDefaultOptionsObject() { + @PlaywrightTest + void shouldNotModifyPassedDefaultOptionsObject(Browser browser) { Geolocation geolocation = new Geolocation(10, 10); Browser.NewContextOptions options = new Browser.NewContextOptions().setGeolocation(geolocation); BrowserContext context = browser.newContext(options); @@ -88,8 +88,8 @@ void shouldThrowWithMissingLongitudeInDefaultOptions() { // Not applicable in Java. } - @Test - void shouldUseContextOptions() { + @PlaywrightTest + void shouldUseContextOptions(Browser browser, Server server) { Browser.NewContextOptions options = new Browser.NewContextOptions() .setGeolocation(new Geolocation(10, 10)) .setPermissions(asList("geolocation")); @@ -103,8 +103,8 @@ void shouldUseContextOptions() { context.close(); } - @Test - void watchPositionShouldBeNotified() { + @PlaywrightTest + void watchPositionShouldBeNotified(Page page, BrowserContext context, Server server) { context.grantPermissions(asList("geolocation")); page.navigate(server.EMPTY_PAGE); List messages = new ArrayList<>(); @@ -143,8 +143,8 @@ void watchPositionShouldBeNotified() { assertTrue(messages.contains("lat=40 lng=50")); } - @Test - void shouldUseContextOptionsForPopup() { + @PlaywrightTest + void shouldUseContextOptionsForPopup(Page page, BrowserContext context, Server server) { context.grantPermissions(asList("geolocation")); context.setGeolocation(new Geolocation(10, 10)); Page popup = page.waitForPopup(() -> page.evaluate( diff --git a/playwright/src/test/java/com/microsoft/playwright/TestGlobalFetch.java b/playwright/src/test/java/com/microsoft/playwright/TestGlobalFetch.java index 3e5d10991..943db133d 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestGlobalFetch.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestGlobalFetch.java @@ -18,6 +18,7 @@ import com.google.gson.Gson; import com.microsoft.playwright.APIRequest.NewContextOptions; +import com.microsoft.playwright.fixtures.PlaywrightTest; import com.microsoft.playwright.options.Cookie; import com.microsoft.playwright.options.HttpCredentials; import com.microsoft.playwright.options.HttpCredentialsSend; @@ -26,7 +27,6 @@ import com.microsoft.playwright.options.SameSiteAttribute; import com.microsoft.playwright.options.ServerAddr; import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; import java.io.OutputStreamWriter; import java.io.Writer; @@ -42,11 +42,11 @@ import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.*; -public class TestGlobalFetch extends TestBase { +public class TestGlobalFetch { private static final List HTTP_METHODS = asList("GET", "PUT", "POST", "OPTIONS", "HEAD", "PATCH"); - @Test - void shouldHaveJavaInDefaultUesrAgent() throws ExecutionException, InterruptedException { + @PlaywrightTest + void shouldHaveJavaInDefaultUesrAgent(Playwright playwright, Server server) throws ExecutionException, InterruptedException { APIRequestContext request = playwright.request().newContext(new APIRequest.NewContextOptions()); Future serverRequest = server.futureRequest("/empty.html"); APIResponse response = request.get(server.EMPTY_PAGE); @@ -64,8 +64,8 @@ void shouldHaveJavaInDefaultUesrAgent() throws ExecutionException, InterruptedEx assertTrue(serverRequest.get().headers.get("user-agent").get(0).contains("java/" + version)); } - @Test - void fetchShouldWork() { + @PlaywrightTest + void fetchShouldWork(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(); APIResponse response = request.fetch(server.PREFIX + "/simple.json"); assertEquals(server.PREFIX + "/simple.json", response.url()); @@ -79,8 +79,8 @@ void fetchShouldWork() { assertEquals("{\"foo\": \"bar\"}\n", response.text()); } - @Test - void deleteShouldWork() { + @PlaywrightTest + void deleteShouldWork(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(); APIResponse response = request.delete(server.PREFIX + "/simple.json"); assertEquals(server.PREFIX + "/simple.json", response.url()); @@ -94,8 +94,8 @@ void deleteShouldWork() { assertEquals("{\"foo\": \"bar\"}\n", response.text()); } - @Test - void getShouldWork() { + @PlaywrightTest + void getShouldWork(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(); APIResponse response = request.get(server.PREFIX + "/simple.json"); assertEquals(server.PREFIX + "/simple.json", response.url()); @@ -109,8 +109,8 @@ void getShouldWork() { assertEquals("{\"foo\": \"bar\"}\n", response.text()); } - @Test - void headShouldWork() { + @PlaywrightTest + void headShouldWork(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(); APIResponse response = request.head(server.EMPTY_PAGE); assertEquals(server.EMPTY_PAGE, response.url()); @@ -124,8 +124,8 @@ void headShouldWork() { assertEquals("", response.text()); } - @Test - void patchShouldWork() { + @PlaywrightTest + void patchShouldWork(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(); APIResponse response = request.patch(server.PREFIX + "/simple.json"); assertEquals(server.PREFIX + "/simple.json", response.url()); @@ -139,8 +139,8 @@ void patchShouldWork() { assertEquals("{\"foo\": \"bar\"}\n", response.text()); } - @Test - void postShouldWork() { + @PlaywrightTest + void postShouldWork(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(); APIResponse response = request.post(server.PREFIX + "/simple.json"); assertEquals(server.PREFIX + "/simple.json", response.url()); @@ -154,8 +154,8 @@ void postShouldWork() { assertEquals("{\"foo\": \"bar\"}\n", response.text()); } - @Test - void putShouldWork() { + @PlaywrightTest + void putShouldWork(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(); APIResponse response = request.put(server.PREFIX + "/simple.json"); assertEquals(server.PREFIX + "/simple.json", response.url()); @@ -177,8 +177,8 @@ private static List sortedCookieValues(APIRequestContext request) { return request.cookies().stream().map(c -> c.value).sorted().collect(Collectors.toList()); } - @Test - void addCookiesShouldAddCookiesToTheCookieJar() throws ExecutionException, InterruptedException { + @PlaywrightTest + void addCookiesShouldAddCookiesToTheCookieJar(Playwright playwright, Server server) throws ExecutionException, InterruptedException { APIRequestContext request = playwright.request().newContext(); request.addCookies(asList( new Cookie("a", "b").setUrl(server.EMPTY_PAGE), @@ -200,16 +200,16 @@ void addCookiesShouldAddCookiesToTheCookieJar() throws ExecutionException, Inter request.dispose(); } - @Test - void addCookiesShouldValidateCookies() { + @PlaywrightTest + void addCookiesShouldValidateCookies(Playwright playwright) { APIRequestContext request = playwright.request().newContext(); PlaywrightException e = assertThrows(PlaywrightException.class, () -> request.addCookies(asList(new Cookie("a", "b")))); assertTrue(e.getMessage().contains("Cookie should have a url or a domain/path pair"), e.getMessage()); request.dispose(); } - @Test - void cookiesShouldReturnCookiesFilteredByUrls() { + @PlaywrightTest + void cookiesShouldReturnCookiesFilteredByUrls(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(); request.addCookies(asList( new Cookie("a", "b").setDomain("localhost").setPath("/"), @@ -225,8 +225,8 @@ void cookiesShouldReturnCookiesFilteredByUrls() { request.dispose(); } - @Test - void clearCookiesShouldRemoveAllCookies() throws ExecutionException, InterruptedException { + @PlaywrightTest + void clearCookiesShouldRemoveAllCookies(Playwright playwright, Server server) throws ExecutionException, InterruptedException { APIRequestContext request = playwright.request().newContext(); request.addCookies(asList( new Cookie("a", "b").setUrl(server.EMPTY_PAGE), @@ -239,8 +239,8 @@ void clearCookiesShouldRemoveAllCookies() throws ExecutionException, Interrupted request.dispose(); } - @Test - void clearCookiesShouldFilterByNameDomainAndPath() { + @PlaywrightTest + void clearCookiesShouldFilterByNameDomainAndPath(Playwright playwright) { APIRequestContext request = playwright.request().newContext(); request.addCookies(asList( new Cookie("session", "1").setDomain("one.com").setPath("/"), @@ -259,8 +259,8 @@ void clearCookiesShouldFilterByNameDomainAndPath() { request.dispose(); } - @Test - void shouldDisposeGlobalRequest() { + @PlaywrightTest + void shouldDisposeGlobalRequest(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(); APIResponse response = request.get(server.PREFIX + "/simple.json"); assertEquals("{\"foo\": \"bar\"}\n", response.text()); @@ -269,8 +269,8 @@ void shouldDisposeGlobalRequest() { assertTrue(e.getMessage().contains("Response has been disposed"), e.getMessage()); } - @Test - void shouldSupportGlobalUserAgentOption() throws ExecutionException, InterruptedException { + @PlaywrightTest + void shouldSupportGlobalUserAgentOption(Playwright playwright, Server server) throws ExecutionException, InterruptedException { APIRequestContext request = playwright.request().newContext(new APIRequest.NewContextOptions().setUserAgent("My Agent")); Future serverRequest = server.futureRequest("/empty.html"); APIResponse response = request.get(server.EMPTY_PAGE); @@ -279,16 +279,16 @@ void shouldSupportGlobalUserAgentOption() throws ExecutionException, Interrupted assertEquals(asList("My Agent"), serverRequest.get().headers.get("user-agent")); } - @Test - void shouldSupportGlobalTimeoutOption() { + @PlaywrightTest + void shouldSupportGlobalTimeoutOption(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(new APIRequest.NewContextOptions().setTimeout(100)); server.setRoute("/empty.html", exchange -> {}); PlaywrightException e = assertThrows(PlaywrightException.class, () -> request.get(server.EMPTY_PAGE)); assertTrue(e.getMessage().contains("Timeout 100ms exceeded"), e.getMessage()); } - @Test - void shouldPropagateExtraHttpHeadersWithRedirects() throws ExecutionException, InterruptedException { + @PlaywrightTest + void shouldPropagateExtraHttpHeadersWithRedirects(Playwright playwright, Server server) throws ExecutionException, InterruptedException { server.setRedirect("/a/redirect1", "/b/c/redirect2"); server.setRedirect("/b/c/redirect2", "/simple.json"); APIRequestContext request = playwright.request().newContext(new APIRequest.NewContextOptions().setExtraHTTPHeaders(mapOf("My-Secret", "Value"))); @@ -301,8 +301,8 @@ void shouldPropagateExtraHttpHeadersWithRedirects() throws ExecutionException, I assertEquals(asList("Value"), req3.get().headers.get("my-secret")); } - @Test - void shouldSupportGlobalHttpCredentialsOption() { + @PlaywrightTest + void shouldSupportGlobalHttpCredentialsOption(Playwright playwright, Server server) { server.setAuth("/empty.html", "user", "pass"); APIRequestContext request1 = playwright.request().newContext(); APIResponse response1 = request1.get(server.EMPTY_PAGE); @@ -315,8 +315,8 @@ void shouldSupportGlobalHttpCredentialsOption() { request2.dispose(); } - @Test - void shouldReturnErrorWithWrongCredentials() { + @PlaywrightTest + void shouldReturnErrorWithWrongCredentials(Playwright playwright, Server server) { server.setAuth("/empty.html", "user", "pass"); APIRequestContext request = playwright.request().newContext(new APIRequest.NewContextOptions().setHttpCredentials("user", "wrong")); APIResponse response = request.get(server.EMPTY_PAGE); @@ -329,25 +329,25 @@ void shouldUseSocksProxy() { void shouldPassProxyCredentials() { } - @Test + @PlaywrightTest @Disabled("Error: socket hang up") - void shouldSupportGlobalIgnoreHTTPSErrorsOption() { + void shouldSupportGlobalIgnoreHTTPSErrorsOption(Playwright playwright, HttpsServer httpsServer) { APIRequestContext request = playwright.request().newContext(new APIRequest.NewContextOptions().setIgnoreHTTPSErrors(true)); APIResponse response = request.get(httpsServer.EMPTY_PAGE); assertEquals(200, response.status()); } - @Test + @PlaywrightTest @Disabled("Error: socket hang up") - void shouldPropagateIgnoreHTTPSErrorsOnRedirects() { + void shouldPropagateIgnoreHTTPSErrorsOnRedirects(Playwright playwright, HttpsServer httpsServer) { httpsServer.setRedirect("/redir", "/empty.html"); APIRequestContext request = playwright.request().newContext(); APIResponse response = request.get(httpsServer.PREFIX + "/redir", RequestOptions.create().setIgnoreHTTPSErrors(true)); assertEquals(200, response.status()); } - @Test - void shouldReturnServerAddressFromResponse() { + @PlaywrightTest + void shouldReturnServerAddressFromResponse(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(); APIResponse response = request.get(server.EMPTY_PAGE); ServerAddr address = response.serverAddr(); @@ -357,23 +357,23 @@ void shouldReturnServerAddressFromResponse() { request.dispose(); } - @Test - void shouldReturnNullSecurityDetailsForHttpResponse() { + @PlaywrightTest + void shouldReturnNullSecurityDetailsForHttpResponse(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(); APIResponse response = request.get(server.EMPTY_PAGE); assertNull(response.securityDetails()); request.dispose(); } - @Test - void shouldResolveUrlRelativeToGobalBaseURLOption() { + @PlaywrightTest + void shouldResolveUrlRelativeToGobalBaseURLOption(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(new APIRequest.NewContextOptions().setBaseURL(server.PREFIX)); APIResponse response = request.get("/empty.html"); assertEquals(server.EMPTY_PAGE, response.url()); } - @Test - void shouldSetPlaywrightAsUserAgent() throws ExecutionException, InterruptedException { + @PlaywrightTest + void shouldSetPlaywrightAsUserAgent(Playwright playwright, Server server) throws ExecutionException, InterruptedException { APIRequestContext request = playwright.request().newContext(); Future serverRequest = server.futureRequest("/empty.html"); request.get(server.EMPTY_PAGE); @@ -386,8 +386,8 @@ void shouldSetPlaywrightAsUserAgent() throws ExecutionException, InterruptedExce void shouldBeAbleToConstructWithContextOptions() { } - @Test - void shouldReturnEmptyBody() { + @PlaywrightTest + void shouldReturnEmptyBody(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(); APIResponse response = request.get(server.EMPTY_PAGE); byte[] body = response.body(); @@ -398,8 +398,8 @@ void shouldReturnEmptyBody() { assertTrue(e.getMessage().contains("Response has been disposed"), e.getMessage()); } - @Test - void shouldRemoveContentLengthFromReidrectedPostRequests() throws ExecutionException, InterruptedException { + @PlaywrightTest + void shouldRemoveContentLengthFromReidrectedPostRequests(Playwright playwright, Server server) throws ExecutionException, InterruptedException { server.setRedirect("/redirect", "/empty.html"); APIRequestContext request = playwright.request().newContext(); Future req1 = server.futureRequest("/redirect"); @@ -420,8 +420,8 @@ void shouldRemoveContentLengthFromReidrectedPostRequests() throws ExecutionExcep 2021 ); - @Test - void shouldJsonStringifyTypeBodyWhenContentTypeIsApplicationJson() throws ExecutionException, InterruptedException { + @PlaywrightTest + void shouldJsonStringifyTypeBodyWhenContentTypeIsApplicationJson(Playwright playwright, Server server) throws ExecutionException, InterruptedException { APIRequestContext request = playwright.request().newContext(); for (Object value : values) { Future req = server.futureRequest("/empty.html"); @@ -432,8 +432,8 @@ void shouldJsonStringifyTypeBodyWhenContentTypeIsApplicationJson() throws Execut request.dispose(); } - @Test - void shouldNotDoubleStringifyTypeBodyWhenContentTypeIsApplicationJson() throws ExecutionException, InterruptedException { + @PlaywrightTest + void shouldNotDoubleStringifyTypeBodyWhenContentTypeIsApplicationJson(Playwright playwright, Server server) throws ExecutionException, InterruptedException { APIRequestContext request = playwright.request().newContext(); for (Object value : values) { String stringifiedValue = new Gson().toJson(value); @@ -447,8 +447,8 @@ void shouldNotDoubleStringifyTypeBodyWhenContentTypeIsApplicationJson() throws E request.dispose(); } - @Test - void shouldReturnBodyForFailingRequests() { + @PlaywrightTest + void shouldReturnBodyForFailingRequests(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(); for (String method : new String[] {"head", "put", "trace"}) { server.setRoute("/empty.html", exchange -> { @@ -466,8 +466,8 @@ void shouldReturnBodyForFailingRequests() { request.dispose(); } - @Test - void shouldThrowAnErrorWhenMaxRedirectsIsExceeded() { + @PlaywrightTest + void shouldThrowAnErrorWhenMaxRedirectsIsExceeded(Playwright playwright, Server server) { server.setRedirect("/a/redirect1", "/b/c/redirect2"); server.setRedirect("/b/c/redirect2", "/b/c/redirect3"); server.setRedirect("/b/c/redirect3", "/b/c/redirect4"); @@ -486,8 +486,8 @@ void shouldThrowAnErrorWhenMaxRedirectsIsExceeded() { request.dispose(); } - @Test - void shouldUseMaxRedirectsFromFetchWhenProvidedOverridingNewContext() { + @PlaywrightTest + void shouldUseMaxRedirectsFromFetchWhenProvidedOverridingNewContext(Playwright playwright, Server server) { server.setRedirect("/a/redirect1", "/b/c/redirect2"); server.setRedirect("/b/c/redirect2", "/b/c/redirect3"); server.setRedirect("/b/c/redirect3", "/b/c/redirect4"); @@ -502,8 +502,8 @@ void shouldUseMaxRedirectsFromFetchWhenProvidedOverridingNewContext() { request.dispose(); } - @Test - void shouldFollowRedirectsUpToMaxRedirectsLimitSetInNewContext() { + @PlaywrightTest + void shouldFollowRedirectsUpToMaxRedirectsLimitSetInNewContext(Playwright playwright, Server server) { server.setRedirect("/a/redirect1", "/b/c/redirect2"); server.setRedirect("/b/c/redirect2", "/b/c/redirect3"); server.setRedirect("/b/c/redirect3", "/b/c/redirect4"); @@ -527,8 +527,8 @@ void shouldFollowRedirectsUpToMaxRedirectsLimitSetInNewContext() { } } - @Test - void shouldNotFollowRedirectsWhenMaxRedirectsIsSetTo0InNewContext() { + @PlaywrightTest + void shouldNotFollowRedirectsWhenMaxRedirectsIsSetTo0InNewContext(Playwright playwright, Server server) { server.setRedirect("/a/redirect1", "/b/c/redirect2"); server.setRedirect("/b/c/redirect2", "/simple.json"); @@ -542,8 +542,8 @@ void shouldNotFollowRedirectsWhenMaxRedirectsIsSetTo0InNewContext() { request.dispose(); } - @Test - void shouldNotFollowRedirectsWhenMaxRedirectsIsSetTo0() { + @PlaywrightTest + void shouldNotFollowRedirectsWhenMaxRedirectsIsSetTo0(Playwright playwright, Server server) { server.setRedirect("/a/redirect1", "/b/c/redirect2"); server.setRedirect("/b/c/redirect2", "/simple.json"); @@ -557,8 +557,8 @@ void shouldNotFollowRedirectsWhenMaxRedirectsIsSetTo0() { request.dispose(); } - @Test - void shouldThrowAnErrorWhenMaxRedirectsIsLessThan0() { + @PlaywrightTest + void shouldThrowAnErrorWhenMaxRedirectsIsLessThan0(Playwright playwright, Server server) { server.setRedirect("/a/redirect1", "/b/c/redirect2"); server.setRedirect("/b/c/redirect2", "/simple.json"); @@ -572,8 +572,8 @@ void shouldThrowAnErrorWhenMaxRedirectsIsLessThan0() { request.dispose(); } - @Test - void shouldNotModifyRequestMethodInOptions() { + @PlaywrightTest + void shouldNotModifyRequestMethodInOptions(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(); server.setRoute("/empty.html", exchange -> { exchange.getResponseHeaders().set("Content-type", "text/plain"); @@ -602,8 +602,8 @@ void shouldNotModifyRequestMethodInOptions() { request.dispose(); } - @Test - void shouldSupportGlobalHttpCredentialsOptionAndMatchingOrigin() { + @PlaywrightTest + void shouldSupportGlobalHttpCredentialsOptionAndMatchingOrigin(Playwright playwright, Server server) { server.setAuth("/empty.html", "user", "pass"); APIRequestContext request1 = playwright.request().newContext(); APIResponse response1 = request1.get(server.EMPTY_PAGE); @@ -618,8 +618,8 @@ void shouldSupportGlobalHttpCredentialsOptionAndMatchingOrigin() { request2.dispose(); } - @Test - void shouldSupportGlobalHttpCredentialsOptionAndMatchingOriginCaseInsensitive() { + @PlaywrightTest + void shouldSupportGlobalHttpCredentialsOptionAndMatchingOriginCaseInsensitive(Playwright playwright, Server server) { server.setAuth("/empty.html", "user", "pass"); APIRequestContext request1 = playwright.request().newContext(); APIResponse response1 = request1.get(server.EMPTY_PAGE); @@ -634,8 +634,8 @@ void shouldSupportGlobalHttpCredentialsOptionAndMatchingOriginCaseInsensitive() request2.dispose(); } - @Test - void shouldReturnErrorWithCorrectCredentialsAndWrongOriginScheme() { + @PlaywrightTest + void shouldReturnErrorWithCorrectCredentialsAndWrongOriginScheme(Playwright playwright, Server server) { server.setAuth("/empty.html", "user", "pass"); final HttpCredentials httpCredentials = new HttpCredentials("user", "pass"); httpCredentials.setOrigin(Utils.generateDifferentOriginScheme(server)); @@ -644,8 +644,8 @@ void shouldReturnErrorWithCorrectCredentialsAndWrongOriginScheme() { assertEquals(401, response.status()); } - @Test - void shouldReturnErrorWithCorrectCredentialsAndWrongOriginHostname() { + @PlaywrightTest + void shouldReturnErrorWithCorrectCredentialsAndWrongOriginHostname(Playwright playwright, Server server) { server.setAuth("/empty.html", "user", "pass"); final HttpCredentials httpCredentials = new HttpCredentials("user", "pass"); httpCredentials.setOrigin(Utils.generateDifferentOriginHostname(server)); @@ -654,8 +654,8 @@ void shouldReturnErrorWithCorrectCredentialsAndWrongOriginHostname() { assertEquals(401, response.status()); } - @Test - void shouldReturnErrorWithCorrectCredentialsAndWrongOriginPort() { + @PlaywrightTest + void shouldReturnErrorWithCorrectCredentialsAndWrongOriginPort(Playwright playwright, Server server) { server.setAuth("/empty.html", "user", "pass"); final HttpCredentials httpCredentials = new HttpCredentials("user", "pass"); httpCredentials.setOrigin(Utils.generateDifferentOriginPort(server)); @@ -664,8 +664,8 @@ void shouldReturnErrorWithCorrectCredentialsAndWrongOriginPort() { assertEquals(401, response.status()); } - @Test - void shouldSupportHTTPCredentialsSendImmediately() throws InterruptedException, ExecutionException { + @PlaywrightTest + void shouldSupportHTTPCredentialsSendImmediately(Playwright playwright, Server server) throws InterruptedException, ExecutionException { APIRequestContext request = playwright.request().newContext(new APIRequest.NewContextOptions() .setHttpCredentials(new HttpCredentials("user", "pass") .setOrigin(server.PREFIX.toUpperCase()) @@ -688,16 +688,16 @@ void shouldSupportHTTPCredentialsSendImmediately() throws InterruptedException, request.dispose(); } - @Test - void shouldSupportDisposeReason() { + @PlaywrightTest + void shouldSupportDisposeReason(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(); request.dispose(new APIRequestContext.DisposeOptions().setReason("My reason")); PlaywrightException e = assertThrows(PlaywrightException.class, () -> request.get(server.EMPTY_PAGE)); assertTrue(e.getMessage().contains("My reason"), e.getMessage()); } - @Test - public void shouldRetryECONNRESET() { + @PlaywrightTest + public void shouldRetryECONNRESET(Playwright playwright, Server server) { int[] requestCount = {0}; server.setRoute("/test", exchange -> { if (requestCount[0]++ < 3) { @@ -721,8 +721,8 @@ public void shouldRetryECONNRESET() { requestContext.dispose(); } - @Test - public void shouldThrowWhenFailOnStatusCodeIsSetToTrue() { + @PlaywrightTest + public void shouldThrowWhenFailOnStatusCodeIsSetToTrue(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(new APIRequest.NewContextOptions().setFailOnStatusCode(true)); server.setRoute("/empty.html", exchange -> { exchange.getResponseHeaders().set("Content-Length", "10"); @@ -738,8 +738,8 @@ public void shouldThrowWhenFailOnStatusCodeIsSetToTrue() { assertTrue(error.getMessage().contains("404 Not Found")); } - @Test - public void shouldNotThrowWhenFailOnStatusCodeIsSetToFalse() { + @PlaywrightTest + public void shouldNotThrowWhenFailOnStatusCodeIsSetToFalse(Playwright playwright, Server server) { APIRequestContext request = playwright.request().newContext(new APIRequest.NewContextOptions().setFailOnStatusCode(false)); server.setRoute("/empty.html", exchange -> { exchange.getResponseHeaders().set("Content-Length", "10"); @@ -753,8 +753,8 @@ public void shouldNotThrowWhenFailOnStatusCodeIsSetToFalse() { assertEquals(404, response.status()); } - @Test - void shouldSupportMultipleHttpCredentials() { + @PlaywrightTest + void shouldSupportMultipleHttpCredentials(Playwright playwright, Server server) { server.setAuth("/empty.html", "user1", "pass1"); APIRequestContext request = playwright.request().newContext(new APIRequest.NewContextOptions() .setHttpCredentials(asList( @@ -768,8 +768,8 @@ void shouldSupportMultipleHttpCredentials() { request.dispose(); } - @Test - void shouldSupportHTTPCredentialsSendWithMultipleHttpCredentials() throws InterruptedException, ExecutionException { + @PlaywrightTest + void shouldSupportHTTPCredentialsSendWithMultipleHttpCredentials(Playwright playwright, Server server) throws InterruptedException, ExecutionException { APIRequestContext request = playwright.request().newContext(new APIRequest.NewContextOptions() .setHttpCredentials(asList( new HttpCredentials("user1", "pass1").setOrigin(server.PREFIX).setSend(HttpCredentialsSend.ALWAYS), diff --git a/playwright/src/test/java/com/microsoft/playwright/TestHar.java b/playwright/src/test/java/com/microsoft/playwright/TestHar.java index 825b1102d..e891f7cc3 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestHar.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestHar.java @@ -17,10 +17,10 @@ package com.microsoft.playwright; import com.google.gson.*; +import com.microsoft.playwright.fixtures.BrowserName; +import com.microsoft.playwright.fixtures.Fixture; +import com.microsoft.playwright.fixtures.PlaywrightTest; import com.microsoft.playwright.options.HarContentPolicy; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import java.io.*; @@ -30,28 +30,27 @@ import java.util.Map; import java.util.regex.Pattern; +import static com.microsoft.playwright.fixtures.BrowserName.FIREFOX; import static com.microsoft.playwright.options.LoadState.DOMCONTENTLOADED; import static org.junit.jupiter.api.Assertions.*; -public class TestHar extends TestBase { - private PageWithHar pageWithHar; - +public class TestHar { private static JsonObject parseHar(Path harFile) throws IOException { try (FileReader json = new FileReader(harFile.toFile())) { return new Gson().fromJson(json, JsonObject.class).getAsJsonObject("log"); } } - private class PageWithHar { + private static class PageWithHar implements AutoCloseable { final Path harFile; final BrowserContext context; final Page page; - PageWithHar() throws IOException { - this(new Browser.NewContextOptions(), null); + PageWithHar(Browser browser) throws IOException { + this(browser, new Browser.NewContextOptions(), null); } - PageWithHar(Browser.NewContextOptions options, Path harFilePath) throws IOException { + PageWithHar(Browser browser, Browser.NewContextOptions options, Path harFilePath) throws IOException { harFile = harFilePath == null ? Files.createTempFile("test-", ".har") : harFilePath; context = browser.newContext(options .setRecordHarPath(harFile).setIgnoreHTTPSErrors(true)); @@ -68,44 +67,40 @@ Map parseZip() throws IOException { return Utils.parseZip(harFile); } - void dispose() throws IOException { + @Override + public void close() throws IOException { context.close(); Files.deleteIfExists(harFile); } } - @BeforeEach - void createPageWithHar() throws IOException { - pageWithHar = new PageWithHar(); - } - - @AfterEach - void deletePageWithHar() throws IOException { - pageWithHar.dispose(); + @Fixture + PageWithHar pageWithHar(Browser browser) throws IOException { + return new PageWithHar(browser); } void shouldThrowWithoutPath() { // not applicable in java } - @Test - void shouldHaveVersionAndCreator() throws IOException { + @PlaywrightTest + void shouldHaveVersionAndCreator(Server server, PageWithHar pageWithHar) throws IOException { pageWithHar.page.navigate(server.EMPTY_PAGE); JsonObject log = pageWithHar.log(); assertEquals("1.2", log.get("version").getAsString()); assertEquals("Playwright", log.getAsJsonObject("creator").get("name").getAsString()); } - @Test - void shouldHaveBrowser() throws IOException { + @PlaywrightTest + void shouldHaveBrowser(Browser browser, BrowserType browserType, Server server, PageWithHar pageWithHar) throws IOException { pageWithHar.page.navigate(server.EMPTY_PAGE); JsonObject log = pageWithHar.log(); assertEquals(browserType.name(), log.getAsJsonObject("browser").get("name").getAsString().toLowerCase()); assertEquals(browser.version(), log.getAsJsonObject("browser").get("version").getAsString()); } - @Test - void shouldHavePages() throws IOException { + @PlaywrightTest + void shouldHavePages(PageWithHar pageWithHar) throws IOException { pageWithHar.page.navigate("data:text/html,Hello"); // For data: load comes before domcontentloaded... pageWithHar.page.waitForLoadState(DOMCONTENTLOADED); @@ -120,8 +115,8 @@ void shouldHavePages() throws IOException { assertTrue(pageEntry.getAsJsonObject("pageTimings").get("onLoad").getAsDouble() > 0); } - @Test - void shouldHavePagesInPersistentContext() throws IOException { + @PlaywrightTest + void shouldHavePagesInPersistentContext(BrowserType browserType, PageWithHar pageWithHar) throws IOException { Path harPath = pageWithHar.harFile; Path userDataDir = Files.createTempDirectory("user-data-dir-"); BrowserContext context = browserType.launchPersistentContext(userDataDir, @@ -143,8 +138,8 @@ void shouldHavePagesInPersistentContext() throws IOException { assertEquals("Hello", pageEntry.get("title").getAsString()); } - @Test - void shouldIncludeRequest() throws IOException { + @PlaywrightTest + void shouldIncludeRequest(Server server, PageWithHar pageWithHar) throws IOException { pageWithHar.page.navigate(server.EMPTY_PAGE); JsonObject log = pageWithHar.log(); assertEquals(1, log.getAsJsonArray("entries").size()); @@ -165,8 +160,8 @@ void shouldIncludeRequest() throws IOException { assertTrue(foundUserAgentHeader); } - @Test - void shouldIncludeResponse() throws IOException { + @PlaywrightTest + void shouldIncludeResponse(Server server, PageWithHar pageWithHar) throws IOException { pageWithHar.page.navigate(server.EMPTY_PAGE); JsonObject log = pageWithHar.log(); JsonObject entry = log.getAsJsonArray("entries").get(0).getAsJsonObject(); @@ -186,8 +181,8 @@ void shouldIncludeResponse() throws IOException { assertTrue(foundUserContentType); } - @Test - void shouldFilterByGlob(@TempDir Path tmpDir) throws IOException { + @PlaywrightTest + void shouldFilterByGlob(Browser browser, Server server, BrowserName browserName, @TempDir Path tmpDir) throws IOException { Path harPath = tmpDir.resolve("test.har"); BrowserContext context = browser.newContext(new Browser.NewContextOptions() .setBaseURL(server.PREFIX) @@ -200,7 +195,7 @@ void shouldFilterByGlob(@TempDir Path tmpDir) throws IOException { JsonObject log = parseHar(harPath); JsonArray entries = log.getAsJsonArray("entries"); // There are 2 entries for the same .css request in firefox. - if (isFirefox()) { + if (browserName == FIREFOX) { assertEquals(2, entries.size()); } else { assertEquals(1, entries.size()); @@ -208,8 +203,8 @@ void shouldFilterByGlob(@TempDir Path tmpDir) throws IOException { assertTrue(entries.get(0).getAsJsonObject().getAsJsonObject("request").get("url").getAsString().endsWith("one-style.css")); } - @Test - void shouldFilterByRegexp(@TempDir Path tmpDir) throws IOException { + @PlaywrightTest + void shouldFilterByRegexp(Browser browser, Server server, @TempDir Path tmpDir) throws IOException { Path harPath = tmpDir.resolve("test.har"); BrowserContext context = browser.newContext(new Browser.NewContextOptions() .setBaseURL(server.PREFIX) @@ -225,15 +220,15 @@ void shouldFilterByRegexp(@TempDir Path tmpDir) throws IOException { assertTrue(entries.get(0).getAsJsonObject().getAsJsonObject("request").get("url").getAsString().endsWith("har.html")); } - @Test - void shouldOmitContent(@TempDir Path tmpDir) throws IOException { + @PlaywrightTest + void shouldOmitContent(Server server, Browser browser, @TempDir Path tmpDir) throws IOException { Path harPath = tmpDir.resolve("test.har"); - PageWithHar pageWithHar = new PageWithHar(new Browser.NewContextOptions() + PageWithHar pageWithHar = new PageWithHar(browser, new Browser.NewContextOptions() .setRecordHarContent(HarContentPolicy.OMIT), harPath); pageWithHar.page.navigate(server.PREFIX + "/har.html"); pageWithHar.page.evaluate("() => fetch('/pptr.png').then(r => r.arrayBuffer())"); JsonObject log = pageWithHar.log(); - pageWithHar.dispose(); + pageWithHar.close(); JsonArray entries = log.getAsJsonArray("entries"); assertFalse(entries.get(0).getAsJsonObject() .getAsJsonObject("response") @@ -245,15 +240,15 @@ void shouldOmitContent(@TempDir Path tmpDir) throws IOException { .has("_file")); } - @Test - void shouldOmitContentLegacy(@TempDir Path tmpDir) throws IOException { + @PlaywrightTest + void shouldOmitContentLegacy(Server server, Browser browser, @TempDir Path tmpDir) throws IOException { Path harPath = tmpDir.resolve("test.har"); - PageWithHar pageWithHar = new PageWithHar(new Browser.NewContextOptions() + PageWithHar pageWithHar = new PageWithHar(browser, new Browser.NewContextOptions() .setRecordHarOmitContent(true), harPath); pageWithHar.page.navigate(server.PREFIX + "/har.html"); pageWithHar.page.evaluate("() => fetch('/pptr.png').then(r => r.arrayBuffer())"); JsonObject log = pageWithHar.log(); - pageWithHar.dispose(); + pageWithHar.close(); JsonArray entries = log.getAsJsonArray("entries"); assertFalse(entries.get(0).getAsJsonObject() .getAsJsonObject("response") @@ -265,16 +260,16 @@ void shouldOmitContentLegacy(@TempDir Path tmpDir) throws IOException { .has("_file")); } - @Test - void shouldAttachContent(@TempDir Path tmpDir) throws IOException { + @PlaywrightTest + void shouldAttachContent(Server server, Browser browser, @TempDir Path tmpDir) throws IOException { Path harPath = tmpDir.resolve("test.har.zip"); - PageWithHar pageWithHar = new PageWithHar(new Browser.NewContextOptions() + PageWithHar pageWithHar = new PageWithHar(browser, new Browser.NewContextOptions() .setRecordHarContent(HarContentPolicy.ATTACH), harPath); pageWithHar.page.navigate(server.PREFIX + "/har.html"); pageWithHar.page.evaluate("() => fetch('/pptr.png').then(r => r.arrayBuffer())"); Map zip = pageWithHar.parseZip(); JsonObject log = new Gson().fromJson(new InputStreamReader(new ByteArrayInputStream(zip.get("har.har"))), JsonObject.class).getAsJsonObject("log"); - pageWithHar.dispose(); + pageWithHar.close(); JsonArray entries = log.getAsJsonArray("entries"); { diff --git a/playwright/src/test/java/com/microsoft/playwright/TestJavaSourceLocationInConstructor.java b/playwright/src/test/java/com/microsoft/playwright/TestJavaSourceLocationInConstructor.java index 223939866..7be989e28 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestJavaSourceLocationInConstructor.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestJavaSourceLocationInConstructor.java @@ -16,7 +16,9 @@ package com.microsoft.playwright; -import org.junit.jupiter.api.Test; +import com.microsoft.playwright.fixtures.Fixture; +import com.microsoft.playwright.fixtures.PlaywrightTest; +import com.microsoft.playwright.fixtures.Scope; import org.junit.jupiter.api.io.TempDir; import java.io.File; @@ -31,16 +33,16 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertEquals; -public class TestJavaSourceLocationInConstructor extends TestBase { +public class TestJavaSourceLocationInConstructor { private static final String SRC_DIRS = System.getenv("PLAYWRIGHT_JAVA_SRC") == null ? "src/test/java" : System.getenv("PLAYWRIGHT_JAVA_SRC"); - @Override - Playwright.CreateOptions playwrightOptions() { + @Fixture(scope = Scope.WORKER) + static Playwright.CreateOptions createOptions() { return new Playwright.CreateOptions().setEnv(mapOf("PLAYWRIGHT_JAVA_SRC", SRC_DIRS)); } - @Test - void shouldSupportSourcesLocationPassedToPlaywrightCreate(@TempDir Path tmpDir) throws IOException { + @PlaywrightTest + void shouldSupportSourcesLocationPassedToPlaywrightCreate(Page page, BrowserContext context, Server server, @TempDir Path tmpDir) throws IOException { context.tracing().start(new Tracing.StartOptions().setSources(true)); page.navigate(server.EMPTY_PAGE); page.setContent(""); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAnyFrame.java b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAnyFrame.java index 59d5b0114..b6aee4e9b 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAnyFrame.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAnyFrame.java @@ -17,15 +17,15 @@ package com.microsoft.playwright; import com.microsoft.playwright.assertions.LocatorAssertions; +import com.microsoft.playwright.fixtures.PlaywrightTest; import com.microsoft.playwright.options.AriaRole; import com.microsoft.playwright.options.WaitForSelectorState; -import org.junit.jupiter.api.Test; import org.opentest4j.AssertionFailedError; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; import static org.junit.jupiter.api.Assertions.*; -public class TestLocatorAnyFrame extends TestBase { +public class TestLocatorAnyFrame { private static void routePage(Page page, String url, String body) { page.route("**/" + url, route -> route.fulfill(new Route.FulfillOptions().setBody(body).setContentType("text/html"))); } @@ -41,8 +41,8 @@ private static void waitForAllFrames(Page page, int frameCount, String selector) } } - @Test - void shouldClickAButtonInsideAnIframe() { + @PlaywrightTest + void shouldClickAButtonInsideAnIframe(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", ""); page.navigate(server.EMPTY_PAGE); @@ -50,8 +50,8 @@ void shouldClickAButtonInsideAnIframe() { assertEquals(true, page.frames().get(1).evaluate("() => window.__clicked")); } - @Test - void shouldClickAButtonInTheMainFrame() { + @PlaywrightTest + void shouldClickAButtonInTheMainFrame(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", "
          No buttons here
          "); page.navigate(server.EMPTY_PAGE); @@ -59,8 +59,8 @@ void shouldClickAButtonInTheMainFrame() { assertEquals(true, page.evaluate("() => window.__clicked")); } - @Test - void shouldFailClickWhenElementsMatchInMultipleFrames() { + @PlaywrightTest + void shouldFailClickWhenElementsMatchInMultipleFrames(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", ""); routePage(page, "b.html", ""); @@ -71,8 +71,8 @@ void shouldFailClickWhenElementsMatchInMultipleFrames() { assertTrue(e.getMessage().contains("frameLocator() matched elements in multiple frames"), e.getMessage()); } - @Test - void shouldFailClickUponStrictModeViolationInsideASingleFrame() { + @PlaywrightTest + void shouldFailClickUponStrictModeViolationInsideASingleFrame(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", ""); page.navigate(server.EMPTY_PAGE); @@ -82,8 +82,8 @@ void shouldFailClickUponStrictModeViolationInsideASingleFrame() { assertTrue(e.getMessage().contains("strict mode violation"), e.getMessage()); } - @Test - void shouldTimeOutOnClickWhenThereAreNoMatches() { + @PlaywrightTest + void shouldTimeOutOnClickWhenThereAreNoMatches(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", "
          Nothing here
          "); page.navigate(server.EMPTY_PAGE); @@ -92,8 +92,8 @@ void shouldTimeOutOnClickWhenThereAreNoMatches() { assertTrue(e.getMessage().contains("Timeout 1000ms exceeded"), e.getMessage()); } - @Test - void shouldCountElementsInASingleFrame() { + @PlaywrightTest + void shouldCountElementsInASingleFrame(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", "
          1
          2
          3
          "); page.navigate(server.EMPTY_PAGE); @@ -102,8 +102,8 @@ void shouldCountElementsInASingleFrame() { assertEquals(0, page.frameLocator().locator("button").count()); } - @Test - void shouldFailCountWhenElementsMatchInMultipleFrames() { + @PlaywrightTest + void shouldFailCountWhenElementsMatchInMultipleFrames(Page page, Server server) { routePage(page, "empty.html", "
          main
          "); routePage(page, "a.html", "
          child
          "); page.navigate(server.EMPTY_PAGE); @@ -112,8 +112,8 @@ void shouldFailCountWhenElementsMatchInMultipleFrames() { assertTrue(e.getMessage().contains("frameLocator() matched elements in multiple frames"), e.getMessage()); } - @Test - void shouldSupportHasCount() { + @PlaywrightTest + void shouldSupportHasCount(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", "onetwo"); page.navigate(server.EMPTY_PAGE); @@ -121,8 +121,8 @@ void shouldSupportHasCount() { assertThat(page.frameLocator().locator("button")).hasCount(0); } - @Test - void shouldWaitForAFrameToAppearWithHasCount() { + @PlaywrightTest + void shouldWaitForAFrameToAppearWithHasCount(Page page, Server server) { routePage(page, "empty.html", "
          No frames yet
          "); routePage(page, "a.html", "onetwo"); page.navigate(server.EMPTY_PAGE); @@ -136,8 +136,8 @@ void shouldWaitForAFrameToAppearWithHasCount() { assertThat(page.frameLocator().locator("span")).hasCount(2); } - @Test - void shouldFailHasCountWhenElementsMatchInMultipleFrames() { + @PlaywrightTest + void shouldFailHasCountWhenElementsMatchInMultipleFrames(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", "one"); routePage(page, "b.html", "two"); @@ -148,24 +148,24 @@ void shouldFailHasCountWhenElementsMatchInMultipleFrames() { assertTrue(e.getMessage().contains("frameLocator() matched elements in multiple frames"), e.getMessage()); } - @Test - void shouldSupportHasText() { + @PlaywrightTest + void shouldSupportHasText(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", "
          Hello iframe
          "); page.navigate(server.EMPTY_PAGE); assertThat(page.frameLocator().locator("div")).hasText("Hello iframe"); } - @Test - void shouldSupportEvaluate() { + @PlaywrightTest + void shouldSupportEvaluate(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", ""); page.navigate(server.EMPTY_PAGE); assertEquals("one", page.frameLocator().locator("button").evaluate("e => e.textContent")); } - @Test - void shouldSupportFirstLastNth() { + @PlaywrightTest + void shouldSupportFirstLastNth(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", "onetwothree"); page.navigate(server.EMPTY_PAGE); @@ -174,16 +174,16 @@ void shouldSupportFirstLastNth() { assertThat(page.frameLocator().locator("span").nth(1)).hasText("two"); } - @Test - void shouldNotAllowNthFrameOnAnyFrameLocator() { + @PlaywrightTest + void shouldNotAllowNthFrameOnAnyFrameLocator(Page page) { PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.frameLocator().first()); assertTrue(e.getMessage().contains("Selecting the nth frame is not allowed on frameLocator()"), e.getMessage()); assertThrows(PlaywrightException.class, () -> page.frameLocator().last()); assertThrows(PlaywrightException.class, () -> page.frameLocator().nth(1)); } - @Test - void shouldSupportTwoFrameLocators() { + @PlaywrightTest + void shouldSupportTwoFrameLocators(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", ""); routePage(page, "b.html", ""); @@ -192,8 +192,8 @@ void shouldSupportTwoFrameLocators() { assertThat(page.frameLocator().frameLocator("#x").frameLocator("#y").locator("button")).hasText("bottom"); } - @Test - void shouldSupportLocatorBeforeFrameLocator() { + @PlaywrightTest + void shouldSupportLocatorBeforeFrameLocator(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", "
          "); routePage(page, "b.html", ""); @@ -202,8 +202,8 @@ void shouldSupportLocatorBeforeFrameLocator() { assertThat(page.frameLocator().locator("section").frameLocator("iframe").locator("button")).hasText("in-section"); } - @Test - void shouldSupportOwnerOfAFrameLocator() { + @PlaywrightTest + void shouldSupportOwnerOfAFrameLocator(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", ""); routePage(page, "b.html", ""); @@ -211,8 +211,8 @@ void shouldSupportOwnerOfAFrameLocator() { assertEquals("target", page.frameLocator().frameLocator("#target").owner().getAttribute("id")); } - @Test - void shouldSupportContentFrameAfterAnyFrameLocator() { + @PlaywrightTest + void shouldSupportContentFrameAfterAnyFrameLocator(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", ""); routePage(page, "b.html", ""); @@ -220,8 +220,8 @@ void shouldSupportContentFrameAfterAnyFrameLocator() { assertThat(page.frameLocator().locator("#my-frame").contentFrame().getByRole(AriaRole.BUTTON)).hasText("inside"); } - @Test - void shouldWorkOnFrame() { + @PlaywrightTest + void shouldWorkOnFrame(Page page, Server server) { routePage(page, "empty.html", ""); routePage(page, "a.html", ""); routePage(page, "b.html", ""); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java index 27fa7dc2f..c0d7db266 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java @@ -17,22 +17,21 @@ package com.microsoft.playwright; import com.microsoft.playwright.assertions.LocatorAssertions; -import com.microsoft.playwright.assertions.PlaywrightAssertions; import com.microsoft.playwright.assertions.LocatorAssertions.ContainsClassOptions; - -import org.junit.jupiter.api.Test; +import com.microsoft.playwright.assertions.PlaywrightAssertions; +import com.microsoft.playwright.fixtures.PlaywrightTest; import org.opentest4j.AssertionFailedError; -import static java.util.Arrays.asList; import java.util.regex.Pattern; import static com.microsoft.playwright.Utils.mapOf; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; +import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.*; -public class TestLocatorAssertions extends TestBase { - @Test - void containsTextWRegexPass() { +public class TestLocatorAssertions { + @PlaywrightTest + void containsTextWRegexPass(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); assertThat(locator).containsText(Pattern.compile("ex")); @@ -40,29 +39,29 @@ void containsTextWRegexPass() { assertThat(locator).containsText(Pattern.compile("ext cont")); } - @Test - void containsTextWRegexCaseInsensitivePass() { + @PlaywrightTest + void containsTextWRegexCaseInsensitivePass(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); assertThat(locator).containsText(Pattern.compile("text", Pattern.CASE_INSENSITIVE)); } - @Test - void containsTextWRegexMultilinePass() { + @PlaywrightTest + void containsTextWRegexMultilinePass(Page page) { page.setContent("
          Text \nContent
          "); Locator locator = page.locator("#node"); assertThat(locator).containsText(Pattern.compile("^Content", Pattern.MULTILINE)); } - @Test - void containsTextWRegexDotAllPass() { + @PlaywrightTest + void containsTextWRegexDotAllPass(Page page) { page.setContent("
          foo\nbar
          "); Locator locator = page.locator("#node"); assertThat(locator).containsText(Pattern.compile("foo.bar", Pattern.DOTALL)); } - @Test - void containsTextWRegexFail() { + @PlaywrightTest + void containsTextWRegexFail(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -73,8 +72,8 @@ void containsTextWRegexFail() { assertTrue(e.getMessage().contains("Locator expected to contain regex"), e.getMessage()); } - @Test - void containsTextWTextPass() { + @PlaywrightTest + void containsTextWTextPass(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); assertThat(locator).containsText("Text"); @@ -86,8 +85,8 @@ void containsTextWTextPass() { assertThat(locator).not().containsText("TEXT", new LocatorAssertions.ContainsTextOptions().setIgnoreCase(false)); } - @Test - void containsTextWTextArrayPass() { + @PlaywrightTest + void containsTextWTextArrayPass(Page page) { page.setContent("
          Text \n1
          Text2
          Text3
          "); Locator locator = page.locator("div"); assertThat(locator).containsText(new String[] {"ext 1", "ext3"}); @@ -95,8 +94,8 @@ void containsTextWTextArrayPass() { assertThat(locator).containsText(new String[] {"EXT 1", "eXt3"}, new LocatorAssertions.ContainsTextOptions().setIgnoreCase(true)); } - @Test - void hasTextWRegexPass() { + @PlaywrightTest + void hasTextWRegexPass(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); assertThat(locator).hasText(Pattern.compile("Te.t")); @@ -108,8 +107,8 @@ void hasTextWRegexPass() { assertThat(locator).not().hasText(Pattern.compile("text content", Pattern.CASE_INSENSITIVE), new LocatorAssertions.HasTextOptions().setIgnoreCase(false)); } - @Test - void hasTextWRegexFail() { + @PlaywrightTest + void hasTextWRegexFail(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -120,8 +119,8 @@ void hasTextWRegexFail() { assertTrue(e.getMessage().contains("Locator expected to have text matching regex"), e.getMessage()); } - @Test - void hasTextWTextPass() { + @PlaywrightTest + void hasTextWTextPass(Page page) { page.setContent("
          Text \ncontent 
          "); Locator locator = page.locator("#node"); // Should normalize whitespace. @@ -132,8 +131,8 @@ void hasTextWTextPass() { assertThat(locator).not().hasText("TEXT", new LocatorAssertions.HasTextOptions().setIgnoreCase(false)); } - @Test - void hasTextWTextFail() { + @PlaywrightTest + void hasTextWTextFail(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); // Should normalize whitespace. @@ -145,15 +144,15 @@ void hasTextWTextFail() { assertTrue(e.getMessage().contains("Locator expected to have text"), e.getMessage()); } - @Test - void hasTextWTextInnerTextPass() { + @PlaywrightTest + void hasTextWTextInnerTextPass(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); assertThat(locator).hasText("Text content", new LocatorAssertions.HasTextOptions().setUseInnerText(true)); } - @Test - void hasTextWTextArrayPass() { + @PlaywrightTest + void hasTextWTextArrayPass(Page page) { page.setContent("
          Text \n1
          Text 2a
          "); Locator locator = page.locator("div"); // Should normalize whitespace. @@ -162,32 +161,32 @@ void hasTextWTextArrayPass() { assertThat(locator).hasText(new String[] {"tEXT 1", "TExt 2A"}, new LocatorAssertions.HasTextOptions().setIgnoreCase(true)); } - @Test - void hasTextWTextArrayPassEmpty() { + @PlaywrightTest + void hasTextWTextArrayPassEmpty(Page page) { page.setContent("
          "); Locator locator = page.locator("p"); // Should normalize whitespace. assertThat(locator).hasText(new String[] {}); } - @Test - void hasTextWTextArrayPassNotEmpty() { + @PlaywrightTest + void hasTextWTextArrayPassNotEmpty(Page page) { page.setContent("

          Test

          "); Locator locator = page.locator("div"); // Should normalize whitespace. assertThat(locator).not().hasText(new String[] {}); } - @Test - void hasTextWTextArrayPassOnEmpty() { + @PlaywrightTest + void hasTextWTextArrayPassOnEmpty(Page page) { page.setContent("
          "); Locator locator = page.locator("p"); // Should normalize whitespace. assertThat(locator).not().hasText(new String[] {"Test"}); } - @Test - void hasTextWTextArrayFailOnNotEmpty() { + @PlaywrightTest + void hasTextWTextArrayFailOnNotEmpty(Page page) { page.setContent("
          "); Locator locator = page.locator("p"); // Should normalize whitespace. @@ -199,8 +198,8 @@ void hasTextWTextArrayFailOnNotEmpty() { assertTrue(e.getMessage().contains("Locator expected not to have text"), e.getMessage()); } - @Test - void hasTextWTextArrayPassLazyPass() { + @PlaywrightTest + void hasTextWTextArrayPassLazyPass(Page page) { page.setContent("
          "); Locator locator = page.locator("p"); page.evaluate("setTimeout(() => {\n" + @@ -210,8 +209,8 @@ void hasTextWTextArrayPassLazyPass() { assertThat(locator).hasText(new String[] {"Text 1", "Text 2"}, new LocatorAssertions.HasTextOptions().setTimeout(1000)); } - @Test - void hasTextWTextArrayFail() { + @PlaywrightTest + void hasTextWTextArrayFail(Page page) { page.setContent("
          Text 1
          Text 3
          "); Locator locator = page.locator("div"); page.evaluate("setTimeout(() => {\n" + @@ -227,16 +226,16 @@ void hasTextWTextArrayFail() { assertTrue(e.getMessage().contains("Received: [Text 1, Text 3]"), e.getMessage()); } - @Test - void hasTextWRegExArrayPass() { + @PlaywrightTest + void hasTextWRegExArrayPass(Page page) { page.setContent("
          Text \n1
          Text 2a
          "); Locator locator = page.locator("div"); // Should normalize whitespace. assertThat(locator).hasText(new Pattern[] {Pattern.compile( "Text \n1"), Pattern.compile("Text \\d+a")}); } - @Test - void hasTextWRegExArrayFail() { + @PlaywrightTest + void hasTextWRegExArrayFail(Page page) { page.setContent("
          Text 1
          Text 3
          "); Locator locator = page.locator("div"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -248,23 +247,23 @@ void hasTextWRegExArrayFail() { assertTrue(e.getMessage().contains("Locator expected to have text"), e.getMessage()); } - @Test - void hasAttributeTextIgnoreCase() { + @PlaywrightTest + void hasAttributeTextIgnoreCase(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#NoDe"); assertThat(locator).hasAttribute("id", "node", new LocatorAssertions.HasAttributeOptions().setIgnoreCase(true)); assertThat(locator).not().hasAttribute("id", "node"); } - @Test - void hasAttributeTextPass() { + @PlaywrightTest + void hasAttributeTextPass(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); assertThat(locator).hasAttribute("id", "node"); } - @Test - void hasAttributeTextFail() { + @PlaywrightTest + void hasAttributeTextFail(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -275,15 +274,15 @@ void hasAttributeTextFail() { assertTrue(e.getMessage().contains("Locator expected to have attribute 'id'\nExpected: foo\nReceived: node"), e.getMessage()); } - @Test - void hasAttributeRegExpPass() { + @PlaywrightTest + void hasAttributeRegExpPass(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); assertThat(locator).hasAttribute("id", Pattern.compile("n..e")); } - @Test - void hasAttributeRegExpFail() { + @PlaywrightTest + void hasAttributeRegExpFail(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -294,15 +293,15 @@ void hasAttributeRegExpFail() { assertTrue(e.getMessage().contains("Locator expected to have attribute 'id' matching regex\nExpected: .Nod..\nReceived: node"), e.getMessage()); } - @Test - void hasClassTextPass() { + @PlaywrightTest + void hasClassTextPass(Page page) { page.setContent("
          "); Locator locator = page.locator("div"); assertThat(locator).hasClass("foo bar baz"); } - @Test - void hasClassTextFail() { + @PlaywrightTest + void hasClassTextFail(Page page) { page.setContent("
          "); Locator locator = page.locator("div"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -313,15 +312,15 @@ void hasClassTextFail() { assertTrue(e.getMessage().contains("Locator expected to have class"), e.getMessage()); } - @Test - void hasClassRegExpPass() { + @PlaywrightTest + void hasClassRegExpPass(Page page) { page.setContent("
          "); Locator locator = page.locator("div"); assertThat(locator).hasClass(Pattern.compile("foo.* baz")); } - @Test - void hasClassRegExpFail() { + @PlaywrightTest + void hasClassRegExpFail(Page page) { page.setContent("
          "); Locator locator = page.locator("div"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -332,15 +331,15 @@ void hasClassRegExpFail() { assertTrue(e.getMessage().contains("Locator expected to have class matching regex"), e.getMessage()); } - @Test - void hasClassTextArrayPass() { + @PlaywrightTest + void hasClassTextArrayPass(Page page) { page.setContent("
          "); Locator locator = page.locator("div"); assertThat(locator).hasClass(new String[] {"foo", "bar", "baz"}); } - @Test - void hasClassTextArrayFail() { + @PlaywrightTest + void hasClassTextArrayFail(Page page) { page.setContent("
          "); Locator locator = page.locator("div"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -351,15 +350,15 @@ void hasClassTextArrayFail() { assertTrue(e.getMessage().contains("Locator expected to have class"), e.getMessage()); } - @Test - void hasClassRegExpArrayPass() { + @PlaywrightTest + void hasClassRegExpArrayPass(Page page) { page.setContent("
          "); Locator locator = page.locator("div"); assertThat(locator).hasClass(new Pattern[] {Pattern.compile("fo.*"), Pattern.compile(".ar"), Pattern.compile("baz")}); } - @Test - void hasClassRegExpArrayFail() { + @PlaywrightTest + void hasClassRegExpArrayFail(Page page) { page.setContent("
          "); Locator locator = page.locator("div"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -370,15 +369,15 @@ void hasClassRegExpArrayFail() { assertTrue(e.getMessage().contains("Locator expected to have class matching regex"), e.getMessage()); } - @Test - void hasCountPass() { + @PlaywrightTest + void hasCountPass(Page page) { page.setContent(""); Locator locator = page.locator("option"); assertThat(locator).hasCount(2); } - @Test - void hasCountFail() { + @PlaywrightTest + void hasCountFail(Page page) { page.setContent(""); Locator locator = page.locator("option"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -389,23 +388,23 @@ void hasCountFail() { assertTrue(e.getMessage().contains("Locator expected to have count"), e.getMessage()); } - @Test - void hasCountPassZero() { + @PlaywrightTest + void hasCountPassZero(Page page) { page.setContent("
          "); Locator locator = page.locator("span"); assertThat(locator).hasCount(0); assertThat(locator).not().hasCount(1); } - @Test - void hasCSSPass() { + @PlaywrightTest + void hasCSSPass(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); assertThat(locator).hasCSS("color", "rgb(255, 0, 0)"); } - @Test - void hasCSSFail() { + @PlaywrightTest + void hasCSSFail(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -416,15 +415,15 @@ void hasCSSFail() { assertTrue(e.getMessage().contains("Locator expected to have CSS property 'color'"), e.getMessage()); } - @Test - void hasCSSRegExPass() { + @PlaywrightTest + void hasCSSRegExPass(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); assertThat(locator).hasCSS("color", Pattern.compile("rgb.*")); } - @Test - void hasCSSRegExFail() { + @PlaywrightTest + void hasCSSRegExFail(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -435,15 +434,15 @@ void hasCSSRegExFail() { assertTrue(e.getMessage().contains("Locator expected to have CSS property 'color' matching regex"), e.getMessage()); } - @Test - void hasIdPass() { + @PlaywrightTest + void hasIdPass(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); assertThat(locator).hasId("node"); } - @Test - void hasIdFail() { + @PlaywrightTest + void hasIdFail(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -454,16 +453,16 @@ void hasIdFail() { assertTrue(e.getMessage().contains("Locator expected to have ID"), e.getMessage()); } - @Test - void hasJSPropertyPass() { + @PlaywrightTest + void hasJSPropertyPass(Page page) { page.setContent("
          "); page.evalOnSelector("div", "e => e.foo = { a: 1, b: 'string' }"); Locator locator = page.locator("div"); assertThat(locator).hasJSProperty("foo", mapOf("a", 1, "b", "string")); } - @Test - void hasJSPropertyNumberFail() { + @PlaywrightTest + void hasJSPropertyNumberFail(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); page.evalOnSelector("div", "e => e.foo = 2021"); @@ -475,8 +474,8 @@ void hasJSPropertyNumberFail() { assertTrue(e.getMessage().contains("Locator expected to have JavaScript property 'foo'"), e.getMessage()); } - @Test - void hasJSPropertyObjectFail() { + @PlaywrightTest + void hasJSPropertyObjectFail(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); page.evalOnSelector("div", "e => e.foo = { a: 1, b: 'string' }"); @@ -488,8 +487,8 @@ void hasJSPropertyObjectFail() { assertTrue(e.getMessage().contains("Locator expected to have JavaScript property 'foo'"), e.getMessage()); } - @Test - void hasJSPropertyStringFail() { + @PlaywrightTest + void hasJSPropertyStringFail(Page page) { page.setContent("
          Text content
          "); Locator locator = page.locator("#node"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -500,16 +499,16 @@ void hasJSPropertyStringFail() { assertTrue(e.getMessage().contains("Locator expected to have JavaScript property 'id'"), e.getMessage()); } - @Test - void hasValueTextPass() { + @PlaywrightTest + void hasValueTextPass(Page page) { page.setContent(""); Locator locator = page.locator("#node"); locator.fill("Text content"); assertThat(locator).hasValue("Text content"); } - @Test - void hasValueTextFail() { + @PlaywrightTest + void hasValueTextFail(Page page) { page.setContent(""); Locator locator = page.locator("#node"); locator.fill("Text content"); @@ -521,24 +520,24 @@ void hasValueTextFail() { assertTrue(e.getMessage().contains("Locator expected to have value"), e.getMessage()); } - @Test - void hasValueRegExpPass() { + @PlaywrightTest + void hasValueRegExpPass(Page page) { page.setContent(""); Locator locator = page.locator("#node"); locator.fill("Text content"); assertThat(locator).hasValue(Pattern.compile("Text")); } - @Test - void hasValueRegExpPassWithNot() { + @PlaywrightTest + void hasValueRegExpPassWithNot(Page page) { page.setContent(""); Locator locator = page.locator("#node"); locator.fill("Text content"); assertThat(locator).not().hasValue(Pattern.compile("Text2")); } - @Test - void hasValueRegExpFail() { + @PlaywrightTest + void hasValueRegExpFail(Page page) { page.setContent(""); Locator locator = page.locator("#node"); locator.fill("Text content"); @@ -550,8 +549,8 @@ void hasValueRegExpFail() { assertTrue(e.getMessage().contains("Locator expected to have value matching regex"), e.getMessage()); } - @Test - void hasValuesWorksWithText() { + @PlaywrightTest + void hasValuesWorksWithText(Page page) { page.setContent("\n" + " \n" + @@ -575,8 +574,8 @@ void hasValuesFollowsLabels() { assertThat(locator).hasValues(new String[]{"R", "G"}); } - @Test - void hasValuesExactMatchWithText() { + @PlaywrightTest + void hasValuesExactMatchWithText(Page page) { page.setContent("\n" + " \n" + " \n" + @@ -603,8 +602,8 @@ void hasValuesWorksWithRegex() { assertThat(locator).hasValues(new Pattern[]{ Pattern.compile("R"), Pattern.compile("G")}); } - @Test - void hasValuesFailsWhenItemsNotSelected() { + @PlaywrightTest + void hasValuesFailsWhenItemsNotSelected(Page page) { page.setContent("\n" + " \n" + " \n" + @@ -635,8 +634,8 @@ void hasValuesFailsWhenMultipleNotSpecified() { assertTrue(e.getMessage().contains("Not a select element with a multiple attribute"), e.getMessage()); } - @Test - void hasValuesFailsWhenNotASelectElement() { + @PlaywrightTest + void hasValuesFailsWhenNotASelectElement(Page page) { page.setContent(""); Locator locator = page.locator("input"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -645,15 +644,15 @@ void hasValuesFailsWhenNotASelectElement() { assertTrue(e.getMessage().contains("Not a select element with a multiple attribute"), e.getMessage()); } - @Test - void isCheckedPass() { + @PlaywrightTest + void isCheckedPass(Page page) { page.setContent(""); Locator locator = page.locator("input"); assertThat(locator).isChecked(); } - @Test - void isCheckedFail() { + @PlaywrightTest + void isCheckedFail(Page page) { page.setContent(""); Locator locator = page.locator("input"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -664,8 +663,8 @@ void isCheckedFail() { assertTrue(e.getMessage().contains("Locator expected to be\nExpected: checked"), e.getMessage()); } - @Test - void notIsCheckedFail() { + @PlaywrightTest + void notIsCheckedFail(Page page) { page.setContent(""); Locator locator = page.locator("input"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -677,15 +676,15 @@ void notIsCheckedFail() { assertTrue(e.getMessage().contains("Locator expected not to be\nExpected: checked"), e.getMessage()); } - @Test - void isCheckedFalsePass() { + @PlaywrightTest + void isCheckedFalsePass(Page page) { page.setContent(""); Locator locator = page.locator("input"); assertThat(locator).isChecked(new LocatorAssertions.IsCheckedOptions().setChecked(false)); } - @Test - void isCheckedFalseFail() { + @PlaywrightTest + void isCheckedFalseFail(Page page) { page.setContent(""); Locator locator = page.locator("input"); AssertionFailedError error = assertThrows(AssertionFailedError.class, @@ -693,15 +692,15 @@ void isCheckedFalseFail() { assertTrue(error.getMessage().contains("Locator expected to be\nExpected: unchecked"), error.getMessage()); } - @Test - void isDisabledPass() { + @PlaywrightTest + void isDisabledPass(Page page) { page.setContent(""); Locator locator = page.locator("button"); assertThat(locator).isDisabled(); } - @Test - void isDisabledFail() { + @PlaywrightTest + void isDisabledFail(Page page) { page.setContent(""); Locator locator = page.locator("button"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -712,8 +711,8 @@ void isDisabledFail() { assertTrue(e.getMessage().contains("Locator expected to be disabled"), e.getMessage()); } - @Test - void notIsDisabledFail() { + @PlaywrightTest + void notIsDisabledFail(Page page) { page.setContent(""); Locator locator = page.locator("button"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -724,15 +723,15 @@ void notIsDisabledFail() { assertTrue(e.getMessage().contains("Locator expected not to be disabled"), e.getMessage()); } - @Test - void isEditablePass() { + @PlaywrightTest + void isEditablePass(Page page) { page.setContent(""); Locator locator = page.locator("input"); assertThat(locator).isEditable(); } - @Test - void isEditableFail() { + @PlaywrightTest + void isEditableFail(Page page) { page.setContent(""); Locator locator = page.locator("input"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -743,8 +742,8 @@ void isEditableFail() { assertTrue(e.getMessage().contains("Locator expected to be editable"), e.getMessage()); } - @Test - void isEditableFalseFail() { + @PlaywrightTest + void isEditableFalseFail(Page page) { page.setContent(""); Locator locator = page.locator("input"); AssertionFailedError error = assertThrows(AssertionFailedError.class, @@ -752,8 +751,8 @@ void isEditableFalseFail() { assertTrue(error.getMessage().contains("Locator expected to be readonly"), error.getMessage()); } - @Test - void notIsEditableFail() { + @PlaywrightTest + void notIsEditableFail(Page page) { page.setContent(""); Locator locator = page.locator("input"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { @@ -764,51 +763,51 @@ void notIsEditableFail() { assertTrue(e.getMessage().contains("Locator expected not to be editable"), e.getMessage()); } - @Test - void isEditableWithNot() { + @PlaywrightTest + void isEditableWithNot(Page page) { page.setContent(""); Locator locator = page.locator("input"); assertThat(locator).not().isEditable(); } - @Test - void isEditableWithEditableTrue() { + @PlaywrightTest + void isEditableWithEditableTrue(Page page) { page.setContent(""); Locator locator = page.locator("input"); assertThat(locator).isEditable(new LocatorAssertions.IsEditableOptions().setEditable(true)); } - @Test - void isEditableWithEditableFalse() { + @PlaywrightTest + void isEditableWithEditableFalse(Page page) { page.setContent(""); Locator locator = page.locator("input"); assertThat(locator).isEditable(new LocatorAssertions.IsEditableOptions().setEditable(false)); } - @Test - void isEditableWithNotAndEditableFalse() { + @PlaywrightTest + void isEditableWithNotAndEditableFalse(Page page) { page.setContent(""); Locator locator = page.locator("input"); assertThat(locator).not().isEditable(new LocatorAssertions.IsEditableOptions().setEditable(false)); } - @Test - void isEditableThrowsOnNonInputElement() { + @PlaywrightTest + void isEditableThrowsOnNonInputElement(Page page) { page.setContent("").setContentType("text/html")); }); @@ -157,8 +157,8 @@ void shouldClickInLazyIframe() { assertEquals("Hello iframe", button.innerText()); } - @Test - void waitForShouldSurviveFrameReattach() { + @PlaywrightTest + void waitForShouldSurviveFrameReattach(Page page, Server server) { routeIframe(page); page.navigate(server.EMPTY_PAGE); Locator button = page.frameLocator("iframe").locator("button:has-text('Hello nested iframe')"); @@ -173,8 +173,8 @@ void waitForShouldSurviveFrameReattach() { button.waitFor(); } - @Test - void clickShouldSurviveFrameReattach() { + @PlaywrightTest + void clickShouldSurviveFrameReattach(Page page, Server server) { routeIframe(page); page.navigate(server.EMPTY_PAGE); Locator button = page.frameLocator("iframe").locator("button:has-text('Hello nested iframe')"); @@ -190,8 +190,8 @@ void clickShouldSurviveFrameReattach() { button.click(); } - @Test - void clickShouldSurviveIframeNavigation() { + @PlaywrightTest + void clickShouldSurviveIframeNavigation(Page page, Server server) { routeIframe(page); page.navigate(server.EMPTY_PAGE); Locator button = page.frameLocator("iframe").locator("button:has-text('Hello nested iframe')"); @@ -201,8 +201,8 @@ void clickShouldSurviveIframeNavigation() { button.click(); } - @Test - void shouldNonWorkForNonFrame() { + @PlaywrightTest + void shouldNonWorkForNonFrame(Page page) { routeIframe(page); page.setContent("
          "); Locator button = page.frameLocator("div").locator("button"); @@ -211,8 +211,8 @@ void shouldNonWorkForNonFrame() { assertTrue(e.getMessage().contains("\n"); Locator inputLocator = page.locator("input"); @@ -118,15 +118,15 @@ void LocatorLocatorAndFrameLocatorLocatorShouldAcceptLocator() { assertEquals("inner", page.frameLocator("iframe").locator(divLocator).locator("input").inputValue()); } - @Test - void shouldPressSequentially() { + @PlaywrightTest + void shouldPressSequentially(Page page) { page.setContent(""); page.locator("input").pressSequentially("hello"); assertEquals("hello", page.evalOnSelector("input", "input => input.value")); } - @Test - public void shouldSupportFilterVisible() { + @PlaywrightTest + public void shouldSupportFilterVisible(Page page) { page.setContent("
          \n" + "
          Hidden data0
          \n" + "
          visible data1
          \n" + @@ -141,44 +141,44 @@ public void shouldSupportFilterVisible() { assertThat(page.locator(".item").filter(new Locator.FilterOptions().setVisible(false)).getByText("data1")).hasText("Hidden data1"); } - @Test - void waitForFunctionShouldWaitForAnAttributeToAppear() { + @PlaywrightTest + void waitForFunctionShouldWaitForAnAttributeToAppear(Page page) { page.setContent(""); page.evaluate("() => setTimeout(() => document.querySelector('#toggle').setAttribute('aria-expanded', 'true'), 500)"); page.locator("#toggle").waitForFunction("element => element.hasAttribute('aria-expanded')"); } - @Test - void waitForFunctionShouldReturnImmediatelyWhenAlreadyTruthy() { + @PlaywrightTest + void waitForFunctionShouldReturnImmediatelyWhenAlreadyTruthy(Page page) { page.setContent("
          yes
          "); page.locator("#target").waitForFunction("element => element.textContent === 'yes'"); } - @Test - void waitForFunctionShouldAcceptElementHandleArguments() { + @PlaywrightTest + void waitForFunctionShouldAcceptElementHandleArguments(Page page) { page.setContent("
          value
          "); ElementHandle handle = page.querySelector("#b"); page.locator("#a").waitForFunction("(element, other) => other.textContent === 'value'", handle); } - @Test - void waitForFunctionShouldThrowWhenPredicateThrows() { + @PlaywrightTest + void waitForFunctionShouldThrowWhenPredicateThrows(Page page) { page.setContent("
          no
          "); PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.locator("#target").waitForFunction("() => { throw new Error('oh my'); }")); assertTrue(e.getMessage().contains("oh my"), e.getMessage()); } - @Test - void waitForFunctionShouldThrowOnStrictModeViolation() { + @PlaywrightTest + void waitForFunctionShouldThrowOnStrictModeViolation(Page page) { page.setContent("
          1
          2
          "); PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.locator("div.x").waitForFunction("() => true")); assertTrue(e.getMessage().contains("strict mode violation"), e.getMessage()); } - @Test - void waitForFunctionShouldRespectTimeout() { + @PlaywrightTest + void waitForFunctionShouldRespectTimeout(Page page) { page.setContent("
          no
          "); PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.locator("#target").waitForFunction("element => element.textContent === 'yes'", null, @@ -186,8 +186,8 @@ void waitForFunctionShouldRespectTimeout() { assertTrue(e.getMessage().contains("Timeout 500ms exceeded"), e.getMessage()); } - @Test - public void shouldSupportVisible() { + @PlaywrightTest + public void shouldSupportVisible(Page page) { page.setContent("
          \n" + "
          Hidden data0
          \n" + "
          visible data1
          \n" + diff --git a/playwright/src/test/java/com/microsoft/playwright/TestNetworkPostData.java b/playwright/src/test/java/com/microsoft/playwright/TestNetworkPostData.java index 6c7c88cf2..b06d8299f 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestNetworkPostData.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestNetworkPostData.java @@ -17,7 +17,7 @@ package com.microsoft.playwright; import com.google.gson.Gson; -import org.junit.jupiter.api.Test; +import com.microsoft.playwright.fixtures.PlaywrightTest; import java.nio.charset.StandardCharsets; import java.util.Arrays; @@ -26,9 +26,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -public class TestNetworkPostData extends TestBase { - @Test - void shouldReturnCorrectPostDataBufferForUtf8Body() { +public class TestNetworkPostData { + @PlaywrightTest + void shouldReturnCorrectPostDataBufferForUtf8Body(Page page, Server server) { page.navigate(server.EMPTY_PAGE); String value = "baẞ"; Request request = page.waitForRequest("**", () -> { @@ -45,8 +45,8 @@ void shouldReturnCorrectPostDataBufferForUtf8Body() { assertEquals(new Gson().toJson(value), request.postData()); } - @Test - void shouldReturnPostDataWOContentType() { + @PlaywrightTest + void shouldReturnPostDataWOContentType(Page page, Server server) { page.navigate(server.EMPTY_PAGE); Request request = page.waitForRequest("**", () -> { page.evaluate("({url}) => {\n" + @@ -65,8 +65,8 @@ void shouldThrowOnInvalidJSONInPostData() { // Thre is no postDataJSON() in java } - @Test - void shouldReturnPostDataForPUTRequests() { + @PlaywrightTest + void shouldReturnPostDataForPUTRequests(Page page, Server server) { page.navigate(server.EMPTY_PAGE); Request request = page.waitForRequest("**", () -> { page.evaluate("({url}) => {\n" + diff --git a/playwright/src/test/java/com/microsoft/playwright/TestNetworkRequest.java b/playwright/src/test/java/com/microsoft/playwright/TestNetworkRequest.java index bedb76100..609e106e3 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestNetworkRequest.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestNetworkRequest.java @@ -16,9 +16,11 @@ package com.microsoft.playwright; +import com.microsoft.playwright.fixtures.BrowserName; +import com.microsoft.playwright.fixtures.DisabledOnBrowser; +import com.microsoft.playwright.fixtures.PlaywrightTest; import com.microsoft.playwright.options.HttpHeader; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.DisabledIf; +import org.junit.jupiter.api.condition.OS; import java.io.OutputStreamWriter; import java.util.*; @@ -27,11 +29,14 @@ import java.util.stream.Collectors; import static com.microsoft.playwright.Utils.*; +import static com.microsoft.playwright.fixtures.BrowserName.CHROMIUM; +import static com.microsoft.playwright.fixtures.BrowserName.FIREFOX; +import static com.microsoft.playwright.fixtures.BrowserName.WEBKIT; import static org.junit.jupiter.api.Assertions.*; -public class TestNetworkRequest extends TestBase { - @Test - void shouldWorkForMainFrameNavigationRequest() { +public class TestNetworkRequest { + @PlaywrightTest + void shouldWorkForMainFrameNavigationRequest(Page page, Server server) { List requests = new ArrayList<>(); page.onRequest(request -> requests.add(request)); page.navigate(server.EMPTY_PAGE); @@ -39,8 +44,8 @@ void shouldWorkForMainFrameNavigationRequest() { assertEquals(page.mainFrame(), requests.get(0).frame()); } - @Test - void shouldWorkForSubframeNavigationRequest() { + @PlaywrightTest + void shouldWorkForSubframeNavigationRequest(Page page, Server server) { page.navigate(server.EMPTY_PAGE); List requests = new ArrayList<>(); page.onRequest(request -> requests.add(request)); @@ -49,8 +54,8 @@ void shouldWorkForSubframeNavigationRequest() { assertEquals(page.frames().get(1), requests.get(0).frame()); } - @Test - void shouldWorkForFetchRequests() { + @PlaywrightTest + void shouldWorkForFetchRequests(Page page, Server server) { page.navigate(server.EMPTY_PAGE); List requests = new ArrayList<>(); page.onRequest(request -> requests.add(request)); @@ -59,8 +64,8 @@ void shouldWorkForFetchRequests() { assertEquals(page.mainFrame(), requests.get(0).frame()); } - @Test - void shouldWorkForARedirect() { + @PlaywrightTest + void shouldWorkForARedirect(Page page, Server server) { server.setRedirect("/foo.html", "/empty.html"); List requests = new ArrayList<>(); page.onRequest(request -> requests.add(request)); @@ -71,8 +76,8 @@ void shouldWorkForARedirect() { assertEquals(server.PREFIX + "/empty.html", requests.get(1).url()); } - @Test - void shouldWorkAllHeadersInsideRoute() { + @PlaywrightTest + void shouldWorkAllHeadersInsideRoute(Page page, Server server) { List requests = new ArrayList<>(); page.route("**", route -> { assertTrue(route.request().allHeaders().get("accept").length() > 5); @@ -84,8 +89,8 @@ void shouldWorkAllHeadersInsideRoute() { } // https://github.com/microsoft/playwright/issues/3993 - @Test - void shouldNotWorkForARedirectAndInterception() { + @PlaywrightTest + void shouldNotWorkForARedirectAndInterception(Page page, Server server) { server.setRedirect("/foo.html", "/empty.html"); List requests = new ArrayList<>(); page.route("**", route -> { @@ -100,21 +105,17 @@ void shouldNotWorkForARedirectAndInterception() { assertEquals(server.PREFIX + "/foo.html", requests.get(0).url()); } - @Test - void shouldReturnHeaders() { + @PlaywrightTest + void shouldReturnHeaders(Page page, Server server, BrowserName browserName) { Response response = page.navigate(server.EMPTY_PAGE); - if (isChromium()) + if (browserName == CHROMIUM) assertTrue(response.request().headers().get("user-agent").contains("Chrome")); - else if (isFirefox()) + else if (browserName == FIREFOX) assertTrue(response.request().headers().get("user-agent").contains("Firefox")); - else if (isWebKit()) + else if (browserName == WEBKIT) assertTrue(response.request().headers().get("user-agent").contains("WebKit")); } - static boolean isWebKitWindows() { - return isWebKit() && getOS() == Utils.OS.WINDOWS; - } - // HTTP server in java does not preserve headers order. static List normalizeServerHeaders(Map> headers) { List serverHeaders = new ArrayList<>(); @@ -144,8 +145,8 @@ static List normalizeAllHeaders(Map headers) { return serverHeaders; } - static List adjustServerHeaders(List headers) { - if (isFirefox()) { + static List adjustServerHeaders(BrowserName browserName, List headers) { + if (browserName == FIREFOX) { for (Iterator it = headers.iterator(); it.hasNext(); ) { if ("priority".equals(it.next().name)) { it.remove(); @@ -155,9 +156,9 @@ static List adjustServerHeaders(List headers) { return headers; } - @Test - @DisabledIf(value="isWebKitWindows", disabledReason="Flaky, see https://github.com/microsoft/playwright/issues/6690") - void shouldGetTheSameHeadersAsTheServer() throws ExecutionException, InterruptedException { + @PlaywrightTest + @DisabledOnBrowser(value = WEBKIT, os = OS.WINDOWS, reason = "Flaky, see https://github.com/microsoft/playwright/issues/6690") + void shouldGetTheSameHeadersAsTheServer(Page page, Server server, BrowserName browserName) throws ExecutionException, InterruptedException { Future serverRequest = server.futureRequest("/empty.html"); server.setRoute("/empty.html", exchange -> { exchange.sendResponseHeaders(200, 0); @@ -167,14 +168,14 @@ void shouldGetTheSameHeadersAsTheServer() throws ExecutionException, Interrupted }); Response response = page.navigate(server.PREFIX + "/empty.html"); - List expectedHeaders = adjustServerHeaders(normalizeServerHeaders(serverRequest.get().headers)); + List expectedHeaders = adjustServerHeaders(browserName, normalizeServerHeaders(serverRequest.get().headers)); List allHeaders = normalizeAllHeaders(response.request().allHeaders()); assertJsonEquals(expectedHeaders, allHeaders); } - @Test - @DisabledIf(value="com.microsoft.playwright.TestBase#isWebKit", disabledReason="fail") - void shouldGetTheSameHeadersAsTheServerCORP() throws ExecutionException, InterruptedException { + @PlaywrightTest + @DisabledOnBrowser(value = WEBKIT, reason = "fail") + void shouldGetTheSameHeadersAsTheServerCORP(Page page, Server server, BrowserName browserName) throws ExecutionException, InterruptedException { page.navigate(server.PREFIX + "/empty.html"); Future serverRequest = server.futureRequest("/something"); server.setRoute("/something", exchange -> { @@ -191,13 +192,13 @@ void shouldGetTheSameHeadersAsTheServerCORP() throws ExecutionException, Interru "}", server.CROSS_PROCESS_PREFIX + "/something"); assertEquals("done", text); }); - List expectedHeaders = adjustServerHeaders(normalizeServerHeaders(serverRequest.get().headers)); + List expectedHeaders = adjustServerHeaders(browserName, normalizeServerHeaders(serverRequest.get().headers)); List allHeaders = normalizeAllHeaders(response.request().allHeaders()); assertJsonEquals(expectedHeaders, allHeaders); } - @Test - void shouldReturnPostData() { + @PlaywrightTest + void shouldReturnPostData(Page page, Server server) { page.navigate(server.EMPTY_PAGE); server.setRoute("/post", exchange -> { exchange.sendResponseHeaders(200, 0); @@ -210,8 +211,8 @@ void shouldReturnPostData() { assertEquals("{\"foo\":\"bar\"}", request[0].postData()); } - @Test - void shouldWorkWithBinaryPostData() { + @PlaywrightTest + void shouldWorkWithBinaryPostData(Page page, Server server) { page.navigate(server.EMPTY_PAGE); server.setRoute("/post", exchange -> { exchange.sendResponseHeaders(200, 0); @@ -230,8 +231,8 @@ void shouldWorkWithBinaryPostData() { } } - @Test - void shouldWorkWithBinaryPostDataAndInterception() { + @PlaywrightTest + void shouldWorkWithBinaryPostDataAndInterception(Page page, Server server) { page.navigate(server.EMPTY_PAGE); server.setRoute("/post", exchange -> { exchange.sendResponseHeaders(200, 0); @@ -251,8 +252,8 @@ void shouldWorkWithBinaryPostDataAndInterception() { } } - @Test - void shouldBeUndefinedWhenThereIsNoPostData() { + @PlaywrightTest + void shouldBeUndefinedWhenThereIsNoPostData(Page page, Server server) { Response response = page.navigate(server.EMPTY_PAGE); assertNull(response.request().postData()); } @@ -265,8 +266,8 @@ void shouldParseTheDataIfContentTypeIsApplicationXWwwFormUrlencoded() { // Not supported in Java. } - @Test - void shouldReturnEventSource() { + @PlaywrightTest + void shouldReturnEventSource(Page page, Server server) { // 1. Setup server-sent events on server that immediately sends a message to the client. server.setRoute("/sse", exchange -> { exchange.getResponseHeaders().add("Content-Type", "text/event-stream"); @@ -292,8 +293,8 @@ void shouldReturnEventSource() { assertEquals("eventsource", requests.get(0).resourceType()); } - @Test - void shouldReturnNavigationBit() { + @PlaywrightTest + void shouldReturnNavigationBit(Page page, Server server) { Map requests = new HashMap<>(); page.onRequest(request -> { String name = request.url(); @@ -312,8 +313,8 @@ void shouldReturnNavigationBit() { assertFalse(requests.get("style.css").isNavigationRequest()); } - @Test - void shouldReturnNavigationBitWhenNavigatingToImage() { + @PlaywrightTest + void shouldReturnNavigationBitWhenNavigatingToImage(Page page, Server server) { List requests = new ArrayList<>(); page.onRequest(request -> requests.add(request)); page.navigate(server.PREFIX + "/pptr.png"); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestNetworkResponse.java b/playwright/src/test/java/com/microsoft/playwright/TestNetworkResponse.java index 1dc08d16a..150d716cb 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestNetworkResponse.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestNetworkResponse.java @@ -16,8 +16,8 @@ package com.microsoft.playwright; +import com.microsoft.playwright.fixtures.PlaywrightTest; import com.microsoft.playwright.options.ServerAddr; -import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.OutputStreamWriter; @@ -30,9 +30,9 @@ import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.*; -public class TestNetworkResponse extends TestBase { - @Test - void shouldWork() { +public class TestNetworkResponse { + @PlaywrightTest + void shouldWork(Page page, Server server) { server.setRoute("/empty.html", exchange -> { exchange.getResponseHeaders().add("foo", "bar"); exchange.getResponseHeaders().add("BaZ", "bAz"); @@ -45,22 +45,22 @@ void shouldWork() { assertNull(response.headers().get("BaZ")); } - @Test - void shouldReturnText() { + @PlaywrightTest + void shouldReturnText(Page page, Server server) { Response response = page.navigate(server.PREFIX + "/simple.json"); assertEquals("{\"foo\": \"bar\"}\n", response.text()); } - @Test - void shouldReturnUncompressedText() { + @PlaywrightTest + void shouldReturnUncompressedText(Page page, Server server) { server.enableGzip("/simple.json"); Response response = page.navigate(server.PREFIX + "/simple.json"); assertEquals("gzip", response.headers().get("content-encoding")); assertEquals("{\"foo\": \"bar\"}\n", response.text()); } - @Test - void shouldThrowWhenRequestingBodyOfRedirectedResponse() { + @PlaywrightTest + void shouldThrowWhenRequestingBodyOfRedirectedResponse(Page page, Server server) { server.setRedirect("/foo.html", "/empty.html"); Response response = page.navigate(server.PREFIX + "/foo.html"); Request redirectedFrom = response.request().redirectedFrom(); @@ -71,8 +71,8 @@ void shouldThrowWhenRequestingBodyOfRedirectedResponse() { assertTrue(e.getMessage().contains("Response body is unavailable for redirect responses")); } - @Test - void shouldWaitUntilResponseCompletes() throws ExecutionException, InterruptedException { + @PlaywrightTest + void shouldWaitUntilResponseCompletes(Page page, Server server) throws ExecutionException, InterruptedException { page.navigate(server.EMPTY_PAGE); Semaphore responseWritten = new Semaphore(0); Semaphore responseRead = new Semaphore(0); @@ -115,23 +115,23 @@ void shouldWaitUntilResponseCompletes() throws ExecutionException, InterruptedEx void shouldReturnJson() { // Not exposed in Java. } - @Test - void shouldReturnBody() throws IOException { + @PlaywrightTest + void shouldReturnBody(Page page, Server server) throws IOException { Response response = page.navigate(server.PREFIX + "/pptr.png"); byte[] expected = Files.readAllBytes(Paths.get("src/test/resources/pptr.png")); assertTrue(Arrays.equals(expected, response.body())); } - @Test - void shouldReturnBodyWithCompression() throws IOException { + @PlaywrightTest + void shouldReturnBodyWithCompression(Page page, Server server) throws IOException { server.enableGzip("/pptr.png"); Response response = page.navigate(server.PREFIX + "/pptr.png"); byte[] expected = Files.readAllBytes(Paths.get("src/test/resources/pptr.png")); assertTrue(Arrays.equals(expected, response.body())); } - @Test - void shouldReturnStatusText() { + @PlaywrightTest + void shouldReturnStatusText(Page page, Server server) { server.setRoute("/cool", exchange -> { exchange.sendResponseHeaders(200, 0); exchange.getResponseBody().close(); @@ -140,8 +140,8 @@ void shouldReturnStatusText() { assertEquals("OK", response.statusText()); } - @Test - void shouldReturnServerAddress() { + @PlaywrightTest + void shouldReturnServerAddress(Page page, Server server) { Response response = page.navigate(server.EMPTY_PAGE); ServerAddr address = response.serverAddr(); assertNotNull(address); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestOptionsFactories.java b/playwright/src/test/java/com/microsoft/playwright/TestOptionsFactories.java deleted file mode 100644 index ce28fa3fa..000000000 --- a/playwright/src/test/java/com/microsoft/playwright/TestOptionsFactories.java +++ /dev/null @@ -1,69 +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; - -import com.microsoft.playwright.junit.Options; -import com.microsoft.playwright.junit.OptionsFactory; - -public class TestOptionsFactories { - - public static class BasicOptionsFactory implements OptionsFactory { - @Override - public Options getOptions() { - return new Options().setBrowserName(getBrowserName()); - } - } - - public static String getBrowserChannelFromEnv() { - return System.getenv("BROWSER_CHANNEL"); - } - - public static BrowserType.LaunchOptions createLaunchOptions() { - BrowserType.LaunchOptions options; - options = new BrowserType.LaunchOptions(); - options.headless = !getHeaded(); - return options; - } - - private static boolean getHeaded() { - String headedEnv = System.getenv("HEADED"); - return headedEnv != null && !"0".equals(headedEnv) && !"false".equals(headedEnv); - } - - public static String getBrowserName() { - String browserName = System.getenv("BROWSER"); - if (browserName == null) { - browserName = "chromium"; - } - return browserName; - } - - public static boolean isChromium() { - return getBrowserName().equals("chromium"); - } - - public static boolean isFirefox() { - return getBrowserName().equals("firefox"); - } - - public static boolean isWebKit() { - return getBrowserName().equals("webkit"); - } - - static final boolean isMac = Utils.getOS() == Utils.OS.MAC; - static final boolean isWindows = Utils.getOS() == Utils.OS.WINDOWS; -} diff --git a/playwright/src/test/java/com/microsoft/playwright/TestPageAddLocatorHandler.java b/playwright/src/test/java/com/microsoft/playwright/TestPageAddLocatorHandler.java index 5b5cab3e2..0de92caaf 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestPageAddLocatorHandler.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestPageAddLocatorHandler.java @@ -16,16 +16,16 @@ package com.microsoft.playwright; +import com.microsoft.playwright.fixtures.PlaywrightTest; 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; import static org.junit.jupiter.api.Assertions.*; -public class TestPageAddLocatorHandler extends TestBase { - @Test - void shouldWork() { +public class TestPageAddLocatorHandler { + @PlaywrightTest + void shouldWork(Page page, Server server) { page.navigate(server.PREFIX + "/input/handle-locator.html"); int[] beforeCount = {0}; @@ -73,8 +73,8 @@ void shouldWork() { } } - @Test - void shouldWorkWithCustomCheck() { + @PlaywrightTest + void shouldWorkWithCustomCheck(Page page, Server server) { page.navigate(server.PREFIX + "/input/handle-locator.html"); page.addLocatorHandler(page.locator("body"), locator -> { @@ -103,8 +103,8 @@ void shouldWorkWithCustomCheck() { } } - @Test - void shouldWorkWithLocatorHover() { + @PlaywrightTest + void shouldWorkWithLocatorHover(Page page, Server server) { page.navigate(server.PREFIX + "/input/handle-locator.html"); page.addLocatorHandler(page.getByText("This interstitial covers the button"), locator -> { @@ -120,8 +120,8 @@ void shouldWorkWithLocatorHover() { assertEquals("rgb(255, 255, 0)", page.evalOnSelector("#target", "element => getComputedStyle(element).backgroundColor")); } - @Test - void shouldNotWorkWithForceTrue() { + @PlaywrightTest + void shouldNotWorkWithForceTrue(Page page, Server server) { page.navigate(server.PREFIX + "/input/handle-locator.html"); page.addLocatorHandler(page.getByText("This interstitial covers the button"), locator -> { @@ -138,8 +138,8 @@ void shouldNotWorkWithForceTrue() { assertNull(page.evaluate("window.clicked")); } - @Test - void shouldThrowWhenPageCloses() { + @PlaywrightTest + void shouldThrowWhenPageCloses(Page page, Server server) { page.navigate(server.PREFIX + "/input/handle-locator.html"); page.addLocatorHandler(page.getByText("This interstitial covers the button"), locator -> { @@ -155,8 +155,8 @@ void shouldThrowWhenPageCloses() { assertTrue(e.getMessage().contains("Target page, context or browser has been closed"), e.getMessage()); } - @Test - void shouldWorkWithToBeVisible() { + @PlaywrightTest + void shouldWorkWithToBeVisible(Page page, Server server) { page.navigate(server.PREFIX + "/input/handle-locator.html"); int[] called = {0}; @@ -174,8 +174,8 @@ void shouldWorkWithToBeVisible() { assertEquals(1, called[0]); } - @Test - public void shouldWorkWhenOwnerFrameDetaches() { + @PlaywrightTest + public void shouldWorkWhenOwnerFrameDetaches(Browser browser, Server server) { Page page = browser.newPage(); page.navigate(server.EMPTY_PAGE); @@ -206,8 +206,8 @@ public void shouldWorkWhenOwnerFrameDetaches() { assertTrue((Boolean) page.evaluate("window._clicked")); } - @Test - public void shouldWorkWithTimesOption() { + @PlaywrightTest + public void shouldWorkWithTimesOption(Browser browser, Server server) { Page page = browser.newPage(); page.navigate(server.PREFIX + "/input/handle-locator.html"); @@ -230,8 +230,8 @@ public void shouldWorkWithTimesOption() { assertTrue(e.getMessage().contains("
          This interstitial covers the button
          from
          …
          subtree intercepts pointer events"), e.getMessage()); } - @Test - public void shouldWaitForHiddenByDefault() { + @PlaywrightTest + public void shouldWaitForHiddenByDefault(Browser browser, Server server) { Page page = browser.newPage(); page.navigate(server.PREFIX + "/input/handle-locator.html"); @@ -253,8 +253,8 @@ public void shouldWaitForHiddenByDefault() { assertEquals(1, called[0]); } - @Test - public void shouldWaitForHiddenByDefault2() { + @PlaywrightTest + public void shouldWaitForHiddenByDefault2(Browser browser, Server server) { Page page = browser.newPage(); page.navigate(server.PREFIX + "/input/handle-locator.html"); @@ -276,8 +276,8 @@ public void shouldWaitForHiddenByDefault2() { 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() { + @PlaywrightTest + public void shouldWorkWithNoWaitAfter(Browser browser, Server server) { Page page = browser.newPage(); page.navigate(server.PREFIX + "/input/handle-locator.html"); @@ -303,8 +303,8 @@ public void shouldWorkWithNoWaitAfter() { assertEquals(2, called[0]); } - @Test - public void shouldRemoveLocatorHandler() { + @PlaywrightTest + public void shouldRemoveLocatorHandler(Browser browser, Server server) { Page page = browser.newPage(); page.navigate(server.PREFIX + "/input/handle-locator.html"); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestPageAddScriptTag.java b/playwright/src/test/java/com/microsoft/playwright/TestPageAddScriptTag.java index 385b33fe7..1afee45d9 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestPageAddScriptTag.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestPageAddScriptTag.java @@ -16,19 +16,20 @@ package com.microsoft.playwright; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.DisabledIf; +import com.microsoft.playwright.fixtures.DisabledOnBrowser; +import com.microsoft.playwright.fixtures.PlaywrightTest; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; +import static com.microsoft.playwright.fixtures.BrowserName.WEBKIT; import static org.junit.jupiter.api.Assertions.assertTrue; -public class TestPageAddScriptTag extends TestBase { - @Test - @DisabledIf(value="com.microsoft.playwright.TestBase#isWebKit", disabledReason="Upstream behavior") - void shouldIncludeSourceURLWhenPathIsProvided() { +public class TestPageAddScriptTag { + @PlaywrightTest + @DisabledOnBrowser(value = WEBKIT, reason = "Upstream behavior") + void shouldIncludeSourceURLWhenPathIsProvided(Page page, Server server) { page.navigate(server.EMPTY_PAGE); Path path = Paths.get("src/test/resources/injectedfile.js"); page.addScriptTag(new Page.AddScriptTagOptions().setPath(path)); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestPageAriaSnapshot.java b/playwright/src/test/java/com/microsoft/playwright/TestPageAriaSnapshot.java index 442f2cd01..a41cce6a0 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestPageAriaSnapshot.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestPageAriaSnapshot.java @@ -1,8 +1,6 @@ package com.microsoft.playwright; -import com.microsoft.playwright.junit.FixtureTest; -import com.microsoft.playwright.junit.UsePlaywright; -import org.junit.jupiter.api.Test; +import com.microsoft.playwright.fixtures.PlaywrightTest; import org.opentest4j.AssertionFailedError; import java.util.Arrays; @@ -15,8 +13,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -@FixtureTest -@UsePlaywright public class TestPageAriaSnapshot { public static String unshift(String snapshot) { List lines = Arrays.asList(snapshot.split("\n")); @@ -46,13 +42,13 @@ private static void checkAndMatchSnapshot(Locator locator, String snapshot) { assertThat(locator).matchesAriaSnapshot(snapshot); } - @Test + @PlaywrightTest void shouldSnapshot(Page page) { page.setContent("

          title

          "); checkAndMatchSnapshot(page.locator("body"), "- heading \"title\" [level=1]"); } - @Test + @PlaywrightTest void shouldSnapshotList(Page page) { page.setContent("

          title

          title 2

          "); checkAndMatchSnapshot(page.locator("body"), "" + @@ -60,19 +56,19 @@ void shouldSnapshotList(Page page) { " - heading \"title 2\" [level=1]"); } - @Test + @PlaywrightTest void shouldSnapshotListWithAccessibleName(Page page) { page.setContent("
          • one
          • two
          "); checkAndMatchSnapshot(page.locator("body"), "- list \"my list\":\n - listitem: one\n - listitem: two"); } - @Test + @PlaywrightTest void shouldSnapshotComplex(Page page) { page.setContent(""); checkAndMatchSnapshot(page.locator("body"), "- list:\n - listitem:\n - link \"link\":\n - /url: about:blank"); } - @Test + @PlaywrightTest void shouldAllowTextNodes(Page page) { page.setContent("

          Microsoft

          Open source projects and samples from Microsoft
          "); checkAndMatchSnapshot(page.locator("body"), "" + @@ -80,13 +76,13 @@ void shouldAllowTextNodes(Page page) { " - text: Open source projects and samples from Microsoft"); } - @Test + @PlaywrightTest void shouldSnapshotDetailsVisibility(Page page) { page.setContent("
          Summary
          Details
          "); checkAndMatchSnapshot(page.locator("body"), "- group: Summary"); } - @Test + @PlaywrightTest void shouldSnapshotChildren(Page page) { page.setContent("
          • One
          • Two
          • Three
          "); assertThat(page.locator("body")).matchesAriaSnapshot("- list:\n - /children: equal\n - listitem\n - listitem: Two\n - listitem: Three"); @@ -97,7 +93,7 @@ void shouldSnapshotChildren(Page page) { assertThat(page.locator("body")).matchesAriaSnapshot("- list:\n - /children: deep-equal\n - listitem:\n - /children: contain\n - text: One\n - listitem: Two\n - listitem: Three"); } - @Test + @PlaywrightTest void shouldMatchUrl(Page page) { page.setContent("Link"); assertThat(page.locator("body")).matchesAriaSnapshot("" + @@ -105,7 +101,7 @@ void shouldMatchUrl(Page page) { " - /url: /.*example.com/"); } - @Test + @PlaywrightTest void shouldHandleTopLevelDeepEqual(Page page) { // https://github.com/microsoft/playwright/issues/36456 page.setContent("" + @@ -128,7 +124,7 @@ void shouldHandleTopLevelDeepEqual(Page page) { }); } - @Test + @PlaywrightTest void matchValuesBothAgainstRegexAndString(Page page) { page.setContent("Log in"); checkAndMatchSnapshot(page.locator("body"), @@ -136,7 +132,7 @@ void matchValuesBothAgainstRegexAndString(Page page) { " - /url: /auth?r=/"); } - @Test + @PlaywrightTest void shouldSnapshotIntegration(Page page) { page.setContent( "

          Microsoft

          " + @@ -160,7 +156,7 @@ void shouldSnapshotIntegration(Page page) { " - /url: about:blank"); } - @Test + @PlaywrightTest void shouldSupportMultilineText(Page page) { page.setContent("

          \n Line 1\n Line 2\n Line 3\n

          "); checkAndMatchSnapshot(page.locator("body"), "- paragraph: Line 1 Line 2 Line 3"); @@ -171,25 +167,25 @@ void shouldSupportMultilineText(Page page) { " Line 3"); } - @Test + @PlaywrightTest void shouldConcatenateSpanText(Page page) { page.setContent("One Two Three"); checkAndMatchSnapshot(page.locator("body"), "- text: One Two Three"); } - @Test + @PlaywrightTest void shouldConcatenateSpanText2(Page page) { page.setContent("One Two Three"); checkAndMatchSnapshot(page.locator("body"), "- text: One Two Three"); } - @Test + @PlaywrightTest void shouldConcatenateDivTextWithSpaces(Page page) { page.setContent("
          One
          Two
          Three
          "); checkAndMatchSnapshot(page.locator("body"), "- text: One Two Three"); } - @Test + @PlaywrightTest void shouldIncludePseudoInText(Page page) { page.setContent( "" + @@ -199,7 +195,7 @@ void shouldIncludePseudoInText(Page page) { " - /url: about:blank"); } - @Test + @PlaywrightTest void shouldNotIncludeHiddenPseudoInText(Page page) { page.setContent( "" + @@ -209,7 +205,7 @@ void shouldNotIncludeHiddenPseudoInText(Page page) { " - /url: about:blank"); } - @Test + @PlaywrightTest void shouldIncludeNewLineForBlockPseudo(Page page) { page.setContent( "" + @@ -219,7 +215,7 @@ void shouldIncludeNewLineForBlockPseudo(Page page) { " - /url: about:blank"); } - @Test + @PlaywrightTest void shouldWorkWithSlots(Page page) { // Text "foo" is assigned to the slot, should not be used twice. page.setContent( @@ -265,7 +261,7 @@ void shouldWorkWithSlots(Page page) { checkAndMatchSnapshot(page.locator("body"), "- button \"pre\""); } - @Test + @PlaywrightTest void shouldSnapshotInnerText(Page page) { page.setContent( "
          a.test.ts
          " + @@ -286,25 +282,25 @@ void shouldSnapshotInnerText(Page page) { " - button \"Watch\""); } - @Test + @PlaywrightTest void checkAriaHiddenText(Page page) { page.setContent("

          helloworld

          "); checkAndMatchSnapshot(page.locator("body"), "- paragraph: hello"); } - @Test + @PlaywrightTest void shouldIgnorePresentationAndNoneRoles(Page page) { page.setContent("
          • hello
          • world
          "); checkAndMatchSnapshot(page.locator("body"), "- list: hello world"); } - @Test + @PlaywrightTest void shouldNotUseOnAsCheckboxValue(Page page) { page.setContent(""); checkAndMatchSnapshot(page.locator("body"), "- checkbox\n- radio"); } - @Test + @PlaywrightTest void shouldNotReportTextareaTextContent(Page page) { page.setContent(""); checkAndMatchSnapshot(page.locator("body"), "- textbox: Before"); @@ -312,7 +308,7 @@ void shouldNotReportTextareaTextContent(Page page) { checkAndMatchSnapshot(page.locator("body"), "- textbox: After"); } - @Test + @PlaywrightTest void shouldNotShowVisibleChildrenOfHiddenElements(Page page) { page.setContent( "
          " + @@ -321,7 +317,7 @@ void shouldNotShowVisibleChildrenOfHiddenElements(Page page) { assertEquals("", page.locator("body").ariaSnapshot()); } - @Test + @PlaywrightTest void shouldNotShowUnhiddenChildrenOfAriaHiddenElements(Page page) { page.setContent( "
          " + @@ -330,7 +326,7 @@ void shouldNotShowUnhiddenChildrenOfAriaHiddenElements(Page page) { assertEquals("", page.locator("body").ariaSnapshot()); } - @Test + @PlaywrightTest void shouldSnapshotPlaceholderWhenDifferentFromName(Page page) { page.setContent(""); assertThat(page.locator("body")).matchesAriaSnapshot("- textbox \"Placeholder\""); @@ -341,7 +337,7 @@ void shouldSnapshotPlaceholderWhenDifferentFromName(Page page) { " - /placeholder: Placeholder"); } - @Test + @PlaywrightTest void pageMatchesAriaSnapshot(Page page) { page.setContent("

          hello

          "); assertThat(page).matchesAriaSnapshot("- heading \"hello\" [level=1]"); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestPageAriaSnapshotAI.java b/playwright/src/test/java/com/microsoft/playwright/TestPageAriaSnapshotAI.java index 233ba61e3..245ffee86 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestPageAriaSnapshotAI.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestPageAriaSnapshotAI.java @@ -1,21 +1,17 @@ package com.microsoft.playwright; -import com.microsoft.playwright.junit.FixtureTest; -import com.microsoft.playwright.junit.UsePlaywright; +import com.microsoft.playwright.fixtures.PlaywrightTest; import com.microsoft.playwright.options.AriaSnapshotMode; -import org.junit.jupiter.api.Test; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; import static org.junit.jupiter.api.Assertions.*; -@FixtureTest -@UsePlaywright public class TestPageAriaSnapshotAI { private static String aiSnapshot(Page page) { return page.ariaSnapshot(new Page.AriaSnapshotOptions().setMode(AriaSnapshotMode.AI)); } - @Test + @PlaywrightTest void shouldGenerateRefs(Page page) { page.setContent(""); @@ -35,7 +31,7 @@ void shouldGenerateRefs(Page page) { assertTrue(snapshot2.contains("button \"Three\" [ref=e4]"), snapshot2); } - @Test + @PlaywrightTest void shouldListIframes(Page page) { page.setContent( "

          Hello

          " + @@ -48,7 +44,7 @@ void shouldListIframes(Page page) { assertEquals("- heading \"World\" [level=1]", frameSnapshot); } - @Test + @PlaywrightTest void shouldSnapshotLocatorInsideIframe(Page page) { page.setContent( "

          Main Page

          " + @@ -61,21 +57,21 @@ void shouldSnapshotLocatorInsideIframe(Page page) { assertTrue(snapshot.contains("listitem [ref=f1e3]: Item 2"), snapshot); } - @Test + @PlaywrightTest void shouldCollapseGenericNodes(Page page) { page.setContent("
          "); String snapshot = aiSnapshot(page); assertTrue(snapshot.contains("button \"Button\" [ref=e5]"), snapshot); } - @Test + @PlaywrightTest void shouldIncludeCursorPointerHint(Page page) { page.setContent(""); String snapshot = aiSnapshot(page); assertTrue(snapshot.contains("button \"Button\" [ref=e2] [cursor=pointer]"), snapshot); } - @Test + @PlaywrightTest void shouldNotNestCursorPointerHints(Page page) { page.setContent( "" + @@ -91,7 +87,7 @@ void shouldNotNestCursorPointerHints(Page page) { assertFalse(snapshot.contains("button \"Button\" [ref=e3] [cursor=pointer]"), snapshot); } - @Test + @PlaywrightTest void shouldShowVisibleChildrenOfHiddenElements(Page page) { page.setContent( "
          " + @@ -110,7 +106,7 @@ void shouldShowVisibleChildrenOfHiddenElements(Page page) { snapshot); } - @Test + @PlaywrightTest void shouldIncludeActiveElementInformation(Page page) { page.setContent( "" + @@ -123,7 +119,7 @@ void shouldIncludeActiveElementInformation(Page page) { assertFalse(snapshot.contains("button \"Button 1\" [active]"), snapshot); } - @Test + @PlaywrightTest void shouldUpdateActiveElementOnFocus(Page page) { page.setContent( "" + @@ -142,7 +138,7 @@ void shouldUpdateActiveElementOnFocus(Page page) { assertFalse(afterFocusSnapshot.contains("textbox \"First input\" [active]"), afterFocusSnapshot); } - @Test + @PlaywrightTest void shouldCollapseInlineGenericNodes(Page page) { page.setContent( "