1
0
mirror of synced 2026-05-22 18:53:15 +00:00

chore: roll driver, implement new features (#1559)

This commit is contained in:
Yury Semikhatsky
2024-04-27 08:46:04 -07:00
committed by GitHub
parent a654a4234e
commit 7b8efadc57
28 changed files with 1114 additions and 101 deletions
+2 -2
View File
@@ -11,9 +11,9 @@ Playwright is a Java library to automate [Chromium](https://www.chromium.org/Hom
| | Linux | macOS | Windows |
| :--- | :---: | :---: | :---: |
| Chromium <!-- GEN:chromium-version -->124.0.6367.18<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| Chromium <!-- GEN:chromium-version -->125.0.6422.14<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| WebKit <!-- GEN:webkit-version -->17.4<!-- GEN:stop --> | ✅ | ✅ | ✅ |
| Firefox <!-- GEN:firefox-version -->124.0<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| Firefox <!-- GEN:firefox-version -->125.0.1<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
Headless execution is supported for all the browsers on all platforms. Check out [system requirements](https://playwright.dev/java/docs/intro#system-requirements) for details.
@@ -91,10 +91,11 @@ public interface APIRequestContext {
void dispose();
/**
* Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and update
* context cookies from the response. The method will automatically follow redirects. JSON objects can be passed directly
* to the request.
* context cookies from the response. The method will automatically follow redirects.
*
* <p> <strong>Usage</strong>
*
* <p> JSON objects can be passed directly to the request:
* <pre>{@code
* Map<String, Object> data = new HashMap();
* data.put("title", "Book Title");
@@ -102,8 +103,9 @@ public interface APIRequestContext {
* request.fetch("https://example.com/api/createBook", RequestOptions.create().setMethod("post").setData(data));
* }</pre>
*
* <p> 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:
* <p> The common way to send file(s) in the body of a request is to upload them as form fields with {@code
* multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code
* multipart} parameter:
* <pre>{@code
* // Pass file path to the form data constructor:
* Path file = Paths.get("team.csv");
@@ -114,7 +116,7 @@ public interface APIRequestContext {
* // Or you can pass the file content directly as FilePayload object:
* FilePayload filePayload = new FilePayload("f.js", "text/javascript",
* "console.log(2022);".getBytes(StandardCharsets.UTF_8));
* APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
* APIResponse response = request.fetch("https://example.com/api/uploadScript",
* RequestOptions.create().setMethod("post").setMultipart(
* FormData.create().set("fileField", filePayload)));
* }</pre>
@@ -127,10 +129,11 @@ public interface APIRequestContext {
}
/**
* Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and update
* context cookies from the response. The method will automatically follow redirects. JSON objects can be passed directly
* to the request.
* context cookies from the response. The method will automatically follow redirects.
*
* <p> <strong>Usage</strong>
*
* <p> JSON objects can be passed directly to the request:
* <pre>{@code
* Map<String, Object> data = new HashMap();
* data.put("title", "Book Title");
@@ -138,8 +141,9 @@ public interface APIRequestContext {
* request.fetch("https://example.com/api/createBook", RequestOptions.create().setMethod("post").setData(data));
* }</pre>
*
* <p> 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:
* <p> The common way to send file(s) in the body of a request is to upload them as form fields with {@code
* multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code
* multipart} parameter:
* <pre>{@code
* // Pass file path to the form data constructor:
* Path file = Paths.get("team.csv");
@@ -150,7 +154,7 @@ public interface APIRequestContext {
* // Or you can pass the file content directly as FilePayload object:
* FilePayload filePayload = new FilePayload("f.js", "text/javascript",
* "console.log(2022);".getBytes(StandardCharsets.UTF_8));
* APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
* APIResponse response = request.fetch("https://example.com/api/uploadScript",
* RequestOptions.create().setMethod("post").setMultipart(
* FormData.create().set("fileField", filePayload)));
* }</pre>
@@ -162,10 +166,11 @@ public interface APIRequestContext {
APIResponse fetch(String urlOrRequest, RequestOptions params);
/**
* Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and update
* context cookies from the response. The method will automatically follow redirects. JSON objects can be passed directly
* to the request.
* context cookies from the response. The method will automatically follow redirects.
*
* <p> <strong>Usage</strong>
*
* <p> JSON objects can be passed directly to the request:
* <pre>{@code
* Map<String, Object> data = new HashMap();
* data.put("title", "Book Title");
@@ -173,8 +178,9 @@ public interface APIRequestContext {
* request.fetch("https://example.com/api/createBook", RequestOptions.create().setMethod("post").setData(data));
* }</pre>
*
* <p> 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:
* <p> The common way to send file(s) in the body of a request is to upload them as form fields with {@code
* multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code
* multipart} parameter:
* <pre>{@code
* // Pass file path to the form data constructor:
* Path file = Paths.get("team.csv");
@@ -185,7 +191,7 @@ public interface APIRequestContext {
* // Or you can pass the file content directly as FilePayload object:
* FilePayload filePayload = new FilePayload("f.js", "text/javascript",
* "console.log(2022);".getBytes(StandardCharsets.UTF_8));
* APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
* APIResponse response = request.fetch("https://example.com/api/uploadScript",
* RequestOptions.create().setMethod("post").setMultipart(
* FormData.create().set("fileField", filePayload)));
* }</pre>
@@ -198,10 +204,11 @@ public interface APIRequestContext {
}
/**
* Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and update
* context cookies from the response. The method will automatically follow redirects. JSON objects can be passed directly
* to the request.
* context cookies from the response. The method will automatically follow redirects.
*
* <p> <strong>Usage</strong>
*
* <p> JSON objects can be passed directly to the request:
* <pre>{@code
* Map<String, Object> data = new HashMap();
* data.put("title", "Book Title");
@@ -209,8 +216,9 @@ public interface APIRequestContext {
* request.fetch("https://example.com/api/createBook", RequestOptions.create().setMethod("post").setData(data));
* }</pre>
*
* <p> 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:
* <p> The common way to send file(s) in the body of a request is to upload them as form fields with {@code
* multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code
* multipart} parameter:
* <pre>{@code
* // Pass file path to the form data constructor:
* Path file = Paths.get("team.csv");
@@ -221,7 +229,7 @@ public interface APIRequestContext {
* // Or you can pass the file content directly as FilePayload object:
* FilePayload filePayload = new FilePayload("f.js", "text/javascript",
* "console.log(2022);".getBytes(StandardCharsets.UTF_8));
* APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
* APIResponse response = request.fetch("https://example.com/api/uploadScript",
* RequestOptions.create().setMethod("post").setMultipart(
* FormData.create().set("fileField", filePayload)));
* }</pre>
@@ -337,7 +345,8 @@ public interface APIRequestContext {
* }</pre>
*
* <p> The common way to send file(s) in the body of a request is to upload them as form fields with {@code
* multipart/form-data} encoding. You can achieve that with Playwright API like this:
* multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code
* multipart} parameter:
* <pre>{@code
* // Pass file path to the form data constructor:
* Path file = Paths.get("team.csv");
@@ -346,9 +355,9 @@ public interface APIRequestContext {
* FormData.create().set("fileField", file)));
*
* // Or you can pass the file content directly as FilePayload object:
* FilePayload filePayload = new FilePayload("f.js", "text/javascript",
* FilePayload filePayload1 = new FilePayload("f1.js", "text/javascript",
* "console.log(2022);".getBytes(StandardCharsets.UTF_8));
* APIResponse response = request.post("https://example.com/api/uploadTeamList",
* APIResponse response = request.post("https://example.com/api/uploadScript",
* RequestOptions.create().setMultipart(
* FormData.create().set("fileField", filePayload)));
* }</pre>
@@ -384,7 +393,8 @@ public interface APIRequestContext {
* }</pre>
*
* <p> The common way to send file(s) in the body of a request is to upload them as form fields with {@code
* multipart/form-data} encoding. You can achieve that with Playwright API like this:
* multipart/form-data} encoding. Use {@code FormData} to construct request body and pass it to the request as {@code
* multipart} parameter:
* <pre>{@code
* // Pass file path to the form data constructor:
* Path file = Paths.get("team.csv");
@@ -393,9 +403,9 @@ public interface APIRequestContext {
* FormData.create().set("fileField", file)));
*
* // Or you can pass the file content directly as FilePayload object:
* FilePayload filePayload = new FilePayload("f.js", "text/javascript",
* FilePayload filePayload1 = new FilePayload("f1.js", "text/javascript",
* "console.log(2022);".getBytes(StandardCharsets.UTF_8));
* APIResponse response = request.post("https://example.com/api/uploadTeamList",
* APIResponse response = request.post("https://example.com/api/uploadScript",
* RequestOptions.create().setMultipart(
* FormData.create().set("fileField", filePayload)));
* }</pre>
@@ -49,10 +49,9 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> Emitted when new background page is created in the context.
* <pre>{@code
* Page backgroundPage = context.waitForBackgroundPage(() -> {
* page.getByText("activate extension").click();
* context.onBackgroundPage(backgroundPage -> {
* System.out.println(backgroundPage.url());
* });
* System.out.println(backgroundPage.evaluate("location.href"));
* }</pre>
*/
void onBackgroundPage(Consumer<Page> handler);
@@ -128,7 +127,10 @@ public interface BrowserContext extends AutoCloseable {
*
* <p> The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
* popup with {@code window.open('http://example.com')}, this event will fire when the network request to
* "http://example.com" is done and its response has started loading in the popup.
* "http://example.com" is done and its response has started loading in the popup. If you would like to route/listen to
* this network request, use {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} and {@link
* com.microsoft.playwright.BrowserContext#onRequest BrowserContext.onRequest()} respectively instead of similar methods on
* the {@code Page}.
* <pre>{@code
* Page newPage = context.waitForPage(() -> {
* page.getByText("open new page").click();
@@ -4989,6 +4989,9 @@ public interface Frame {
* <p> This returns when the frame reaches a required load state, {@code load} by default. The navigation must have been
* committed when this method is called. If current document has already reached the required state, resolves immediately.
*
* <p> <strong>NOTE:</strong> Most of the time, this method is not needed because Playwright <a
* href="https://playwright.dev/java/docs/actionability">auto-waits before every action</a>.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* frame.click("button"); // Click triggers navigation.
@@ -5014,6 +5017,9 @@ public interface Frame {
* <p> This returns when the frame reaches a required load state, {@code load} by default. The navigation must have been
* committed when this method is called. If current document has already reached the required state, resolves immediately.
*
* <p> <strong>NOTE:</strong> Most of the time, this method is not needed because Playwright <a
* href="https://playwright.dev/java/docs/actionability">auto-waits before every action</a>.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* frame.click("button"); // Click triggers navigation.
@@ -5031,6 +5037,9 @@ public interface Frame {
* <p> This returns when the frame reaches a required load state, {@code load} by default. The navigation must have been
* committed when this method is called. If current document has already reached the required state, resolves immediately.
*
* <p> <strong>NOTE:</strong> Most of the time, this method is not needed because Playwright <a
* href="https://playwright.dev/java/docs/actionability">auto-waits before every action</a>.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* frame.click("button"); // Click triggers navigation.
@@ -242,7 +242,10 @@ public interface Page extends AutoCloseable {
*
* <p> The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
* popup with {@code window.open('http://example.com')}, this event will fire when the network request to
* "http://example.com" is done and its response has started loading in the popup.
* "http://example.com" is done and its response has started loading in the popup. If you would like to route/listen to
* this network request, use {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} and {@link
* com.microsoft.playwright.BrowserContext#onRequest BrowserContext.onRequest()} respectively instead of similar methods on
* the {@code Page}.
* <pre>{@code
* Page popup = page.waitForPopup(() -> {
* page.getByText("open the popup").click();
@@ -2327,6 +2330,35 @@ public interface Page extends AutoCloseable {
return this;
}
}
class AddLocatorHandlerOptions {
/**
* By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then Playwright
* will continue with the action/assertion that triggered the handler. This option allows to opt-out of this behavior, so
* that overlay can stay visible after the handler has run.
*/
public Boolean noWaitAfter;
/**
* Specifies the maximum number of times this handler should be called. Unlimited by default.
*/
public Integer times;
/**
* By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then Playwright
* will continue with the action/assertion that triggered the handler. This option allows to opt-out of this behavior, so
* that overlay can stay visible after the handler has run.
*/
public AddLocatorHandlerOptions setNoWaitAfter(boolean noWaitAfter) {
this.noWaitAfter = noWaitAfter;
return this;
}
/**
* Specifies the maximum number of times this handler should be called. Unlimited by default.
*/
public AddLocatorHandlerOptions setTimes(int times) {
this.times = times;
return this;
}
}
class ReloadOptions {
/**
* Maximum operation time in milliseconds, defaults to 30 seconds, pass {@code 0} to disable timeout. The default value can
@@ -6058,9 +6090,7 @@ public interface Page extends AutoCloseable {
*/
List<ElementHandle> querySelectorAll(String selector);
/**
* <strong>NOTE:</strong> This method is experimental and its behavior may change in the upcoming releases.
*
* <p> When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to
* When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to
* automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making them
* tricky to handle in automated tests.
*
@@ -6077,6 +6107,8 @@ public interface Page extends AutoCloseable {
* assertion check. When overlay is visible, Playwright calls the handler first, and then proceeds with the
* action/assertion. Note that the handler is only called when you perform an action/assertion - if the overlay becomes
* visible but you don't perform any actions, the handler will not be triggered.</li>
* <li> After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible anymore. You
* can opt-out of this behavior with {@code noWaitAfter}.</li>
* <li> The execution time of the handler counts towards the timeout of the action/assertion that executed the handler. If your
* handler takes too long, it might cause timeouts.</li>
* <li> You can register multiple handlers. However, only a single handler will be running at a time. Make sure the actions
@@ -6122,24 +6154,135 @@ public interface Page extends AutoCloseable {
* }</pre>
*
* <p> An example with a custom callback on every actionability check. It uses a {@code <body>} locator that is always visible,
* so the handler is called before every actionability check:
* so the handler is called before every actionability check. It is important to specify {@code noWaitAfter}, because the
* handler does not hide the {@code <body>} element.
* <pre>{@code
* // Setup the handler.
* page.addLocatorHandler(page.locator("body")), () => {
* page.evaluate("window.removeObstructionsForTestIfNeeded()");
* });
* }, new Page.AddLocatorHandlerOptions.setNoWaitAfter(true));
*
* // Write the test as usual.
* page.goto("https://example.com");
* page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
* }</pre>
*
* <p> Handler takes the original locator as an argument. You can also automatically remove the handler after a number of
* invocations by setting {@code times}:
* <pre>{@code
* page.addLocatorHandler(page.getByLabel("Close"), locator => {
* locator.click();
* }, new Page.AddLocatorHandlerOptions().setTimes(1));
* }</pre>
*
* @param locator Locator that triggers the handler.
* @param handler Function that should be run once {@code locator} appears. This function should get rid of the element that blocks
* actions like click.
* @since v1.42
*/
void addLocatorHandler(Locator locator, Runnable handler);
default void addLocatorHandler(Locator locator, Consumer<Locator> handler) {
addLocatorHandler(locator, handler, null);
}
/**
* When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to
* automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making them
* tricky to handle in automated tests.
*
* <p> This method lets you set up a special function, called a handler, that activates when it detects that overlay is
* visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there.
*
* <p> Things to keep in mind:
* <ul>
* <li> When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as a part of
* your normal test flow, instead of using {@link com.microsoft.playwright.Page#addLocatorHandler
* Page.addLocatorHandler()}.</li>
* <li> Playwright checks for the overlay every time before executing or retrying an action that requires an <a
* href="https://playwright.dev/java/docs/actionability">actionability check</a>, or before performing an auto-waiting
* assertion check. When overlay is visible, Playwright calls the handler first, and then proceeds with the
* action/assertion. Note that the handler is only called when you perform an action/assertion - if the overlay becomes
* visible but you don't perform any actions, the handler will not be triggered.</li>
* <li> After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible anymore. You
* can opt-out of this behavior with {@code noWaitAfter}.</li>
* <li> The execution time of the handler counts towards the timeout of the action/assertion that executed the handler. If your
* handler takes too long, it might cause timeouts.</li>
* <li> You can register multiple handlers. However, only a single handler will be running at a time. Make sure the actions
* within a handler don't depend on another handler.</li>
* </ul>
*
* <p> <strong>NOTE:</strong> Running the handler will alter your page state mid-test. For example it will change the currently focused element and
* move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on the focus and
* mouse state being unchanged. <br /> <br /> For example, consider a test that calls {@link
* com.microsoft.playwright.Locator#focus Locator.focus()} followed by {@link com.microsoft.playwright.Keyboard#press
* Keyboard.press()}. If your handler clicks a button between these two actions, the focused element most likely will be
* wrong, and key press will happen on the unexpected element. Use {@link com.microsoft.playwright.Locator#press
* Locator.press()} instead to avoid this problem. <br /> <br /> Another example is a series of mouse actions, where {@link
* com.microsoft.playwright.Mouse#move Mouse.move()} is followed by {@link com.microsoft.playwright.Mouse#down
* Mouse.down()}. Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse
* down. Prefer self-contained actions like {@link com.microsoft.playwright.Locator#click Locator.click()} that do not rely
* on the state being unchanged by a handler.
*
* <p> <strong>Usage</strong>
*
* <p> An example that closes a "Sign up to the newsletter" dialog when it appears:
* <pre>{@code
* // Setup the handler.
* page.addLocatorHandler(page.getByText("Sign up to the newsletter"), () => {
* page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("No thanks")).click();
* });
*
* // Write the test as usual.
* page.goto("https://example.com");
* page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
* }</pre>
*
* <p> An example that skips the "Confirm your security details" page when it is shown:
* <pre>{@code
* // Setup the handler.
* page.addLocatorHandler(page.getByText("Confirm your security details")), () => {
* page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Remind me later")).click();
* });
*
* // Write the test as usual.
* page.goto("https://example.com");
* page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
* }</pre>
*
* <p> An example with a custom callback on every actionability check. It uses a {@code <body>} locator that is always visible,
* so the handler is called before every actionability check. It is important to specify {@code noWaitAfter}, because the
* handler does not hide the {@code <body>} element.
* <pre>{@code
* // Setup the handler.
* page.addLocatorHandler(page.locator("body")), () => {
* page.evaluate("window.removeObstructionsForTestIfNeeded()");
* }, new Page.AddLocatorHandlerOptions.setNoWaitAfter(true));
*
* // Write the test as usual.
* page.goto("https://example.com");
* page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
* }</pre>
*
* <p> Handler takes the original locator as an argument. You can also automatically remove the handler after a number of
* invocations by setting {@code times}:
* <pre>{@code
* page.addLocatorHandler(page.getByLabel("Close"), locator => {
* locator.click();
* }, new Page.AddLocatorHandlerOptions().setTimes(1));
* }</pre>
*
* @param locator Locator that triggers the handler.
* @param handler Function that should be run once {@code locator} appears. This function should get rid of the element that blocks
* actions like click.
* @since v1.42
*/
void addLocatorHandler(Locator locator, Consumer<Locator> handler, AddLocatorHandlerOptions options);
/**
* Removes all locator handlers added by {@link com.microsoft.playwright.Page#addLocatorHandler Page.addLocatorHandler()}
* for a specific locator.
*
* @param locator Locator passed to {@link com.microsoft.playwright.Page#addLocatorHandler Page.addLocatorHandler()}.
* @since v1.44
*/
void removeLocatorHandler(Locator locator);
/**
* This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the main
* resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
@@ -6175,6 +6318,9 @@ public interface Page extends AutoCloseable {
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
*
* <p> <strong>Usage</strong>
*
* <p> An example of a naive handler that aborts all image requests:
@@ -6231,6 +6377,9 @@ public interface Page extends AutoCloseable {
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
*
* <p> <strong>Usage</strong>
*
* <p> An example of a naive handler that aborts all image requests:
@@ -6285,6 +6434,9 @@ public interface Page extends AutoCloseable {
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
*
* <p> <strong>Usage</strong>
*
* <p> An example of a naive handler that aborts all image requests:
@@ -6341,6 +6493,9 @@ public interface Page extends AutoCloseable {
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
*
* <p> <strong>Usage</strong>
*
* <p> An example of a naive handler that aborts all image requests:
@@ -6395,6 +6550,9 @@ public interface Page extends AutoCloseable {
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
*
* <p> <strong>Usage</strong>
*
* <p> An example of a naive handler that aborts all image requests:
@@ -6451,6 +6609,9 @@ public interface Page extends AutoCloseable {
* <a href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers
* when using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
*
* <p> <strong>NOTE:</strong> {@link com.microsoft.playwright.Page#route Page.route()} will not intercept the first request of a popup page. Use
* {@link com.microsoft.playwright.BrowserContext#route BrowserContext.route()} instead.
*
* <p> <strong>Usage</strong>
*
* <p> An example of a naive handler that aborts all image requests:
@@ -7588,6 +7749,9 @@ public interface Page extends AutoCloseable {
* <p> This resolves when the page reaches a required load state, {@code load} by default. The navigation must have been
* committed when this method is called. If current document has already reached the required state, resolves immediately.
*
* <p> <strong>NOTE:</strong> Most of the time, this method is not needed because Playwright <a
* href="https://playwright.dev/java/docs/actionability">auto-waits before every action</a>.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.getByRole(AriaRole.BUTTON).click(); // Click triggers navigation.
@@ -7621,6 +7785,9 @@ public interface Page extends AutoCloseable {
* <p> This resolves when the page reaches a required load state, {@code load} by default. The navigation must have been
* committed when this method is called. If current document has already reached the required state, resolves immediately.
*
* <p> <strong>NOTE:</strong> Most of the time, this method is not needed because Playwright <a
* href="https://playwright.dev/java/docs/actionability">auto-waits before every action</a>.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.getByRole(AriaRole.BUTTON).click(); // Click triggers navigation.
@@ -7646,6 +7813,9 @@ public interface Page extends AutoCloseable {
* <p> This resolves when the page reaches a required load state, {@code load} by default. The navigation must have been
* committed when this method is called. If current document has already reached the required state, resolves immediately.
*
* <p> <strong>NOTE:</strong> Most of the time, this method is not needed because Playwright <a
* href="https://playwright.dev/java/docs/actionability">auto-waits before every action</a>.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* page.getByRole(AriaRole.BUTTON).click(); // Click triggers navigation.
@@ -17,6 +17,7 @@
package com.microsoft.playwright.assertions;
import java.util.regex.Pattern;
import com.microsoft.playwright.options.AriaRole;
/**
* The {@code LocatorAssertions} class provides assertion methods that can be used to make assertions about the {@code
@@ -253,6 +254,60 @@ public interface LocatorAssertions {
return this;
}
}
class HasAccessibleDescriptionOptions {
/**
* Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
* expression flag if specified.
*/
public Boolean ignoreCase;
/**
* Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
*/
public Double timeout;
/**
* Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
* expression flag if specified.
*/
public HasAccessibleDescriptionOptions setIgnoreCase(boolean ignoreCase) {
this.ignoreCase = ignoreCase;
return this;
}
/**
* Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
*/
public HasAccessibleDescriptionOptions setTimeout(double timeout) {
this.timeout = timeout;
return this;
}
}
class HasAccessibleNameOptions {
/**
* Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
* expression flag if specified.
*/
public Boolean ignoreCase;
/**
* Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
*/
public Double timeout;
/**
* Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
* expression flag if specified.
*/
public HasAccessibleNameOptions setIgnoreCase(boolean ignoreCase) {
this.ignoreCase = ignoreCase;
return this;
}
/**
* Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
*/
public HasAccessibleNameOptions setTimeout(double timeout) {
this.timeout = timeout;
return this;
}
}
class HasAttributeOptions {
/**
* Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
@@ -350,6 +405,20 @@ public interface LocatorAssertions {
return this;
}
}
class HasRoleOptions {
/**
* Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
*/
public Double timeout;
/**
* Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
*/
public HasRoleOptions setTimeout(double timeout) {
this.timeout = timeout;
return this;
}
}
class HasTextOptions {
/**
* Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
@@ -1076,6 +1145,126 @@ public interface LocatorAssertions {
* @since v1.20
*/
void containsText(Pattern[] expected, ContainsTextOptions options);
/**
* Ensures the {@code Locator} points to an element with a given <a
* href="https://w3c.github.io/accname/#dfn-accessible-description">accessible description</a>.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* Locator locator = page.getByTestId("save-button");
* assertThat(locator).hasAccessibleDescription("Save results to disk");
* }</pre>
*
* @param description Expected accessible description.
* @since v1.44
*/
default void hasAccessibleDescription(String description) {
hasAccessibleDescription(description, null);
}
/**
* Ensures the {@code Locator} points to an element with a given <a
* href="https://w3c.github.io/accname/#dfn-accessible-description">accessible description</a>.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* Locator locator = page.getByTestId("save-button");
* assertThat(locator).hasAccessibleDescription("Save results to disk");
* }</pre>
*
* @param description Expected accessible description.
* @since v1.44
*/
void hasAccessibleDescription(String description, HasAccessibleDescriptionOptions options);
/**
* Ensures the {@code Locator} points to an element with a given <a
* href="https://w3c.github.io/accname/#dfn-accessible-description">accessible description</a>.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* Locator locator = page.getByTestId("save-button");
* assertThat(locator).hasAccessibleDescription("Save results to disk");
* }</pre>
*
* @param description Expected accessible description.
* @since v1.44
*/
default void hasAccessibleDescription(Pattern description) {
hasAccessibleDescription(description, null);
}
/**
* Ensures the {@code Locator} points to an element with a given <a
* href="https://w3c.github.io/accname/#dfn-accessible-description">accessible description</a>.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* Locator locator = page.getByTestId("save-button");
* assertThat(locator).hasAccessibleDescription("Save results to disk");
* }</pre>
*
* @param description Expected accessible description.
* @since v1.44
*/
void hasAccessibleDescription(Pattern description, HasAccessibleDescriptionOptions options);
/**
* Ensures the {@code Locator} points to an element with a given <a
* href="https://w3c.github.io/accname/#dfn-accessible-name">accessible name</a>.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* Locator locator = page.getByTestId("save-button");
* assertThat(locator).hasAccessibleName("Save to disk");
* }</pre>
*
* @param name Expected accessible name.
* @since v1.44
*/
default void hasAccessibleName(String name) {
hasAccessibleName(name, null);
}
/**
* Ensures the {@code Locator} points to an element with a given <a
* href="https://w3c.github.io/accname/#dfn-accessible-name">accessible name</a>.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* Locator locator = page.getByTestId("save-button");
* assertThat(locator).hasAccessibleName("Save to disk");
* }</pre>
*
* @param name Expected accessible name.
* @since v1.44
*/
void hasAccessibleName(String name, HasAccessibleNameOptions options);
/**
* Ensures the {@code Locator} points to an element with a given <a
* href="https://w3c.github.io/accname/#dfn-accessible-name">accessible name</a>.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* Locator locator = page.getByTestId("save-button");
* assertThat(locator).hasAccessibleName("Save to disk");
* }</pre>
*
* @param name Expected accessible name.
* @since v1.44
*/
default void hasAccessibleName(Pattern name) {
hasAccessibleName(name, null);
}
/**
* Ensures the {@code Locator} points to an element with a given <a
* href="https://w3c.github.io/accname/#dfn-accessible-name">accessible name</a>.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* Locator locator = page.getByTestId("save-button");
* assertThat(locator).hasAccessibleName("Save to disk");
* }</pre>
*
* @param name Expected accessible name.
* @since v1.44
*/
void hasAccessibleName(Pattern name, HasAccessibleNameOptions options);
/**
* Ensures the {@code Locator} points to an element with given attribute.
*
@@ -1456,6 +1645,42 @@ public interface LocatorAssertions {
* @since v1.20
*/
void hasJSProperty(String name, Object value, HasJSPropertyOptions options);
/**
* Ensures the {@code Locator} points to an element with a given <a href="https://www.w3.org/TR/wai-aria-1.2/#roles">ARIA
* role</a>.
*
* <p> Note that role is matched as a string, disregarding the ARIA role hierarchy. For example, asserting a superclass role
* {@code "checkbox"} on an element with a subclass role {@code "switch"} will fail.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* Locator locator = page.getByTestId("save-button");
* assertThat(locator).hasRole(AriaRole.BUTTON);
* }</pre>
*
* @param role Required aria role.
* @since v1.44
*/
default void hasRole(AriaRole role) {
hasRole(role, null);
}
/**
* Ensures the {@code Locator} points to an element with a given <a href="https://www.w3.org/TR/wai-aria-1.2/#roles">ARIA
* role</a>.
*
* <p> Note that role is matched as a string, disregarding the ARIA role hierarchy. For example, asserting a superclass role
* {@code "checkbox"} on an element with a subclass role {@code "switch"} will fail.
*
* <p> <strong>Usage</strong>
* <pre>{@code
* Locator locator = page.getByTestId("save-button");
* assertThat(locator).hasRole(AriaRole.BUTTON);
* }</pre>
*
* @param role Required aria role.
* @since v1.44
*/
void hasRole(AriaRole role, HasRoleOptions options);
/**
* Ensures the {@code Locator} points to an element with the given text. All nested elements will be considered when
* computing the text content of the element. You can use regular expressions for the value as well.
@@ -52,11 +52,24 @@ public interface PageAssertions {
}
}
class HasURLOptions {
/**
* Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
* expression flag if specified.
*/
public Boolean ignoreCase;
/**
* Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
*/
public Double timeout;
/**
* Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
* expression flag if specified.
*/
public HasURLOptions setIgnoreCase(boolean ignoreCase) {
this.ignoreCase = ignoreCase;
return this;
}
/**
* Time to retry the assertion for in milliseconds. Defaults to {@code 5000}.
*/
@@ -29,6 +29,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static com.microsoft.playwright.impl.Serialization.*;
@@ -86,7 +87,7 @@ class APIRequestContextImpl extends ChannelOwner implements APIRequestContext {
for (Map.Entry<String, ?> e : options.params.entrySet()) {
queryParams.put(e.getKey(), "" + e.getValue());
}
params.add("params", toNameValueArray(queryParams));
params.add("params", toNameValueArray(queryParams.entrySet()));
}
if (options.method != null) {
params.addProperty("method", options.method);
@@ -149,9 +150,9 @@ class APIRequestContextImpl extends ChannelOwner implements APIRequestContext {
return false;
}
private static JsonArray serializeMultipartData(Map<String, Object> data) {
private static JsonArray serializeMultipartData(List<? extends Map.Entry<String, Object>> data) {
JsonArray result = new JsonArray();
for (Map.Entry<String, Object> e : data.entrySet()) {
for (Map.Entry<String, ?> e : data) {
FilePayload filePayload = null;
if (e.getValue() instanceof FilePayload) {
filePayload = (FilePayload) e.getValue();
@@ -20,6 +20,7 @@ import com.microsoft.playwright.PlaywrightException;
import org.opentest4j.AssertionFailedError;
import org.opentest4j.ValueWrapper;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
@@ -91,4 +92,17 @@ class AssertionsBase {
}
return expected;
}
static Boolean shouldIgnoreCase(Object options) {
if (options == null) {
return null;
}
try {
Field fromField = options.getClass().getDeclaredField("ignoreCase");
Object value = fromField.get(options);
return (Boolean) value;
} catch (NoSuchFieldException | IllegalAccessException e) {
return null;
}
}
}
@@ -20,39 +20,93 @@ import com.microsoft.playwright.options.FilePayload;
import com.microsoft.playwright.options.FormData;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;
public class FormDataImpl implements FormData {
Map<String, Object> fields = new LinkedHashMap<>();
static class Field implements Map.Entry<String, Object> {
final String name;
final Object value;
private Field(String name, Object value) {
this.name = name;
this.value = value;
}
@Override
public String getKey() {
return name;
}
@Override
public Object getValue() {
return value;
}
@Override
public Object setValue(Object value) {
throw new UnsupportedOperationException();
}
}
List<Field> fields = new ArrayList();
@Override
public FormData append(String name, String value) {
return appendImpl(name, value);
}
@Override
public FormData append(String name, boolean value) {
return appendImpl(name, value);
}
@Override
public FormData append(String name, int value) {
return appendImpl(name, value);
}
@Override
public FormData append(String name, Path value) {
return appendImpl(name, value);
}
@Override
public FormData append(String name, FilePayload value) {
return appendImpl(name, value);
}
@Override
public FormData set(String name, String value) {
fields.put(name, value);
return this;
return setImpl(name, value);
}
@Override
public FormData set(String name, boolean value) {
fields.put(name, value);
return this;
return setImpl(name, value);
}
@Override
public FormData set(String name, int value) {
fields.put(name, value);
return this;
return setImpl(name, value);
}
@Override
public FormData set(String name, Path value) {
fields.put(name, value);
return this;
return setImpl(name, value);
}
@Override
public FormData set(String name, FilePayload value) {
fields.put(name, value);
return setImpl(name, value);
}
private FormData setImpl(String name, Object value) {
fields = fields.stream().filter(f -> !name.equals(f.name)).collect(Collectors.toList());
return appendImpl(name, value);
}
private FormData appendImpl(String name, Object value) {
fields.add(new Field(name, value));
return this;
}
}
@@ -33,6 +33,7 @@ class JsonPipe extends ChannelOwner implements Transport {
private ListenerCollection<EventType> listeners = new ListenerCollection<>();
private enum EventType { CLOSE }
private boolean isClosed;
private String closeReason = "Browser has been closed";
JsonPipe(ChannelOwner parent, String type, String guid, JsonObject initializer) {
super(parent, type, guid, initializer);
@@ -97,13 +98,19 @@ class JsonPipe extends ChannelOwner implements Transport {
incoming.add(params.get("message").getAsJsonObject());
} else if ("closed".equals(event)) {
isClosed = true;
if (params.has("reason")) {
String reason = params.get("reason").getAsString();
if (reason.trim().length() > 0) {
closeReason = reason;
}
}
listeners.notify(EventType.CLOSE, this);
}
}
private void checkIfClosed() {
if (isClosed) {
throw new PlaywrightException("Browser has been closed");
throw new PlaywrightException(closeReason);
}
}
}
@@ -18,6 +18,7 @@ package com.microsoft.playwright.impl;
import com.microsoft.playwright.Locator;
import com.microsoft.playwright.assertions.LocatorAssertions;
import com.microsoft.playwright.options.AriaRole;
import java.lang.reflect.Field;
import java.util.ArrayList;
@@ -82,6 +83,36 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
expectImpl("to.contain.text.array", list, patterns, "Locator expected to contain text", convertType(options, FrameExpectOptions.class));
}
@Override
public void hasAccessibleDescription(String description, HasAccessibleDescriptionOptions options) {
ExpectedTextValue expected = new ExpectedTextValue();
expected.string = description;
expected.ignoreCase = shouldIgnoreCase(options);
expectImpl("to.have.accessible.description", expected, description, "Locator expected to have accessible description", convertType(options, FrameExpectOptions.class));
}
@Override
public void hasAccessibleDescription(Pattern pattern, HasAccessibleDescriptionOptions options) {
ExpectedTextValue expected = expectedRegex(pattern);
expected.ignoreCase = shouldIgnoreCase(options);
expectImpl("to.have.accessible.description", expected, pattern, "Locator expected to have accessible description", convertType(options, FrameExpectOptions.class));
}
@Override
public void hasAccessibleName(String name, HasAccessibleNameOptions options) {
ExpectedTextValue expected = new ExpectedTextValue();
expected.string = name;
expected.ignoreCase = shouldIgnoreCase(options);
expectImpl("to.have.accessible.name", expected, name, "Locator expected to have accessible name", convertType(options, FrameExpectOptions.class));
}
@Override
public void hasAccessibleName(Pattern pattern, HasAccessibleNameOptions options) {
ExpectedTextValue expected = expectedRegex(pattern);
expected.ignoreCase = shouldIgnoreCase(options);
expectImpl("to.have.accessible.name", expected, pattern, "Locator expected to have accessible name", convertType(options, FrameExpectOptions.class));
}
@Override
public void hasAttribute(String name, String text, HasAttributeOptions options) {
ExpectedTextValue expected = new ExpectedTextValue();
@@ -206,6 +237,13 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
expectImpl("to.have.property", list, value, "Locator expected to have JavaScript property '" + name + "'", commonOptions);
}
@Override
public void hasRole(AriaRole role, HasRoleOptions options) {
ExpectedTextValue expected = new ExpectedTextValue();
expected.string = role.toString().toLowerCase();
expectImpl("to.have.role", expected, expected.string, "Locator expected to have role", convertType(options, FrameExpectOptions.class));
}
@Override
public void hasText(String text, HasTextOptions options) {
ExpectedTextValue expected = new ExpectedTextValue();
@@ -366,17 +404,4 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
String message = "Locator expected to be " + (attached ? "attached" : "detached");
expectTrue(attached ? "to.be.attached" : "to.be.detached", message, frameOptions);
}
private static Boolean shouldIgnoreCase(Object options) {
if (options == null) {
return null;
}
try {
Field fromField = options.getClass().getDeclaredField("ignoreCase");
Object value = fromField.get(options);
return (Boolean) value;
} catch (NoSuchFieldException | IllegalAccessException e) {
return null;
}
}
}
@@ -624,6 +624,20 @@ class LocatorImpl implements Locator {
return "Locator@" + selector;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof LocatorImpl)) {
return false;
}
LocatorImpl locator = (LocatorImpl) obj;
return frame.equals(locator.frame) && selector.equals(locator.selector);
}
@Override
public int hashCode() {
return frame.hashCode() ^ selector.hashCode();
}
FrameExpectResult expect(String expression, FrameExpectOptions options) {
return frame.withLogging("Locator.expect", () -> expectImpl(expression, options));
}
@@ -21,6 +21,7 @@ import com.microsoft.playwright.assertions.PageAssertions;
import java.util.regex.Pattern;
import static com.microsoft.playwright.impl.LocatorAssertionsImpl.shouldIgnoreCase;
import static com.microsoft.playwright.impl.UrlMatcher.resolveUrl;
import static com.microsoft.playwright.impl.Utils.convertType;
@@ -57,6 +58,7 @@ public class PageAssertionsImpl extends AssertionsBase implements PageAssertions
url = resolveUrl(actualPage.context().baseUrl, url);
}
expected.string = url;
expected.ignoreCase = shouldIgnoreCase(options);
expectImpl("to.have.url", expected, url, "Page URL expected to be", convertType(options, FrameExpectOptions.class));
}
@@ -49,7 +49,34 @@ public class PageImpl extends ChannelOwner implements Page {
private ViewportSize viewport;
private final Router routes = new Router();
private final Set<FrameImpl> frames = new LinkedHashSet<>();
private final Map<Integer, Runnable> locatorHandlers = new HashMap<>();
private final Map<Integer, LocatorHandler> locatorHandlers = new HashMap<>();
private static class LocatorHandler {
private final Locator locator;
private final Consumer<Locator> handler;
private Integer times;
LocatorHandler(Locator locator, Consumer<Locator> handler, Integer times) {
this.locator = locator;
this.handler = handler;
this.times = times;
}
boolean call() {
if (shouldRemove()) {
return true;
}
if (times != null) {
--times;
}
handler.accept(locator);
return shouldRemove();
}
private boolean shouldRemove() {
return times != null && times == 0;
}
}
private static final Map<EventType, String> eventSubscriptions() {
Map<EventType, String> result = new HashMap<>();
@@ -530,29 +557,55 @@ public class PageImpl extends ChannelOwner implements Page {
}
@Override
public void addLocatorHandler(Locator locator, Runnable handler) {
public void addLocatorHandler(Locator locator, Consumer<Locator> handler, AddLocatorHandlerOptions options) {
LocatorImpl locatorImpl = (LocatorImpl) locator;
if (locatorImpl.frame != mainFrame) {
throw new PlaywrightException("Locator must belong to the main frame of this page");
}
if (options == null) {
options = new AddLocatorHandlerOptions();
}
if (options.times != null && options.times == 0) {
return;
}
AddLocatorHandlerOptions finalOptions = options;
withLogging("Page.addLocatorHandler", () -> {
JsonObject params = new JsonObject();
params.addProperty("selector", locatorImpl.selector);
if (finalOptions.noWaitAfter != null && finalOptions.noWaitAfter) {
params.addProperty("noWaitAfter", true);
}
params.addProperty("selector", locatorImpl.selector);
JsonObject json = (JsonObject) sendMessage("registerLocatorHandler", params);
int uid = json.get("uid").getAsInt();
locatorHandlers.put(uid, handler);
locatorHandlers.put(uid, new LocatorHandler(locator, handler, finalOptions.times));
});
}
private void onLocatorHandlerTriggered(int uid) {
try {
Runnable handler = locatorHandlers.get(uid);
if (handler != null) {
handler.run();
@Override
public void removeLocatorHandler(Locator locator) {
for (Map.Entry<Integer, LocatorHandler> entry: locatorHandlers.entrySet()) {
if (entry.getValue().locator.equals(locator)) {
locatorHandlers.remove(locator);
JsonObject params = new JsonObject();
params.addProperty("uid", entry.getKey());
try {
sendMessage("unregisterLocatorHandler", params);
} catch (PlaywrightException e) {
}
}
}
}
private void onLocatorHandlerTriggered(int uid) {
boolean remove = false;
try {
LocatorHandler handler = locatorHandlers.get(uid);
remove = handler != null && handler.call();
} finally {
JsonObject params = new JsonObject();
params.addProperty("uid", uid);
params.addProperty("remove", remove);
sendMessageAsync("resolveLocatorHandlerNoReply", params);
}
}
@@ -351,7 +351,7 @@ class Serialization {
throw new PlaywrightException("Value cannot be null");
}
}
return toNameValueArray(map);
return toNameValueArray(map.entrySet());
}
static void addHarUrlFilter(JsonObject options, Object urlFilter) {
@@ -364,9 +364,9 @@ class Serialization {
}
}
static JsonArray toNameValueArray(Map<String, ?> map) {
static JsonArray toNameValueArray(Iterable<? extends Map.Entry<String, ?>> collection) {
JsonArray array = new JsonArray();
for (Map.Entry<String, ?> e : map.entrySet()) {
for (Map.Entry<String, ?> e : collection) {
JsonObject item = new JsonObject();
item.addProperty("name", e.getKey());
if (e.getValue() instanceof FilePayload) {
@@ -32,6 +32,141 @@ import java.nio.file.Path;
* }</pre>
*/
public interface FormData {
/**
* Appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. File
* values can be passed either as {@code Path} or as {@code FilePayload}. Multiple fields with the same name can be added.
*
* <p> The difference between {@link com.microsoft.playwright.FormData#set FormData.set()} and {@link
* com.microsoft.playwright.FormData#append FormData.append()} is that if the specified key already exists, {@link
* com.microsoft.playwright.FormData#set FormData.set()} will overwrite all existing values with the new one, whereas
* {@link com.microsoft.playwright.FormData#append FormData.append()} will append the new value onto the end of the
* existing set of values.
* <pre>{@code
* import com.microsoft.playwright.options.FormData;
* ...
* FormData form = FormData.create()
* // Only name and value are set.
* .append("firstName", "John")
* // Name and value are set, filename and Content-Type are inferred from the file path.
* .append("attachment", Paths.get("pic.jpg"))
* // Name, value, filename and Content-Type are set.
* .append("attachment", new FilePayload("table.csv", "text/csv", Files.readAllBytes(Paths.get("my-tble.csv"))));
* page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
* }</pre>
*
* @param name Field name.
* @param value Field value.
* @since v1.44
*/
FormData append(String name, String value);
/**
* Appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. File
* values can be passed either as {@code Path} or as {@code FilePayload}. Multiple fields with the same name can be added.
*
* <p> The difference between {@link com.microsoft.playwright.FormData#set FormData.set()} and {@link
* com.microsoft.playwright.FormData#append FormData.append()} is that if the specified key already exists, {@link
* com.microsoft.playwright.FormData#set FormData.set()} will overwrite all existing values with the new one, whereas
* {@link com.microsoft.playwright.FormData#append FormData.append()} will append the new value onto the end of the
* existing set of values.
* <pre>{@code
* import com.microsoft.playwright.options.FormData;
* ...
* FormData form = FormData.create()
* // Only name and value are set.
* .append("firstName", "John")
* // Name and value are set, filename and Content-Type are inferred from the file path.
* .append("attachment", Paths.get("pic.jpg"))
* // Name, value, filename and Content-Type are set.
* .append("attachment", new FilePayload("table.csv", "text/csv", Files.readAllBytes(Paths.get("my-tble.csv"))));
* page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
* }</pre>
*
* @param name Field name.
* @param value Field value.
* @since v1.44
*/
FormData append(String name, boolean value);
/**
* Appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. File
* values can be passed either as {@code Path} or as {@code FilePayload}. Multiple fields with the same name can be added.
*
* <p> The difference between {@link com.microsoft.playwright.FormData#set FormData.set()} and {@link
* com.microsoft.playwright.FormData#append FormData.append()} is that if the specified key already exists, {@link
* com.microsoft.playwright.FormData#set FormData.set()} will overwrite all existing values with the new one, whereas
* {@link com.microsoft.playwright.FormData#append FormData.append()} will append the new value onto the end of the
* existing set of values.
* <pre>{@code
* import com.microsoft.playwright.options.FormData;
* ...
* FormData form = FormData.create()
* // Only name and value are set.
* .append("firstName", "John")
* // Name and value are set, filename and Content-Type are inferred from the file path.
* .append("attachment", Paths.get("pic.jpg"))
* // Name, value, filename and Content-Type are set.
* .append("attachment", new FilePayload("table.csv", "text/csv", Files.readAllBytes(Paths.get("my-tble.csv"))));
* page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
* }</pre>
*
* @param name Field name.
* @param value Field value.
* @since v1.44
*/
FormData append(String name, int value);
/**
* Appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. File
* values can be passed either as {@code Path} or as {@code FilePayload}. Multiple fields with the same name can be added.
*
* <p> The difference between {@link com.microsoft.playwright.FormData#set FormData.set()} and {@link
* com.microsoft.playwright.FormData#append FormData.append()} is that if the specified key already exists, {@link
* com.microsoft.playwright.FormData#set FormData.set()} will overwrite all existing values with the new one, whereas
* {@link com.microsoft.playwright.FormData#append FormData.append()} will append the new value onto the end of the
* existing set of values.
* <pre>{@code
* import com.microsoft.playwright.options.FormData;
* ...
* FormData form = FormData.create()
* // Only name and value are set.
* .append("firstName", "John")
* // Name and value are set, filename and Content-Type are inferred from the file path.
* .append("attachment", Paths.get("pic.jpg"))
* // Name, value, filename and Content-Type are set.
* .append("attachment", new FilePayload("table.csv", "text/csv", Files.readAllBytes(Paths.get("my-tble.csv"))));
* page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
* }</pre>
*
* @param name Field name.
* @param value Field value.
* @since v1.44
*/
FormData append(String name, Path value);
/**
* Appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. File
* values can be passed either as {@code Path} or as {@code FilePayload}. Multiple fields with the same name can be added.
*
* <p> The difference between {@link com.microsoft.playwright.FormData#set FormData.set()} and {@link
* com.microsoft.playwright.FormData#append FormData.append()} is that if the specified key already exists, {@link
* com.microsoft.playwright.FormData#set FormData.set()} will overwrite all existing values with the new one, whereas
* {@link com.microsoft.playwright.FormData#append FormData.append()} will append the new value onto the end of the
* existing set of values.
* <pre>{@code
* import com.microsoft.playwright.options.FormData;
* ...
* FormData form = FormData.create()
* // Only name and value are set.
* .append("firstName", "John")
* // Name and value are set, filename and Content-Type are inferred from the file path.
* .append("attachment", Paths.get("pic.jpg"))
* // Name, value, filename and Content-Type are set.
* .append("attachment", new FilePayload("table.csv", "text/csv", Files.readAllBytes(Paths.get("my-tble.csv"))));
* page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
* }</pre>
*
* @param name Field name.
* @param value Field value.
* @since v1.44
*/
FormData append(String name, FilePayload value);
/**
* Creates new instance of {@code FormData}.
*
@@ -51,7 +186,7 @@ public interface FormData {
* // Name and value are set, filename and Content-Type are inferred from the file path.
* .set("profilePicture1", Paths.get("john.jpg"))
* // Name, value, filename and Content-Type are set.
* .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg"))));
* .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg"))))
* .set("age", 30);
* page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
* }</pre>
@@ -72,7 +207,7 @@ public interface FormData {
* // Name and value are set, filename and Content-Type are inferred from the file path.
* .set("profilePicture1", Paths.get("john.jpg"))
* // Name, value, filename and Content-Type are set.
* .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg"))));
* .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg"))))
* .set("age", 30);
* page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
* }</pre>
@@ -93,7 +228,7 @@ public interface FormData {
* // Name and value are set, filename and Content-Type are inferred from the file path.
* .set("profilePicture1", Paths.get("john.jpg"))
* // Name, value, filename and Content-Type are set.
* .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg"))));
* .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg"))))
* .set("age", 30);
* page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
* }</pre>
@@ -114,7 +249,7 @@ public interface FormData {
* // Name and value are set, filename and Content-Type are inferred from the file path.
* .set("profilePicture1", Paths.get("john.jpg"))
* // Name, value, filename and Content-Type are set.
* .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg"))));
* .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg"))))
* .set("age", 30);
* page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
* }</pre>
@@ -135,7 +270,7 @@ public interface FormData {
* // Name and value are set, filename and Content-Type are inferred from the file path.
* .set("profilePicture1", Paths.get("john.jpg"))
* // Name, value, filename and Content-Type are set.
* .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg"))));
* .set("profilePicture2", new FilePayload("john.jpg", "image/jpeg", Files.readAllBytes(Paths.get("john.jpg"))))
* .set("age", 30);
* page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
* }</pre>
@@ -591,6 +591,46 @@ public class TestBrowserContextFetch extends TestBase {
assertEquals(200, response.status());
}
@Test
public void shouldSupportRepeatingNamesInMultipartFormData() throws InterruptedException, ExecutionException {
Future<Server.Request> serverRequest = server.futureRequest("/empty.html");
FilePayload file1 = new FilePayload("f.js", "text/javascript",
"var x = 10;\r\n;console.log(x);".getBytes(StandardCharsets.UTF_8));
FilePayload file2 = new FilePayload("f2.txt", "text/plain",
"hello".getBytes(StandardCharsets.UTF_8));
APIResponse response = context.request().post(server.EMPTY_PAGE, RequestOptions.create().setMultipart(
FormData.create()
.set("name", "John")
.append("name", "Doe")
.append("file", file1)
.append("file", file2)));
assertEquals("POST", serverRequest.get().method);
List<String> contentType = serverRequest.get().headers.get("content-type");
assertNotNull(contentType);
assertEquals(1, contentType.size());
assertTrue(contentType.get(0).contains("multipart/form-data"), contentType.get(0));
String body = new String(serverRequest.get().postBody);
assertTrue(body.contains("content-disposition: form-data; name=\"name\"\r\n" +
"\r\n" +
"John"), body);
assertTrue(body.contains("content-disposition: form-data; name=\"name\"\r\n" +
"\r\n" +
"Doe"), body);
assertTrue(body.contains("content-disposition: form-data; name=\"file\"; filename=\"f.js\"\r\n" +
"content-type: text/javascript\r\n" +
"\r\n" +
"var x = 10;\r\n" +
";console.log(x);"), body);
assertTrue(body.contains("content-disposition: form-data; name=\"file\"; filename=\"f2.txt\"\r\n" +
"content-type: text/plain\r\n" +
"\r\n" +
"hello"), body);
assertEquals(200, response.status());
}
@Test
void shouldSupportMultipartFormDataWithPathValues(@TempDir Path tmp) throws ExecutionException, InterruptedException, IOException {
Future<Server.Request> serverRequest = server.futureRequest("/empty.html");
@@ -238,7 +238,7 @@ public class TestBrowserTypeConnect extends TestBase {
}
assertFalse(remote.isConnected());
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.evaluate("1 + 1"));
assertTrue(e.getMessage().contains("Browser has been closed"), e.getMessage());
assertTrue(e.getMessage().contains("Browser has been closed") || e.getMessage().contains("Browser closed"), e.getMessage());
assertFalse(remote.isConnected());
}
@@ -259,7 +259,7 @@ public class TestBrowserTypeConnect extends TestBase {
}
assertFalse(browser.isConnected());
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.waitForNavigation(() -> {}));
assertTrue(e.getMessage().contains("Page closed") || e.getMessage().contains("Browser has been closed"), e.getMessage());
assertTrue(e.getMessage().contains("Browser closed") || e.getMessage().contains("Page closed") || e.getMessage().contains("Browser has been closed"), e.getMessage());
}
@Test
@@ -17,9 +17,12 @@
package com.microsoft.playwright;
import com.microsoft.playwright.assertions.LocatorAssertions;
import com.microsoft.playwright.options.AriaRole;
import org.junit.jupiter.api.Test;
import org.opentest4j.AssertionFailedError;
import java.util.regex.Pattern;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
@@ -115,4 +118,36 @@ public class TestLocatorAssertions2 extends TestBase {
page.setContent("<div id=node>Text content</div>");
assertThat(page.locator("no-such-thing")).not().isAttached(new LocatorAssertions.IsAttachedOptions().setTimeout(1));
}
@Test
public void toHaveAccessibleName() {
page.setContent("<div role=\"button\" aria-label=\"Hello\"></div>");
assertThat(page.locator("div")).hasAccessibleName("Hello");
assertThat(page.locator("div")).not().hasAccessibleName("hello");
assertThat(page.locator("div")).hasAccessibleName("hello", new LocatorAssertions.HasAccessibleNameOptions().setIgnoreCase(true));
assertThat(page.locator("div")).hasAccessibleName(Pattern.compile("ell\\w"));
assertThat(page.locator("div")).not().hasAccessibleName(Pattern.compile("hello"));
assertThat(page.locator("div")).hasAccessibleName(Pattern.compile("hello"), new LocatorAssertions.HasAccessibleNameOptions().setIgnoreCase(true));
}
@Test
public void toHaveAccessibleDescription() {
page.setContent("<div role=\"button\" aria-description=\"Hello\"></div>");
assertThat(page.locator("div")).hasAccessibleDescription("Hello");
assertThat(page.locator("div")).not().hasAccessibleDescription("hello");
assertThat(page.locator("div")).hasAccessibleDescription("hello", new LocatorAssertions.HasAccessibleDescriptionOptions().setIgnoreCase(true));
assertThat(page.locator("div")).hasAccessibleDescription(Pattern.compile("ell\\w"));
assertThat(page.locator("div")).not().hasAccessibleDescription(Pattern.compile("hello"));
assertThat(page.locator("div")).hasAccessibleDescription(Pattern.compile("hello"), new LocatorAssertions.HasAccessibleDescriptionOptions().setIgnoreCase(true));
}
@Test
public void toHaveRole() {
page.setContent("<div role=\"button\">Button!</div>");
assertThat(page.locator("div")).hasRole(AriaRole.BUTTON);
assertThat(page.locator("div")).not().hasRole(AriaRole.CHECKBOX);
}
}
@@ -16,6 +16,8 @@
package com.microsoft.playwright;
import com.microsoft.playwright.options.AriaRole;
import com.microsoft.playwright.options.WaitForSelectorState;
import org.junit.jupiter.api.Test;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
@@ -29,11 +31,13 @@ public class TestPageAddLocatorHandler extends TestBase {
int[] beforeCount = {0};
int[] afterCount = {0};
page.addLocatorHandler(page.getByText("This interstitial covers the button"), () -> {
Locator originalLocator = page.getByText("This interstitial covers the button");
page.addLocatorHandler(originalLocator, locator -> {
assertEquals(originalLocator, locator);
++beforeCount[0];
page.locator("#close").click();
++afterCount[0];
});
}, new Page.AddLocatorHandlerOptions().setNoWaitAfter(true));
String[][] argsList = {
{"mouseover", "1"},
@@ -73,10 +77,10 @@ public class TestPageAddLocatorHandler extends TestBase {
void shouldWorkWithCustomCheck() {
page.navigate(server.PREFIX + "/input/handle-locator.html");
page.addLocatorHandler(page.locator("body"), () -> {
page.addLocatorHandler(page.locator("body"), locator -> {
if (page.getByText("This interstitial covers the button").isVisible())
page.locator("#close").click();
});
}, new Page.AddLocatorHandlerOptions().setNoWaitAfter(true));
String[][] argsList = {
{"mouseover", "2"},
@@ -103,7 +107,7 @@ public class TestPageAddLocatorHandler extends TestBase {
void shouldWorkWithLocatorHover() {
page.navigate(server.PREFIX + "/input/handle-locator.html");
page.addLocatorHandler(page.getByText("This interstitial covers the button"), () -> {
page.addLocatorHandler(page.getByText("This interstitial covers the button"), locator -> {
page.locator("#close").click();
});
@@ -120,7 +124,7 @@ public class TestPageAddLocatorHandler extends TestBase {
void shouldNotWorkWithForceTrue() {
page.navigate(server.PREFIX + "/input/handle-locator.html");
page.addLocatorHandler(page.getByText("This interstitial covers the button"), () -> {
page.addLocatorHandler(page.getByText("This interstitial covers the button"), locator -> {
page.locator("#close").click();
});
@@ -138,7 +142,7 @@ public class TestPageAddLocatorHandler extends TestBase {
void shouldThrowWhenPageCloses() {
page.navigate(server.PREFIX + "/input/handle-locator.html");
page.addLocatorHandler(page.getByText("This interstitial covers the button"), () -> {
page.addLocatorHandler(page.getByText("This interstitial covers the button"), locator -> {
page.close();
});
@@ -156,7 +160,7 @@ public class TestPageAddLocatorHandler extends TestBase {
page.navigate(server.PREFIX + "/input/handle-locator.html");
int[] called = {0};
page.addLocatorHandler(page.getByText("This interstitial covers the button"), () -> {
page.addLocatorHandler(page.getByText("This interstitial covers the button"), locator -> {
++called[0];
page.locator("#close").click();
});
@@ -169,4 +173,168 @@ public class TestPageAddLocatorHandler extends TestBase {
assertThat(page.locator("#interstitial")).not().isVisible();
assertEquals(1, called[0]);
}
@Test
public void shouldWorkWhenOwnerFrameDetaches() {
Page page = browser.newPage();
page.navigate(server.EMPTY_PAGE);
page.evaluate("() => {\n" +
" const iframe = document.createElement('iframe');\n" +
" iframe.src = 'data:text/html,<body>hello from iframe</body>';\n" +
" document.body.append(iframe);\n" +
"\n" +
" const target = document.createElement('button');\n" +
" target.textContent = 'Click me';\n" +
" target.id = 'target';\n" +
" target.addEventListener('click', () => window._clicked = true);\n" +
" document.body.appendChild(target);\n" +
"\n" +
" const closeButton = document.createElement('button');\n" +
" closeButton.textContent = 'close';\n" +
" closeButton.id = 'close';\n" +
" closeButton.addEventListener('click', () => iframe.remove());\n" +
" document.body.appendChild(closeButton);\n" +
" }");
page.addLocatorHandler(page.frameLocator("iframe").locator("body"), locator -> {
page.locator("#close").click();
});
page.locator("#target").click();
assertNull(page.querySelector("iframe"));
assertTrue((Boolean) page.evaluate("window._clicked"));
}
@Test
public void shouldWorkWithTimesOption() {
Page page = browser.newPage();
page.navigate(server.PREFIX + "/input/handle-locator.html");
int[] called = {0};
page.addLocatorHandler(page.locator("body"), locator -> {
++called[0];
}, new Page.AddLocatorHandlerOptions().setNoWaitAfter(true).setTimes(2));
page.locator("#aside").hover();
page.evaluate("() => {\n" +
" window.clicked = 0;\n" +
" window.setupAnnoyingInterstitial('mouseover', 4);\n" +
" }");
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.locator("#target").click(new Locator.ClickOptions().setTimeout(3_000)));
assertEquals(2, called[0]);
assertEquals(0, (int) page.evaluate("window.clicked"));
assertTrue(page.locator("#interstitial").isVisible());
assertTrue(e.getMessage().contains("Timeout 3000ms exceeded"), e.getMessage());
assertTrue(e.getMessage().contains("<div>This interstitial covers the button</div> from <div class=\"visible\" id=\"interstitial\">…</div> subtree intercepts pointer events"), e.getMessage());
}
@Test
public void shouldWaitForHiddenByDefault() {
Page page = browser.newPage();
page.navigate(server.PREFIX + "/input/handle-locator.html");
int[] called = {0};
page.addLocatorHandler(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("close")), button -> {
++called[0];
button.click();
});
page.locator("#aside").hover();
page.evaluate("() => {" +
"window.clicked = 0;" +
"window.setupAnnoyingInterstitial('timeout', 1);" +
"}");
page.locator("#target").click();
assertEquals(1, (int) page.evaluate("window.clicked"));
assertFalse(page.locator("#interstitial").isVisible());
assertEquals(1, called[0]);
}
@Test
public void shouldWaitForHiddenByDefault2() {
Page page = browser.newPage();
page.navigate(server.PREFIX + "/input/handle-locator.html");
int[] called = {0};
page.addLocatorHandler(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("close")), button -> {
++called[0];
});
page.locator("#aside").hover();
page.evaluate("() => {" +
"window.clicked = 0;" +
"window.setupAnnoyingInterstitial('hide', 1);" +
"}");
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.locator("#target").click(new Locator.ClickOptions().setTimeout(3_000)));
assertEquals(0, (int) page.evaluate("window.clicked"));
assertThat(page.locator("#interstitial")).isVisible();
assertEquals(1, called[0]);
assertTrue(e.getMessage().contains("locator handler has finished, waiting for getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"close\")) to be hidden"), e.getMessage());
}
@Test
public void shouldWorkWithNoWaitAfter() {
Page page = browser.newPage();
page.navigate(server.PREFIX + "/input/handle-locator.html");
int[] called = {0};
page.addLocatorHandler(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("close")), button -> {
++called[0];
if (called[0] == 1) {
button.click();
} else {
page.locator("#interstitial").waitFor(new Locator.WaitForOptions().setState(WaitForSelectorState.HIDDEN));
}
}, new Page.AddLocatorHandlerOptions().setNoWaitAfter(true));
page.locator("#aside").hover();
page.evaluate("() => {" +
"window.clicked = 0;" +
"window.setupAnnoyingInterstitial('timeout', 1);" +
"}");
page.locator("#target").click();
assertEquals(1, (int) page.evaluate("window.clicked"));
assertThat(page.locator("#interstitial")).not().isVisible();
assertEquals(2, called[0]);
}
@Test
public void shouldRemoveLocatorHandler() {
Page page = browser.newPage();
page.navigate(server.PREFIX + "/input/handle-locator.html");
int[] called = {0};
page.addLocatorHandler(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("close")), button -> {
++called[0];
button.click();
});
page.evaluate("() => {" +
"window.clicked = 0;" +
"window.setupAnnoyingInterstitial('hide', 1);" +
"}");
page.locator("#target").click();
assertEquals(1, called[0]);
assertEquals(1, (int) page.evaluate("window.clicked"));
assertThat(page.locator("#interstitial")).not().isVisible();
page.evaluate("() => {" +
"window.clicked = 0;" +
"window.setupAnnoyingInterstitial('hide', 1);" +
"}");
page.removeLocatorHandler(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("close")));
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.locator("#target").click(new Locator.ClickOptions().setTimeout(3_000)));
assertEquals(1, called[0]);
assertEquals(0, (int) page.evaluate("window.clicked"));
assertThat(page.locator("#interstitial")).isVisible();
assertTrue(e.getMessage().contains("Timeout 3000ms exceeded"));
}
}
@@ -58,6 +58,12 @@ public class TestPageAssertions extends TestBase {
assertThat(page).not().hasURL("about:blank", new PageAssertions.HasURLOptions().setTimeout(1000));
}
@Test
public void hasUrlSupportIgnoreCase() {
page.navigate("data:text/html,<div>A</div>");
assertThat(page).hasURL("DATA:teXT/HTml,<div>a</div>", new PageAssertions.HasURLOptions().setIgnoreCase(true));
}
@Test
void hasURLRegexPass() {
page.navigate("data:text/html,<div>A</div>");
@@ -252,8 +252,20 @@ public class TestPageScreenshot extends TestBase {
assertThrows(AssertionError.class, () -> assertArrayEquals(screenshot1, screenshot2));
}
static boolean isScreenshotTestDisabled() {
if (isWebKit()) {
// Array lengths differ.
return true;
}
if (getBrowserChannelFromEnv() != null) {
// Stable builds may have different expectations.
return true;
}
return false;
}
@Test
@DisabledIf(value="com.microsoft.playwright.TestBase#isWebKit", disabledReason="array lengths differ")
@DisabledIf(value="com.microsoft.playwright.TestPageScreenshot#isScreenshotTestDisabled", disabledReason="array lengths differ")
void shouldHideElementsBasedOnAttr() throws IOException {
page.setViewportSize(500, 500);
page.navigate(server.PREFIX + "/grid.html");
@@ -269,7 +281,7 @@ public class TestPageScreenshot extends TestBase {
}
@Test
@DisabledIf(value="com.microsoft.playwright.TestBase#isWebKit", disabledReason="array lengths differ")
@DisabledIf(value="com.microsoft.playwright.TestPageScreenshot#isScreenshotTestDisabled", disabledReason="array lengths differ")
void shouldRemoveElementsBasedOnAttr() throws IOException {
page.setViewportSize(500, 500);
page.navigate(server.PREFIX + "/grid.html");
Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 32 KiB

@@ -50,9 +50,16 @@
}, false);
close.addEventListener('click', () => {
interstitial.classList.remove('visible');
target.classList.remove('hidden');
target.classList.remove('removed');
const closeInterstitial = () => {
interstitial.classList.remove('visible');
target.classList.remove('hidden');
target.classList.remove('removed');
};
if (interstitial.classList.contains('timeout'))
setTimeout(closeInterstitial, 3000);
else
closeInterstitial();
});
let timesToShow = 0;
@@ -65,9 +72,11 @@
if (!timesToShow && event !== 'none')
target.removeEventListener(event, listener, capture === 'capture');
};
if (event === 'hide') {
if (event === 'hide' || event === 'timeout') {
target.classList.add('hidden');
listener();
if (event === 'timeout')
interstitial.classList.add('timeout');
} else if (event === 'remove') {
target.classList.add('removed');
listener();
+1 -1
View File
@@ -1 +1 @@
1.44.0-alpha-2024-04-02
1.44.0-alpha-2024-04-27
@@ -294,6 +294,7 @@ class TypeRef extends Element {
customTypeNames.put("Frame.setInputFiles.files", "FilePayload");
customTypeNames.put("Page.setInputFiles.files", "FilePayload");
customTypeNames.put("Page.setInputFiles.files", "FilePayload");
customTypeNames.put("FormData.append.value", "FilePayload");
customTypeNames.put("FormData.set.value", "FilePayload");
customTypeNames.put("Locator.dragTo.options.sourcePosition", "Position");
@@ -996,6 +997,9 @@ class Interface extends TypeDefinition {
if ("CDPSession".equals(jsonName)) {
output.add("import com.google.gson.JsonObject;");
}
if ("LocatorAssertions".equals(jsonName)) {
output.add("import com.microsoft.playwright.options.AriaRole;");
}
if ("PlaywrightAssertions".equals(jsonName)) {
output.add("import com.microsoft.playwright.APIResponse;");
output.add("import com.microsoft.playwright.Locator;");
@@ -1215,6 +1219,11 @@ public class ApiGenerator {
}
}
// No options under assertions.
if (packageName.contains(".assertions")) {
return;
}
dir = new File(dir, "options");
for (TypeDefinition e : topLevelTypes.values()) {
List<String> lines = new ArrayList<>();