Compare commits
61 Commits
release-1.22
...
v1.26.1
| Author | SHA1 | Date | |
|---|---|---|---|
| c1c538c7dc | |||
| bfc7645d20 | |||
| c34a35d6a7 | |||
| 6ef0cc29dd | |||
| 8dfe959cce | |||
| 5979077403 | |||
| 020618d83d | |||
| 6bef6bb4a7 | |||
| 734d56f5d5 | |||
| 6e66861db3 | |||
| cf73a8d525 | |||
| 4a0ff6ef5c | |||
| 398c979378 | |||
| 39be690062 | |||
| b5b0a983bd | |||
| 6b842e0d50 | |||
| 321673407a | |||
| 4d278c391e | |||
| 5c47cfb1d5 | |||
| f036b3d38a | |||
| 385131e51b | |||
| 6cb9f60988 | |||
| aef9badd64 | |||
| 64f7a059af | |||
| 436fc12609 | |||
| 560575a9b5 | |||
| 0afaf6c561 | |||
| 202371b5d7 | |||
| 2093bba554 | |||
| 77538dcf7f | |||
| f759222755 | |||
| d87c6b24ca | |||
| 41355bd059 | |||
| e372513fa4 | |||
| b8e1e1d935 | |||
| a0745735d9 | |||
| b90de26d23 | |||
| adfdf92eaa | |||
| 60cb6ea7b3 | |||
| 44cb76d92c | |||
| 9fac877892 | |||
| ec8fb9f191 | |||
| 844d1665b2 | |||
| 484a255ec7 | |||
| 3f60144e0f | |||
| 8004e5d0ff | |||
| 3604aab710 | |||
| 2fdb89c94e | |||
| 4fee61a655 | |||
| efb281e016 | |||
| fdec32c650 | |||
| 7e285ffe44 | |||
| edf0e45fb4 | |||
| c8eb4f9eeb | |||
| e4ec9b8dbe | |||
| ef13ab86b8 | |||
| a48fef6b01 | |||
| 1c1f3d43ac | |||
| 8f59cd73f5 | |||
| e04ef2132c | |||
| 34d23a833e |
+4
-2
@@ -1,3 +1,5 @@
|
||||
# text files must be lf for golden file tests to work
|
||||
*.txt eol=lf
|
||||
*.json eol=lf
|
||||
* text=auto eol=lf
|
||||
|
||||
# make project show as TS on GitHub
|
||||
*.js linguist-detectable=false
|
||||
|
||||
@@ -31,18 +31,14 @@ jobs:
|
||||
- name: Build & Install
|
||||
run: mvn -B install -D skipTests --no-transfer-progress
|
||||
- name: Run tests
|
||||
run: mvn test -DexcludedGroups=isolated --no-transfer-progress --fail-at-end
|
||||
run: mvn test --no-transfer-progress --fail-at-end
|
||||
env:
|
||||
BROWSER: ${{ matrix.browser }}
|
||||
- name: Run tracing tests w/ sources
|
||||
run: mvn test -DexcludedGroups=isolated --no-transfer-progress --fail-at-end -D test=*TestTracing*
|
||||
run: mvn test --no-transfer-progress --fail-at-end -D test=*TestTracing*
|
||||
env:
|
||||
BROWSER: ${{ matrix.browser }}
|
||||
PLAYWRIGHT_JAVA_SRC: src/test/java
|
||||
- name: Run driver throw tests
|
||||
run: mvn test -Dgroups=driverThrowTest --no-transfer-progress --fail-at-end
|
||||
env:
|
||||
BROWSER: ${{ matrix.browser }}
|
||||
- name: Test Spring Boot Starter
|
||||
shell: bash
|
||||
env:
|
||||
@@ -83,12 +79,7 @@ jobs:
|
||||
- name: Build & Install
|
||||
run: mvn -B install -D skipTests --no-transfer-progress
|
||||
- name: Run tests
|
||||
run: mvn test -DexcludedGroups=isolated --no-transfer-progress --fail-at-end
|
||||
env:
|
||||
BROWSER: chromium
|
||||
BROWSER_CHANNEL: ${{ matrix.browser-channel }}
|
||||
- name: Run driver throw tests
|
||||
run: mvn test -Dgroups=driverThrowTest --no-transfer-progress --fail-at-end
|
||||
run: mvn test --no-transfer-progress --fail-at-end
|
||||
env:
|
||||
BROWSER: chromium
|
||||
BROWSER_CHANNEL: ${{ matrix.browser-channel }}
|
||||
|
||||
@@ -11,9 +11,9 @@ Playwright is a Java library to automate [Chromium](https://www.chromium.org/Hom
|
||||
|
||||
| | Linux | macOS | Windows |
|
||||
| :--- | :---: | :---: | :---: |
|
||||
| Chromium <!-- GEN:chromium-version -->102.0.5005.40<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
|
||||
| WebKit <!-- GEN:webkit-version -->15.4<!-- GEN:stop --> | ✅ | ✅ | ✅ |
|
||||
| Firefox <!-- GEN:firefox-version -->99.0.1<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
|
||||
| Chromium <!-- GEN:chromium-version -->106.0.5249.30<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
|
||||
| WebKit <!-- GEN:webkit-version -->16.0<!-- GEN:stop --> | ✅ | ✅ | ✅ |
|
||||
| Firefox <!-- GEN:firefox-version -->104.0<!-- 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/next/intro/#system-requirements) for details.
|
||||
|
||||
@@ -47,6 +47,14 @@ To run Playwright simply add following dependency to your Maven project:
|
||||
</dependency>
|
||||
```
|
||||
|
||||
To run Playwright using Gradle add following dependency to your build.gradle file:
|
||||
|
||||
```json lines
|
||||
dependencies {
|
||||
implementation group: 'com.microsoft.playwright', name: 'playwright', version: '1.25.0'
|
||||
}
|
||||
```
|
||||
|
||||
#### Is Playwright thread-safe?
|
||||
|
||||
No, Playwright is not thread safe, i.e. all its methods as well as methods on all objects created by it (such as BrowserContext, Browser, Page etc.) are expected to be called on the same thread where Playwright object was created or proper synchronization should be implemented to ensure only one thread calls Playwright methods at any given time. Having said that it's okay to create multiple Playwright instances each on its own thread.
|
||||
@@ -173,7 +181,7 @@ public class InterceptNetworkRequests {
|
||||
|
||||
## Documentation
|
||||
|
||||
Check out our [new documentation site](https://playwright.dev/java)!.
|
||||
Check out our official [documentation site](https://playwright.dev/java).
|
||||
|
||||
You can also browse [javadoc online](https://www.javadoc.io/doc/com.microsoft.playwright/playwright/latest/index.html).
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<parent>
|
||||
<groupId>com.microsoft.playwright</groupId>
|
||||
<artifactId>parent-pom</artifactId>
|
||||
<version>1.22.0-SNAPSHOT</version>
|
||||
<version>1.26.1</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>driver-bundle</artifactId>
|
||||
|
||||
+39
-8
@@ -14,7 +14,9 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.microsoft.playwright.impl;
|
||||
package com.microsoft.playwright.impl.driver.jar;
|
||||
|
||||
import com.microsoft.playwright.impl.driver.Driver;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
@@ -26,7 +28,10 @@ import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class DriverJar extends Driver {
|
||||
private static final String PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD = "PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD";
|
||||
private static final String SELENIUM_REMOTE_URL = "SELENIUM_REMOTE_URL";
|
||||
static final String PLAYWRIGHT_NODEJS_PATH = "PLAYWRIGHT_NODEJS_PATH";
|
||||
private final Path driverTempDir;
|
||||
private Path preinstalledNodePath;
|
||||
|
||||
public DriverJar() throws IOException {
|
||||
// Allow specifying custom path for the driver installation
|
||||
@@ -37,11 +42,27 @@ public class DriverJar extends Driver {
|
||||
? Files.createTempDirectory(prefix)
|
||||
: Files.createTempDirectory(Paths.get(alternativeTmpdir), prefix);
|
||||
driverTempDir.toFile().deleteOnExit();
|
||||
String nodePath = System.getProperty("playwright.nodejs.path");
|
||||
if (nodePath != null) {
|
||||
preinstalledNodePath = Paths.get(nodePath);
|
||||
if (!Files.exists(preinstalledNodePath)) {
|
||||
throw new RuntimeException("Invalid Node.js path specified: " + nodePath);
|
||||
}
|
||||
}
|
||||
logMessage("created DriverJar: " + driverTempDir);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void initialize(Map<String, String> env, Boolean installBrowsers) throws Exception {
|
||||
protected void initialize(Boolean installBrowsers) throws Exception {
|
||||
if (preinstalledNodePath == null && env.containsKey(PLAYWRIGHT_NODEJS_PATH)) {
|
||||
preinstalledNodePath = Paths.get(env.get(PLAYWRIGHT_NODEJS_PATH));
|
||||
if (!Files.exists(preinstalledNodePath)) {
|
||||
throw new RuntimeException("Invalid Node.js path specified: " + preinstalledNodePath);
|
||||
}
|
||||
} else if (preinstalledNodePath != null) {
|
||||
// Pass the env variable to the driver process.
|
||||
env.put(PLAYWRIGHT_NODEJS_PATH, preinstalledNodePath.toString());
|
||||
}
|
||||
extractDriverToTempDir();
|
||||
logMessage("extracted driver from jar to " + driverPath());
|
||||
if (installBrowsers)
|
||||
@@ -57,13 +78,16 @@ public class DriverJar extends Driver {
|
||||
System.out.println("Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set");
|
||||
return;
|
||||
}
|
||||
if (env.get(SELENIUM_REMOTE_URL) != null || System.getenv(SELENIUM_REMOTE_URL) != null) {
|
||||
logMessage("Skipping browsers download because `SELENIUM_REMOTE_URL` env variable is set");
|
||||
return;
|
||||
}
|
||||
Path driver = driverPath();
|
||||
if (!Files.exists(driver)) {
|
||||
throw new RuntimeException("Failed to find driver: " + driver);
|
||||
}
|
||||
ProcessBuilder pb = new ProcessBuilder(driver.toString(), "install");
|
||||
pb.environment().putAll(env);
|
||||
setRequiredEnvironmentVariables(pb);
|
||||
ProcessBuilder pb = createProcessBuilder();
|
||||
pb.command().add("install");
|
||||
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
|
||||
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
|
||||
Process p = pb.start();
|
||||
@@ -82,9 +106,10 @@ public class DriverJar extends Driver {
|
||||
return name.endsWith(".sh") || name.endsWith(".exe") || !name.contains(".");
|
||||
}
|
||||
|
||||
private void extractDriverToTempDir() throws URISyntaxException, IOException {
|
||||
void extractDriverToTempDir() throws URISyntaxException, IOException {
|
||||
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
|
||||
URI originalUri = classloader.getResource("driver/" + platformDir()).toURI();
|
||||
URI originalUri = classloader.getResource(
|
||||
"driver/" + platformDir()).toURI();
|
||||
URI uri = maybeExtractNestedJar(originalUri);
|
||||
|
||||
// Create zip filesystem if loading from jar.
|
||||
@@ -96,6 +121,12 @@ public class DriverJar extends Driver {
|
||||
// See https://github.com/microsoft/playwright-java/issues/306
|
||||
Path srcRootDefaultFs = Paths.get(srcRoot.toString());
|
||||
Files.walk(srcRoot).forEach(fromPath -> {
|
||||
if (preinstalledNodePath != null) {
|
||||
String fileName = fromPath.getFileName().toString();
|
||||
if ("node.exe".equals(fileName) || "node".equals(fileName)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
Path relative = srcRootDefaultFs.relativize(Paths.get(fromPath.toString()));
|
||||
Path toPath = driverTempDir.resolve(relative.toString());
|
||||
try {
|
||||
@@ -158,7 +189,7 @@ public class DriverJar extends Driver {
|
||||
}
|
||||
|
||||
@Override
|
||||
Path driverDir() {
|
||||
protected Path driverDir() {
|
||||
return driverTempDir;
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
* <p>
|
||||
* 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
|
||||
* <p>
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* <p>
|
||||
* 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.impl.Driver;
|
||||
import com.microsoft.playwright.impl.DriverJar;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestInstall {
|
||||
@BeforeEach
|
||||
void clearSystemProperties() {
|
||||
// Clear system property to ensure that the driver is loaded from jar.
|
||||
System.clearProperty("playwright.cli.dir");
|
||||
System.clearProperty("playwright.driver.tmpdir");
|
||||
// Clear system property to ensure that the default driver is loaded.
|
||||
System.clearProperty("playwright.driver.impl");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Tags({@Tag("isolated"), @Tag("driverThrowTest")})
|
||||
void shouldThrowWhenBrowserPathIsInvalid(@TempDir Path tmpDir) {
|
||||
Map<String,String> env = new HashMap<>();
|
||||
env.put("PLAYWRIGHT_DOWNLOAD_HOST", "https://127.0.0.127");
|
||||
// Make sure the browsers are not installed yet by pointing at an empty dir.
|
||||
env.put("PLAYWRIGHT_BROWSERS_PATH", tmpDir.toString());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> Driver.ensureDriverInstalled(env, true));
|
||||
assertThrows(RuntimeException.class, () -> Driver.ensureDriverInstalled(env, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void playwrightCliInstalled() throws Exception {
|
||||
Path cli = Driver.ensureDriverInstalled(Collections.emptyMap(), false);
|
||||
assertTrue(Files.exists(cli));
|
||||
|
||||
ProcessBuilder pb = new ProcessBuilder(cli.toString(), "install");
|
||||
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
|
||||
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
|
||||
Process p = pb.start();
|
||||
boolean result = p.waitFor(1, TimeUnit.MINUTES);
|
||||
assertTrue(result, "Timed out waiting for browsers to install");
|
||||
}
|
||||
|
||||
@Test
|
||||
void playwrightDriverInAlternativeTmpdir(@TempDir Path tmpdir) throws Exception {
|
||||
System.setProperty("playwright.driver.tmpdir", tmpdir.toString());
|
||||
DriverJar driver = new DriverJar();
|
||||
assertTrue(driver.driverPath().startsWith(tmpdir), "Driver path: " + driver.driverPath() + " tmp: " + tmpdir);
|
||||
}
|
||||
|
||||
@Test
|
||||
void playwrightDriverDefaultImpl() {
|
||||
assertDoesNotThrow(() -> Driver.ensureDriverInstalled(Collections.emptyMap(), false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void playwrightDriverAlternativeImpl() {
|
||||
System.setProperty("playwright.driver.impl", "com.microsoft.playwright.impl.AlternativeDriver");
|
||||
RuntimeException thrown =
|
||||
assertThrows(
|
||||
RuntimeException.class,
|
||||
() -> Driver.ensureDriverInstalled(Collections.emptyMap(), false));
|
||||
assertEquals("Failed to create driver", thrown.getMessage());
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
/*
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
* <p>
|
||||
* 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
|
||||
* <p>
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* <p>
|
||||
* 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.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;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.microsoft.playwright.impl.driver.jar.DriverJar.PLAYWRIGHT_NODEJS_PATH;
|
||||
import static java.util.Collections.singletonMap;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestInstall {
|
||||
private static boolean isPortAvailable(int port) {
|
||||
try (ServerSocket ignored = new ServerSocket(port)) {
|
||||
return true;
|
||||
} catch (IOException ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static int unusedPort() {
|
||||
for (int i = 10000; i < 11000; i++) {
|
||||
if (isPortAvailable(i)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("Cannot find unused local port");
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void clearSystemProperties() {
|
||||
// Clear system property to ensure that the driver is loaded from jar.
|
||||
System.clearProperty("playwright.cli.dir");
|
||||
System.clearProperty("playwright.driver.tmpdir");
|
||||
System.clearProperty("playwright.nodejs.path");
|
||||
// Clear system property to ensure that the default driver is loaded.
|
||||
System.clearProperty("playwright.driver.impl");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldThrowWhenBrowserPathIsInvalid(@TempDir Path tmpDir) throws NoSuchFieldException, IllegalAccessException {
|
||||
Map<String,String> env = new HashMap<>();
|
||||
|
||||
// On macOS we can only use 127.0.0.1, so pick unused port instead.
|
||||
// https://superuser.com/questions/458875/how-do-you-get-loopback-addresses-other-than-127-0-0-1-to-work-on-os-x
|
||||
env.put("PLAYWRIGHT_DOWNLOAD_HOST", "https://127.0.0.1:" + unusedPort());
|
||||
// Make sure the browsers are not installed yet by pointing at an empty dir.
|
||||
env.put("PLAYWRIGHT_BROWSERS_PATH", tmpDir.toString());
|
||||
env.put("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "false");
|
||||
|
||||
RuntimeException exception = assertThrows(RuntimeException.class, () -> Driver.createAndInstall(env, true));
|
||||
String message = exception.getMessage();
|
||||
assertTrue(message.contains("Failed to create driver"), message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void playwrightCliInstalled() throws Exception {
|
||||
Driver driver = Driver.createAndInstall(Collections.emptyMap(), false);
|
||||
assertTrue(Files.exists(driver.driverPath()));
|
||||
|
||||
ProcessBuilder pb = driver.createProcessBuilder();
|
||||
pb.command().add("install");
|
||||
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
|
||||
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
|
||||
Process p = pb.start();
|
||||
boolean result = p.waitFor(1, TimeUnit.MINUTES);
|
||||
assertTrue(result, "Timed out waiting for browsers to install");
|
||||
}
|
||||
|
||||
@Test
|
||||
void playwrightDriverInAlternativeTmpdir(@TempDir Path tmpdir) throws Exception {
|
||||
System.setProperty("playwright.driver.tmpdir", tmpdir.toString());
|
||||
DriverJar driver = new DriverJar();
|
||||
assertTrue(driver.driverPath().startsWith(tmpdir), "Driver path: " + driver.driverPath() + " tmp: " + tmpdir);
|
||||
}
|
||||
|
||||
@Test
|
||||
void playwrightDriverDefaultImpl() {
|
||||
assertDoesNotThrow(() -> Driver.createAndInstall(Collections.emptyMap(), false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void playwrightDriverAlternativeImpl() throws NoSuchFieldException, IllegalAccessException {
|
||||
System.setProperty("playwright.driver.impl", "com.microsoft.playwright.impl.AlternativeDriver");
|
||||
RuntimeException thrown =
|
||||
assertThrows(
|
||||
RuntimeException.class,
|
||||
() -> Driver.createAndInstall(Collections.emptyMap(), false));
|
||||
assertEquals("Failed to create driver", thrown.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void canPassPreinstalledNodeJsAsSystemProperty(@TempDir Path tmpDir) throws IOException, URISyntaxException, InterruptedException {
|
||||
String nodePath = extractNodeJsToTemp();
|
||||
System.setProperty("playwright.nodejs.path", nodePath);
|
||||
Driver driver = Driver.createAndInstall(Collections.emptyMap(), false);
|
||||
canSpecifyPreinstalledNodeJsShared(driver, tmpDir);
|
||||
}
|
||||
|
||||
@Test
|
||||
void canSpecifyPreinstalledNodeJsAsEnv(@TempDir Path tmpDir) throws IOException, URISyntaxException, InterruptedException {
|
||||
String nodePath = extractNodeJsToTemp();
|
||||
Driver driver = Driver.createAndInstall(singletonMap(PLAYWRIGHT_NODEJS_PATH, nodePath), false);
|
||||
canSpecifyPreinstalledNodeJsShared(driver, tmpDir);
|
||||
}
|
||||
|
||||
|
||||
private static String extractNodeJsToTemp() throws URISyntaxException, IOException {
|
||||
DriverJar auxDriver = new DriverJar();
|
||||
auxDriver.extractDriverToTempDir();
|
||||
String nodePath = auxDriver.driverPath().getParent().resolve(isWindows() ? "node.exe" : "node").toString();
|
||||
return nodePath;
|
||||
}
|
||||
|
||||
private static boolean isWindows() {
|
||||
String name = System.getProperty("os.name").toLowerCase();
|
||||
return name.contains("win");
|
||||
}
|
||||
|
||||
private static void canSpecifyPreinstalledNodeJsShared(Driver driver, Path tmpDir) throws IOException, URISyntaxException, InterruptedException {
|
||||
Path builtinNode = driver.driverPath().getParent().resolve("node");
|
||||
assertFalse(Files.exists(builtinNode), builtinNode.toString());
|
||||
Path builtinNodeExe = driver.driverPath().getParent().resolve("node.exe");
|
||||
assertFalse(Files.exists(builtinNodeExe), builtinNodeExe.toString());
|
||||
|
||||
ProcessBuilder pb = driver.createProcessBuilder();
|
||||
pb.command().add("--version");
|
||||
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
|
||||
Path out = tmpDir.resolve("out.txt");
|
||||
pb.redirectOutput(out.toFile());
|
||||
Process p = pb.start();
|
||||
boolean result = p.waitFor(1, TimeUnit.MINUTES);
|
||||
assertTrue(result, "Timed out waiting for version to be printed");
|
||||
String stdout = new String(Files.readAllBytes(out), StandardCharsets.UTF_8);
|
||||
assertTrue(stdout.contains("Version "), stdout);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
<parent>
|
||||
<groupId>com.microsoft.playwright</groupId>
|
||||
<artifactId>parent-pom</artifactId>
|
||||
<version>1.22.0-SNAPSHOT</version>
|
||||
<version>1.26.1</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>driver</artifactId>
|
||||
|
||||
+34
-21
@@ -14,14 +14,15 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.microsoft.playwright.impl;
|
||||
package com.microsoft.playwright.impl.driver;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.microsoft.playwright.impl.DriverLogging.logWithTimestamp;
|
||||
import static com.microsoft.playwright.impl.driver.DriverLogging.logWithTimestamp;
|
||||
|
||||
/**
|
||||
* This class provides access to playwright-cli. It can be either preinstalled
|
||||
@@ -29,6 +30,8 @@ import static com.microsoft.playwright.impl.DriverLogging.logWithTimestamp;
|
||||
* loaded from the driver-bundle module if that module is in the classpath.
|
||||
*/
|
||||
public abstract class Driver {
|
||||
protected final Map<String, String> env = new LinkedHashMap<>();
|
||||
|
||||
private static Driver instance;
|
||||
|
||||
private static class PreinstalledDriver extends Driver {
|
||||
@@ -39,32 +42,28 @@ public abstract class Driver {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void initialize(Map<String, String> env, Boolean installBrowsers) {
|
||||
protected void initialize(Boolean installBrowsers) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
@Override
|
||||
Path driverDir() {
|
||||
protected Path driverDir() {
|
||||
return driverDir;
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized Path ensureDriverInstalled(Map<String, String> env, Boolean installBrowsers) {
|
||||
public static synchronized Driver ensureDriverInstalled(Map<String, String> env, Boolean installBrowsers) {
|
||||
if (instance == null) {
|
||||
try {
|
||||
instance = createDriver();
|
||||
logMessage("initializing driver");
|
||||
instance.initialize(env, installBrowsers);
|
||||
logMessage("driver initialized.");
|
||||
} catch (Exception exception) {
|
||||
instance = null;
|
||||
throw new RuntimeException("Failed to create driver", exception);
|
||||
}
|
||||
instance = createAndInstall(env, installBrowsers);
|
||||
}
|
||||
return instance.driverPath();
|
||||
return instance;
|
||||
}
|
||||
|
||||
protected abstract void initialize(Map<String, String> env, Boolean installBrowsers) throws Exception;
|
||||
private void initialize(Map<String, String> env, Boolean installBrowsers) throws Exception {
|
||||
this.env.putAll(env);
|
||||
initialize(installBrowsers);
|
||||
}
|
||||
protected abstract void initialize(Boolean installBrowsers) throws Exception;
|
||||
|
||||
public Path driverPath() {
|
||||
String cliFileName = System.getProperty("os.name").toLowerCase().contains("windows") ?
|
||||
@@ -72,13 +71,16 @@ public abstract class Driver {
|
||||
return driverDir().resolve(cliFileName);
|
||||
}
|
||||
|
||||
public static void setRequiredEnvironmentVariables(ProcessBuilder pb) {
|
||||
public ProcessBuilder createProcessBuilder() {
|
||||
ProcessBuilder pb = new ProcessBuilder(driverPath().toString());
|
||||
pb.environment().putAll(env);
|
||||
pb.environment().put("PW_LANG_NAME", "java");
|
||||
pb.environment().put("PW_LANG_NAME_VERSION", getMajorJavaVersion());
|
||||
String version = Driver.class.getPackage().getImplementationVersion();
|
||||
if (version != null) {
|
||||
pb.environment().put("PW_CLI_DISPLAY_VERSION", version);
|
||||
}
|
||||
return pb;
|
||||
}
|
||||
|
||||
private static String getMajorJavaVersion() {
|
||||
@@ -92,20 +94,31 @@ public abstract class Driver {
|
||||
}
|
||||
return version;
|
||||
}
|
||||
public static Driver createAndInstall(Map<String, String> env, Boolean installBrowsers) {
|
||||
try {
|
||||
Driver instance = newInstance();
|
||||
logMessage("initializing driver");
|
||||
instance.initialize(env, installBrowsers);
|
||||
logMessage("driver initialized.");
|
||||
return instance;
|
||||
} catch (Exception exception) {
|
||||
throw new RuntimeException("Failed to create driver", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static Driver createDriver() throws Exception {
|
||||
private static Driver newInstance() throws Exception {
|
||||
String pathFromProperty = System.getProperty("playwright.cli.dir");
|
||||
if (pathFromProperty != null) {
|
||||
return new PreinstalledDriver(Paths.get(pathFromProperty));
|
||||
}
|
||||
|
||||
String driverImpl =
|
||||
System.getProperty("playwright.driver.impl", "com.microsoft.playwright.impl.DriverJar");
|
||||
System.getProperty("playwright.driver.impl", "com.microsoft.playwright.impl.driver.jar.DriverJar");
|
||||
Class<?> jarDriver = Class.forName(driverImpl);
|
||||
return (Driver) jarDriver.getDeclaredConstructor().newInstance();
|
||||
}
|
||||
|
||||
abstract Path driverDir();
|
||||
protected abstract Path driverDir();
|
||||
|
||||
protected static void logMessage(String message) {
|
||||
// This matches log format produced by the server.
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.microsoft.playwright.impl;
|
||||
package com.microsoft.playwright.impl.driver;
|
||||
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
+2
-2
@@ -6,7 +6,7 @@
|
||||
|
||||
<groupId>org.example</groupId>
|
||||
<artifactId>examples</artifactId>
|
||||
<version>1.22.0-SNAPSHOT</version>
|
||||
<version>1.26.1</version>
|
||||
<name>Playwright Client Examples</name>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
@@ -15,7 +15,7 @@
|
||||
<dependency>
|
||||
<groupId>com.microsoft.playwright</groupId>
|
||||
<artifactId>playwright</artifactId>
|
||||
<version>1.17.0</version>
|
||||
<version>1.22.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
package org.example;
|
||||
|
||||
import java.nio.file.Paths;
|
||||
import com.microsoft.playwright.*;
|
||||
|
||||
public class SelectorsAndKeyboardManipulation {
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>com.microsoft.playwright</groupId>
|
||||
<artifactId>parent-pom</artifactId>
|
||||
<version>1.22.0-SNAPSHOT</version>
|
||||
<version>1.26.1</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>playwright</artifactId>
|
||||
|
||||
@@ -30,15 +30,15 @@ import java.nio.file.Path;
|
||||
*
|
||||
* <p> **Cookie management**
|
||||
*
|
||||
* <p> {@code APIRequestContext} retuned by {@link BrowserContext#request BrowserContext.request()} and {@link Page#request
|
||||
* <p> {@code APIRequestContext} returned by {@link BrowserContext#request BrowserContext.request()} and {@link Page#request
|
||||
* Page.request()} shares cookie storage with the corresponding {@code BrowserContext}. Each API request will have {@code Cookie}
|
||||
* header populated with the values from the browser context. If the API response contains {@code Set-Cookie} header it will
|
||||
* automatically update {@code BrowserContext} cookies and requests made from the page will pick them up. This means that if you
|
||||
* log in using this API, your e2e test will be logged in and vice versa.
|
||||
*
|
||||
* <p> If you want API requests to not interfere with the browser cookies you shoud create a new {@code APIRequestContext} by calling
|
||||
* {@link APIRequest#newContext APIRequest.newContext()}. Such {@code APIRequestContext} object will have its own isolated cookie
|
||||
* storage.
|
||||
* <p> If you want API requests to not interfere with the browser cookies you should create a new {@code APIRequestContext} by
|
||||
* calling {@link APIRequest#newContext APIRequest.newContext()}. Such {@code APIRequestContext} object will have its own
|
||||
* isolated cookie storage.
|
||||
*/
|
||||
public interface APIRequestContext {
|
||||
class StorageStateOptions {
|
||||
|
||||
@@ -20,6 +20,7 @@ import com.microsoft.playwright.options.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A Browser is created via {@link BrowserType#launch BrowserType.launch()}. An example of using a {@code Browser} to create a
|
||||
@@ -94,9 +95,6 @@ public interface Browser extends AutoCloseable {
|
||||
/**
|
||||
* Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link Page#emulateMedia
|
||||
* Page.emulateMedia()} for more details. Defaults to {@code "none"}.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> It's not supported in WebKit, see <a href="https://bugs.webkit.org/show_bug.cgi?id=225281">here</a> in their issue
|
||||
* tracker.
|
||||
*/
|
||||
public ForcedColors forcedColors;
|
||||
public Geolocation geolocation;
|
||||
@@ -143,6 +141,17 @@ public interface Browser extends AutoCloseable {
|
||||
* 'http://per-context' } })}.
|
||||
*/
|
||||
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.
|
||||
* Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification.
|
||||
*/
|
||||
public 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;
|
||||
/**
|
||||
* Optional setting to control whether to omit request content from the HAR. Defaults to {@code false}.
|
||||
*/
|
||||
@@ -153,6 +162,7 @@ public interface Browser extends AutoCloseable {
|
||||
* BrowserContext.close()} for the HAR to be saved.
|
||||
*/
|
||||
public Path recordHarPath;
|
||||
public Object recordHarUrlFilter;
|
||||
/**
|
||||
* Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make sure
|
||||
* to call {@link BrowserContext#close BrowserContext.close()} for videos to be saved.
|
||||
@@ -174,6 +184,15 @@ public interface Browser extends AutoCloseable {
|
||||
* is set.
|
||||
*/
|
||||
public ScreenSize screenSize;
|
||||
/**
|
||||
* Whether to allow sites to register Service workers. Defaults to {@code "allow"}.
|
||||
* <ul>
|
||||
* <li> {@code "allow"}: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API">Service Workers</a> can be
|
||||
* registered.</li>
|
||||
* <li> {@code "block"}: Playwright will block all registration of Service Workers.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public ServiceWorkerPolicy serviceWorkers;
|
||||
/**
|
||||
* Populates context with given storage state. This option can be used to initialize context with logged-in information
|
||||
* obtained via {@link BrowserContext#storageState BrowserContext.storageState()}.
|
||||
@@ -186,7 +205,7 @@ public interface Browser extends AutoCloseable {
|
||||
*/
|
||||
public Path storageStatePath;
|
||||
/**
|
||||
* It specified, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
|
||||
* If specified, 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. See {@code Locator} to learn
|
||||
* more about the strict mode.
|
||||
*/
|
||||
@@ -262,9 +281,6 @@ public interface Browser extends AutoCloseable {
|
||||
/**
|
||||
* Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link Page#emulateMedia
|
||||
* Page.emulateMedia()} for more details. Defaults to {@code "none"}.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> It's not supported in WebKit, see <a href="https://bugs.webkit.org/show_bug.cgi?id=225281">here</a> in their issue
|
||||
* tracker.
|
||||
*/
|
||||
public NewContextOptions setForcedColors(ForcedColors forcedColors) {
|
||||
this.forcedColors = forcedColors;
|
||||
@@ -363,6 +379,23 @@ public interface Browser extends AutoCloseable {
|
||||
this.proxy = proxy;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* 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.
|
||||
* Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification.
|
||||
*/
|
||||
public NewContextOptions setRecordHarContent(HarContentPolicy recordHarContent) {
|
||||
this.recordHarContent = recordHarContent;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* 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 NewContextOptions setRecordHarMode(HarMode recordHarMode) {
|
||||
this.recordHarMode = recordHarMode;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Optional setting to control whether to omit request content from the HAR. Defaults to {@code false}.
|
||||
*/
|
||||
@@ -379,6 +412,14 @@ public interface Browser extends AutoCloseable {
|
||||
this.recordHarPath = recordHarPath;
|
||||
return this;
|
||||
}
|
||||
public NewContextOptions setRecordHarUrlFilter(String recordHarUrlFilter) {
|
||||
this.recordHarUrlFilter = recordHarUrlFilter;
|
||||
return this;
|
||||
}
|
||||
public NewContextOptions setRecordHarUrlFilter(Pattern recordHarUrlFilter) {
|
||||
this.recordHarUrlFilter = recordHarUrlFilter;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make sure
|
||||
* to call {@link BrowserContext#close BrowserContext.close()} for videos to be saved.
|
||||
@@ -427,6 +468,18 @@ public interface Browser extends AutoCloseable {
|
||||
this.screenSize = screenSize;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Whether to allow sites to register Service workers. Defaults to {@code "allow"}.
|
||||
* <ul>
|
||||
* <li> {@code "allow"}: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API">Service Workers</a> can be
|
||||
* registered.</li>
|
||||
* <li> {@code "block"}: Playwright will block all registration of Service Workers.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public NewContextOptions setServiceWorkers(ServiceWorkerPolicy serviceWorkers) {
|
||||
this.serviceWorkers = serviceWorkers;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Populates context with given storage state. This option can be used to initialize context with logged-in information
|
||||
* obtained via {@link BrowserContext#storageState BrowserContext.storageState()}.
|
||||
@@ -445,7 +498,7 @@ public interface Browser extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* It specified, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
|
||||
* If specified, 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. See {@code Locator} to learn
|
||||
* more about the strict mode.
|
||||
*/
|
||||
@@ -522,9 +575,6 @@ public interface Browser extends AutoCloseable {
|
||||
/**
|
||||
* Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link Page#emulateMedia
|
||||
* Page.emulateMedia()} for more details. Defaults to {@code "none"}.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> It's not supported in WebKit, see <a href="https://bugs.webkit.org/show_bug.cgi?id=225281">here</a> in their issue
|
||||
* tracker.
|
||||
*/
|
||||
public ForcedColors forcedColors;
|
||||
public Geolocation geolocation;
|
||||
@@ -571,6 +621,17 @@ public interface Browser extends AutoCloseable {
|
||||
* 'http://per-context' } })}.
|
||||
*/
|
||||
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.
|
||||
* Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification.
|
||||
*/
|
||||
public 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;
|
||||
/**
|
||||
* Optional setting to control whether to omit request content from the HAR. Defaults to {@code false}.
|
||||
*/
|
||||
@@ -581,6 +642,7 @@ public interface Browser extends AutoCloseable {
|
||||
* BrowserContext.close()} for the HAR to be saved.
|
||||
*/
|
||||
public Path recordHarPath;
|
||||
public Object recordHarUrlFilter;
|
||||
/**
|
||||
* Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make sure
|
||||
* to call {@link BrowserContext#close BrowserContext.close()} for videos to be saved.
|
||||
@@ -602,6 +664,15 @@ public interface Browser extends AutoCloseable {
|
||||
* is set.
|
||||
*/
|
||||
public ScreenSize screenSize;
|
||||
/**
|
||||
* Whether to allow sites to register Service workers. Defaults to {@code "allow"}.
|
||||
* <ul>
|
||||
* <li> {@code "allow"}: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API">Service Workers</a> can be
|
||||
* registered.</li>
|
||||
* <li> {@code "block"}: Playwright will block all registration of Service Workers.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public ServiceWorkerPolicy serviceWorkers;
|
||||
/**
|
||||
* Populates context with given storage state. This option can be used to initialize context with logged-in information
|
||||
* obtained via {@link BrowserContext#storageState BrowserContext.storageState()}.
|
||||
@@ -614,7 +685,7 @@ public interface Browser extends AutoCloseable {
|
||||
*/
|
||||
public Path storageStatePath;
|
||||
/**
|
||||
* It specified, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
|
||||
* If specified, 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. See {@code Locator} to learn
|
||||
* more about the strict mode.
|
||||
*/
|
||||
@@ -690,9 +761,6 @@ public interface Browser extends AutoCloseable {
|
||||
/**
|
||||
* Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link Page#emulateMedia
|
||||
* Page.emulateMedia()} for more details. Defaults to {@code "none"}.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> It's not supported in WebKit, see <a href="https://bugs.webkit.org/show_bug.cgi?id=225281">here</a> in their issue
|
||||
* tracker.
|
||||
*/
|
||||
public NewPageOptions setForcedColors(ForcedColors forcedColors) {
|
||||
this.forcedColors = forcedColors;
|
||||
@@ -791,6 +859,23 @@ public interface Browser extends AutoCloseable {
|
||||
this.proxy = proxy;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* 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.
|
||||
* Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification.
|
||||
*/
|
||||
public NewPageOptions setRecordHarContent(HarContentPolicy recordHarContent) {
|
||||
this.recordHarContent = recordHarContent;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* 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 NewPageOptions setRecordHarMode(HarMode recordHarMode) {
|
||||
this.recordHarMode = recordHarMode;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Optional setting to control whether to omit request content from the HAR. Defaults to {@code false}.
|
||||
*/
|
||||
@@ -807,6 +892,14 @@ public interface Browser extends AutoCloseable {
|
||||
this.recordHarPath = recordHarPath;
|
||||
return this;
|
||||
}
|
||||
public NewPageOptions setRecordHarUrlFilter(String recordHarUrlFilter) {
|
||||
this.recordHarUrlFilter = recordHarUrlFilter;
|
||||
return this;
|
||||
}
|
||||
public NewPageOptions setRecordHarUrlFilter(Pattern recordHarUrlFilter) {
|
||||
this.recordHarUrlFilter = recordHarUrlFilter;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make sure
|
||||
* to call {@link BrowserContext#close BrowserContext.close()} for videos to be saved.
|
||||
@@ -855,6 +948,18 @@ public interface Browser extends AutoCloseable {
|
||||
this.screenSize = screenSize;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Whether to allow sites to register Service workers. Defaults to {@code "allow"}.
|
||||
* <ul>
|
||||
* <li> {@code "allow"}: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API">Service Workers</a> can be
|
||||
* registered.</li>
|
||||
* <li> {@code "block"}: Playwright will block all registration of Service Workers.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public NewPageOptions setServiceWorkers(ServiceWorkerPolicy serviceWorkers) {
|
||||
this.serviceWorkers = serviceWorkers;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Populates context with given storage state. This option can be used to initialize context with logged-in information
|
||||
* obtained via {@link BrowserContext#storageState BrowserContext.storageState()}.
|
||||
@@ -873,7 +978,7 @@ public interface Browser extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* It specified, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
|
||||
* If specified, 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. See {@code Locator} to learn
|
||||
* more about the strict mode.
|
||||
*/
|
||||
@@ -947,6 +1052,10 @@ public interface Browser extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Get the browser type (chromium, firefox or webkit) that the browser belongs to.
|
||||
*/
|
||||
BrowserType browserType();
|
||||
/**
|
||||
* In case this browser is obtained using {@link BrowserType#launch BrowserType.launch()}, closes the browser and all of
|
||||
* its pages (if any were opened).
|
||||
@@ -954,6 +1063,10 @@ public interface Browser extends AutoCloseable {
|
||||
* <p> In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from the
|
||||
* browser server.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> This is similar to force quitting the browser. Therefore, you should call {@link BrowserContext#close
|
||||
* BrowserContext.close()} on any {@code BrowserContext}'s you explicitly created earlier with {@link Browser#newContext
|
||||
* Browser.newContext()} **before** calling {@link Browser#close Browser.close()}.
|
||||
*
|
||||
* <p> The {@code Browser} object itself is considered to be disposed and cannot be used anymore.
|
||||
*/
|
||||
void close();
|
||||
@@ -973,6 +1086,11 @@ public interface Browser extends AutoCloseable {
|
||||
boolean isConnected();
|
||||
/**
|
||||
* Creates a new browser context. It won't share cookies/cache with other browser contexts.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> If directly using this method to create {@code BrowserContext}s, it is best practice to explicitly close the returned context
|
||||
* via {@link BrowserContext#close BrowserContext.close()} when your code is done with the {@code BrowserContext}, and before
|
||||
* calling {@link Browser#close Browser.close()}. This will ensure the {@code context} is closed gracefully and any
|
||||
* artifacts—like HARs and videos—are fully flushed and saved.
|
||||
* <pre>{@code
|
||||
* Browser browser = playwright.firefox().launch(); // Or 'chromium' or 'webkit'.
|
||||
* // Create a new incognito browser context.
|
||||
@@ -980,6 +1098,10 @@ public interface Browser extends AutoCloseable {
|
||||
* // Create a new page in a pristine context.
|
||||
* Page page = context.newPage();
|
||||
* page.navigate('https://example.com');
|
||||
*
|
||||
* // Graceful close up everything
|
||||
* context.close();
|
||||
* browser.close();
|
||||
* }</pre>
|
||||
*/
|
||||
default BrowserContext newContext() {
|
||||
@@ -987,6 +1109,11 @@ public interface Browser extends AutoCloseable {
|
||||
}
|
||||
/**
|
||||
* Creates a new browser context. It won't share cookies/cache with other browser contexts.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> If directly using this method to create {@code BrowserContext}s, it is best practice to explicitly close the returned context
|
||||
* via {@link BrowserContext#close BrowserContext.close()} when your code is done with the {@code BrowserContext}, and before
|
||||
* calling {@link Browser#close Browser.close()}. This will ensure the {@code context} is closed gracefully and any
|
||||
* artifacts—like HARs and videos—are fully flushed and saved.
|
||||
* <pre>{@code
|
||||
* Browser browser = playwright.firefox().launch(); // Or 'chromium' or 'webkit'.
|
||||
* // Create a new incognito browser context.
|
||||
@@ -994,6 +1121,10 @@ public interface Browser extends AutoCloseable {
|
||||
* // Create a new page in a pristine context.
|
||||
* Page page = context.newPage();
|
||||
* page.navigate('https://example.com');
|
||||
*
|
||||
* // Graceful close up everything
|
||||
* context.close();
|
||||
* browser.close();
|
||||
* }</pre>
|
||||
*/
|
||||
BrowserContext newContext(NewContextOptions options);
|
||||
|
||||
@@ -67,7 +67,7 @@ public interface BrowserContext extends AutoCloseable {
|
||||
* done and its response has started loading in the popup.
|
||||
* <pre>{@code
|
||||
* Page newPage = context.waitForPage(() -> {
|
||||
* page.click("a[target=_blank]");
|
||||
* page.locator("a[target=_blank]").click();
|
||||
* });
|
||||
* System.out.println(newPage.evaluate("location.href"));
|
||||
* }</pre>
|
||||
@@ -174,6 +174,62 @@ public interface BrowserContext extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
class RouteFromHAROptions {
|
||||
/**
|
||||
* <ul>
|
||||
* <li> If set to 'abort' any request not found in the HAR file will be aborted.</li>
|
||||
* <li> If set to 'fallback' falls through to the next route handler in the handler chain.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p> Defaults to abort.
|
||||
*/
|
||||
public HarNotFound notFound;
|
||||
/**
|
||||
* If specified, updates the given HAR with the actual network information instead of serving from file.
|
||||
*/
|
||||
public Boolean update;
|
||||
/**
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* <ul>
|
||||
* <li> If set to 'abort' any request not found in the HAR file will be aborted.</li>
|
||||
* <li> If set to 'fallback' falls through to the next route handler in the handler chain.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p> Defaults to abort.
|
||||
*/
|
||||
public RouteFromHAROptions setNotFound(HarNotFound notFound) {
|
||||
this.notFound = notFound;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* If specified, updates the given HAR with the actual network information instead of serving from file.
|
||||
*/
|
||||
public RouteFromHAROptions setUpdate(boolean update) {
|
||||
this.update = update;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* 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 RouteFromHAROptions setUrl(String url) {
|
||||
this.url = url;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* 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 RouteFromHAROptions setUrl(Pattern url) {
|
||||
this.url = url;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
class StorageStateOptions {
|
||||
/**
|
||||
* The file path to save the storage state to. If {@code path} is a relative path, then it is resolved relative to current
|
||||
@@ -348,7 +404,7 @@ public interface BrowserContext extends AutoCloseable {
|
||||
* "</script>\n" +
|
||||
* "<button onclick=\"onClick()\">Click me</button>\n" +
|
||||
* "<div></div>");
|
||||
* page.click("button");
|
||||
* page.locator("button").click();
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
@@ -407,7 +463,7 @@ public interface BrowserContext extends AutoCloseable {
|
||||
* "</script>\n" +
|
||||
* "<button onclick=\"onClick()\">Click me</button>\n" +
|
||||
* "<div></div>");
|
||||
* page.click("button");
|
||||
* page.locator("button").click();
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
@@ -477,7 +533,7 @@ public interface BrowserContext extends AutoCloseable {
|
||||
* "</script>\n" +
|
||||
* "<button onclick=\"onClick()\">Click me</button>\n" +
|
||||
* "<div></div>\n");
|
||||
* page.click("button");
|
||||
* page.locator("button").click();
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
@@ -553,9 +609,9 @@ public interface BrowserContext extends AutoCloseable {
|
||||
* 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.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> {@link Page#route Page.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* <p> <strong>NOTE:</strong> {@link BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
|
||||
* using request interception. Via {@code await context.addInitScript(() => delete window.navigator.serviceWorker);}
|
||||
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
|
||||
*
|
||||
* <p> An example of a naive handler that aborts all image requests:
|
||||
* <pre>{@code
|
||||
@@ -605,9 +661,9 @@ public interface BrowserContext extends AutoCloseable {
|
||||
* 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.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> {@link Page#route Page.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* <p> <strong>NOTE:</strong> {@link BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
|
||||
* using request interception. Via {@code await context.addInitScript(() => delete window.navigator.serviceWorker);}
|
||||
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
|
||||
*
|
||||
* <p> An example of a naive handler that aborts all image requests:
|
||||
* <pre>{@code
|
||||
@@ -655,9 +711,9 @@ public interface BrowserContext extends AutoCloseable {
|
||||
* 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.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> {@link Page#route Page.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* <p> <strong>NOTE:</strong> {@link BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
|
||||
* using request interception. Via {@code await context.addInitScript(() => delete window.navigator.serviceWorker);}
|
||||
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
|
||||
*
|
||||
* <p> An example of a naive handler that aborts all image requests:
|
||||
* <pre>{@code
|
||||
@@ -707,9 +763,9 @@ public interface BrowserContext extends AutoCloseable {
|
||||
* 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.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> {@link Page#route Page.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* <p> <strong>NOTE:</strong> {@link BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
|
||||
* using request interception. Via {@code await context.addInitScript(() => delete window.navigator.serviceWorker);}
|
||||
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
|
||||
*
|
||||
* <p> An example of a naive handler that aborts all image requests:
|
||||
* <pre>{@code
|
||||
@@ -757,9 +813,9 @@ public interface BrowserContext extends AutoCloseable {
|
||||
* 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.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> {@link Page#route Page.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* <p> <strong>NOTE:</strong> {@link BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
|
||||
* using request interception. Via {@code await context.addInitScript(() => delete window.navigator.serviceWorker);}
|
||||
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
|
||||
*
|
||||
* <p> An example of a naive handler that aborts all image requests:
|
||||
* <pre>{@code
|
||||
@@ -809,9 +865,9 @@ public interface BrowserContext extends AutoCloseable {
|
||||
* 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.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> {@link Page#route Page.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* <p> <strong>NOTE:</strong> {@link BrowserContext#route BrowserContext.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
|
||||
* using request interception. Via {@code await context.addInitScript(() => delete window.navigator.serviceWorker);}
|
||||
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
|
||||
*
|
||||
* <p> An example of a naive handler that aborts all image requests:
|
||||
* <pre>{@code
|
||||
@@ -855,6 +911,32 @@ public interface BrowserContext extends AutoCloseable {
|
||||
* @param handler handler function to route the request.
|
||||
*/
|
||||
void route(Predicate<String> url, Consumer<Route> handler, RouteOptions options);
|
||||
/**
|
||||
* If specified the network requests that are made in the context will be served from the HAR file. Read more about <a
|
||||
* href="https://playwright.dev/java/docs/network#replaying-from-har">Replaying from HAR</a>.
|
||||
*
|
||||
* <p> Playwright will not serve requests intercepted by Service Worker from the HAR file. See <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"}.
|
||||
*
|
||||
* @param har Path to a <a href="http://www.softwareishard.com/blog/har-12-spec">HAR</a> file with prerecorded network data. If {@code path}
|
||||
* is a relative path, then it is resolved relative to the current working directory.
|
||||
*/
|
||||
default void routeFromHAR(Path har) {
|
||||
routeFromHAR(har, null);
|
||||
}
|
||||
/**
|
||||
* If specified the network requests that are made in the context will be served from the HAR file. Read more about <a
|
||||
* href="https://playwright.dev/java/docs/network#replaying-from-har">Replaying from HAR</a>.
|
||||
*
|
||||
* <p> Playwright will not serve requests intercepted by Service Worker from the HAR file. See <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"}.
|
||||
*
|
||||
* @param har Path to a <a href="http://www.softwareishard.com/blog/har-12-spec">HAR</a> file with prerecorded network data. If {@code path}
|
||||
* is a relative path, then it is resolved relative to the current working directory.
|
||||
*/
|
||||
void routeFromHAR(Path har, RouteFromHAROptions options);
|
||||
/**
|
||||
* This setting will change the default maximum navigation time for the following methods and related shortcuts:
|
||||
* <ul>
|
||||
|
||||
@@ -19,6 +19,7 @@ package com.microsoft.playwright;
|
||||
import com.microsoft.playwright.options.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* BrowserType provides methods to launch a specific browser instance or connect to an existing one. The following is a
|
||||
@@ -441,9 +442,6 @@ public interface BrowserType {
|
||||
/**
|
||||
* Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link Page#emulateMedia
|
||||
* Page.emulateMedia()} for more details. Defaults to {@code "none"}.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> It's not supported in WebKit, see <a href="https://bugs.webkit.org/show_bug.cgi?id=225281">here</a> in their issue
|
||||
* tracker.
|
||||
*/
|
||||
public ForcedColors forcedColors;
|
||||
public Geolocation geolocation;
|
||||
@@ -515,6 +513,17 @@ public interface BrowserType {
|
||||
* Network proxy settings.
|
||||
*/
|
||||
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.
|
||||
* Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification.
|
||||
*/
|
||||
public 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;
|
||||
/**
|
||||
* Optional setting to control whether to omit request content from the HAR. Defaults to {@code false}.
|
||||
*/
|
||||
@@ -525,6 +534,7 @@ public interface BrowserType {
|
||||
* BrowserContext.close()} for the HAR to be saved.
|
||||
*/
|
||||
public Path recordHarPath;
|
||||
public Object recordHarUrlFilter;
|
||||
/**
|
||||
* Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make sure
|
||||
* to call {@link BrowserContext#close BrowserContext.close()} for videos to be saved.
|
||||
@@ -546,12 +556,21 @@ public interface BrowserType {
|
||||
* is set.
|
||||
*/
|
||||
public ScreenSize screenSize;
|
||||
/**
|
||||
* Whether to allow sites to register Service workers. Defaults to {@code "allow"}.
|
||||
* <ul>
|
||||
* <li> {@code "allow"}: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API">Service Workers</a> can be
|
||||
* registered.</li>
|
||||
* <li> {@code "block"}: Playwright will block all registration of Service Workers.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public 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;
|
||||
/**
|
||||
* It specified, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
|
||||
* If specified, 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. See {@code Locator} to learn
|
||||
* more about the strict mode.
|
||||
*/
|
||||
@@ -703,9 +722,6 @@ public interface BrowserType {
|
||||
/**
|
||||
* Emulates {@code "forced-colors"} media feature, supported values are {@code "active"}, {@code "none"}. See {@link Page#emulateMedia
|
||||
* Page.emulateMedia()} for more details. Defaults to {@code "none"}.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> It's not supported in WebKit, see <a href="https://bugs.webkit.org/show_bug.cgi?id=225281">here</a> in their issue
|
||||
* tracker.
|
||||
*/
|
||||
public LaunchPersistentContextOptions setForcedColors(ForcedColors forcedColors) {
|
||||
this.forcedColors = forcedColors;
|
||||
@@ -843,6 +859,23 @@ public interface BrowserType {
|
||||
this.proxy = proxy;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* 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.
|
||||
* Defaults to {@code embed}, which stores content inline the HAR file as per HAR specification.
|
||||
*/
|
||||
public LaunchPersistentContextOptions setRecordHarContent(HarContentPolicy recordHarContent) {
|
||||
this.recordHarContent = recordHarContent;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* 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 LaunchPersistentContextOptions setRecordHarMode(HarMode recordHarMode) {
|
||||
this.recordHarMode = recordHarMode;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Optional setting to control whether to omit request content from the HAR. Defaults to {@code false}.
|
||||
*/
|
||||
@@ -859,6 +892,14 @@ public interface BrowserType {
|
||||
this.recordHarPath = recordHarPath;
|
||||
return this;
|
||||
}
|
||||
public LaunchPersistentContextOptions setRecordHarUrlFilter(String recordHarUrlFilter) {
|
||||
this.recordHarUrlFilter = recordHarUrlFilter;
|
||||
return this;
|
||||
}
|
||||
public LaunchPersistentContextOptions setRecordHarUrlFilter(Pattern recordHarUrlFilter) {
|
||||
this.recordHarUrlFilter = recordHarUrlFilter;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make sure
|
||||
* to call {@link BrowserContext#close BrowserContext.close()} for videos to be saved.
|
||||
@@ -907,6 +948,18 @@ public interface BrowserType {
|
||||
this.screenSize = screenSize;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Whether to allow sites to register Service workers. Defaults to {@code "allow"}.
|
||||
* <ul>
|
||||
* <li> {@code "allow"}: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API">Service Workers</a> can be
|
||||
* registered.</li>
|
||||
* <li> {@code "block"}: Playwright will block all registration of Service Workers.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public LaunchPersistentContextOptions setServiceWorkers(ServiceWorkerPolicy serviceWorkers) {
|
||||
this.serviceWorkers = serviceWorkers;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.
|
||||
*/
|
||||
@@ -915,7 +968,7 @@ public interface BrowserType {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* It specified, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
|
||||
* If specified, 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. See {@code Locator} to learn
|
||||
* more about the strict mode.
|
||||
*/
|
||||
@@ -969,7 +1022,9 @@ public interface BrowserType {
|
||||
}
|
||||
}
|
||||
/**
|
||||
* This method attaches Playwright to an existing browser instance.
|
||||
* This method attaches Playwright to an existing browser instance. When connecting to another browser launched via
|
||||
* {@code BrowserType.launchServer} in Node.js, the major and minor version needs to match the client version (1.2.3 → is
|
||||
* compatible with 1.2.x).
|
||||
*
|
||||
* @param wsEndpoint A browser websocket endpoint to connect to.
|
||||
*/
|
||||
@@ -977,7 +1032,9 @@ public interface BrowserType {
|
||||
return connect(wsEndpoint, null);
|
||||
}
|
||||
/**
|
||||
* This method attaches Playwright to an existing browser instance.
|
||||
* This method attaches Playwright to an existing browser instance. When connecting to another browser launched via
|
||||
* {@code BrowserType.launchServer} in Node.js, the major and minor version needs to match the client version (1.2.3 → is
|
||||
* compatible with 1.2.x).
|
||||
*
|
||||
* @param wsEndpoint A browser websocket endpoint to connect to.
|
||||
*/
|
||||
@@ -988,6 +1045,11 @@ public interface BrowserType {
|
||||
* <p> The default browser context is accessible via {@link Browser#contexts Browser.contexts()}.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers.
|
||||
* <pre>{@code
|
||||
* Browser browser = playwright.chromium().connectOverCDP("http://localhost:9222");
|
||||
* BrowserContext defaultContext = browser.contexts().get(0);
|
||||
* Page page = defaultContext.pages().get(0);
|
||||
* }</pre>
|
||||
*
|
||||
* @param endpointURL A CDP websocket endpoint or http url to connect to. For example {@code http://localhost:9222/} or
|
||||
* {@code ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4}.
|
||||
@@ -1001,6 +1063,11 @@ public interface BrowserType {
|
||||
* <p> The default browser context is accessible via {@link Browser#contexts Browser.contexts()}.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers.
|
||||
* <pre>{@code
|
||||
* Browser browser = playwright.chromium().connectOverCDP("http://localhost:9222");
|
||||
* BrowserContext defaultContext = browser.contexts().get(0);
|
||||
* Page page = defaultContext.pages().get(0);
|
||||
* }</pre>
|
||||
*
|
||||
* @param endpointURL A CDP websocket endpoint or http url to connect to. For example {@code http://localhost:9222/} or
|
||||
* {@code ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4}.
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
package com.microsoft.playwright;
|
||||
|
||||
import com.microsoft.playwright.impl.Driver;
|
||||
import com.microsoft.playwright.impl.driver.Driver;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
@@ -29,10 +29,9 @@ import static java.util.Arrays.asList;
|
||||
*/
|
||||
public class CLI {
|
||||
public static void main(String[] args) throws IOException, InterruptedException {
|
||||
Path driver = Driver.ensureDriverInstalled(Collections.emptyMap(), false);
|
||||
ProcessBuilder pb = new ProcessBuilder(driver.toString());
|
||||
Driver driver = Driver.ensureDriverInstalled(Collections.emptyMap(), false);
|
||||
ProcessBuilder pb = driver.createProcessBuilder();
|
||||
pb.command().addAll(asList(args));
|
||||
Driver.setRequiredEnvironmentVariables(pb);
|
||||
String version = Playwright.class.getPackage().getImplementationVersion();
|
||||
if (version != null) {
|
||||
pb.environment().put("PW_CLI_DISPLAY_VERSION", version);
|
||||
|
||||
@@ -27,14 +27,14 @@ import java.nio.file.Path;
|
||||
* <p> Download event is emitted once the download starts. Download path becomes available once download completes:
|
||||
* <pre>{@code
|
||||
* // wait for download to start
|
||||
* Download download = page.waitForDownload(() -> page.click("a"));
|
||||
* Download download = page.waitForDownload(() -> page.locator("a").click());
|
||||
* // wait for download to complete
|
||||
* Path path = download.path();
|
||||
* }</pre>
|
||||
* <pre>{@code
|
||||
* // wait for download to start
|
||||
* Download download = page.waitForDownload(() -> {
|
||||
* page.click("a");
|
||||
* page.locator("a").click();
|
||||
* });
|
||||
* // wait for download to complete
|
||||
* Path path = download.path();
|
||||
|
||||
@@ -586,7 +586,7 @@ public interface ElementHandle extends JSHandle {
|
||||
*/
|
||||
public ScreenshotCaret caret;
|
||||
/**
|
||||
* Specify locators that should be masked when the screenshot is taken. Masked elements will be overlayed with a pink box
|
||||
* Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink box
|
||||
* {@code #FF00FF} that completely covers its bounding box.
|
||||
*/
|
||||
public List<Locator> mask;
|
||||
@@ -608,7 +608,9 @@ public interface ElementHandle extends JSHandle {
|
||||
/**
|
||||
* 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
|
||||
* high-dpi devices will be twice as large or even larger. Defaults to {@code "device"}.
|
||||
* high-dpi devices will be twice as large or even larger.
|
||||
*
|
||||
* <p> Defaults to {@code "device"}.
|
||||
*/
|
||||
public ScreenshotScale scale;
|
||||
/**
|
||||
@@ -645,7 +647,7 @@ public interface ElementHandle extends JSHandle {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Specify locators that should be masked when the screenshot is taken. Masked elements will be overlayed with a pink box
|
||||
* Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink box
|
||||
* {@code #FF00FF} that completely covers its bounding box.
|
||||
*/
|
||||
public ScreenshotOptions setMask(List<Locator> mask) {
|
||||
@@ -679,7 +681,9 @@ public interface ElementHandle extends JSHandle {
|
||||
/**
|
||||
* 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
|
||||
* high-dpi devices will be twice as large or even larger. Defaults to {@code "device"}.
|
||||
* high-dpi devices will be twice as large or even larger.
|
||||
*
|
||||
* <p> Defaults to {@code "device"}.
|
||||
*/
|
||||
public ScreenshotOptions setScale(ScreenshotScale scale) {
|
||||
this.scale = scale;
|
||||
@@ -1162,7 +1166,7 @@ public interface ElementHandle extends JSHandle {
|
||||
*/
|
||||
public WaitForSelectorState state;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1189,7 +1193,7 @@ public interface ElementHandle extends JSHandle {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 WaitForSelectorOptions setStrict(boolean strict) {
|
||||
@@ -1210,7 +1214,7 @@ public interface ElementHandle extends JSHandle {
|
||||
* This method returns the bounding box of the element, or {@code null} if the element is not visible. The bounding box is
|
||||
* calculated relative to the main frame viewport - which is usually the same as the browser window.
|
||||
*
|
||||
* <p> Scrolling affects the returned bonding box, similarly to <a
|
||||
* <p> Scrolling affects the returned bounding box, similarly to <a
|
||||
* href="https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect">Element.getBoundingClientRect</a>.
|
||||
* That means {@code x} and/or {@code y} may be negative.
|
||||
*
|
||||
|
||||
@@ -22,7 +22,7 @@ import java.nio.file.Path;
|
||||
/**
|
||||
* {@code FileChooser} objects are dispatched by the page in the {@link Page#onFileChooser Page.onFileChooser()} event.
|
||||
* <pre>{@code
|
||||
* FileChooser fileChooser = page.waitForFileChooser(() -> page.click("upload"));
|
||||
* FileChooser fileChooser = page.waitForFileChooser(() -> page.locator("upload").click());
|
||||
* fileChooser.setFiles(Paths.get("myfile.pdf"));
|
||||
* }</pre>
|
||||
*/
|
||||
|
||||
@@ -167,7 +167,7 @@ public interface Frame {
|
||||
*/
|
||||
public Position position;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -217,7 +217,7 @@ public interface Frame {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 CheckOptions setStrict(boolean strict) {
|
||||
@@ -278,7 +278,7 @@ public interface Frame {
|
||||
*/
|
||||
public Position position;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -357,7 +357,7 @@ public interface Frame {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 ClickOptions setStrict(boolean strict) {
|
||||
@@ -414,7 +414,7 @@ public interface Frame {
|
||||
*/
|
||||
public Position position;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -486,7 +486,7 @@ public interface Frame {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 DblclickOptions setStrict(boolean strict) {
|
||||
@@ -514,7 +514,7 @@ public interface Frame {
|
||||
}
|
||||
class DispatchEventOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -526,7 +526,7 @@ public interface Frame {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 DispatchEventOptions setStrict(boolean strict) {
|
||||
@@ -561,7 +561,7 @@ public interface Frame {
|
||||
*/
|
||||
public Position sourcePosition;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -616,7 +616,7 @@ public interface Frame {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 DragAndDropOptions setStrict(boolean strict) {
|
||||
@@ -659,13 +659,13 @@ public interface Frame {
|
||||
}
|
||||
class EvalOnSelectorOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 EvalOnSelectorOptions setStrict(boolean strict) {
|
||||
@@ -686,7 +686,7 @@ public interface Frame {
|
||||
*/
|
||||
public Boolean noWaitAfter;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -715,7 +715,7 @@ public interface Frame {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 FillOptions setStrict(boolean strict) {
|
||||
@@ -734,7 +734,7 @@ public interface Frame {
|
||||
}
|
||||
class FocusOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -746,7 +746,7 @@ public interface Frame {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 FocusOptions setStrict(boolean strict) {
|
||||
@@ -765,7 +765,7 @@ public interface Frame {
|
||||
}
|
||||
class GetAttributeOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -777,7 +777,7 @@ public interface Frame {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 GetAttributeOptions setStrict(boolean strict) {
|
||||
@@ -867,7 +867,7 @@ public interface Frame {
|
||||
*/
|
||||
public Position position;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -916,7 +916,7 @@ public interface Frame {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 HoverOptions setStrict(boolean strict) {
|
||||
@@ -944,7 +944,7 @@ public interface Frame {
|
||||
}
|
||||
class InnerHTMLOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -956,7 +956,7 @@ public interface Frame {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 InnerHTMLOptions setStrict(boolean strict) {
|
||||
@@ -975,7 +975,7 @@ public interface Frame {
|
||||
}
|
||||
class InnerTextOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -987,7 +987,7 @@ public interface Frame {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 InnerTextOptions setStrict(boolean strict) {
|
||||
@@ -1006,7 +1006,7 @@ public interface Frame {
|
||||
}
|
||||
class InputValueOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1018,7 +1018,7 @@ public interface Frame {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 InputValueOptions setStrict(boolean strict) {
|
||||
@@ -1037,7 +1037,7 @@ public interface Frame {
|
||||
}
|
||||
class IsCheckedOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1049,7 +1049,7 @@ public interface Frame {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 IsCheckedOptions setStrict(boolean strict) {
|
||||
@@ -1068,7 +1068,7 @@ public interface Frame {
|
||||
}
|
||||
class IsDisabledOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1080,7 +1080,7 @@ public interface Frame {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 IsDisabledOptions setStrict(boolean strict) {
|
||||
@@ -1099,7 +1099,7 @@ public interface Frame {
|
||||
}
|
||||
class IsEditableOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1111,7 +1111,7 @@ public interface Frame {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 IsEditableOptions setStrict(boolean strict) {
|
||||
@@ -1130,7 +1130,7 @@ public interface Frame {
|
||||
}
|
||||
class IsEnabledOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1142,7 +1142,7 @@ public interface Frame {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 IsEnabledOptions setStrict(boolean strict) {
|
||||
@@ -1161,7 +1161,7 @@ public interface Frame {
|
||||
}
|
||||
class IsHiddenOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1172,7 +1172,7 @@ public interface Frame {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 IsHiddenOptions setStrict(boolean strict) {
|
||||
@@ -1190,7 +1190,7 @@ public interface Frame {
|
||||
}
|
||||
class IsVisibleOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1201,7 +1201,7 @@ public interface Frame {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 IsVisibleOptions setStrict(boolean strict) {
|
||||
@@ -1273,7 +1273,7 @@ public interface Frame {
|
||||
*/
|
||||
public Boolean noWaitAfter;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1301,7 +1301,7 @@ public interface Frame {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 PressOptions setStrict(boolean strict) {
|
||||
@@ -1320,13 +1320,13 @@ public interface Frame {
|
||||
}
|
||||
class QuerySelectorOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 QuerySelectorOptions setStrict(boolean strict) {
|
||||
@@ -1347,7 +1347,7 @@ public interface Frame {
|
||||
*/
|
||||
public Boolean noWaitAfter;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1376,7 +1376,7 @@ public interface Frame {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 SelectOptionOptions setStrict(boolean strict) {
|
||||
@@ -1411,7 +1411,7 @@ public interface Frame {
|
||||
*/
|
||||
public Position position;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1461,7 +1461,7 @@ public interface Frame {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 SetCheckedOptions setStrict(boolean strict) {
|
||||
@@ -1538,7 +1538,7 @@ public interface Frame {
|
||||
*/
|
||||
public Boolean noWaitAfter;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1559,7 +1559,7 @@ public interface Frame {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 SetInputFilesOptions setStrict(boolean strict) {
|
||||
@@ -1599,7 +1599,7 @@ public interface Frame {
|
||||
*/
|
||||
public Position position;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1657,7 +1657,7 @@ public interface Frame {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 TapOptions setStrict(boolean strict) {
|
||||
@@ -1685,7 +1685,7 @@ public interface Frame {
|
||||
}
|
||||
class TextContentOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1697,7 +1697,7 @@ public interface Frame {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 TextContentOptions setStrict(boolean strict) {
|
||||
@@ -1726,7 +1726,7 @@ public interface Frame {
|
||||
*/
|
||||
public Boolean noWaitAfter;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1754,7 +1754,7 @@ public interface Frame {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 TypeOptions setStrict(boolean strict) {
|
||||
@@ -1789,7 +1789,7 @@ public interface Frame {
|
||||
*/
|
||||
public Position position;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1839,7 +1839,7 @@ public interface Frame {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 UncheckOptions setStrict(boolean strict) {
|
||||
@@ -2004,7 +2004,7 @@ public interface Frame {
|
||||
*/
|
||||
public WaitForSelectorState state;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -2031,7 +2031,7 @@ public interface Frame {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 WaitForSelectorOptions setStrict(boolean strict) {
|
||||
@@ -2366,9 +2366,25 @@ public interface Frame {
|
||||
* @param eventInit Optional event-specific initialization properties.
|
||||
*/
|
||||
void dispatchEvent(String selector, String type, Object eventInit, DispatchEventOptions options);
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @param source A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be
|
||||
* used. See <a href="https://playwright.dev/java/docs/selectors">working with selectors</a> for more details.
|
||||
* @param target A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will
|
||||
* be used. See <a href="https://playwright.dev/java/docs/selectors">working with selectors</a> for more details.
|
||||
*/
|
||||
default void dragAndDrop(String source, String target) {
|
||||
dragAndDrop(source, target, null);
|
||||
}
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @param source A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be
|
||||
* used. See <a href="https://playwright.dev/java/docs/selectors">working with selectors</a> for more details.
|
||||
* @param target A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will
|
||||
* be used. See <a href="https://playwright.dev/java/docs/selectors">working with selectors</a> for more details.
|
||||
*/
|
||||
void dragAndDrop(String source, String target, DragAndDropOptions options);
|
||||
/**
|
||||
* Returns the return value of {@code expression}.
|
||||
|
||||
@@ -30,7 +30,7 @@ import java.util.regex.Pattern;
|
||||
* <p> **Strictness**
|
||||
*
|
||||
* <p> Frame locators are strict. This means that all operations on frame locators will throw if more than one element matches
|
||||
* given selector.
|
||||
* a given selector.
|
||||
* <pre>{@code
|
||||
* // Throws if there are several frames in DOM:
|
||||
* page.frame_locator(".result-frame").locator("button").click();
|
||||
|
||||
@@ -1013,7 +1013,7 @@ public interface Locator {
|
||||
*/
|
||||
public ScreenshotCaret caret;
|
||||
/**
|
||||
* Specify locators that should be masked when the screenshot is taken. Masked elements will be overlayed with a pink box
|
||||
* Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink box
|
||||
* {@code #FF00FF} that completely covers its bounding box.
|
||||
*/
|
||||
public List<Locator> mask;
|
||||
@@ -1035,7 +1035,9 @@ public interface Locator {
|
||||
/**
|
||||
* 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
|
||||
* high-dpi devices will be twice as large or even larger. Defaults to {@code "device"}.
|
||||
* high-dpi devices will be twice as large or even larger.
|
||||
*
|
||||
* <p> Defaults to {@code "device"}.
|
||||
*/
|
||||
public ScreenshotScale scale;
|
||||
/**
|
||||
@@ -1072,7 +1074,7 @@ public interface Locator {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Specify locators that should be masked when the screenshot is taken. Masked elements will be overlayed with a pink box
|
||||
* Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink box
|
||||
* {@code #FF00FF} that completely covers its bounding box.
|
||||
*/
|
||||
public ScreenshotOptions setMask(List<Locator> mask) {
|
||||
@@ -1106,7 +1108,9 @@ public interface Locator {
|
||||
/**
|
||||
* 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
|
||||
* high-dpi devices will be twice as large or even larger. Defaults to {@code "device"}.
|
||||
* high-dpi devices will be twice as large or even larger.
|
||||
*
|
||||
* <p> Defaults to {@code "device"}.
|
||||
*/
|
||||
public ScreenshotOptions setScale(ScreenshotScale scale) {
|
||||
this.scale = scale;
|
||||
@@ -1632,7 +1636,7 @@ public interface Locator {
|
||||
* This method returns the bounding box of the element, or {@code null} if the element is not visible. The bounding box is
|
||||
* calculated relative to the main frame viewport - which is usually the same as the browser window.
|
||||
*
|
||||
* <p> Scrolling affects the returned bonding box, similarly to <a
|
||||
* <p> Scrolling affects the returned bounding box, similarly to <a
|
||||
* href="https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect">Element.getBoundingClientRect</a>.
|
||||
* That means {@code x} and/or {@code y} may be negative.
|
||||
*
|
||||
@@ -1653,7 +1657,7 @@ public interface Locator {
|
||||
* This method returns the bounding box of the element, or {@code null} if the element is not visible. The bounding box is
|
||||
* calculated relative to the main frame viewport - which is usually the same as the browser window.
|
||||
*
|
||||
* <p> Scrolling affects the returned bonding box, similarly to <a
|
||||
* <p> Scrolling affects the returned bounding box, similarly to <a
|
||||
* href="https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect">Element.getBoundingClientRect</a>.
|
||||
* That means {@code x} and/or {@code y} may be negative.
|
||||
*
|
||||
@@ -2119,13 +2123,35 @@ public interface Locator {
|
||||
*/
|
||||
void fill(String value, FillOptions options);
|
||||
/**
|
||||
* This method narrows existing locator according to the options, for example filters by text.
|
||||
* This method narrows existing locator according to the options, for example filters by text. It can be chained to filter
|
||||
* multiple times.
|
||||
* <pre>{@code
|
||||
* Locator rowLocator = page.locator("tr");
|
||||
* // ...
|
||||
* rowLocator
|
||||
* .filter(new Locator.FilterOptions().setHasText("text in column 1"))
|
||||
* .filter(new Locator.FilterOptions().setHas(
|
||||
* page.locator("button", new Page.LocatorOptions().setHasText("column 2 button"))
|
||||
* ))
|
||||
* .screenshot();
|
||||
* }</pre>
|
||||
*/
|
||||
default Locator filter() {
|
||||
return filter(null);
|
||||
}
|
||||
/**
|
||||
* This method narrows existing locator according to the options, for example filters by text.
|
||||
* This method narrows existing locator according to the options, for example filters by text. It can be chained to filter
|
||||
* multiple times.
|
||||
* <pre>{@code
|
||||
* Locator rowLocator = page.locator("tr");
|
||||
* // ...
|
||||
* rowLocator
|
||||
* .filter(new Locator.FilterOptions().setHasText("text in column 1"))
|
||||
* .filter(new Locator.FilterOptions().setHas(
|
||||
* page.locator("button", new Page.LocatorOptions().setHasText("column 2 button"))
|
||||
* ))
|
||||
* .screenshot();
|
||||
* }</pre>
|
||||
*/
|
||||
Locator filter(FilterOptions options);
|
||||
/**
|
||||
|
||||
@@ -428,7 +428,7 @@ public interface Page extends AutoCloseable {
|
||||
*/
|
||||
public Position position;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -478,7 +478,7 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 CheckOptions setStrict(boolean strict) {
|
||||
@@ -539,7 +539,7 @@ public interface Page extends AutoCloseable {
|
||||
*/
|
||||
public Position position;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -618,7 +618,7 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 ClickOptions setStrict(boolean strict) {
|
||||
@@ -691,7 +691,7 @@ public interface Page extends AutoCloseable {
|
||||
*/
|
||||
public Position position;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -763,7 +763,7 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 DblclickOptions setStrict(boolean strict) {
|
||||
@@ -791,7 +791,7 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class DispatchEventOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -803,7 +803,7 @@ public interface Page extends AutoCloseable {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 DispatchEventOptions setStrict(boolean strict) {
|
||||
@@ -838,7 +838,7 @@ public interface Page extends AutoCloseable {
|
||||
*/
|
||||
public Position sourcePosition;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -893,7 +893,7 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 DragAndDropOptions setStrict(boolean strict) {
|
||||
@@ -943,9 +943,6 @@ public interface Page extends AutoCloseable {
|
||||
/**
|
||||
* Emulates {@code "forced-colors"} media feature, supported values are {@code "active"} and {@code "none"}. Passing {@code null} disables forced
|
||||
* colors emulation.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> It's not supported in WebKit, see <a href="https://bugs.webkit.org/show_bug.cgi?id=225281">here</a> in their issue
|
||||
* tracker.
|
||||
*/
|
||||
public Optional<ForcedColors> forcedColors;
|
||||
/**
|
||||
@@ -970,9 +967,6 @@ public interface Page extends AutoCloseable {
|
||||
/**
|
||||
* Emulates {@code "forced-colors"} media feature, supported values are {@code "active"} and {@code "none"}. Passing {@code null} disables forced
|
||||
* colors emulation.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> It's not supported in WebKit, see <a href="https://bugs.webkit.org/show_bug.cgi?id=225281">here</a> in their issue
|
||||
* tracker.
|
||||
*/
|
||||
public EmulateMediaOptions setForcedColors(ForcedColors forcedColors) {
|
||||
this.forcedColors = Optional.ofNullable(forcedColors);
|
||||
@@ -997,13 +991,13 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class EvalOnSelectorOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 EvalOnSelectorOptions setStrict(boolean strict) {
|
||||
@@ -1040,7 +1034,7 @@ public interface Page extends AutoCloseable {
|
||||
*/
|
||||
public Boolean noWaitAfter;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1069,7 +1063,7 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 FillOptions setStrict(boolean strict) {
|
||||
@@ -1088,7 +1082,7 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class FocusOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1100,7 +1094,7 @@ public interface Page extends AutoCloseable {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 FocusOptions setStrict(boolean strict) {
|
||||
@@ -1119,7 +1113,7 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class GetAttributeOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1131,7 +1125,7 @@ public interface Page extends AutoCloseable {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 GetAttributeOptions setStrict(boolean strict) {
|
||||
@@ -1307,7 +1301,7 @@ public interface Page extends AutoCloseable {
|
||||
*/
|
||||
public Position position;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1356,7 +1350,7 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 HoverOptions setStrict(boolean strict) {
|
||||
@@ -1384,7 +1378,7 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class InnerHTMLOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1396,7 +1390,7 @@ public interface Page extends AutoCloseable {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 InnerHTMLOptions setStrict(boolean strict) {
|
||||
@@ -1415,7 +1409,7 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class InnerTextOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1427,7 +1421,7 @@ public interface Page extends AutoCloseable {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 InnerTextOptions setStrict(boolean strict) {
|
||||
@@ -1446,7 +1440,7 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class InputValueOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1458,7 +1452,7 @@ public interface Page extends AutoCloseable {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 InputValueOptions setStrict(boolean strict) {
|
||||
@@ -1477,7 +1471,7 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class IsCheckedOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1489,7 +1483,7 @@ public interface Page extends AutoCloseable {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 IsCheckedOptions setStrict(boolean strict) {
|
||||
@@ -1508,7 +1502,7 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class IsDisabledOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1520,7 +1514,7 @@ public interface Page extends AutoCloseable {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 IsDisabledOptions setStrict(boolean strict) {
|
||||
@@ -1539,7 +1533,7 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class IsEditableOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1551,7 +1545,7 @@ public interface Page extends AutoCloseable {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 IsEditableOptions setStrict(boolean strict) {
|
||||
@@ -1570,7 +1564,7 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class IsEnabledOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1582,7 +1576,7 @@ public interface Page extends AutoCloseable {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 IsEnabledOptions setStrict(boolean strict) {
|
||||
@@ -1601,7 +1595,7 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class IsHiddenOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1612,7 +1606,7 @@ public interface Page extends AutoCloseable {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 IsHiddenOptions setStrict(boolean strict) {
|
||||
@@ -1630,7 +1624,7 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class IsVisibleOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1641,7 +1635,7 @@ public interface Page extends AutoCloseable {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 IsVisibleOptions setStrict(boolean strict) {
|
||||
@@ -1879,7 +1873,7 @@ public interface Page extends AutoCloseable {
|
||||
*/
|
||||
public Boolean noWaitAfter;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -1907,7 +1901,7 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 PressOptions setStrict(boolean strict) {
|
||||
@@ -1926,13 +1920,13 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class QuerySelectorOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 QuerySelectorOptions setStrict(boolean strict) {
|
||||
@@ -1997,6 +1991,62 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
class RouteFromHAROptions {
|
||||
/**
|
||||
* <ul>
|
||||
* <li> If set to 'abort' any request not found in the HAR file will be aborted.</li>
|
||||
* <li> If set to 'fallback' missing requests will be sent to the network.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p> Defaults to abort.
|
||||
*/
|
||||
public HarNotFound notFound;
|
||||
/**
|
||||
* If specified, updates the given HAR with the actual network information instead of serving from file.
|
||||
*/
|
||||
public Boolean update;
|
||||
/**
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* <ul>
|
||||
* <li> If set to 'abort' any request not found in the HAR file will be aborted.</li>
|
||||
* <li> If set to 'fallback' missing requests will be sent to the network.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p> Defaults to abort.
|
||||
*/
|
||||
public RouteFromHAROptions setNotFound(HarNotFound notFound) {
|
||||
this.notFound = notFound;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* If specified, updates the given HAR with the actual network information instead of serving from file.
|
||||
*/
|
||||
public RouteFromHAROptions setUpdate(boolean update) {
|
||||
this.update = update;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* 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 RouteFromHAROptions setUrl(String url) {
|
||||
this.url = url;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* 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 RouteFromHAROptions setUrl(Pattern url) {
|
||||
this.url = url;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
class ScreenshotOptions {
|
||||
/**
|
||||
* When set to {@code "disabled"}, stops CSS animations, CSS transitions and Web Animations. Animations get different treatment
|
||||
@@ -2024,7 +2074,7 @@ public interface Page extends AutoCloseable {
|
||||
*/
|
||||
public Boolean fullPage;
|
||||
/**
|
||||
* Specify locators that should be masked when the screenshot is taken. Masked elements will be overlayed with a pink box
|
||||
* Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink box
|
||||
* {@code #FF00FF} that completely covers its bounding box.
|
||||
*/
|
||||
public List<Locator> mask;
|
||||
@@ -2046,7 +2096,9 @@ public interface Page extends AutoCloseable {
|
||||
/**
|
||||
* 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
|
||||
* high-dpi devices will be twice as large or even larger. Defaults to {@code "device"}.
|
||||
* high-dpi devices will be twice as large or even larger.
|
||||
*
|
||||
* <p> Defaults to {@code "device"}.
|
||||
*/
|
||||
public ScreenshotScale scale;
|
||||
/**
|
||||
@@ -2104,7 +2156,7 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Specify locators that should be masked when the screenshot is taken. Masked elements will be overlayed with a pink box
|
||||
* Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink box
|
||||
* {@code #FF00FF} that completely covers its bounding box.
|
||||
*/
|
||||
public ScreenshotOptions setMask(List<Locator> mask) {
|
||||
@@ -2138,7 +2190,9 @@ public interface Page extends AutoCloseable {
|
||||
/**
|
||||
* 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
|
||||
* high-dpi devices will be twice as large or even larger. Defaults to {@code "device"}.
|
||||
* high-dpi devices will be twice as large or even larger.
|
||||
*
|
||||
* <p> Defaults to {@code "device"}.
|
||||
*/
|
||||
public ScreenshotOptions setScale(ScreenshotScale scale) {
|
||||
this.scale = scale;
|
||||
@@ -2174,7 +2228,7 @@ public interface Page extends AutoCloseable {
|
||||
*/
|
||||
public Boolean noWaitAfter;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -2203,7 +2257,7 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 SelectOptionOptions setStrict(boolean strict) {
|
||||
@@ -2238,7 +2292,7 @@ public interface Page extends AutoCloseable {
|
||||
*/
|
||||
public Position position;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -2288,7 +2342,7 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 SetCheckedOptions setStrict(boolean strict) {
|
||||
@@ -2365,7 +2419,7 @@ public interface Page extends AutoCloseable {
|
||||
*/
|
||||
public Boolean noWaitAfter;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -2386,7 +2440,7 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 SetInputFilesOptions setStrict(boolean strict) {
|
||||
@@ -2426,7 +2480,7 @@ public interface Page extends AutoCloseable {
|
||||
*/
|
||||
public Position position;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -2484,7 +2538,7 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 TapOptions setStrict(boolean strict) {
|
||||
@@ -2512,7 +2566,7 @@ public interface Page extends AutoCloseable {
|
||||
}
|
||||
class TextContentOptions {
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -2524,7 +2578,7 @@ public interface Page extends AutoCloseable {
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 TextContentOptions setStrict(boolean strict) {
|
||||
@@ -2553,7 +2607,7 @@ public interface Page extends AutoCloseable {
|
||||
*/
|
||||
public Boolean noWaitAfter;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -2581,7 +2635,7 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 TypeOptions setStrict(boolean strict) {
|
||||
@@ -2616,7 +2670,7 @@ public interface Page extends AutoCloseable {
|
||||
*/
|
||||
public Position position;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -2666,7 +2720,7 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 UncheckOptions setStrict(boolean strict) {
|
||||
@@ -3016,7 +3070,7 @@ public interface Page extends AutoCloseable {
|
||||
*/
|
||||
public WaitForSelectorState state;
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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;
|
||||
@@ -3043,7 +3097,7 @@ public interface Page extends AutoCloseable {
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* When true, the call requires selector to resolve to a single element. If given selector resolves to more then one
|
||||
* 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 WaitForSelectorOptions setStrict(boolean strict) {
|
||||
@@ -3521,9 +3575,25 @@ public interface Page extends AutoCloseable {
|
||||
* @param eventInit Optional event-specific initialization properties.
|
||||
*/
|
||||
void dispatchEvent(String selector, String type, Object eventInit, DispatchEventOptions options);
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @param source A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be
|
||||
* used. See <a href="https://playwright.dev/java/docs/selectors">working with selectors</a> for more details.
|
||||
* @param target A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will
|
||||
* be used. See <a href="https://playwright.dev/java/docs/selectors">working with selectors</a> for more details.
|
||||
*/
|
||||
default void dragAndDrop(String source, String target) {
|
||||
dragAndDrop(source, target, null);
|
||||
}
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @param source A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be
|
||||
* used. See <a href="https://playwright.dev/java/docs/selectors">working with selectors</a> for more details.
|
||||
* @param target A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will
|
||||
* be used. See <a href="https://playwright.dev/java/docs/selectors">working with selectors</a> for more details.
|
||||
*/
|
||||
void dragAndDrop(String source, String target, DragAndDropOptions options);
|
||||
/**
|
||||
* This method changes the {@code CSS media type} through the {@code media} argument, and/or the {@code "prefers-colors-scheme"} media
|
||||
@@ -4764,7 +4834,7 @@ public interface Page extends AutoCloseable {
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> {@link Page#route Page.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
|
||||
* using request interception. Via {@code await context.addInitScript(() => delete window.navigator.serviceWorker);}
|
||||
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
|
||||
*
|
||||
* <p> An example of a naive handler that aborts all image requests:
|
||||
* <pre>{@code
|
||||
@@ -4817,7 +4887,7 @@ public interface Page extends AutoCloseable {
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> {@link Page#route Page.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
|
||||
* using request interception. Via {@code await context.addInitScript(() => delete window.navigator.serviceWorker);}
|
||||
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
|
||||
*
|
||||
* <p> An example of a naive handler that aborts all image requests:
|
||||
* <pre>{@code
|
||||
@@ -4868,7 +4938,7 @@ public interface Page extends AutoCloseable {
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> {@link Page#route Page.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
|
||||
* using request interception. Via {@code await context.addInitScript(() => delete window.navigator.serviceWorker);}
|
||||
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
|
||||
*
|
||||
* <p> An example of a naive handler that aborts all image requests:
|
||||
* <pre>{@code
|
||||
@@ -4921,7 +4991,7 @@ public interface Page extends AutoCloseable {
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> {@link Page#route Page.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
|
||||
* using request interception. Via {@code await context.addInitScript(() => delete window.navigator.serviceWorker);}
|
||||
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
|
||||
*
|
||||
* <p> An example of a naive handler that aborts all image requests:
|
||||
* <pre>{@code
|
||||
@@ -4972,7 +5042,7 @@ public interface Page extends AutoCloseable {
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> {@link Page#route Page.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
|
||||
* using request interception. Via {@code await context.addInitScript(() => delete window.navigator.serviceWorker);}
|
||||
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
|
||||
*
|
||||
* <p> An example of a naive handler that aborts all image requests:
|
||||
* <pre>{@code
|
||||
@@ -5025,7 +5095,7 @@ public interface Page extends AutoCloseable {
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> {@link Page#route Page.route()} will not intercept requests intercepted by Service Worker. See <a
|
||||
* href="https://github.com/microsoft/playwright/issues/1090">this</a> issue. We recommend disabling Service Workers when
|
||||
* using request interception. Via {@code await context.addInitScript(() => delete window.navigator.serviceWorker);}
|
||||
* using request interception by setting {@code Browser.newContext.serviceWorkers} to {@code "block"}.
|
||||
*
|
||||
* <p> An example of a naive handler that aborts all image requests:
|
||||
* <pre>{@code
|
||||
@@ -5067,6 +5137,32 @@ public interface Page extends AutoCloseable {
|
||||
* @param handler handler function to route the request.
|
||||
*/
|
||||
void route(Predicate<String> url, Consumer<Route> handler, RouteOptions options);
|
||||
/**
|
||||
* If specified the network requests that are made in the page will be served from the HAR file. Read more about <a
|
||||
* href="https://playwright.dev/java/docs/network#replaying-from-har">Replaying from HAR</a>.
|
||||
*
|
||||
* <p> Playwright will not serve requests intercepted by Service Worker from the HAR file. See <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"}.
|
||||
*
|
||||
* @param har Path to a <a href="http://www.softwareishard.com/blog/har-12-spec">HAR</a> file with prerecorded network data. If {@code path}
|
||||
* is a relative path, then it is resolved relative to the current working directory.
|
||||
*/
|
||||
default void routeFromHAR(Path har) {
|
||||
routeFromHAR(har, null);
|
||||
}
|
||||
/**
|
||||
* If specified the network requests that are made in the page will be served from the HAR file. Read more about <a
|
||||
* href="https://playwright.dev/java/docs/network#replaying-from-har">Replaying from HAR</a>.
|
||||
*
|
||||
* <p> Playwright will not serve requests intercepted by Service Worker from the HAR file. See <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"}.
|
||||
*
|
||||
* @param har Path to a <a href="http://www.softwareishard.com/blog/har-12-spec">HAR</a> file with prerecorded network data. If {@code path}
|
||||
* is a relative path, then it is resolved relative to the current working directory.
|
||||
*/
|
||||
void routeFromHAR(Path har, RouteFromHAROptions options);
|
||||
/**
|
||||
* Returns the buffer with the captured screenshot.
|
||||
*/
|
||||
@@ -6543,7 +6639,7 @@ public interface Page extends AutoCloseable {
|
||||
* {@code detached}.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> Playwright automatically waits for element to be ready before performing an action. Using {@code Locator} objects and
|
||||
* web-first assertions make the code wait-for-selector-free.
|
||||
* web-first assertions makes the code wait-for-selector-free.
|
||||
*
|
||||
* <p> Wait for the {@code selector} to satisfy {@code state} option (either appear/disappear from dom, or become visible/hidden). If at
|
||||
* the moment of calling the method {@code selector} already satisfies the condition, the method will return immediately. If the
|
||||
@@ -6581,7 +6677,7 @@ public interface Page extends AutoCloseable {
|
||||
* {@code detached}.
|
||||
*
|
||||
* <p> <strong>NOTE:</strong> Playwright automatically waits for element to be ready before performing an action. Using {@code Locator} objects and
|
||||
* web-first assertions make the code wait-for-selector-free.
|
||||
* web-first assertions makes the code wait-for-selector-free.
|
||||
*
|
||||
* <p> Wait for the {@code selector} to satisfy {@code state} option (either appear/disappear from dom, or become visible/hidden). If at
|
||||
* the moment of calling the method {@code selector} already satisfies the condition, the method will return immediately. If the
|
||||
|
||||
@@ -58,8 +58,9 @@ public interface Request {
|
||||
*/
|
||||
Frame frame();
|
||||
/**
|
||||
* **DEPRECATED** Incomplete list of headers as seen by the rendering engine. Use {@link Request#allHeaders
|
||||
* Request.allHeaders()} instead.
|
||||
* An object with the request HTTP headers. The header names are lower-cased. Note that this method does not return
|
||||
* security-related headers, including cookie-related ones. You can use {@link Request#allHeaders Request.allHeaders()} for
|
||||
* complete list of headers that include {@code cookie} information.
|
||||
*/
|
||||
Map<String, String> headers();
|
||||
/**
|
||||
|
||||
@@ -40,8 +40,14 @@ public interface Response {
|
||||
*/
|
||||
Frame frame();
|
||||
/**
|
||||
* **DEPRECATED** Incomplete list of headers as seen by the rendering engine. Use {@link Response#allHeaders
|
||||
* Response.allHeaders()} instead.
|
||||
* Indicates whether this Response was fulfilled by a Service Worker's Fetch Handler (i.e. via <a
|
||||
* href="https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/respondWith">FetchEvent.respondWith</a>).
|
||||
*/
|
||||
boolean fromServiceWorker();
|
||||
/**
|
||||
* An object with the response HTTP headers. The header names are lower-cased. Note that this method does not return
|
||||
* security-related headers, including cookie-related ones. You can use {@link Response#allHeaders Response.allHeaders()}
|
||||
* for complete list of headers that include {@code cookie} information.
|
||||
*/
|
||||
Map<String, String> headers();
|
||||
/**
|
||||
|
||||
@@ -80,6 +80,62 @@ public interface Route {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
class FallbackOptions {
|
||||
/**
|
||||
* If set changes the request HTTP headers. Header values will be converted to a string.
|
||||
*/
|
||||
public Map<String, String> headers;
|
||||
/**
|
||||
* If set changes the request method (e.g. GET or POST)
|
||||
*/
|
||||
public String method;
|
||||
/**
|
||||
* If set changes the post data of request
|
||||
*/
|
||||
public Object postData;
|
||||
/**
|
||||
* If set changes the request URL. New URL must have same protocol as original one. Changing the URL won't affect the route
|
||||
* matching, all the routes are matched using the original request URL.
|
||||
*/
|
||||
public String url;
|
||||
|
||||
/**
|
||||
* If set changes the request HTTP headers. Header values will be converted to a string.
|
||||
*/
|
||||
public FallbackOptions setHeaders(Map<String, String> headers) {
|
||||
this.headers = headers;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* If set changes the request method (e.g. GET or POST)
|
||||
*/
|
||||
public FallbackOptions setMethod(String method) {
|
||||
this.method = method;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* If set changes the post data of request
|
||||
*/
|
||||
public FallbackOptions setPostData(String postData) {
|
||||
this.postData = postData;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* If set changes the post data of request
|
||||
*/
|
||||
public FallbackOptions setPostData(byte[] postData) {
|
||||
this.postData = postData;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* If set changes the request URL. New URL must have same protocol as original one. Changing the URL won't affect the route
|
||||
* matching, all the routes are matched using the original request URL.
|
||||
*/
|
||||
public FallbackOptions setUrl(String url) {
|
||||
this.url = url;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
class FulfillOptions {
|
||||
/**
|
||||
* Optional response body as text.
|
||||
@@ -200,8 +256,8 @@ public interface Route {
|
||||
* page.route("**\/*", route -> {
|
||||
* // Override headers
|
||||
* Map<String, String> headers = new HashMap<>(route.request().headers());
|
||||
* headers.put("foo", "bar"); // set "foo" header
|
||||
* headers.remove("origin"); // remove "origin" header
|
||||
* headers.put("foo", "foo-value"); // set "foo" header
|
||||
* headers.remove("bar"); // remove "bar" header
|
||||
* route.resume(new Route.ResumeOptions().setHeaders(headers));
|
||||
* });
|
||||
* }</pre>
|
||||
@@ -215,13 +271,133 @@ public interface Route {
|
||||
* page.route("**\/*", route -> {
|
||||
* // Override headers
|
||||
* Map<String, String> headers = new HashMap<>(route.request().headers());
|
||||
* headers.put("foo", "bar"); // set "foo" header
|
||||
* headers.remove("origin"); // remove "origin" header
|
||||
* headers.put("foo", "foo-value"); // set "foo" header
|
||||
* headers.remove("bar"); // remove "bar" header
|
||||
* route.resume(new Route.ResumeOptions().setHeaders(headers));
|
||||
* });
|
||||
* }</pre>
|
||||
*/
|
||||
void resume(ResumeOptions options);
|
||||
/**
|
||||
* When several routes match the given pattern, they run in the order opposite to their registration. That way the last
|
||||
* registered route can always override all the previous ones. In the example below, request will be handled by the
|
||||
* bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first
|
||||
* registered route.
|
||||
* <pre>{@code
|
||||
* page.route("**\/*", route -> {
|
||||
* // Runs last.
|
||||
* route.abort();
|
||||
* });
|
||||
*
|
||||
* page.route("**\/*", route -> {
|
||||
* // Runs second.
|
||||
* route.fallback();
|
||||
* });
|
||||
*
|
||||
* page.route("**\/*", route -> {
|
||||
* // Runs first.
|
||||
* route.fallback();
|
||||
* });
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Registering multiple routes is useful when you want separate handlers to handle different kinds of requests, for example
|
||||
* API calls vs page resources or GET requests vs POST requests as in the example below.
|
||||
* <pre>{@code
|
||||
* // Handle GET requests.
|
||||
* page.route("**\/*", route -> {
|
||||
* if (!route.request().method().equals("GET")) {
|
||||
* route.fallback();
|
||||
* return;
|
||||
* }
|
||||
* // Handling GET only.
|
||||
* // ...
|
||||
* });
|
||||
*
|
||||
* // Handle POST requests.
|
||||
* page.route("**\/*", route -> {
|
||||
* if (!route.request().method().equals("POST")) {
|
||||
* route.fallback();
|
||||
* return;
|
||||
* }
|
||||
* // Handling POST only.
|
||||
* // ...
|
||||
* });
|
||||
* }</pre>
|
||||
*
|
||||
* <p> One can also modify request while falling back to the subsequent handler, that way intermediate route handler can modify
|
||||
* url, method, headers and postData of the request.
|
||||
* <pre>{@code
|
||||
* page.route("**\/*", route -> {
|
||||
* // Override headers
|
||||
* Map<String, String> headers = new HashMap<>(route.request().headers());
|
||||
* headers.put("foo", "foo-value"); // set "foo" header
|
||||
* headers.remove("bar"); // remove "bar" header
|
||||
* route.fallback(new Route.ResumeOptions().setHeaders(headers));
|
||||
* });
|
||||
* }</pre>
|
||||
*/
|
||||
default void fallback() {
|
||||
fallback(null);
|
||||
}
|
||||
/**
|
||||
* When several routes match the given pattern, they run in the order opposite to their registration. That way the last
|
||||
* registered route can always override all the previous ones. In the example below, request will be handled by the
|
||||
* bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first
|
||||
* registered route.
|
||||
* <pre>{@code
|
||||
* page.route("**\/*", route -> {
|
||||
* // Runs last.
|
||||
* route.abort();
|
||||
* });
|
||||
*
|
||||
* page.route("**\/*", route -> {
|
||||
* // Runs second.
|
||||
* route.fallback();
|
||||
* });
|
||||
*
|
||||
* page.route("**\/*", route -> {
|
||||
* // Runs first.
|
||||
* route.fallback();
|
||||
* });
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Registering multiple routes is useful when you want separate handlers to handle different kinds of requests, for example
|
||||
* API calls vs page resources or GET requests vs POST requests as in the example below.
|
||||
* <pre>{@code
|
||||
* // Handle GET requests.
|
||||
* page.route("**\/*", route -> {
|
||||
* if (!route.request().method().equals("GET")) {
|
||||
* route.fallback();
|
||||
* return;
|
||||
* }
|
||||
* // Handling GET only.
|
||||
* // ...
|
||||
* });
|
||||
*
|
||||
* // Handle POST requests.
|
||||
* page.route("**\/*", route -> {
|
||||
* if (!route.request().method().equals("POST")) {
|
||||
* route.fallback();
|
||||
* return;
|
||||
* }
|
||||
* // Handling POST only.
|
||||
* // ...
|
||||
* });
|
||||
* }</pre>
|
||||
*
|
||||
* <p> One can also modify request while falling back to the subsequent handler, that way intermediate route handler can modify
|
||||
* url, method, headers and postData of the request.
|
||||
* <pre>{@code
|
||||
* page.route("**\/*", route -> {
|
||||
* // Override headers
|
||||
* Map<String, String> headers = new HashMap<>(route.request().headers());
|
||||
* headers.put("foo", "foo-value"); // set "foo" header
|
||||
* headers.remove("bar"); // remove "bar" header
|
||||
* route.fallback(new Route.ResumeOptions().setHeaders(headers));
|
||||
* });
|
||||
* }</pre>
|
||||
*/
|
||||
void fallback(FallbackOptions options);
|
||||
/**
|
||||
* Fulfills route's request with given response.
|
||||
*
|
||||
|
||||
@@ -44,7 +44,7 @@ public interface Selectors {
|
||||
/**
|
||||
* An example of registering selector engine that queries elements based on a tag name:
|
||||
* <pre>{@code
|
||||
* // Script that evaluates to a selector engine instance.
|
||||
* // Script that evaluates to a selector engine instance. The script is evaluated in the page context.
|
||||
* String createTagNameEngine = "{\n" +
|
||||
* " // Returns the first element matching given selector in the root's subtree.\n" +
|
||||
* " query(root, selector) {\n" +
|
||||
@@ -63,7 +63,7 @@ public interface Selectors {
|
||||
* // Use the selector prefixed with its name.
|
||||
* Locator button = page.locator("tag=button");
|
||||
* // Combine it with other selector engines.
|
||||
* page.click("tag=div >> text=\"Click me\"");
|
||||
* page.locator("tag=div >> text=\"Click me\"").click();
|
||||
* // Can use it in any methods supporting selectors.
|
||||
* int buttonCount = (int) page.locator("tag=button").count();
|
||||
* browser.close();
|
||||
@@ -71,7 +71,7 @@ public interface Selectors {
|
||||
*
|
||||
* @param name Name that is used in selectors as a prefix, e.g. {@code {name: 'foo'}} enables {@code foo=myselectorbody} selectors. May only
|
||||
* contain {@code [a-zA-Z0-9_]} characters.
|
||||
* @param script Script that evaluates to a selector engine instance.
|
||||
* @param script Script that evaluates to a selector engine instance. The script is evaluated in the page context.
|
||||
*/
|
||||
default void register(String name, String script) {
|
||||
register(name, script, null);
|
||||
@@ -79,7 +79,7 @@ public interface Selectors {
|
||||
/**
|
||||
* An example of registering selector engine that queries elements based on a tag name:
|
||||
* <pre>{@code
|
||||
* // Script that evaluates to a selector engine instance.
|
||||
* // Script that evaluates to a selector engine instance. The script is evaluated in the page context.
|
||||
* String createTagNameEngine = "{\n" +
|
||||
* " // Returns the first element matching given selector in the root's subtree.\n" +
|
||||
* " query(root, selector) {\n" +
|
||||
@@ -98,7 +98,7 @@ public interface Selectors {
|
||||
* // Use the selector prefixed with its name.
|
||||
* Locator button = page.locator("tag=button");
|
||||
* // Combine it with other selector engines.
|
||||
* page.click("tag=div >> text=\"Click me\"");
|
||||
* page.locator("tag=div >> text=\"Click me\"").click();
|
||||
* // Can use it in any methods supporting selectors.
|
||||
* int buttonCount = (int) page.locator("tag=button").count();
|
||||
* browser.close();
|
||||
@@ -106,13 +106,13 @@ public interface Selectors {
|
||||
*
|
||||
* @param name Name that is used in selectors as a prefix, e.g. {@code {name: 'foo'}} enables {@code foo=myselectorbody} selectors. May only
|
||||
* contain {@code [a-zA-Z0-9_]} characters.
|
||||
* @param script Script that evaluates to a selector engine instance.
|
||||
* @param script Script that evaluates to a selector engine instance. The script is evaluated in the page context.
|
||||
*/
|
||||
void register(String name, String script, RegisterOptions options);
|
||||
/**
|
||||
* An example of registering selector engine that queries elements based on a tag name:
|
||||
* <pre>{@code
|
||||
* // Script that evaluates to a selector engine instance.
|
||||
* // Script that evaluates to a selector engine instance. The script is evaluated in the page context.
|
||||
* String createTagNameEngine = "{\n" +
|
||||
* " // Returns the first element matching given selector in the root's subtree.\n" +
|
||||
* " query(root, selector) {\n" +
|
||||
@@ -131,7 +131,7 @@ public interface Selectors {
|
||||
* // Use the selector prefixed with its name.
|
||||
* Locator button = page.locator("tag=button");
|
||||
* // Combine it with other selector engines.
|
||||
* page.click("tag=div >> text=\"Click me\"");
|
||||
* page.locator("tag=div >> text=\"Click me\"").click();
|
||||
* // Can use it in any methods supporting selectors.
|
||||
* int buttonCount = (int) page.locator("tag=button").count();
|
||||
* browser.close();
|
||||
@@ -139,7 +139,7 @@ public interface Selectors {
|
||||
*
|
||||
* @param name Name that is used in selectors as a prefix, e.g. {@code {name: 'foo'}} enables {@code foo=myselectorbody} selectors. May only
|
||||
* contain {@code [a-zA-Z0-9_]} characters.
|
||||
* @param script Script that evaluates to a selector engine instance.
|
||||
* @param script Script that evaluates to a selector engine instance. The script is evaluated in the page context.
|
||||
*/
|
||||
default void register(String name, Path script) {
|
||||
register(name, script, null);
|
||||
@@ -147,7 +147,7 @@ public interface Selectors {
|
||||
/**
|
||||
* An example of registering selector engine that queries elements based on a tag name:
|
||||
* <pre>{@code
|
||||
* // Script that evaluates to a selector engine instance.
|
||||
* // Script that evaluates to a selector engine instance. The script is evaluated in the page context.
|
||||
* String createTagNameEngine = "{\n" +
|
||||
* " // Returns the first element matching given selector in the root's subtree.\n" +
|
||||
* " query(root, selector) {\n" +
|
||||
@@ -166,7 +166,7 @@ public interface Selectors {
|
||||
* // Use the selector prefixed with its name.
|
||||
* Locator button = page.locator("tag=button");
|
||||
* // Combine it with other selector engines.
|
||||
* page.click("tag=div >> text=\"Click me\"");
|
||||
* page.locator("tag=div >> text=\"Click me\"").click();
|
||||
* // Can use it in any methods supporting selectors.
|
||||
* int buttonCount = (int) page.locator("tag=button").count();
|
||||
* browser.close();
|
||||
@@ -174,7 +174,7 @@ public interface Selectors {
|
||||
*
|
||||
* @param name Name that is used in selectors as a prefix, e.g. {@code {name: 'foo'}} enables {@code foo=myselectorbody} selectors. May only
|
||||
* contain {@code [a-zA-Z0-9_]} characters.
|
||||
* @param script Script that evaluates to a selector engine instance.
|
||||
* @param script Script that evaluates to a selector engine instance. The script is evaluated in the page context.
|
||||
*/
|
||||
void register(String name, Path script, RegisterOptions options);
|
||||
}
|
||||
|
||||
@@ -192,7 +192,7 @@ public interface Tracing {
|
||||
* page.navigate("https://playwright.dev");
|
||||
*
|
||||
* context.tracing().startChunk();
|
||||
* page.click("text=Get Started");
|
||||
* page.locator("text=Get Started").click();
|
||||
* // Everything between startChunk and stopChunk will be recorded in the trace.
|
||||
* context.tracing().stopChunk(new Tracing.StopChunkOptions()
|
||||
* .setPath(Paths.get("trace1.zip")));
|
||||
@@ -219,7 +219,7 @@ public interface Tracing {
|
||||
* page.navigate("https://playwright.dev");
|
||||
*
|
||||
* context.tracing().startChunk();
|
||||
* page.click("text=Get Started");
|
||||
* page.locator("text=Get Started").click();
|
||||
* // Everything between startChunk and stopChunk will be recorded in the trace.
|
||||
* context.tracing().stopChunk(new Tracing.StopChunkOptions()
|
||||
* .setPath(Paths.get("trace1.zip")));
|
||||
|
||||
+1
-1
@@ -46,7 +46,7 @@ public interface APIResponseAssertions {
|
||||
*/
|
||||
APIResponseAssertions not();
|
||||
/**
|
||||
* Ensures the response status code is within [200..299] range.
|
||||
* Ensures the response status code is within {@code 200..299} range.
|
||||
* <pre>{@code
|
||||
* assertThat(response).isOK();
|
||||
* }</pre>
|
||||
|
||||
+490
-51
@@ -31,7 +31,7 @@ import java.util.regex.Pattern;
|
||||
* @Test
|
||||
* void statusBecomesSubmitted() {
|
||||
* ...
|
||||
* page.click("#submit-button");
|
||||
* page.locator("#submit-button").click();
|
||||
* assertThat(page.locator(".status")).hasText("Submitted");
|
||||
* }
|
||||
* }
|
||||
@@ -72,11 +72,16 @@ public interface LocatorAssertions {
|
||||
}
|
||||
}
|
||||
class IsEditableOptions {
|
||||
public Boolean editable;
|
||||
/**
|
||||
* Time to retry the assertion for.
|
||||
*/
|
||||
public Double timeout;
|
||||
|
||||
public IsEditableOptions setEditable(boolean editable) {
|
||||
this.editable = editable;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Time to retry the assertion for.
|
||||
*/
|
||||
@@ -100,11 +105,16 @@ public interface LocatorAssertions {
|
||||
}
|
||||
}
|
||||
class IsEnabledOptions {
|
||||
public Boolean enabled;
|
||||
/**
|
||||
* Time to retry the assertion for.
|
||||
*/
|
||||
public Double timeout;
|
||||
|
||||
public IsEnabledOptions setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Time to retry the assertion for.
|
||||
*/
|
||||
@@ -146,6 +156,7 @@ public interface LocatorAssertions {
|
||||
* Time to retry the assertion for.
|
||||
*/
|
||||
public Double timeout;
|
||||
public Boolean visible;
|
||||
|
||||
/**
|
||||
* Time to retry the assertion for.
|
||||
@@ -154,8 +165,17 @@ public interface LocatorAssertions {
|
||||
this.timeout = timeout;
|
||||
return this;
|
||||
}
|
||||
public IsVisibleOptions setVisible(boolean visible) {
|
||||
this.visible = visible;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
class ContainsTextOptions {
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
@@ -165,6 +185,14 @@ public interface LocatorAssertions {
|
||||
*/
|
||||
public Boolean useInnerText;
|
||||
|
||||
/**
|
||||
* Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
|
||||
* expression flag if specified.
|
||||
*/
|
||||
public ContainsTextOptions setIgnoreCase(boolean ignoreCase) {
|
||||
this.ignoreCase = ignoreCase;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Time to retry the assertion for.
|
||||
*/
|
||||
@@ -265,6 +293,11 @@ public interface LocatorAssertions {
|
||||
}
|
||||
}
|
||||
class HasTextOptions {
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
@@ -274,6 +307,14 @@ public interface LocatorAssertions {
|
||||
*/
|
||||
public Boolean useInnerText;
|
||||
|
||||
/**
|
||||
* Whether to perform case-insensitive match. {@code ignoreCase} option takes precedence over the corresponding regular
|
||||
* expression flag if specified.
|
||||
*/
|
||||
public HasTextOptions setIgnoreCase(boolean ignoreCase) {
|
||||
this.ignoreCase = ignoreCase;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Time to retry the assertion for.
|
||||
*/
|
||||
@@ -303,6 +344,20 @@ public interface LocatorAssertions {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
class HasValuesOptions {
|
||||
/**
|
||||
* Time to retry the assertion for.
|
||||
*/
|
||||
public Double timeout;
|
||||
|
||||
/**
|
||||
* Time to retry the assertion for.
|
||||
*/
|
||||
public HasValuesOptions setTimeout(double timeout) {
|
||||
this.timeout = timeout;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Makes the assertion check for the opposite condition. For example, this code tests that the Locator doesn't contain text
|
||||
* {@code "error"}:
|
||||
@@ -416,8 +471,8 @@ public interface LocatorAssertions {
|
||||
*/
|
||||
void isFocused(IsFocusedOptions options);
|
||||
/**
|
||||
* Ensures the {@code Locator} points to a hidden DOM node, which is the opposite of <a
|
||||
* href="https://playwright.dev/java/docs/api/actionability#visible">visible</a>.
|
||||
* Ensures that {@code Locator} either does not resolve to any DOM node, or resolves to a <a
|
||||
* href="https://playwright.dev/java/docs/api/actionability#visible">non-visible</a> one.
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator(".my-element")).isHidden();
|
||||
* }</pre>
|
||||
@@ -426,16 +481,16 @@ public interface LocatorAssertions {
|
||||
isHidden(null);
|
||||
}
|
||||
/**
|
||||
* Ensures the {@code Locator} points to a hidden DOM node, which is the opposite of <a
|
||||
* href="https://playwright.dev/java/docs/api/actionability#visible">visible</a>.
|
||||
* Ensures that {@code Locator} either does not resolve to any DOM node, or resolves to a <a
|
||||
* href="https://playwright.dev/java/docs/api/actionability#visible">non-visible</a> one.
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator(".my-element")).isHidden();
|
||||
* }</pre>
|
||||
*/
|
||||
void isHidden(IsHiddenOptions options);
|
||||
/**
|
||||
* Ensures the {@code Locator} points to a <a href="https://playwright.dev/java/docs/api/actionability#visible">visible</a> DOM
|
||||
* node.
|
||||
* Ensures that {@code Locator} points to an <a href="https://playwright.dev/java/docs/api/actionability#visible">attached</a>
|
||||
* and <a href="https://playwright.dev/java/docs/api/actionability#visible">visible</a> DOM node.
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator(".my-element")).isVisible();
|
||||
* }</pre>
|
||||
@@ -444,8 +499,8 @@ public interface LocatorAssertions {
|
||||
isVisible(null);
|
||||
}
|
||||
/**
|
||||
* Ensures the {@code Locator} points to a <a href="https://playwright.dev/java/docs/api/actionability#visible">visible</a> DOM
|
||||
* node.
|
||||
* Ensures that {@code Locator} points to an <a href="https://playwright.dev/java/docs/api/actionability#visible">attached</a>
|
||||
* and <a href="https://playwright.dev/java/docs/api/actionability#visible">visible</a> DOM node.
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator(".my-element")).isVisible();
|
||||
* }</pre>
|
||||
@@ -458,9 +513,29 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).containsText("substring");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> Elements from a **subset** of this list contain text from the expected array, respectively.</li>
|
||||
* <li> The matching subset of elements has the same order as the expected array.</li>
|
||||
* <li> Each text value from the expected array is matched by some element from the list.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .list-item")).containsText(new String[] {"Text 1", "Text 4", "Text 5"});
|
||||
* // ✓ Contains the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 1", "Text 3", "Text 4"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 3", "Text 2"});
|
||||
*
|
||||
* // ✖ No item contains this text
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Some 33"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).containsText(new String[] {"Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -475,9 +550,29 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).containsText("substring");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> Elements from a **subset** of this list contain text from the expected array, respectively.</li>
|
||||
* <li> The matching subset of elements has the same order as the expected array.</li>
|
||||
* <li> Each text value from the expected array is matched by some element from the list.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .list-item")).containsText(new String[] {"Text 1", "Text 4", "Text 5"});
|
||||
* // ✓ Contains the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 1", "Text 3", "Text 4"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 3", "Text 2"});
|
||||
*
|
||||
* // ✖ No item contains this text
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Some 33"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).containsText(new String[] {"Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -490,9 +585,29 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).containsText("substring");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> Elements from a **subset** of this list contain text from the expected array, respectively.</li>
|
||||
* <li> The matching subset of elements has the same order as the expected array.</li>
|
||||
* <li> Each text value from the expected array is matched by some element from the list.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .list-item")).containsText(new String[] {"Text 1", "Text 4", "Text 5"});
|
||||
* // ✓ Contains the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 1", "Text 3", "Text 4"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 3", "Text 2"});
|
||||
*
|
||||
* // ✖ No item contains this text
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Some 33"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).containsText(new String[] {"Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -507,9 +622,29 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).containsText("substring");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> Elements from a **subset** of this list contain text from the expected array, respectively.</li>
|
||||
* <li> The matching subset of elements has the same order as the expected array.</li>
|
||||
* <li> Each text value from the expected array is matched by some element from the list.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .list-item")).containsText(new String[] {"Text 1", "Text 4", "Text 5"});
|
||||
* // ✓ Contains the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 1", "Text 3", "Text 4"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 3", "Text 2"});
|
||||
*
|
||||
* // ✖ No item contains this text
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Some 33"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).containsText(new String[] {"Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -522,9 +657,29 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).containsText("substring");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> Elements from a **subset** of this list contain text from the expected array, respectively.</li>
|
||||
* <li> The matching subset of elements has the same order as the expected array.</li>
|
||||
* <li> Each text value from the expected array is matched by some element from the list.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .list-item")).containsText(new String[] {"Text 1", "Text 4", "Text 5"});
|
||||
* // ✓ Contains the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 1", "Text 3", "Text 4"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 3", "Text 2"});
|
||||
*
|
||||
* // ✖ No item contains this text
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Some 33"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).containsText(new String[] {"Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -539,9 +694,29 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).containsText("substring");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> Elements from a **subset** of this list contain text from the expected array, respectively.</li>
|
||||
* <li> The matching subset of elements has the same order as the expected array.</li>
|
||||
* <li> Each text value from the expected array is matched by some element from the list.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .list-item")).containsText(new String[] {"Text 1", "Text 4", "Text 5"});
|
||||
* // ✓ Contains the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 1", "Text 3", "Text 4"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 3", "Text 2"});
|
||||
*
|
||||
* // ✖ No item contains this text
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Some 33"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).containsText(new String[] {"Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -554,9 +729,29 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).containsText("substring");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> Elements from a **subset** of this list contain text from the expected array, respectively.</li>
|
||||
* <li> The matching subset of elements has the same order as the expected array.</li>
|
||||
* <li> Each text value from the expected array is matched by some element from the list.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .list-item")).containsText(new String[] {"Text 1", "Text 4", "Text 5"});
|
||||
* // ✓ Contains the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 1", "Text 3", "Text 4"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 3", "Text 2"});
|
||||
*
|
||||
* // ✖ No item contains this text
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Some 33"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).containsText(new String[] {"Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -571,9 +766,29 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).containsText("substring");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> Elements from a **subset** of this list contain text from the expected array, respectively.</li>
|
||||
* <li> The matching subset of elements has the same order as the expected array.</li>
|
||||
* <li> Each text value from the expected array is matched by some element from the list.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .list-item")).containsText(new String[] {"Text 1", "Text 4", "Text 5"});
|
||||
* // ✓ Contains the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 1", "Text 3", "Text 4"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Text 3", "Text 2"});
|
||||
*
|
||||
* // ✖ No item contains this text
|
||||
* assertThat(page.locator("ul > li")).containsText(new String[] {"Some 33"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).containsText(new String[] {"Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -589,7 +804,7 @@ public interface LocatorAssertions {
|
||||
* @param value Expected attribute value.
|
||||
*/
|
||||
default void hasAttribute(String name, String value) {
|
||||
hasAttribute(name, value, null);
|
||||
hasAttribute(name, value, (HasAttributeOptions) null);
|
||||
}
|
||||
/**
|
||||
* Ensures the {@code Locator} points to an element with given attribute.
|
||||
@@ -611,7 +826,7 @@ public interface LocatorAssertions {
|
||||
* @param value Expected attribute value.
|
||||
*/
|
||||
default void hasAttribute(String name, Pattern value) {
|
||||
hasAttribute(name, value, null);
|
||||
hasAttribute(name, value, (HasAttributeOptions) null);
|
||||
}
|
||||
/**
|
||||
* Ensures the {@code Locator} points to an element with given attribute.
|
||||
@@ -624,9 +839,11 @@ public interface LocatorAssertions {
|
||||
*/
|
||||
void hasAttribute(String name, Pattern value, HasAttributeOptions options);
|
||||
/**
|
||||
* Ensures the {@code Locator} points to an element with given CSS class.
|
||||
* Ensures the {@code Locator} points to an element with given CSS classes. This needs to be a full match or using a relaxed
|
||||
* regular expression.
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("#component")).hasClass(Pattern.compile("selected"));
|
||||
* assertThat(page.locator("#component")).hasClass("selected row");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
@@ -640,9 +857,11 @@ public interface LocatorAssertions {
|
||||
hasClass(expected, null);
|
||||
}
|
||||
/**
|
||||
* Ensures the {@code Locator} points to an element with given CSS class.
|
||||
* Ensures the {@code Locator} points to an element with given CSS classes. This needs to be a full match or using a relaxed
|
||||
* regular expression.
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("#component")).hasClass(Pattern.compile("selected"));
|
||||
* assertThat(page.locator("#component")).hasClass("selected row");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
@@ -654,9 +873,11 @@ public interface LocatorAssertions {
|
||||
*/
|
||||
void hasClass(String expected, HasClassOptions options);
|
||||
/**
|
||||
* Ensures the {@code Locator} points to an element with given CSS class.
|
||||
* Ensures the {@code Locator} points to an element with given CSS classes. This needs to be a full match or using a relaxed
|
||||
* regular expression.
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("#component")).hasClass(Pattern.compile("selected"));
|
||||
* assertThat(page.locator("#component")).hasClass("selected row");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
@@ -670,9 +891,11 @@ public interface LocatorAssertions {
|
||||
hasClass(expected, null);
|
||||
}
|
||||
/**
|
||||
* Ensures the {@code Locator} points to an element with given CSS class.
|
||||
* Ensures the {@code Locator} points to an element with given CSS classes. This needs to be a full match or using a relaxed
|
||||
* regular expression.
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("#component")).hasClass(Pattern.compile("selected"));
|
||||
* assertThat(page.locator("#component")).hasClass("selected row");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
@@ -684,9 +907,11 @@ public interface LocatorAssertions {
|
||||
*/
|
||||
void hasClass(Pattern expected, HasClassOptions options);
|
||||
/**
|
||||
* Ensures the {@code Locator} points to an element with given CSS class.
|
||||
* Ensures the {@code Locator} points to an element with given CSS classes. This needs to be a full match or using a relaxed
|
||||
* regular expression.
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("#component")).hasClass(Pattern.compile("selected"));
|
||||
* assertThat(page.locator("#component")).hasClass("selected row");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
@@ -700,9 +925,11 @@ public interface LocatorAssertions {
|
||||
hasClass(expected, null);
|
||||
}
|
||||
/**
|
||||
* Ensures the {@code Locator} points to an element with given CSS class.
|
||||
* Ensures the {@code Locator} points to an element with given CSS classes. This needs to be a full match or using a relaxed
|
||||
* regular expression.
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("#component")).hasClass(Pattern.compile("selected"));
|
||||
* assertThat(page.locator("#component")).hasClass("selected row");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
@@ -714,9 +941,11 @@ public interface LocatorAssertions {
|
||||
*/
|
||||
void hasClass(String[] expected, HasClassOptions options);
|
||||
/**
|
||||
* Ensures the {@code Locator} points to an element with given CSS class.
|
||||
* Ensures the {@code Locator} points to an element with given CSS classes. This needs to be a full match or using a relaxed
|
||||
* regular expression.
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("#component")).hasClass(Pattern.compile("selected"));
|
||||
* assertThat(page.locator("#component")).hasClass("selected row");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
@@ -730,9 +959,11 @@ public interface LocatorAssertions {
|
||||
hasClass(expected, null);
|
||||
}
|
||||
/**
|
||||
* Ensures the {@code Locator} points to an element with given CSS class.
|
||||
* Ensures the {@code Locator} points to an element with given CSS classes. This needs to be a full match or using a relaxed
|
||||
* regular expression.
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("#component")).hasClass(Pattern.compile("selected"));
|
||||
* assertThat(page.locator("#component")).hasClass("selected row");
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
@@ -878,9 +1109,28 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).hasText(Pattern.compile("Welcome, .*"));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> The number of elements equals the number of expected values in the array.</li>
|
||||
* <li> Elements from the list have text matching expected array values, one by one, in order.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .component")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* // ✓ Has the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 3", "Text 2", "Text 1"});
|
||||
*
|
||||
* // ✖ Last item does not match
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -895,9 +1145,28 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).hasText(Pattern.compile("Welcome, .*"));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> The number of elements equals the number of expected values in the array.</li>
|
||||
* <li> Elements from the list have text matching expected array values, one by one, in order.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .component")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* // ✓ Has the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 3", "Text 2", "Text 1"});
|
||||
*
|
||||
* // ✖ Last item does not match
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -910,9 +1179,28 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).hasText(Pattern.compile("Welcome, .*"));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> The number of elements equals the number of expected values in the array.</li>
|
||||
* <li> Elements from the list have text matching expected array values, one by one, in order.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .component")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* // ✓ Has the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 3", "Text 2", "Text 1"});
|
||||
*
|
||||
* // ✖ Last item does not match
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -927,9 +1215,28 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).hasText(Pattern.compile("Welcome, .*"));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> The number of elements equals the number of expected values in the array.</li>
|
||||
* <li> Elements from the list have text matching expected array values, one by one, in order.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .component")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* // ✓ Has the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 3", "Text 2", "Text 1"});
|
||||
*
|
||||
* // ✖ Last item does not match
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -942,9 +1249,28 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).hasText(Pattern.compile("Welcome, .*"));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> The number of elements equals the number of expected values in the array.</li>
|
||||
* <li> Elements from the list have text matching expected array values, one by one, in order.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .component")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* // ✓ Has the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 3", "Text 2", "Text 1"});
|
||||
*
|
||||
* // ✖ Last item does not match
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -959,9 +1285,28 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).hasText(Pattern.compile("Welcome, .*"));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> The number of elements equals the number of expected values in the array.</li>
|
||||
* <li> Elements from the list have text matching expected array values, one by one, in order.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .component")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* // ✓ Has the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 3", "Text 2", "Text 1"});
|
||||
*
|
||||
* // ✖ Last item does not match
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -974,9 +1319,28 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).hasText(Pattern.compile("Welcome, .*"));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> The number of elements equals the number of expected values in the array.</li>
|
||||
* <li> Elements from the list have text matching expected array values, one by one, in order.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .component")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* // ✓ Has the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 3", "Text 2", "Text 1"});
|
||||
*
|
||||
* // ✖ Last item does not match
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -991,9 +1355,28 @@ public interface LocatorAssertions {
|
||||
* assertThat(page.locator(".title")).hasText(Pattern.compile("Welcome, .*"));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Note that if array is passed as an expected value, entire lists of elements can be asserted:
|
||||
* <p> If you pass an array as an expected value, the expectations are:
|
||||
* <ol>
|
||||
* <li> Locator resolves to a list of elements.</li>
|
||||
* <li> The number of elements equals the number of expected values in the array.</li>
|
||||
* <li> Elements from the list have text matching expected array values, one by one, in order.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p> For example, consider the following list:
|
||||
*
|
||||
* <p> Let's see how we can use the assertion:
|
||||
* <pre>{@code
|
||||
* assertThat(page.locator("list > .component")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* // ✓ Has the right items in the right order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
*
|
||||
* // ✖ Wrong order
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 3", "Text 2", "Text 1"});
|
||||
*
|
||||
* // ✖ Last item does not match
|
||||
* assertThat(page.locator("ul > li")).hasText(new String[] {"Text 1", "Text 2", "Text"});
|
||||
*
|
||||
* // ✖ Locator points to the outer list element, not to the list items
|
||||
* assertThat(page.locator("ul")).hasText(new String[] {"Text 1", "Text 2", "Text 3"});
|
||||
* }</pre>
|
||||
*
|
||||
* @param expected Expected substring or RegExp or a list of those.
|
||||
@@ -1043,5 +1426,61 @@ public interface LocatorAssertions {
|
||||
* @param value Expected value.
|
||||
*/
|
||||
void hasValue(Pattern value, HasValueOptions options);
|
||||
/**
|
||||
* Ensures the {@code Locator} points to multi-select/combobox (i.e. a {@code select} with the {@code multiple} attribute) and the specified
|
||||
* values are selected.
|
||||
*
|
||||
* <p> For example, given the following element:
|
||||
* <pre>{@code
|
||||
* page.locator("id=favorite-colors").selectOption(["R", "G"]);
|
||||
* assertThat(page.locator("id=favorite-colors")).hasValues(new Pattern[] { Pattern.compile("R"), Pattern.compile("G") });
|
||||
* }</pre>
|
||||
*
|
||||
* @param values Expected options currently selected.
|
||||
*/
|
||||
default void hasValues(String[] values) {
|
||||
hasValues(values, null);
|
||||
}
|
||||
/**
|
||||
* Ensures the {@code Locator} points to multi-select/combobox (i.e. a {@code select} with the {@code multiple} attribute) and the specified
|
||||
* values are selected.
|
||||
*
|
||||
* <p> For example, given the following element:
|
||||
* <pre>{@code
|
||||
* page.locator("id=favorite-colors").selectOption(["R", "G"]);
|
||||
* assertThat(page.locator("id=favorite-colors")).hasValues(new Pattern[] { Pattern.compile("R"), Pattern.compile("G") });
|
||||
* }</pre>
|
||||
*
|
||||
* @param values Expected options currently selected.
|
||||
*/
|
||||
void hasValues(String[] values, HasValuesOptions options);
|
||||
/**
|
||||
* Ensures the {@code Locator} points to multi-select/combobox (i.e. a {@code select} with the {@code multiple} attribute) and the specified
|
||||
* values are selected.
|
||||
*
|
||||
* <p> For example, given the following element:
|
||||
* <pre>{@code
|
||||
* page.locator("id=favorite-colors").selectOption(["R", "G"]);
|
||||
* assertThat(page.locator("id=favorite-colors")).hasValues(new Pattern[] { Pattern.compile("R"), Pattern.compile("G") });
|
||||
* }</pre>
|
||||
*
|
||||
* @param values Expected options currently selected.
|
||||
*/
|
||||
default void hasValues(Pattern[] values) {
|
||||
hasValues(values, null);
|
||||
}
|
||||
/**
|
||||
* Ensures the {@code Locator} points to multi-select/combobox (i.e. a {@code select} with the {@code multiple} attribute) and the specified
|
||||
* values are selected.
|
||||
*
|
||||
* <p> For example, given the following element:
|
||||
* <pre>{@code
|
||||
* page.locator("id=favorite-colors").selectOption(["R", "G"]);
|
||||
* assertThat(page.locator("id=favorite-colors")).hasValues(new Pattern[] { Pattern.compile("R"), Pattern.compile("G") });
|
||||
* }</pre>
|
||||
*
|
||||
* @param values Expected options currently selected.
|
||||
*/
|
||||
void hasValues(Pattern[] values, HasValuesOptions options);
|
||||
}
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ import java.util.regex.Pattern;
|
||||
* @Test
|
||||
* void navigatesToLoginPage() {
|
||||
* ...
|
||||
* page.click("#login");
|
||||
* page.locator("#login").click();
|
||||
* assertThat(page).hasURL(Pattern.compile(".*\/login"));
|
||||
* }
|
||||
* }
|
||||
@@ -120,7 +120,7 @@ public interface PageAssertions {
|
||||
* assertThat(page).hasURL(".com");
|
||||
* }</pre>
|
||||
*
|
||||
* @param urlOrRegExp Expected substring or RegExp.
|
||||
* @param urlOrRegExp Expected URL string or RegExp.
|
||||
*/
|
||||
default void hasURL(String urlOrRegExp) {
|
||||
hasURL(urlOrRegExp, null);
|
||||
@@ -131,7 +131,7 @@ public interface PageAssertions {
|
||||
* assertThat(page).hasURL(".com");
|
||||
* }</pre>
|
||||
*
|
||||
* @param urlOrRegExp Expected substring or RegExp.
|
||||
* @param urlOrRegExp Expected URL string or RegExp.
|
||||
*/
|
||||
void hasURL(String urlOrRegExp, HasURLOptions options);
|
||||
/**
|
||||
@@ -140,7 +140,7 @@ public interface PageAssertions {
|
||||
* assertThat(page).hasURL(".com");
|
||||
* }</pre>
|
||||
*
|
||||
* @param urlOrRegExp Expected substring or RegExp.
|
||||
* @param urlOrRegExp Expected URL string or RegExp.
|
||||
*/
|
||||
default void hasURL(Pattern urlOrRegExp) {
|
||||
hasURL(urlOrRegExp, null);
|
||||
@@ -151,7 +151,7 @@ public interface PageAssertions {
|
||||
* assertThat(page).hasURL(".com");
|
||||
* }</pre>
|
||||
*
|
||||
* @param urlOrRegExp Expected substring or RegExp.
|
||||
* @param urlOrRegExp Expected URL string or RegExp.
|
||||
*/
|
||||
void hasURL(Pattern urlOrRegExp, HasURLOptions options);
|
||||
}
|
||||
|
||||
+14
-1
@@ -20,6 +20,7 @@ import com.microsoft.playwright.APIResponse;
|
||||
import com.microsoft.playwright.Locator;
|
||||
import com.microsoft.playwright.Page;
|
||||
import com.microsoft.playwright.impl.APIResponseAssertionsImpl;
|
||||
import com.microsoft.playwright.impl.AssertionsTimeout;
|
||||
import com.microsoft.playwright.impl.LocatorAssertionsImpl;
|
||||
import com.microsoft.playwright.impl.PageAssertionsImpl;
|
||||
|
||||
@@ -37,7 +38,7 @@ import com.microsoft.playwright.impl.PageAssertionsImpl;
|
||||
* @Test
|
||||
* void statusBecomesSubmitted() {
|
||||
* ...
|
||||
* page.click("#submit-button");
|
||||
* page.locator("#submit-button").click();
|
||||
* assertThat(page.locator(".status")).hasText("Submitted");
|
||||
* }
|
||||
* }
|
||||
@@ -86,5 +87,17 @@ public interface PlaywrightAssertions {
|
||||
return new PageAssertionsImpl(page);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes default timeout for Playwright assertions from 5 seconds to the specified value.
|
||||
* <pre>{@code
|
||||
* PlaywrightAssertions.setDefaultAssertionTimeout(30_000);
|
||||
* }</pre>
|
||||
*
|
||||
* @param timeout Timeout in milliseconds.
|
||||
*/
|
||||
static void setDefaultAssertionTimeout(double milliseconds) {
|
||||
AssertionsTimeout.setDefaultTimeout(milliseconds);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -110,6 +110,12 @@ class APIRequestContextImpl extends ChannelOwner implements APIRequestContext {
|
||||
if (options.ignoreHTTPSErrors != null) {
|
||||
params.addProperty("ignoreHTTPSErrors", options.ignoreHTTPSErrors);
|
||||
}
|
||||
if (options.maxRedirects != null) {
|
||||
if (options.maxRedirects < 0) {
|
||||
throw new PlaywrightException("'maxRedirects' should be greater than or equal to '0'");
|
||||
}
|
||||
params.addProperty("maxRedirects", options.maxRedirects);
|
||||
}
|
||||
JsonObject json = sendMessage("fetch", params).getAsJsonObject();
|
||||
return new APIResponseImpl(this, json.getAsJsonObject("response"));
|
||||
}
|
||||
|
||||
+16
-1
@@ -21,6 +21,7 @@ import com.microsoft.playwright.assertions.APIResponseAssertions;
|
||||
import org.opentest4j.AssertionFailedError;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class APIResponseAssertionsImpl implements APIResponseAssertions {
|
||||
private final APIResponse actual;
|
||||
@@ -54,6 +55,20 @@ public class APIResponseAssertionsImpl implements APIResponseAssertions {
|
||||
if (!log.isEmpty()) {
|
||||
log = "\nCall log:\n" + log;
|
||||
}
|
||||
throw new AssertionFailedError(message + log);
|
||||
|
||||
String contentType = actual.headers().get("content-type");
|
||||
boolean isTextEncoding = contentType == null ? false : isTextualMimeType(contentType);
|
||||
String responseText = "";
|
||||
if (isTextEncoding) {
|
||||
String text = actual.text();
|
||||
if (text != null) {
|
||||
responseText = "\nResponse text:\n" + (text.length() > 1000 ? text.substring(0, 1000) : text);
|
||||
}
|
||||
}
|
||||
|
||||
throw new AssertionFailedError(message + log + responseText);
|
||||
}
|
||||
static boolean isTextualMimeType(String mimeType) {
|
||||
return Pattern.matches("^(text/.*?|application/(json|(x-)?javascript|xml.*?|ecmascript|graphql|x-www-form-urlencoded)|image/svg(\\+xml)?|application/.*?(\\+json|\\+xml))(;\\s*charset=.*)?$", mimeType);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ class AssertionsBase {
|
||||
|
||||
void expectImpl(String expression, FrameExpectOptions expectOptions, Object expected, String message) {
|
||||
if (expectOptions.timeout == null) {
|
||||
expectOptions.timeout = 5_000.0;
|
||||
expectOptions.timeout = AssertionsTimeout.defaultTimeout;
|
||||
}
|
||||
if (expectOptions.isNot) {
|
||||
message = message.replace("expected to", "expected not to");
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* 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.impl;
|
||||
|
||||
import com.microsoft.playwright.PlaywrightException;
|
||||
|
||||
public class AssertionsTimeout {
|
||||
static double defaultTimeout = 5_000;
|
||||
|
||||
public static void setDefaultTimeout(double ms) {
|
||||
if (ms < 0) {
|
||||
throw new PlaywrightException("Timeout cannot be negative");
|
||||
}
|
||||
defaultTimeout = ms;
|
||||
}
|
||||
}
|
||||
@@ -20,21 +20,20 @@ import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.microsoft.playwright.*;
|
||||
import com.microsoft.playwright.options.BindingCallback;
|
||||
import com.microsoft.playwright.options.Cookie;
|
||||
import com.microsoft.playwright.options.FunctionCallback;
|
||||
import com.microsoft.playwright.options.Geolocation;
|
||||
import com.microsoft.playwright.options.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static com.microsoft.playwright.impl.Serialization.addHarUrlFilter;
|
||||
import static com.microsoft.playwright.impl.Serialization.gson;
|
||||
import static com.microsoft.playwright.impl.Utils.isSafeCloseError;
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
@@ -54,7 +53,17 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
|
||||
final TimeoutSettings timeoutSettings = new TimeoutSettings();
|
||||
Path videosDir;
|
||||
URL baseUrl;
|
||||
Path recordHarPath;
|
||||
final Map<String, HarRecorder> harRecorders = new HashMap<>();
|
||||
|
||||
static class HarRecorder {
|
||||
final Path path;
|
||||
final HarContentPolicy contentPolicy;
|
||||
|
||||
HarRecorder(Path har, HarContentPolicy policy) {
|
||||
path = har;
|
||||
contentPolicy = policy;
|
||||
}
|
||||
}
|
||||
|
||||
enum EventType {
|
||||
CLOSE,
|
||||
@@ -74,7 +83,13 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
|
||||
}
|
||||
this.tracing = connection.getExistingObject(initializer.getAsJsonObject("tracing").get("guid").getAsString());
|
||||
tracing.isRemote = browser != null && browser.isRemote;
|
||||
this.request = connection.getExistingObject(initializer.getAsJsonObject("APIRequestContext").get("guid").getAsString());
|
||||
this.request = connection.getExistingObject(initializer.getAsJsonObject("requestContext").get("guid").getAsString());
|
||||
}
|
||||
|
||||
void setRecordHar(Path path, HarContentPolicy policy) {
|
||||
if (path != null) {
|
||||
harRecorders.put("", new HarRecorder(path, policy));
|
||||
}
|
||||
}
|
||||
|
||||
void setBaseUrl(String spec) {
|
||||
@@ -155,7 +170,7 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
|
||||
|
||||
@Override
|
||||
public Page waitForPage(WaitForPageOptions options, Runnable code) {
|
||||
return withWaitLogging("BrowserContext.close", () -> waitForPageImpl(options, code));
|
||||
return withWaitLogging("BrowserContext.close", logger -> waitForPageImpl(options, code));
|
||||
}
|
||||
|
||||
private Page waitForPageImpl(WaitForPageOptions options, Runnable code) {
|
||||
@@ -181,15 +196,31 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
|
||||
}
|
||||
isClosedOrClosing = true;
|
||||
try {
|
||||
if (recordHarPath != null) {
|
||||
JsonObject json = sendMessage("harExport").getAsJsonObject();
|
||||
for (Map.Entry<String, HarRecorder> entry : harRecorders.entrySet()) {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("harId", entry.getKey());
|
||||
JsonObject json = sendMessage("harExport", params).getAsJsonObject();
|
||||
ArtifactImpl artifact = connection.getExistingObject(json.getAsJsonObject("artifact").get("guid").getAsString());
|
||||
// In case of CDP connection browser is null but since the connection is established by
|
||||
// the driver it is safe to consider the artifact local.
|
||||
if (browser() != null && browser().isRemote) {
|
||||
artifact.isRemote = true;
|
||||
}
|
||||
artifact.saveAs(recordHarPath);
|
||||
|
||||
// Server side will compress artifact if content is attach or if file is .zip.
|
||||
HarRecorder harParams = entry.getValue();
|
||||
boolean isCompressed = harParams.contentPolicy == HarContentPolicy.ATTACH || harParams.path.toString().endsWith(".zip");
|
||||
boolean needCompressed = harParams.path.toString().endsWith(".zip");
|
||||
if (isCompressed && !needCompressed) {
|
||||
String tmpPath = harParams.path + ".tmp";
|
||||
artifact.saveAs(Paths.get(tmpPath));
|
||||
JsonObject unzipParams = new JsonObject();
|
||||
unzipParams.addProperty("zipFile", tmpPath);
|
||||
unzipParams.addProperty("harFile", harParams.path.toString());
|
||||
connection.localUtils.sendMessage("harUnzip", unzipParams);
|
||||
} else {
|
||||
artifact.saveAs(harParams.path);
|
||||
}
|
||||
artifact.delete();
|
||||
}
|
||||
|
||||
@@ -336,7 +367,7 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
|
||||
|
||||
@Override
|
||||
public void route(String url, Consumer<Route> handler, RouteOptions options) {
|
||||
route(new UrlMatcher(this.baseUrl, url), handler, options);
|
||||
route(new UrlMatcher(baseUrl, url), handler, options);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -349,6 +380,21 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
|
||||
route(new UrlMatcher(url), handler, options);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void routeFromHAR(Path har, RouteFromHAROptions options) {
|
||||
if (options == null) {
|
||||
options = new RouteFromHAROptions();
|
||||
}
|
||||
if (options.update != null && options.update) {
|
||||
recordIntoHar(null, har, options);
|
||||
return;
|
||||
}
|
||||
UrlMatcher matcher = UrlMatcher.forOneOf(baseUrl, options.url);
|
||||
HARRouter harRouter = new HARRouter(connection.localUtils, har, options.notFound);
|
||||
onClose(context -> harRouter.dispose());
|
||||
route(matcher, route -> harRouter.handle(route), null);
|
||||
}
|
||||
|
||||
private void route(UrlMatcher matcher, Consumer<Route> handler, RouteOptions options) {
|
||||
withLogging("BrowserContext.route", () -> {
|
||||
routes.add(matcher, handler, options == null ? null : options.times);
|
||||
@@ -360,6 +406,22 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
|
||||
});
|
||||
}
|
||||
|
||||
void recordIntoHar(PageImpl page, Path har, RouteFromHAROptions options) {
|
||||
JsonObject params = new JsonObject();
|
||||
if (page != null) {
|
||||
params.add("page", page.toProtocolRef());
|
||||
}
|
||||
JsonObject jsonOptions = new JsonObject();
|
||||
jsonOptions.addProperty("path", har.toAbsolutePath().toString());
|
||||
jsonOptions.addProperty("content", HarContentPolicy.ATTACH.name().toLowerCase());
|
||||
jsonOptions.addProperty("mode", HarMode.MINIMAL.name().toLowerCase());
|
||||
addHarUrlFilter(jsonOptions, options.url);
|
||||
params.add("options", jsonOptions);
|
||||
JsonObject json = sendMessage("harStart", params).getAsJsonObject();
|
||||
String harId = json.get("harId").getAsString();
|
||||
harRecorders.put(harId, new HarRecorder(har, HarContentPolicy.ATTACH));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDefaultNavigationTimeout(double timeout) {
|
||||
withLogging("BrowserContext.setDefaultNavigationTimeout", () -> {
|
||||
@@ -474,11 +536,12 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
|
||||
}
|
||||
}
|
||||
|
||||
void handleRoute(Route route) {
|
||||
boolean handled = routes.handle(route);
|
||||
if (handled) {
|
||||
void handleRoute(RouteImpl route) {
|
||||
Router.HandleResult handled = routes.handle(route);
|
||||
if (handled == Router.HandleResult.FoundMatchingHandler) {
|
||||
maybeDisableNetworkInterception();
|
||||
} else {
|
||||
}
|
||||
if (!route.isHandled()){
|
||||
route.resume();
|
||||
}
|
||||
}
|
||||
@@ -490,7 +553,7 @@ class BrowserContextImpl extends ChannelOwner implements BrowserContext {
|
||||
@Override
|
||||
protected void handleEvent(String event, JsonObject params) {
|
||||
if ("route".equals(event)) {
|
||||
Route route = connection.getExistingObject(params.getAsJsonObject("route").get("guid").getAsString());
|
||||
RouteImpl route = connection.getExistingObject(params.getAsJsonObject("route").get("guid").getAsString());
|
||||
handleRoute(route);
|
||||
} else if ("page".equals(event)) {
|
||||
PageImpl page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString());
|
||||
|
||||
@@ -19,20 +19,21 @@ package com.microsoft.playwright.impl;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.microsoft.playwright.Browser;
|
||||
import com.microsoft.playwright.BrowserContext;
|
||||
import com.microsoft.playwright.Page;
|
||||
import com.microsoft.playwright.PlaywrightException;
|
||||
import com.microsoft.playwright.*;
|
||||
import com.microsoft.playwright.options.HarContentPolicy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static com.microsoft.playwright.impl.Serialization.addHarUrlFilter;
|
||||
import static com.microsoft.playwright.impl.Serialization.gson;
|
||||
import static com.microsoft.playwright.impl.Utils.*;
|
||||
import static com.microsoft.playwright.impl.Utils.convertType;
|
||||
import static com.microsoft.playwright.impl.Utils.isSafeCloseError;
|
||||
|
||||
class BrowserImpl extends ChannelOwner implements Browser {
|
||||
final Set<BrowserContextImpl> contexts = new HashSet<>();
|
||||
@@ -40,7 +41,7 @@ class BrowserImpl extends ChannelOwner implements Browser {
|
||||
boolean isRemote;
|
||||
boolean isConnectedOverWebSocket;
|
||||
private boolean isConnected = true;
|
||||
LocalUtils localUtils;
|
||||
BrowserTypeImpl browserType;
|
||||
|
||||
enum EventType {
|
||||
DISCONNECTED,
|
||||
@@ -60,6 +61,11 @@ class BrowserImpl extends ChannelOwner implements Browser {
|
||||
listeners.remove(EventType.DISCONNECTED, handler);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BrowserType browserType() {
|
||||
return browserType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
withLogging("Browser.close", () -> closeImpl());
|
||||
@@ -112,6 +118,9 @@ class BrowserImpl extends ChannelOwner implements Browser {
|
||||
private BrowserContextImpl newContextImpl(NewContextOptions options) {
|
||||
if (options == null) {
|
||||
options = new NewContextOptions();
|
||||
} else {
|
||||
// Make a copy so that we can nullify some fields below.
|
||||
options = convertType(options, NewContextOptions.class);
|
||||
}
|
||||
if (options.storageStatePath != null) {
|
||||
try {
|
||||
@@ -127,21 +136,50 @@ class BrowserImpl extends ChannelOwner implements Browser {
|
||||
storageState = new Gson().fromJson(options.storageState, JsonObject.class);
|
||||
options.storageState = null;
|
||||
}
|
||||
JsonObject recordHar = null;
|
||||
Path recordHarPath = options.recordHarPath;
|
||||
HarContentPolicy harContentPolicy = null;
|
||||
if (options.recordHarPath != null) {
|
||||
recordHar = new JsonObject();
|
||||
recordHar.addProperty("path", options.recordHarPath.toString());
|
||||
if (options.recordHarContent != null) {
|
||||
harContentPolicy = options.recordHarContent;
|
||||
} else if (options.recordHarOmitContent != null && options.recordHarOmitContent) {
|
||||
harContentPolicy = HarContentPolicy.OMIT;
|
||||
}
|
||||
if (harContentPolicy != null) {
|
||||
recordHar.addProperty("content", harContentPolicy.name().toLowerCase());
|
||||
}
|
||||
if (options.recordHarMode != null) {
|
||||
recordHar.addProperty("mode", options.recordHarMode.name().toLowerCase());
|
||||
}
|
||||
addHarUrlFilter(recordHar, options.recordHarUrlFilter);
|
||||
options.recordHarPath = null;
|
||||
options.recordHarMode = null;
|
||||
options.recordHarOmitContent = null;
|
||||
options.recordHarContent = null;
|
||||
options.recordHarUrlFilter = null;
|
||||
} else {
|
||||
if (options.recordHarOmitContent != null) {
|
||||
throw new PlaywrightException("recordHarOmitContent is set but recordHarPath is null");
|
||||
}
|
||||
if (options.recordHarUrlFilter != null) {
|
||||
throw new PlaywrightException("recordHarUrlFilter is set but recordHarPath is null");
|
||||
}
|
||||
if (options.recordHarMode != null) {
|
||||
throw new PlaywrightException("recordHarMode is set but recordHarPath is null");
|
||||
}
|
||||
if (options.recordHarContent != null) {
|
||||
throw new PlaywrightException("recordHarContent is set but recordHarPath is null");
|
||||
}
|
||||
}
|
||||
|
||||
JsonObject params = gson().toJsonTree(options).getAsJsonObject();
|
||||
if (storageState != null) {
|
||||
params.add("storageState", storageState);
|
||||
}
|
||||
if (options.recordHarPath != null) {
|
||||
JsonObject recordHar = new JsonObject();
|
||||
recordHar.addProperty("path", options.recordHarPath.toString());
|
||||
if (options.recordHarOmitContent != null) {
|
||||
recordHar.addProperty("omitContent", true);
|
||||
}
|
||||
params.remove("recordHarPath");
|
||||
params.remove("recordHarOmitContent");
|
||||
if (recordHar != null) {
|
||||
params.add("recordHar", recordHar);
|
||||
} else if (options.recordHarOmitContent != null) {
|
||||
throw new PlaywrightException("recordHarOmitContent is set but recordHarPath is null");
|
||||
}
|
||||
if (options.recordVideoDir != null) {
|
||||
JsonObject recordVideo = new JsonObject();
|
||||
@@ -171,8 +209,7 @@ class BrowserImpl extends ChannelOwner implements Browser {
|
||||
if (options.baseURL != null) {
|
||||
context.setBaseUrl(options.baseURL);
|
||||
}
|
||||
context.recordHarPath = options.recordHarPath;
|
||||
context.tracing().localUtils = localUtils;
|
||||
context.setRecordHar(recordHarPath, harContentPolicy);
|
||||
contexts.add(context);
|
||||
return context;
|
||||
}
|
||||
@@ -193,9 +230,7 @@ class BrowserImpl extends ChannelOwner implements Browser {
|
||||
}
|
||||
JsonObject params = gson().toJsonTree(options).getAsJsonObject();
|
||||
if (page != null) {
|
||||
JsonObject jsonPage = new JsonObject();
|
||||
jsonPage.addProperty("guid", ((PageImpl) page).guid);
|
||||
params.add("page", jsonPage);
|
||||
params.add("page", ((PageImpl) page).toProtocolRef());
|
||||
}
|
||||
sendMessage("startTracing", params);
|
||||
}
|
||||
|
||||
@@ -22,12 +22,15 @@ import com.google.gson.JsonObject;
|
||||
import com.microsoft.playwright.Browser;
|
||||
import com.microsoft.playwright.BrowserType;
|
||||
import com.microsoft.playwright.PlaywrightException;
|
||||
import com.microsoft.playwright.options.HarContentPolicy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static com.microsoft.playwright.impl.Serialization.addHarUrlFilter;
|
||||
import static com.microsoft.playwright.impl.Serialization.gson;
|
||||
import static com.microsoft.playwright.impl.Utils.convertType;
|
||||
|
||||
class BrowserTypeImpl extends ChannelOwner implements BrowserType {
|
||||
LocalUtils localUtils;
|
||||
@@ -48,7 +51,7 @@ class BrowserTypeImpl extends ChannelOwner implements BrowserType {
|
||||
JsonObject params = gson().toJsonTree(options).getAsJsonObject();
|
||||
JsonElement result = sendMessage("launch", params);
|
||||
BrowserImpl browser = connection.getExistingObject(result.getAsJsonObject().getAsJsonObject("browser").get("guid").getAsString());
|
||||
browser.localUtils = localUtils;
|
||||
browser.browserType = this;
|
||||
return browser;
|
||||
}
|
||||
|
||||
@@ -82,7 +85,7 @@ class BrowserTypeImpl extends ChannelOwner implements BrowserType {
|
||||
|
||||
JsonObject json = sendMessage("connect", params).getAsJsonObject();
|
||||
JsonPipe pipe = connection.getExistingObject(json.getAsJsonObject("pipe").get("guid").getAsString());
|
||||
Connection connection = new Connection(pipe);
|
||||
Connection connection = new Connection(pipe, this.connection.env);
|
||||
PlaywrightImpl playwright = connection.initializePlaywright();
|
||||
if (!playwright.initializer.has("preLaunchedBrowser")) {
|
||||
try {
|
||||
@@ -96,7 +99,7 @@ class BrowserTypeImpl extends ChannelOwner implements BrowserType {
|
||||
BrowserImpl browser = connection.getExistingObject(playwright.initializer.getAsJsonObject("preLaunchedBrowser").get("guid").getAsString());
|
||||
browser.isRemote = true;
|
||||
browser.isConnectedOverWebSocket = true;
|
||||
browser.localUtils = localUtils;
|
||||
browser.browserType = this;
|
||||
Consumer<JsonPipe> connectionCloseListener = t -> browser.notifyRemoteClosed();
|
||||
pipe.onClose(connectionCloseListener);
|
||||
browser.onDisconnected(b -> {
|
||||
@@ -130,7 +133,7 @@ class BrowserTypeImpl extends ChannelOwner implements BrowserType {
|
||||
|
||||
BrowserImpl browser = connection.getExistingObject(json.getAsJsonObject("browser").get("guid").getAsString());
|
||||
browser.isRemote = true;
|
||||
browser.localUtils = localUtils;
|
||||
browser.browserType = this;
|
||||
if (json.has("defaultContext")) {
|
||||
String contextId = json.getAsJsonObject("defaultContext").get("guid").getAsString();
|
||||
BrowserContextImpl defaultContext = connection.getExistingObject(contextId);
|
||||
@@ -152,20 +155,52 @@ class BrowserTypeImpl extends ChannelOwner implements BrowserType {
|
||||
private BrowserContextImpl launchPersistentContextImpl(Path userDataDir, LaunchPersistentContextOptions options) {
|
||||
if (options == null) {
|
||||
options = new LaunchPersistentContextOptions();
|
||||
} else {
|
||||
// Make a copy so that we can nullify some fields below.
|
||||
options = convertType(options, LaunchPersistentContextOptions.class);
|
||||
}
|
||||
JsonObject recordHar = null;
|
||||
Path recordHarPath = options.recordHarPath;
|
||||
HarContentPolicy harContentPolicy = null;
|
||||
if (options.recordHarPath != null) {
|
||||
recordHar = new JsonObject();
|
||||
recordHar.addProperty("path", options.recordHarPath.toString());
|
||||
if (options.recordHarContent != null) {
|
||||
harContentPolicy = options.recordHarContent;
|
||||
} else if (options.recordHarOmitContent != null && options.recordHarOmitContent) {
|
||||
harContentPolicy = HarContentPolicy.OMIT;
|
||||
}
|
||||
if (harContentPolicy != null) {
|
||||
recordHar.addProperty("content", harContentPolicy.name().toLowerCase());
|
||||
}
|
||||
if (options.recordHarMode != null) {
|
||||
recordHar.addProperty("mode", options.recordHarMode.toString().toLowerCase());
|
||||
}
|
||||
addHarUrlFilter(recordHar, options.recordHarUrlFilter);
|
||||
options.recordHarPath = null;
|
||||
options.recordHarMode = null;
|
||||
options.recordHarOmitContent = null;
|
||||
options.recordHarContent = null;
|
||||
options.recordHarUrlFilter = null;
|
||||
} else {
|
||||
if (options.recordHarOmitContent != null) {
|
||||
throw new PlaywrightException("recordHarOmitContent is set but recordHarPath is null");
|
||||
}
|
||||
if (options.recordHarUrlFilter != null) {
|
||||
throw new PlaywrightException("recordHarUrlFilter is set but recordHarPath is null");
|
||||
}
|
||||
if (options.recordHarMode != null) {
|
||||
throw new PlaywrightException("recordHarMode is set but recordHarPath is null");
|
||||
}
|
||||
if (options.recordHarContent != null) {
|
||||
throw new PlaywrightException("recordHarContent is set but recordHarPath is null");
|
||||
}
|
||||
}
|
||||
|
||||
JsonObject params = gson().toJsonTree(options).getAsJsonObject();
|
||||
params.addProperty("userDataDir", userDataDir.toString());
|
||||
if (options.recordHarPath != null) {
|
||||
JsonObject recordHar = new JsonObject();
|
||||
recordHar.addProperty("path", options.recordHarPath.toString());
|
||||
if (options.recordHarOmitContent != null) {
|
||||
recordHar.addProperty("omitContent", true);
|
||||
}
|
||||
params.remove("recordHarPath");
|
||||
params.remove("recordHarOmitContent");
|
||||
if (recordHar != null) {
|
||||
params.add("recordHar", recordHar);
|
||||
} else if (options.recordHarOmitContent != null) {
|
||||
throw new PlaywrightException("recordHarOmitContent is set but recordHarPath is null");
|
||||
}
|
||||
if (options.recordVideoDir != null) {
|
||||
JsonObject recordVideo = new JsonObject();
|
||||
@@ -195,8 +230,7 @@ class BrowserTypeImpl extends ChannelOwner implements BrowserType {
|
||||
if (options.baseURL != null) {
|
||||
context.setBaseUrl(options.baseURL);
|
||||
}
|
||||
context.recordHarPath = options.recordHarPath;
|
||||
context.tracing().localUtils = localUtils;
|
||||
context.setRecordHar(recordHarPath, harContentPolicy);
|
||||
return context;
|
||||
}
|
||||
|
||||
|
||||
@@ -22,11 +22,13 @@ import com.google.gson.JsonObject;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.BinaryOperator;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
class ChannelOwner extends LoggingSupport {
|
||||
final Connection connection;
|
||||
private final ChannelOwner parent;
|
||||
private ChannelOwner parent;
|
||||
private final Map<String, ChannelOwner> objects = new HashMap<>();
|
||||
|
||||
final String type;
|
||||
@@ -68,7 +70,13 @@ class ChannelOwner extends LoggingSupport {
|
||||
objects.clear();
|
||||
}
|
||||
|
||||
<T> T withWaitLogging(String apiName, Supplier<T> code) {
|
||||
void adopt(ChannelOwner child) {
|
||||
child.parent.objects.remove(child.guid);
|
||||
objects.put(child.guid, child);
|
||||
child.parent = this;
|
||||
}
|
||||
|
||||
<T> T withWaitLogging(String apiName, Function<Logger, T> code) {
|
||||
return new WaitForEventLogger<>(this, apiName, code).get();
|
||||
}
|
||||
|
||||
@@ -108,4 +116,10 @@ class ChannelOwner extends LoggingSupport {
|
||||
|
||||
void handleEvent(String event, JsonObject parameters) {
|
||||
}
|
||||
|
||||
JsonObject toProtocolRef() {
|
||||
JsonObject json = new JsonObject();
|
||||
json.addProperty("guid", guid);
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,6 +64,8 @@ public class Connection {
|
||||
String debug = System.getenv("DEBUG");
|
||||
isLogging = (debug != null) && debug.contains("pw:channel");
|
||||
}
|
||||
LocalUtils localUtils;
|
||||
final Map<String, String> env;
|
||||
|
||||
class Root extends ChannelOwner {
|
||||
Root(Connection connection) {
|
||||
@@ -78,13 +80,14 @@ public class Connection {
|
||||
}
|
||||
}
|
||||
|
||||
Connection(Transport transport) {
|
||||
Connection(Transport transport, Map<String, String> env) {
|
||||
this.env = env;
|
||||
if (isLogging) {
|
||||
transport = new TransportLogger(transport);
|
||||
}
|
||||
this.transport = transport;
|
||||
root = new Root(this);
|
||||
stackTraceCollector = StackTraceCollector.createFromEnv();
|
||||
stackTraceCollector = StackTraceCollector.createFromEnv(env);
|
||||
}
|
||||
|
||||
boolean isCollectingStacks() {
|
||||
@@ -138,6 +141,10 @@ public class Connection {
|
||||
return (PlaywrightImpl) this.root.initialize();
|
||||
}
|
||||
|
||||
LocalUtils localUtils() {
|
||||
return localUtils;
|
||||
}
|
||||
|
||||
public <T> T getExistingObject(String guid) {
|
||||
@SuppressWarnings("unchecked") T result = (T) objects.get(guid);
|
||||
if (result == null)
|
||||
@@ -194,18 +201,24 @@ public class Connection {
|
||||
createRemoteObject(message.guid, message.params);
|
||||
return;
|
||||
}
|
||||
if (message.method.equals("__dispose__")) {
|
||||
ChannelOwner object = objects.get(message.guid);
|
||||
if (object == null) {
|
||||
throw new PlaywrightException("Cannot find object to dispose: " + message.guid);
|
||||
}
|
||||
object.disconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
ChannelOwner object = objects.get(message.guid);
|
||||
if (object == null) {
|
||||
throw new PlaywrightException("Cannot find object to call " + message.method + ": " + message.guid);
|
||||
}
|
||||
if (message.method.equals("__adopt__")) {
|
||||
String childGuid = message.params.get("guid").getAsString();
|
||||
ChannelOwner child = objects.get(childGuid);
|
||||
if (child == null) {
|
||||
throw new PlaywrightException("Unknown new child: " + childGuid);
|
||||
}
|
||||
object.adopt(child);
|
||||
return;
|
||||
}
|
||||
if (message.method.equals("__dispose__")) {
|
||||
object.disconnect();
|
||||
return;
|
||||
}
|
||||
object.handleEvent(message.method, message.params);
|
||||
}
|
||||
|
||||
@@ -270,7 +283,8 @@ public class Connection {
|
||||
result = new JsonPipe(parent, type, guid, initializer);
|
||||
break;
|
||||
case "LocalUtils":
|
||||
result = new LocalUtils(parent, type, guid, initializer);
|
||||
localUtils = new LocalUtils(parent, type, guid, initializer);
|
||||
result = localUtils;
|
||||
break;
|
||||
case "Page":
|
||||
result = new PageImpl(parent, type, guid, initializer);
|
||||
|
||||
@@ -23,7 +23,6 @@ import com.microsoft.playwright.*;
|
||||
import com.microsoft.playwright.options.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
@@ -812,17 +811,17 @@ public class FrameImpl extends ChannelOwner implements Frame {
|
||||
|
||||
@Override
|
||||
public void waitForLoadState(LoadState state, WaitForLoadStateOptions options) {
|
||||
withWaitLogging("Frame.waitForLoadState", () -> {
|
||||
waitForLoadStateImpl(state, options);
|
||||
withWaitLogging("Frame.waitForLoadState", logger -> {
|
||||
waitForLoadStateImpl(state, options, logger);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
void waitForLoadStateImpl(LoadState state, WaitForLoadStateOptions options) {
|
||||
waitForLoadStateImpl(convertType(state, WaitUntilState.class), options);
|
||||
void waitForLoadStateImpl(LoadState state, WaitForLoadStateOptions options, Logger logger) {
|
||||
waitForLoadStateImpl(convertType(state, WaitUntilState.class), options, logger);
|
||||
}
|
||||
|
||||
private void waitForLoadStateImpl(WaitUntilState state, WaitForLoadStateOptions options) {
|
||||
private void waitForLoadStateImpl(WaitUntilState state, WaitForLoadStateOptions options, Logger logger) {
|
||||
if (options == null) {
|
||||
options = new WaitForLoadStateOptions();
|
||||
}
|
||||
@@ -831,7 +830,7 @@ public class FrameImpl extends ChannelOwner implements Frame {
|
||||
}
|
||||
|
||||
List<Waitable<Void>> waitables = new ArrayList<>();
|
||||
waitables.add(new WaitForLoadStateHelper(state));
|
||||
waitables.add(new WaitForLoadStateHelper(state, logger));
|
||||
waitables.add(page.createWaitForCloseHelper());
|
||||
waitables.add(page.createWaitableTimeout(options.timeout));
|
||||
runUntil(() -> {}, new WaitableRace<>(waitables));
|
||||
@@ -839,10 +838,12 @@ public class FrameImpl extends ChannelOwner implements Frame {
|
||||
|
||||
private class WaitForLoadStateHelper implements Waitable<Void>, Consumer<WaitUntilState> {
|
||||
private final WaitUntilState expectedState;
|
||||
private final Logger logger;
|
||||
private boolean isDone;
|
||||
|
||||
WaitForLoadStateHelper(WaitUntilState state) {
|
||||
WaitForLoadStateHelper(WaitUntilState state, Logger logger) {
|
||||
expectedState = state;
|
||||
this.logger = logger;
|
||||
isDone = loadStates.contains(state);
|
||||
if (!isDone) {
|
||||
internalListeners.add(InternalEventType.LOADSTATE, this);
|
||||
@@ -851,6 +852,7 @@ public class FrameImpl extends ChannelOwner implements Frame {
|
||||
|
||||
@Override
|
||||
public void accept(WaitUntilState state) {
|
||||
logger.log(" load state changed to " + state);
|
||||
if (expectedState.equals(state)) {
|
||||
isDone = true;
|
||||
dispose();
|
||||
@@ -874,20 +876,24 @@ public class FrameImpl extends ChannelOwner implements Frame {
|
||||
private class WaitForNavigationHelper implements Waitable<Response>, Consumer<JsonObject> {
|
||||
private final UrlMatcher matcher;
|
||||
private final WaitUntilState expectedLoadState;
|
||||
private final Logger logger;
|
||||
private WaitForLoadStateHelper loadStateHelper;
|
||||
|
||||
private RequestImpl request;
|
||||
private RuntimeException exception;
|
||||
|
||||
WaitForNavigationHelper(UrlMatcher matcher, WaitUntilState expectedLoadState) {
|
||||
WaitForNavigationHelper(UrlMatcher matcher, WaitUntilState expectedLoadState, Logger logger) {
|
||||
this.matcher = matcher;
|
||||
this.expectedLoadState = expectedLoadState;
|
||||
this.logger = logger;
|
||||
internalListeners.add(InternalEventType.NAVIGATED, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(JsonObject params) {
|
||||
if (!matcher.test(params.get("url").getAsString())) {
|
||||
String url = params.get("url").getAsString();
|
||||
logger.log(" navigated to " + url);
|
||||
if (!matcher.test(url)) {
|
||||
return;
|
||||
}
|
||||
if (params.has("error")) {
|
||||
@@ -899,7 +905,7 @@ public class FrameImpl extends ChannelOwner implements Frame {
|
||||
request = connection.getExistingObject(jsonReq.get("guid").getAsString());
|
||||
}
|
||||
}
|
||||
loadStateHelper = new WaitForLoadStateHelper(expectedLoadState);
|
||||
loadStateHelper = new WaitForLoadStateHelper(expectedLoadState, logger);
|
||||
}
|
||||
internalListeners.remove(InternalEventType.NAVIGATED, this);
|
||||
}
|
||||
@@ -938,14 +944,14 @@ public class FrameImpl extends ChannelOwner implements Frame {
|
||||
|
||||
@Override
|
||||
public Response waitForNavigation(WaitForNavigationOptions options, Runnable code) {
|
||||
return withLogging("Frame.waitForNavigation", () -> waitForNavigationImpl(code, options, null));
|
||||
return withWaitLogging("Frame.waitForNavigation", logger -> waitForNavigationImpl(logger, code, options, null));
|
||||
}
|
||||
|
||||
Response waitForNavigationImpl(Runnable code, WaitForNavigationOptions options) {
|
||||
return waitForNavigationImpl(code, options, null);
|
||||
Response waitForNavigationImpl(Logger logger, Runnable code, WaitForNavigationOptions options) {
|
||||
return waitForNavigationImpl(logger, code, options, null);
|
||||
}
|
||||
|
||||
private Response waitForNavigationImpl(Runnable code, WaitForNavigationOptions options, UrlMatcher matcher) {
|
||||
private Response waitForNavigationImpl(Logger logger, Runnable code, WaitForNavigationOptions options, UrlMatcher matcher) {
|
||||
if (options == null) {
|
||||
options = new WaitForNavigationOptions();
|
||||
}
|
||||
@@ -957,7 +963,8 @@ public class FrameImpl extends ChannelOwner implements Frame {
|
||||
if (matcher == null) {
|
||||
matcher = UrlMatcher.forOneOf(page.context().baseUrl, options.url);
|
||||
}
|
||||
waitables.add(new WaitForNavigationHelper(matcher, options.waitUntil));
|
||||
logger.log("waiting for navigation " + matcher);
|
||||
waitables.add(new WaitForNavigationHelper(matcher, options.waitUntil, logger));
|
||||
waitables.add(page.createWaitForCloseHelper());
|
||||
waitables.add(page.createWaitableFrameDetach(this));
|
||||
waitables.add(page.createWaitableNavigationTimeout(options.timeout));
|
||||
@@ -1015,18 +1022,22 @@ public class FrameImpl extends ChannelOwner implements Frame {
|
||||
}
|
||||
|
||||
private void waitForURL(UrlMatcher matcher, WaitForURLOptions options) {
|
||||
withLogging("Frame.waitForURL", () -> waitForURLImpl(matcher, options));
|
||||
withWaitLogging("Frame.waitForURL", logger -> {
|
||||
waitForURLImpl(logger, matcher, options);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
void waitForURLImpl(UrlMatcher matcher, WaitForURLOptions options) {
|
||||
void waitForURLImpl(Logger logger, UrlMatcher matcher, WaitForURLOptions options) {
|
||||
logger.log("waiting for url " + matcher);
|
||||
if (options == null) {
|
||||
options = new WaitForURLOptions();
|
||||
}
|
||||
if (matcher.test(url())) {
|
||||
waitForLoadStateImpl(options.waitUntil, convertType(options, WaitForLoadStateOptions.class));
|
||||
waitForLoadStateImpl(options.waitUntil, convertType(options, WaitForLoadStateOptions.class), logger);
|
||||
return;
|
||||
}
|
||||
waitForNavigationImpl(() -> {}, convertType(options, WaitForNavigationOptions.class), matcher);
|
||||
waitForNavigationImpl(logger, () -> {}, convertType(options, WaitForNavigationOptions.class), matcher);
|
||||
}
|
||||
|
||||
int queryCount(String selector) {
|
||||
@@ -1048,6 +1059,13 @@ public class FrameImpl extends ChannelOwner implements Frame {
|
||||
if (add != null) {
|
||||
WaitUntilState state = loadStateFromProtocol(add.getAsString());
|
||||
loadStates.add(state);
|
||||
if (parentFrame == null && page != null) {
|
||||
if (state == LOAD) {
|
||||
page.listeners.notify(PageImpl.EventType.LOAD, page);
|
||||
} else if (state == DOMCONTENTLOADED) {
|
||||
page.listeners.notify(PageImpl.EventType.DOMCONTENTLOADED, page);
|
||||
}
|
||||
}
|
||||
internalListeners.notify(InternalEventType.LOADSTATE, state);
|
||||
}
|
||||
JsonElement remove = params.get("remove");
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* 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.impl;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.microsoft.playwright.PlaywrightException;
|
||||
import com.microsoft.playwright.Request;
|
||||
import com.microsoft.playwright.Route;
|
||||
import com.microsoft.playwright.options.HarNotFound;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.microsoft.playwright.impl.LoggingSupport.*;
|
||||
import static com.microsoft.playwright.impl.Serialization.fromNameValues;
|
||||
import static com.microsoft.playwright.impl.Serialization.gson;
|
||||
|
||||
public class HARRouter {
|
||||
private final LocalUtils localUtils;
|
||||
private final HarNotFound defaultAction;
|
||||
private final String harId;
|
||||
|
||||
HARRouter(LocalUtils localUtils, Path harFile, HarNotFound defaultAction) {
|
||||
this.localUtils = localUtils;
|
||||
this.defaultAction = defaultAction;
|
||||
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("file", harFile.toString());
|
||||
JsonObject json = localUtils.sendMessage("harOpen", params).getAsJsonObject();
|
||||
if (json.has("error")) {
|
||||
throw new PlaywrightException(json.get("error").getAsString());
|
||||
}
|
||||
harId = json.get("harId").getAsString();
|
||||
}
|
||||
|
||||
void handle(Route route) {
|
||||
Request request = route.request();
|
||||
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("harId", harId);
|
||||
params.addProperty("url", request.url());
|
||||
params.addProperty("method", request.method());
|
||||
params.add("headers", gson().toJsonTree(request.headersArray()));
|
||||
if (request.postDataBuffer() != null) {
|
||||
String base64 = Base64.getEncoder().encodeToString(request.postDataBuffer());
|
||||
params.addProperty("postData", base64);
|
||||
}
|
||||
params.addProperty("isNavigationRequest", request.isNavigationRequest());
|
||||
JsonObject response = localUtils.sendMessage("harLookup", params).getAsJsonObject();
|
||||
|
||||
String action = response.get("action").getAsString();
|
||||
if ("redirect".equals(action)) {
|
||||
String redirectURL = response.get("redirectURL").getAsString();
|
||||
logApiIfEnabled("HAR: " + route.request().url() + " redirected to " + redirectURL);
|
||||
((RouteImpl) route).redirectNavigationRequest(redirectURL);
|
||||
return;
|
||||
}
|
||||
|
||||
if ("fulfill".equals(action)) {
|
||||
int status = response.get("status").getAsInt();
|
||||
Map<String, String> headers = fromNameValues(response.getAsJsonArray("headers"));
|
||||
byte[] buffer = Base64.getDecoder().decode(response.get("body").getAsString());
|
||||
route.fulfill(new Route.FulfillOptions()
|
||||
.setStatus(status)
|
||||
.setHeaders(headers)
|
||||
.setBodyBytes(buffer));
|
||||
return;
|
||||
}
|
||||
|
||||
if ("error".equals(action)) {
|
||||
logApiIfEnabled("HAR: " + response.get("message").getAsString());
|
||||
// Report the error, but fall through to the default handler.
|
||||
}
|
||||
|
||||
if (defaultAction == HarNotFound.FALLBACK) {
|
||||
route.fallback();
|
||||
return;
|
||||
}
|
||||
|
||||
// By default abort not matching requests.
|
||||
route.abort();
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("harId", harId);
|
||||
localUtils.sendMessageAsync("harClose", params);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ package com.microsoft.playwright.impl;
|
||||
import com.microsoft.playwright.Locator;
|
||||
import com.microsoft.playwright.assertions.LocatorAssertions;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
@@ -39,6 +40,7 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
|
||||
public void containsText(String text, ContainsTextOptions options) {
|
||||
ExpectedTextValue expected = new ExpectedTextValue();
|
||||
expected.string = text;
|
||||
expected.ignoreCase = shouldIgnoreCase(options);
|
||||
expected.matchSubstring = true;
|
||||
expected.normalizeWhiteSpace = true;
|
||||
expectImpl("to.have.text", expected, text, "Locator expected to contain text", convertType(options, FrameExpectOptions.class));
|
||||
@@ -47,6 +49,7 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
|
||||
@Override
|
||||
public void containsText(Pattern pattern, ContainsTextOptions options) {
|
||||
ExpectedTextValue expected = expectedRegex(pattern);
|
||||
expected.ignoreCase = shouldIgnoreCase(options);
|
||||
expected.matchSubstring = true;
|
||||
expected.normalizeWhiteSpace = true;
|
||||
expectImpl("to.have.text", expected, pattern, "Locator expected to contain regex", convertType(options, FrameExpectOptions.class));
|
||||
@@ -58,6 +61,7 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
|
||||
for (String text : strings) {
|
||||
ExpectedTextValue expected = new ExpectedTextValue();
|
||||
expected.string = text;
|
||||
expected.ignoreCase = shouldIgnoreCase(options);
|
||||
expected.matchSubstring = true;
|
||||
expected.normalizeWhiteSpace = true;
|
||||
list.add(expected);
|
||||
@@ -70,6 +74,7 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
|
||||
List<ExpectedTextValue> list = new ArrayList<>();
|
||||
for (Pattern pattern : patterns) {
|
||||
ExpectedTextValue expected = expectedRegex(pattern);
|
||||
expected.ignoreCase = shouldIgnoreCase(options);
|
||||
expected.matchSubstring = true;
|
||||
expected.normalizeWhiteSpace = true;
|
||||
list.add(expected);
|
||||
@@ -203,6 +208,7 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
|
||||
public void hasText(String text, HasTextOptions options) {
|
||||
ExpectedTextValue expected = new ExpectedTextValue();
|
||||
expected.string = text;
|
||||
expected.ignoreCase = shouldIgnoreCase(options);
|
||||
expected.matchSubstring = false;
|
||||
expected.normalizeWhiteSpace = true;
|
||||
expectImpl("to.have.text", expected, text, "Locator expected to have text", convertType(options, FrameExpectOptions.class));
|
||||
@@ -211,6 +217,7 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
|
||||
@Override
|
||||
public void hasText(Pattern pattern, HasTextOptions options) {
|
||||
ExpectedTextValue expected = expectedRegex(pattern);
|
||||
expected.ignoreCase = shouldIgnoreCase(options);
|
||||
// Just match substring, same as containsText.
|
||||
expected.matchSubstring = true;
|
||||
expected.normalizeWhiteSpace = true;
|
||||
@@ -223,6 +230,7 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
|
||||
for (String text : strings) {
|
||||
ExpectedTextValue expected = new ExpectedTextValue();
|
||||
expected.string = text;
|
||||
expected.ignoreCase = shouldIgnoreCase(options);
|
||||
expected.matchSubstring = false;
|
||||
expected.normalizeWhiteSpace = true;
|
||||
list.add(expected);
|
||||
@@ -235,6 +243,7 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
|
||||
List<ExpectedTextValue> list = new ArrayList<>();
|
||||
for (Pattern pattern : patterns) {
|
||||
ExpectedTextValue expected = expectedRegex(pattern);
|
||||
expected.ignoreCase = shouldIgnoreCase(options);
|
||||
expected.matchSubstring = true;
|
||||
expected.normalizeWhiteSpace = true;
|
||||
list.add(expected);
|
||||
@@ -255,6 +264,28 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
|
||||
expectImpl("to.have.value", expected, pattern, "Locator expected to have value matching regex", convertType(options, FrameExpectOptions.class));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void hasValues(String[] values, HasValuesOptions options) {
|
||||
List<ExpectedTextValue> list = new ArrayList<>();
|
||||
for (String text : values) {
|
||||
ExpectedTextValue expected = new ExpectedTextValue();
|
||||
expected.string = text;
|
||||
list.add(expected);
|
||||
}
|
||||
expectImpl("to.have.values", list, values, "Locator expected to have values", convertType(options, FrameExpectOptions.class));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void hasValues(Pattern[] patterns, HasValuesOptions options) {
|
||||
List<ExpectedTextValue> list = new ArrayList<>();
|
||||
for (Pattern pattern : patterns) {
|
||||
ExpectedTextValue expected = expectedRegex(pattern);
|
||||
expected.matchSubstring = true;
|
||||
list.add(expected);
|
||||
}
|
||||
expectImpl("to.have.values", list, patterns, "Locator expected to have values matching regex", convertType(options, FrameExpectOptions.class));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void isChecked(IsCheckedOptions options) {
|
||||
String expression = (options != null && options.checked != null && !options.checked) ? "to.be.unchecked" : "to.be.checked";
|
||||
@@ -268,7 +299,9 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
|
||||
|
||||
@Override
|
||||
public void isEditable(IsEditableOptions options) {
|
||||
expectTrue("to.be.editable", "Locator expected to be editable", convertType(options, FrameExpectOptions.class));
|
||||
FrameExpectOptions frameOptions = convertType(options, FrameExpectOptions.class);
|
||||
boolean editable = options == null || options.editable == null || options.editable == true;
|
||||
expectTrue(editable ? "to.be.editable" : "to.be.readonly", "Locator expected to be editable", frameOptions);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -278,7 +311,9 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
|
||||
|
||||
@Override
|
||||
public void isEnabled(IsEnabledOptions options) {
|
||||
expectTrue("to.be.enabled", "Locator expected to be enabled", convertType(options, FrameExpectOptions.class));
|
||||
FrameExpectOptions frameOptions = convertType(options, FrameExpectOptions.class);
|
||||
boolean enabled = options == null || options.enabled == null || options.enabled == true;
|
||||
expectTrue(enabled ? "to.be.enabled" : "to.be.disabled", "Locator expected to be enabled", frameOptions);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -293,7 +328,9 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
|
||||
|
||||
@Override
|
||||
public void isVisible(IsVisibleOptions options) {
|
||||
expectTrue("to.be.visible", "Locator expected to be visible", convertType(options, FrameExpectOptions.class));
|
||||
FrameExpectOptions frameOptions = convertType(options, FrameExpectOptions.class);
|
||||
boolean visible = options == null || options.visible == null || options.visible == true;
|
||||
expectTrue(visible ? "to.be.visible" : "to.be.hidden", "Locator expected to be visible", frameOptions);
|
||||
}
|
||||
|
||||
private void expectTrue(String expression, String message, FrameExpectOptions options) {
|
||||
@@ -305,5 +342,17 @@ public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAsse
|
||||
public LocatorAssertions not() {
|
||||
return new LocatorAssertionsImpl(actualLocator, !isNot);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +67,8 @@ class LocatorImpl implements Locator {
|
||||
if (options.hasText != null) {
|
||||
if (options.hasText instanceof Pattern) {
|
||||
Pattern pattern = (Pattern) options.hasText;
|
||||
selector += " >> :scope:text-matches(" + escapeWithQuotes(pattern.pattern()) + ", \"" + toJsRegexFlags(pattern) + "\")";
|
||||
String jsRegex = "/" + pattern.pattern() + "/" + toJsRegexFlags(pattern);
|
||||
selector += " >> has=" + gson().toJson("text=" + jsRegex);
|
||||
} else if (options.hasText instanceof String) {
|
||||
String text = (String) options.hasText;
|
||||
selector += " >> :scope:has-text(" + escapeWithQuotes(text) + ")";
|
||||
@@ -510,9 +511,7 @@ class LocatorImpl implements Locator {
|
||||
|
||||
JsonObject toProtocol() {
|
||||
JsonObject result = new JsonObject();
|
||||
JsonObject frameJson = new JsonObject();
|
||||
frameJson.addProperty("guid", frame.guid);
|
||||
result.add("frame", frameJson);
|
||||
result.add("frame", frame.toProtocolRef());
|
||||
result.addProperty("selector", selector);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* 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.impl;
|
||||
|
||||
interface Logger {
|
||||
void log(String message);
|
||||
}
|
||||
@@ -60,7 +60,13 @@ class LoggingSupport {
|
||||
System.err.println(timestamp + " " + message);
|
||||
}
|
||||
|
||||
private void logApi(String message) {
|
||||
static void logApiIfEnabled(String message) {
|
||||
if (isEnabled) {
|
||||
logApi(message);
|
||||
}
|
||||
}
|
||||
|
||||
static void logApi(String message) {
|
||||
// This matches log format produced by the server.
|
||||
logWithTimestamp("pw:api " + message);
|
||||
}
|
||||
|
||||
@@ -175,10 +175,6 @@ public class PageImpl extends ChannelOwner implements Page {
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if ("load".equals(event)) {
|
||||
listeners.notify(EventType.LOAD, this);
|
||||
} else if ("domcontentloaded".equals(event)) {
|
||||
listeners.notify(EventType.DOMCONTENTLOADED, this);
|
||||
} else if ("frameAttached".equals(event)) {
|
||||
String guid = params.getAsJsonObject("frame").get("guid").getAsString();
|
||||
FrameImpl frame = connection.getExistingObject(guid);
|
||||
@@ -198,11 +194,12 @@ public class PageImpl extends ChannelOwner implements Page {
|
||||
}
|
||||
listeners.notify(EventType.FRAMEDETACHED, frame);
|
||||
} else if ("route".equals(event)) {
|
||||
Route route = connection.getExistingObject(params.getAsJsonObject("route").get("guid").getAsString());
|
||||
boolean handled = routes.handle(route);
|
||||
if (handled) {
|
||||
RouteImpl route = connection.getExistingObject(params.getAsJsonObject("route").get("guid").getAsString());
|
||||
Router.HandleResult handled = routes.handle(route);
|
||||
if (handled == Router.HandleResult.FoundMatchingHandler) {
|
||||
maybeDisableNetworkInterception();
|
||||
} else {
|
||||
}
|
||||
if (!route.isHandled()) {
|
||||
browserContext.handleRoute(route);
|
||||
}
|
||||
} else if ("video".equals(event)) {
|
||||
@@ -446,7 +443,7 @@ public class PageImpl extends ChannelOwner implements Page {
|
||||
|
||||
@Override
|
||||
public Page waitForClose(WaitForCloseOptions options, Runnable code) {
|
||||
return withWaitLogging("Page.waitForClose", () -> waitForCloseImpl(options, code));
|
||||
return withWaitLogging("Page.waitForClose", logger -> waitForCloseImpl(options, code));
|
||||
}
|
||||
|
||||
private Page waitForCloseImpl(WaitForCloseOptions options, Runnable code) {
|
||||
@@ -458,7 +455,7 @@ public class PageImpl extends ChannelOwner implements Page {
|
||||
|
||||
@Override
|
||||
public ConsoleMessage waitForConsoleMessage(WaitForConsoleMessageOptions options, Runnable code) {
|
||||
return withWaitLogging("Page.waitForConsoleMessage", () -> waitForConsoleMessageImpl(options, code));
|
||||
return withWaitLogging("Page.waitForConsoleMessage", logger -> waitForConsoleMessageImpl(options, code));
|
||||
}
|
||||
|
||||
private ConsoleMessage waitForConsoleMessageImpl(WaitForConsoleMessageOptions options, Runnable code) {
|
||||
@@ -470,7 +467,7 @@ public class PageImpl extends ChannelOwner implements Page {
|
||||
|
||||
@Override
|
||||
public Download waitForDownload(WaitForDownloadOptions options, Runnable code) {
|
||||
return withWaitLogging("Page.waitForDownload", () -> waitForDownloadImpl(options, code));
|
||||
return withWaitLogging("Page.waitForDownload", logger -> waitForDownloadImpl(options, code));
|
||||
}
|
||||
|
||||
private Download waitForDownloadImpl(WaitForDownloadOptions options, Runnable code) {
|
||||
@@ -482,7 +479,7 @@ public class PageImpl extends ChannelOwner implements Page {
|
||||
|
||||
@Override
|
||||
public FileChooser waitForFileChooser(WaitForFileChooserOptions options, Runnable code) {
|
||||
return withWaitLogging("Page.waitForFileChooser", () -> waitForFileChooserImpl(options, code));
|
||||
return withWaitLogging("Page.waitForFileChooser", logger -> waitForFileChooserImpl(options, code));
|
||||
}
|
||||
|
||||
private FileChooser waitForFileChooserImpl(WaitForFileChooserOptions options, Runnable code) {
|
||||
@@ -495,7 +492,7 @@ public class PageImpl extends ChannelOwner implements Page {
|
||||
|
||||
@Override
|
||||
public Page waitForPopup(WaitForPopupOptions options, Runnable code) {
|
||||
return withWaitLogging("Page.waitForPopup", () -> waitForPopupImpl(options, code));
|
||||
return withWaitLogging("Page.waitForPopup", logger -> waitForPopupImpl(options, code));
|
||||
}
|
||||
|
||||
private Page waitForPopupImpl(WaitForPopupOptions options, Runnable code) {
|
||||
@@ -507,7 +504,7 @@ public class PageImpl extends ChannelOwner implements Page {
|
||||
|
||||
@Override
|
||||
public WebSocket waitForWebSocket(WaitForWebSocketOptions options, Runnable code) {
|
||||
return withWaitLogging("Page.waitForWebSocket", () -> waitForWebSocketImpl(options, code));
|
||||
return withWaitLogging("Page.waitForWebSocket", logger -> waitForWebSocketImpl(options, code));
|
||||
}
|
||||
|
||||
private WebSocket waitForWebSocketImpl(WaitForWebSocketOptions options, Runnable code) {
|
||||
@@ -519,7 +516,7 @@ public class PageImpl extends ChannelOwner implements Page {
|
||||
|
||||
@Override
|
||||
public Worker waitForWorker(WaitForWorkerOptions options, Runnable code) {
|
||||
return withWaitLogging("Page.waitForWorker", () -> waitForWorkerImpl(options, code));
|
||||
return withWaitLogging("Page.waitForWorker", logger -> waitForWorkerImpl(options, code));
|
||||
}
|
||||
|
||||
private Worker waitForWorkerImpl(WaitForWorkerOptions options, Runnable code) {
|
||||
@@ -972,6 +969,21 @@ public class PageImpl extends ChannelOwner implements Page {
|
||||
route(new UrlMatcher(url), handler, options);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void routeFromHAR(Path har, RouteFromHAROptions options) {
|
||||
if (options == null) {
|
||||
options = new RouteFromHAROptions();
|
||||
}
|
||||
if (options.update != null && options.update) {
|
||||
browserContext.recordIntoHar(this, har, convertType(options, BrowserContext.RouteFromHAROptions.class));
|
||||
return;
|
||||
}
|
||||
UrlMatcher matcher = UrlMatcher.forOneOf(browserContext.baseUrl, options.url);
|
||||
HARRouter harRouter = new HARRouter(connection.localUtils, har, options.notFound);
|
||||
onClose(context -> harRouter.dispose());
|
||||
route(matcher, route -> harRouter.handle(route), null);
|
||||
}
|
||||
|
||||
private void route(UrlMatcher matcher, Consumer<Route> handler, RouteOptions options) {
|
||||
withLogging("Page.route", () -> {
|
||||
routes.add(matcher, handler, options == null ? null : options.times);
|
||||
@@ -1256,25 +1268,25 @@ public class PageImpl extends ChannelOwner implements Page {
|
||||
|
||||
@Override
|
||||
public void waitForLoadState(LoadState state, WaitForLoadStateOptions options) {
|
||||
withWaitLogging("Page.waitForLoadState", () -> {
|
||||
mainFrame.waitForLoadStateImpl(state, convertType(options, Frame.WaitForLoadStateOptions.class));
|
||||
withWaitLogging("Page.waitForLoadState", logger -> {
|
||||
mainFrame.waitForLoadStateImpl(state, convertType(options, Frame.WaitForLoadStateOptions.class), logger);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response waitForNavigation(WaitForNavigationOptions options, Runnable code) {
|
||||
return withLogging("Page.waitForNavigation", () -> waitForNavigationImpl(code, options));
|
||||
return withWaitLogging("Page.waitForNavigation", logger -> waitForNavigationImpl(logger, code, options));
|
||||
}
|
||||
|
||||
Response waitForNavigationImpl(Runnable code, WaitForNavigationOptions options) {
|
||||
private Response waitForNavigationImpl(Logger logger, Runnable code, WaitForNavigationOptions options) {
|
||||
Frame.WaitForNavigationOptions frameOptions = new Frame.WaitForNavigationOptions();
|
||||
if (options != null) {
|
||||
frameOptions.timeout = options.timeout;
|
||||
frameOptions.waitUntil = options.waitUntil;
|
||||
frameOptions.url = options.url;
|
||||
}
|
||||
return mainFrame.waitForNavigationImpl(code, frameOptions);
|
||||
return mainFrame.waitForNavigationImpl(logger, code, frameOptions);
|
||||
}
|
||||
|
||||
void frameNavigated(FrameImpl frame) {
|
||||
@@ -1326,21 +1338,28 @@ public class PageImpl extends ChannelOwner implements Page {
|
||||
|
||||
@Override
|
||||
public Request waitForRequest(String urlGlob, WaitForRequestOptions options, Runnable code) {
|
||||
return waitForRequest(toRequestPredicate(new UrlMatcher(browserContext.baseUrl, urlGlob)), options, code);
|
||||
return waitForRequest(new UrlMatcher(browserContext.baseUrl, urlGlob), null, options, code);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Request waitForRequest(Pattern urlPattern, WaitForRequestOptions options, Runnable code) {
|
||||
return waitForRequest(toRequestPredicate(new UrlMatcher(urlPattern)), options, code);
|
||||
return waitForRequest(new UrlMatcher(urlPattern), null, options, code);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Request waitForRequest(Predicate<Request> predicate, WaitForRequestOptions options, Runnable code) {
|
||||
return withWaitLogging("Page.waitForRequest", () -> waitForRequestImpl(predicate, options, code));
|
||||
return waitForRequest(null, predicate, options, code);
|
||||
}
|
||||
|
||||
private static Predicate<Request> toRequestPredicate(UrlMatcher matcher) {
|
||||
return request -> matcher.test(request.url());
|
||||
private Request waitForRequest(UrlMatcher urlMatcher, Predicate<Request> predicate, WaitForRequestOptions options, Runnable code) {
|
||||
return withWaitLogging("Page.waitForRequest", logger -> {
|
||||
logger.log("waiting for request " + ((urlMatcher == null) ? "matching predicate" : urlMatcher.toString()));
|
||||
Predicate<Request> requestPredicate = predicate;
|
||||
if (requestPredicate == null) {
|
||||
requestPredicate = request -> urlMatcher.test(request.url());;
|
||||
}
|
||||
return waitForRequestImpl(requestPredicate, options, code);
|
||||
});
|
||||
}
|
||||
|
||||
private Request waitForRequestImpl(Predicate<Request> predicate, WaitForRequestOptions options, Runnable code) {
|
||||
@@ -1352,7 +1371,7 @@ public class PageImpl extends ChannelOwner implements Page {
|
||||
|
||||
@Override
|
||||
public Request waitForRequestFinished(WaitForRequestFinishedOptions options, Runnable code) {
|
||||
return withWaitLogging("Page.waitForRequestFinished", () -> waitForRequestFinishedImpl(options, code));
|
||||
return withWaitLogging("Page.waitForRequestFinished", logger -> waitForRequestFinishedImpl(options, code));
|
||||
}
|
||||
|
||||
private Request waitForRequestFinishedImpl(WaitForRequestFinishedOptions options, Runnable code) {
|
||||
@@ -1364,21 +1383,28 @@ public class PageImpl extends ChannelOwner implements Page {
|
||||
|
||||
@Override
|
||||
public Response waitForResponse(String urlGlob, WaitForResponseOptions options, Runnable code) {
|
||||
return waitForResponse(toResponsePredicate(new UrlMatcher(browserContext.baseUrl, urlGlob)), options, code);
|
||||
return waitForResponse(new UrlMatcher(browserContext.baseUrl, urlGlob), null, options, code);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response waitForResponse(Pattern urlPattern, WaitForResponseOptions options, Runnable code) {
|
||||
return waitForResponse(toResponsePredicate(new UrlMatcher(urlPattern)), options, code);
|
||||
return waitForResponse(new UrlMatcher(urlPattern), null, options, code);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response waitForResponse(Predicate<Response> predicate, WaitForResponseOptions options, Runnable code) {
|
||||
return withLogging("Page.waitForResponse", () -> waitForResponseImpl(predicate, options, code));
|
||||
return waitForResponse(null, predicate, options, code);
|
||||
}
|
||||
|
||||
private static Predicate<Response> toResponsePredicate(UrlMatcher matcher) {
|
||||
return response -> matcher.test(response.url());
|
||||
private Response waitForResponse(UrlMatcher urlMatcher, Predicate<Response> predicate, WaitForResponseOptions options, Runnable code) {
|
||||
return withWaitLogging("Page.waitForResponse", logger -> {
|
||||
logger.log("waiting for response " + ((urlMatcher == null) ? "matching predicate" : urlMatcher.toString()));
|
||||
Predicate<Response> responsePredicate = predicate;
|
||||
if (responsePredicate == null) {
|
||||
responsePredicate = response -> urlMatcher.test(response.url());;
|
||||
}
|
||||
return waitForResponseImpl(responsePredicate, options, code);
|
||||
});
|
||||
}
|
||||
|
||||
private Response waitForResponseImpl(Predicate<Response> predicate, WaitForResponseOptions options, Runnable code) {
|
||||
@@ -1415,7 +1441,10 @@ public class PageImpl extends ChannelOwner implements Page {
|
||||
}
|
||||
|
||||
private void waitForURL(UrlMatcher matcher, WaitForURLOptions options) {
|
||||
withLogging("Page.waitForURL", () -> mainFrame.waitForURLImpl(matcher, convertType(options, Frame.WaitForURLOptions.class)));
|
||||
withWaitLogging("Page.waitForURL", logger -> {
|
||||
mainFrame.waitForURLImpl(logger, matcher, convertType(options, Frame.WaitForURLOptions.class));
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -21,9 +21,9 @@ import com.microsoft.playwright.APIRequest;
|
||||
import com.microsoft.playwright.Playwright;
|
||||
import com.microsoft.playwright.PlaywrightException;
|
||||
import com.microsoft.playwright.Selectors;
|
||||
import com.microsoft.playwright.impl.driver.Driver;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -32,18 +32,23 @@ public class PlaywrightImpl extends ChannelOwner implements Playwright {
|
||||
private Process driverProcess;
|
||||
|
||||
public static PlaywrightImpl create(CreateOptions options) {
|
||||
return createImpl(options, false);
|
||||
}
|
||||
|
||||
public static PlaywrightImpl createImpl(CreateOptions options, boolean forceNewDriverInstanceForTests) {
|
||||
Map<String, String> env = Collections.emptyMap();
|
||||
if (options != null && options.env != null) {
|
||||
env = options.env;
|
||||
}
|
||||
Driver driver = forceNewDriverInstanceForTests ?
|
||||
Driver.createAndInstall(env, true) :
|
||||
Driver.ensureDriverInstalled(env, true);
|
||||
try {
|
||||
Map<String, String> env = Collections.emptyMap();
|
||||
if (options != null && options.env != null) {
|
||||
env = options.env;
|
||||
}
|
||||
Path driver = Driver.ensureDriverInstalled(env, true);
|
||||
ProcessBuilder pb = new ProcessBuilder(driver.toString(), "run-driver");
|
||||
ProcessBuilder pb = driver.createProcessBuilder();
|
||||
pb.command().add("run-driver");
|
||||
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
|
||||
pb.environment().putAll(env);
|
||||
Driver.setRequiredEnvironmentVariables(pb);
|
||||
Process p = pb.start();
|
||||
Connection connection = new Connection(new PipeTransport(p.getInputStream(), p.getOutputStream()));
|
||||
Connection connection = new Connection(new PipeTransport(p.getInputStream(), p.getOutputStream()), env);
|
||||
PlaywrightImpl result = connection.initializePlaywright();
|
||||
result.driverProcess = p;
|
||||
result.initSharedSelectors(null);
|
||||
|
||||
@@ -31,6 +31,7 @@ class SerializedValue{
|
||||
// Possible values: { 'null, 'undefined, 'NaN, 'Infinity, '-Infinity, '-0 }
|
||||
String v;
|
||||
String d;
|
||||
String u;
|
||||
public static class R {
|
||||
String p;
|
||||
String f;
|
||||
@@ -85,6 +86,7 @@ class ExpectedTextValue {
|
||||
String string;
|
||||
String regexSource;
|
||||
String regexFlags;
|
||||
Boolean ignoreCase;
|
||||
Boolean matchSubstring;
|
||||
Boolean normalizeWhiteSpace;
|
||||
}
|
||||
|
||||
@@ -42,6 +42,14 @@ public class RequestImpl extends ChannelOwner implements Request {
|
||||
String failure;
|
||||
Timing timing;
|
||||
boolean didFailOrFinish;
|
||||
private FallbackOverrides fallbackOverrides;
|
||||
|
||||
static class FallbackOverrides {
|
||||
String url;
|
||||
String method;
|
||||
byte[] postData;
|
||||
Map<String, String> headers;
|
||||
}
|
||||
|
||||
RequestImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) {
|
||||
super(parent, type, guid, initializer);
|
||||
@@ -75,6 +83,9 @@ public class RequestImpl extends ChannelOwner implements Request {
|
||||
|
||||
@Override
|
||||
public Map<String, String> headers() {
|
||||
if (fallbackOverrides != null && fallbackOverrides.headers != null) {
|
||||
return new RawHeaders(Utils.toHeadersList(fallbackOverrides.headers)).headers();
|
||||
}
|
||||
return headers.headers();
|
||||
}
|
||||
|
||||
@@ -95,19 +106,26 @@ public class RequestImpl extends ChannelOwner implements Request {
|
||||
|
||||
@Override
|
||||
public String method() {
|
||||
if (fallbackOverrides != null && fallbackOverrides.method != null) {
|
||||
return fallbackOverrides.method;
|
||||
}
|
||||
return initializer.get("method").getAsString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String postData() {
|
||||
if (postData == null) {
|
||||
byte[] buffer = postDataBuffer();
|
||||
if (buffer == null) {
|
||||
return null;
|
||||
}
|
||||
return new String(postData, StandardCharsets.UTF_8);
|
||||
return new String(buffer, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] postDataBuffer() {
|
||||
if (fallbackOverrides != null && fallbackOverrides.postData != null) {
|
||||
return fallbackOverrides.postData;
|
||||
}
|
||||
return postData;
|
||||
}
|
||||
|
||||
@@ -156,6 +174,9 @@ public class RequestImpl extends ChannelOwner implements Request {
|
||||
|
||||
@Override
|
||||
public String url() {
|
||||
if (fallbackOverrides != null && fallbackOverrides.url != null) {
|
||||
return fallbackOverrides.url;
|
||||
}
|
||||
return initializer.get("url").getAsString();
|
||||
}
|
||||
|
||||
@@ -164,6 +185,9 @@ public class RequestImpl extends ChannelOwner implements Request {
|
||||
}
|
||||
|
||||
private RawHeaders getRawHeaders() {
|
||||
if (fallbackOverrides != null && fallbackOverrides.headers != null) {
|
||||
return new RawHeaders(Utils.toHeadersList(fallbackOverrides.headers));
|
||||
}
|
||||
if (rawHeaders != null) {
|
||||
return rawHeaders;
|
||||
}
|
||||
@@ -176,4 +200,26 @@ public class RequestImpl extends ChannelOwner implements Request {
|
||||
rawHeaders = new RawHeaders(asList(gson().fromJson(rawHeadersJson, HttpHeader[].class)));
|
||||
return rawHeaders;
|
||||
}
|
||||
|
||||
void applyFallbackOverrides(FallbackOverrides overrides) {
|
||||
if (fallbackOverrides == null) {
|
||||
fallbackOverrides = new FallbackOverrides();
|
||||
}
|
||||
if (overrides.url != null) {
|
||||
fallbackOverrides.url = overrides.url;
|
||||
}
|
||||
if (overrides.method != null) {
|
||||
fallbackOverrides.method = overrides.method;
|
||||
}
|
||||
if (overrides.headers != null) {
|
||||
fallbackOverrides.headers = overrides.headers;
|
||||
}
|
||||
if (overrides.postData != null) {
|
||||
fallbackOverrides.postData = overrides.postData;
|
||||
}
|
||||
}
|
||||
|
||||
FallbackOverrides fallbackOverridesForResume() {
|
||||
return fallbackOverrides;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ public class RequestOptionsImpl implements RequestOptions {
|
||||
Boolean failOnStatusCode;
|
||||
Boolean ignoreHTTPSErrors;
|
||||
Double timeout;
|
||||
Integer maxRedirects;
|
||||
|
||||
@Override
|
||||
public RequestOptions setHeader(String name, String value) {
|
||||
@@ -118,4 +119,10 @@ public class RequestOptionsImpl implements RequestOptions {
|
||||
this.ignoreHTTPSErrors = ignoreHTTPSErrors;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RequestOptions setMaxRedirects(int maxRedirects) {
|
||||
this.maxRedirects = maxRedirects;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,6 +83,11 @@ public class ResponseImpl extends ChannelOwner implements Response {
|
||||
return request().frame();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean fromServiceWorker() {
|
||||
return initializer.get("fromServiceWorker").getAsBoolean();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> headers() {
|
||||
return headers.headers();
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
package com.microsoft.playwright.impl;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.microsoft.playwright.Frame;
|
||||
import com.microsoft.playwright.PlaywrightException;
|
||||
import com.microsoft.playwright.Route;
|
||||
|
||||
@@ -27,11 +28,15 @@ import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.microsoft.playwright.impl.Utils.convertType;
|
||||
|
||||
public class RouteImpl extends ChannelOwner implements Route {
|
||||
private final RequestImpl request;
|
||||
private boolean handled;
|
||||
|
||||
public RouteImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) {
|
||||
super(parent, type, guid, initializer);
|
||||
request = connection.getExistingObject(initializer.getAsJsonObject("request").get("guid").getAsString());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -44,41 +49,69 @@ public class RouteImpl extends ChannelOwner implements Route {
|
||||
});
|
||||
}
|
||||
|
||||
boolean isHandled() {
|
||||
return handled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resume(ResumeOptions options) {
|
||||
startHandling();
|
||||
withLogging("Route.resume", () -> resumeImpl(options));
|
||||
applyOverrides(convertType(options, FallbackOptions.class));
|
||||
withLogging("Route.resume", () -> resumeImpl(request().fallbackOverridesForResume()));
|
||||
}
|
||||
|
||||
private void resumeImpl(ResumeOptions options) {
|
||||
@Override
|
||||
public void fallback(FallbackOptions options) {
|
||||
if (handled) {
|
||||
throw new PlaywrightException("Route is already handled!");
|
||||
}
|
||||
applyOverrides(options);
|
||||
}
|
||||
|
||||
private void applyOverrides(FallbackOptions options) {
|
||||
if (options == null) {
|
||||
options = new ResumeOptions();
|
||||
}
|
||||
JsonObject params = new JsonObject();
|
||||
if (options.url != null) {
|
||||
params.addProperty("url", options.url);
|
||||
}
|
||||
if (options.method != null) {
|
||||
params.addProperty("method", options.method);
|
||||
}
|
||||
if (options.headers != null) {
|
||||
params.add("headers", Serialization.toProtocol(options.headers));
|
||||
return;
|
||||
}
|
||||
RequestImpl.FallbackOverrides overrides = new RequestImpl.FallbackOverrides();
|
||||
overrides.url = options.url;
|
||||
overrides.method = options.method;
|
||||
overrides.headers = options.headers;
|
||||
if (options.postData != null) {
|
||||
byte[] bytes = null;
|
||||
if (options.postData instanceof byte[]) {
|
||||
bytes = (byte[]) options.postData;
|
||||
} else if (options.postData instanceof String) {
|
||||
bytes = ((String) options.postData).getBytes(StandardCharsets.UTF_8);
|
||||
} else {
|
||||
throw new PlaywrightException("postData must be either String or byte[], found: " + options.postData.getClass().getName());
|
||||
overrides.postData = getPostDataBytes(options.postData);
|
||||
}
|
||||
request().applyFallbackOverrides(overrides);
|
||||
}
|
||||
|
||||
private void resumeImpl(RequestImpl.FallbackOverrides options) {
|
||||
JsonObject params = new JsonObject();
|
||||
if (options != null) {
|
||||
if (options.url != null) {
|
||||
params.addProperty("url", options.url);
|
||||
}
|
||||
if (options.method != null) {
|
||||
params.addProperty("method", options.method);
|
||||
}
|
||||
if (options.headers != null) {
|
||||
params.add("headers", Serialization.toProtocol(options.headers));
|
||||
}
|
||||
if (options.postData != null) {
|
||||
String base64 = Base64.getEncoder().encodeToString(options.postData);
|
||||
params.addProperty("postData", base64);
|
||||
}
|
||||
String base64 = Base64.getEncoder().encodeToString(bytes);
|
||||
params.addProperty("postData", base64);
|
||||
}
|
||||
sendMessageAsync("continue", params);
|
||||
}
|
||||
|
||||
private static byte[] getPostDataBytes(Object postData) {
|
||||
if (postData instanceof byte[]) {
|
||||
return (byte[]) postData;
|
||||
}
|
||||
if (postData instanceof String) {
|
||||
return ((String) postData).getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
throw new PlaywrightException("postData must be either String or byte[], found: " + postData.getClass().getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fulfill(FulfillOptions options) {
|
||||
startHandling();
|
||||
@@ -165,7 +198,15 @@ public class RouteImpl extends ChannelOwner implements Route {
|
||||
|
||||
@Override
|
||||
public RequestImpl request() {
|
||||
return connection.getExistingObject(initializer.getAsJsonObject("request").get("guid").getAsString());
|
||||
return request;
|
||||
}
|
||||
|
||||
void redirectNavigationRequest(String redirectURL) {
|
||||
startHandling();
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("url", redirectURL);
|
||||
// TODO: _raceWithPageClose ?
|
||||
sendMessageAsync("redirectNavigationRequest", params);
|
||||
}
|
||||
|
||||
private void startHandling() {
|
||||
|
||||
@@ -19,6 +19,7 @@ package com.microsoft.playwright.impl;
|
||||
import com.microsoft.playwright.Route;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -37,22 +38,16 @@ class Router {
|
||||
this.times = times;
|
||||
}
|
||||
|
||||
boolean handle(Route route) {
|
||||
if (times != null && times <= 0) {
|
||||
return false;
|
||||
}
|
||||
if (!matcher.test(route.request().url())) {
|
||||
return false;
|
||||
}
|
||||
if (times != null) {
|
||||
--times;
|
||||
}
|
||||
void handle(RouteImpl route) {
|
||||
handler.accept(route);
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean isDone() {
|
||||
return times != null && times <= 0;
|
||||
boolean decrementRemainingCallCount() {
|
||||
if (times == null) {
|
||||
return false;
|
||||
}
|
||||
--times;
|
||||
return times <= 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,15 +65,23 @@ class Router {
|
||||
return routes.size();
|
||||
}
|
||||
|
||||
boolean handle(Route route) {
|
||||
for (RouteInfo info : routes) {
|
||||
if (info.handle(route)) {
|
||||
if (info.isDone()) {
|
||||
routes.remove(info);
|
||||
}
|
||||
return true;
|
||||
enum HandleResult { NoMatchingHandler, FoundMatchingHandler}
|
||||
HandleResult handle(RouteImpl route) {
|
||||
HandleResult result = HandleResult.NoMatchingHandler;
|
||||
for (Iterator<RouteInfo> it = routes.iterator(); it.hasNext();) {
|
||||
RouteInfo info = it.next();
|
||||
if (!info.matcher.test(route.request().url())) {
|
||||
continue;
|
||||
}
|
||||
if (info.decrementRemainingCallCount()) {
|
||||
it.remove();
|
||||
}
|
||||
result = HandleResult.FoundMatchingHandler;
|
||||
info.handle(route);
|
||||
if (route.isHandled()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,12 +28,21 @@ import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintStream;
|
||||
import java.lang.reflect.Type;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static com.microsoft.playwright.impl.Utils.toJsRegexFlags;
|
||||
import static com.microsoft.playwright.impl.Utils.fromJsRegexFlags;
|
||||
|
||||
class Serialization {
|
||||
private static final Gson gson = new GsonBuilder()
|
||||
private static final Gson gson = new GsonBuilder().disableHtmlEscaping()
|
||||
.registerTypeAdapter(SameSiteAttribute.class, new SameSiteAdapter().nullSafe())
|
||||
.registerTypeAdapter(BrowserChannel.class, new ToLowerCaseAndDashSerializer<BrowserChannel>())
|
||||
.registerTypeAdapter(ColorScheme.class, new ToLowerCaseAndDashSerializer<ColorScheme>())
|
||||
@@ -44,6 +53,7 @@ class Serialization {
|
||||
.registerTypeAdapter(ScreenshotType.class, new ToLowerCaseSerializer<ScreenshotType>())
|
||||
.registerTypeAdapter(ScreenshotScale.class, new ToLowerCaseSerializer<ScreenshotScale>())
|
||||
.registerTypeAdapter(ScreenshotCaret.class, new ToLowerCaseSerializer<ScreenshotCaret>())
|
||||
.registerTypeAdapter(ServiceWorkerPolicy.class, new ToLowerCaseAndDashSerializer<ServiceWorkerPolicy>())
|
||||
.registerTypeAdapter(MouseButton.class, new ToLowerCaseSerializer<MouseButton>())
|
||||
.registerTypeAdapter(LoadState.class, new ToLowerCaseSerializer<LoadState>())
|
||||
.registerTypeAdapter(WaitUntilState.class, new ToLowerCaseSerializer<WaitUntilState>())
|
||||
@@ -140,6 +150,16 @@ class Serialization {
|
||||
result.n = (Integer) value;
|
||||
} else if (value instanceof String) {
|
||||
result.s = (String) value;
|
||||
} else if (value instanceof Date) {
|
||||
result.d = ((Date)value).toInstant().toString();
|
||||
} else if (value instanceof LocalDateTime) {
|
||||
result.d = ((LocalDateTime)value).atZone(ZoneId.systemDefault()).toInstant().toString();
|
||||
} else if (value instanceof URL) {
|
||||
result.u = ((URL)value).toString();
|
||||
} else if (value instanceof Pattern) {
|
||||
result.r = new SerializedValue.R();
|
||||
result.r.p = ((Pattern)value).pattern();
|
||||
result.r.f = toJsRegexFlags(((Pattern)value));
|
||||
} else {
|
||||
HashableValue mapKey = new HashableValue(value);
|
||||
Integer id = valueToId.get(mapKey);
|
||||
@@ -203,6 +223,17 @@ class Serialization {
|
||||
return (T) value.b;
|
||||
if (value.s != null)
|
||||
return (T) value.s;
|
||||
if (value.u != null) {
|
||||
try {
|
||||
return (T)(new URL(value.u));
|
||||
} catch (MalformedURLException e) {
|
||||
throw new PlaywrightException("Unexpected value: " + value.u, e);
|
||||
}
|
||||
}
|
||||
if (value.d != null)
|
||||
return (T)(Date.from(Instant.parse(value.d)));
|
||||
if (value.r != null)
|
||||
return (T)(Pattern.compile(value.r.p, fromJsRegexFlags(value.r.f)));
|
||||
if (value.v != null) {
|
||||
switch (value.v) {
|
||||
case "undefined":
|
||||
@@ -287,9 +318,7 @@ class Serialization {
|
||||
static JsonArray toProtocol(ElementHandle[] handles) {
|
||||
JsonArray jsonElements = new JsonArray();
|
||||
for (ElementHandle handle : handles) {
|
||||
JsonObject jsonHandle = new JsonObject();
|
||||
jsonHandle.addProperty("guid", ((ElementHandleImpl) handle).guid);
|
||||
jsonElements.add(jsonHandle);
|
||||
jsonElements.add(((ElementHandleImpl) handle).toProtocolRef());
|
||||
}
|
||||
return jsonElements;
|
||||
}
|
||||
@@ -298,6 +327,16 @@ class Serialization {
|
||||
return toNameValueArray(map);
|
||||
}
|
||||
|
||||
static void addHarUrlFilter(JsonObject options, Object urlFilter) {
|
||||
if (urlFilter instanceof String) {
|
||||
options.addProperty("urlGlob", (String) urlFilter);
|
||||
} else if (urlFilter instanceof Pattern) {
|
||||
Pattern pattern = (Pattern) urlFilter;
|
||||
options.addProperty("urlRegexSource", pattern.pattern());
|
||||
options.addProperty("urlRegexFlags", toJsRegexFlags(pattern));
|
||||
}
|
||||
}
|
||||
|
||||
static JsonArray toNameValueArray(Map<String, ?> map) {
|
||||
JsonArray array = new JsonArray();
|
||||
for (Map.Entry<String, ?> e : map.entrySet()) {
|
||||
@@ -309,6 +348,15 @@ class Serialization {
|
||||
return array;
|
||||
}
|
||||
|
||||
static Map<String, String> fromNameValues(JsonArray array) {
|
||||
Map<String, String> map = new LinkedHashMap<>();
|
||||
for (JsonElement element : array) {
|
||||
JsonObject pair = element.getAsJsonObject();
|
||||
map.put(pair.get("name").getAsString(), pair.get("value").getAsString());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
static List<String> parseStringList(JsonArray array) {
|
||||
List<String> result = new ArrayList<>();
|
||||
for (JsonElement e : array) {
|
||||
@@ -339,9 +387,7 @@ class Serialization {
|
||||
private static class HandleSerializer implements JsonSerializer<JSHandleImpl> {
|
||||
@Override
|
||||
public JsonElement serialize(JSHandleImpl src, Type typeOfSrc, JsonSerializationContext context) {
|
||||
JsonObject json = new JsonObject();
|
||||
json.addProperty("guid", src.guid);
|
||||
return json;
|
||||
return src.toProtocolRef();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,18 +28,25 @@ import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
class StackTraceCollector {
|
||||
static final String PLAYWRIGHT_JAVA_SRC = "PLAYWRIGHT_JAVA_SRC";
|
||||
private final List<Path> srcDirs;
|
||||
private final Map<Path, String> classToSourceCache = new HashMap<>();
|
||||
|
||||
static StackTraceCollector createFromEnv() {
|
||||
String srcRoots = System.getenv("PLAYWRIGHT_JAVA_SRC");
|
||||
static StackTraceCollector createFromEnv(Map<String, String> env) {
|
||||
String srcRoots = null;
|
||||
if (env != null) {
|
||||
srcRoots = env.get(PLAYWRIGHT_JAVA_SRC);
|
||||
}
|
||||
if (srcRoots == null) {
|
||||
srcRoots = System.getenv(PLAYWRIGHT_JAVA_SRC);
|
||||
}
|
||||
if (srcRoots == null) {
|
||||
return null;
|
||||
}
|
||||
List<Path> srcDirs = Arrays.stream(srcRoots.split(File.pathSeparator)).map(p -> Paths.get(p)).collect(Collectors.toList());
|
||||
for (Path srcDir: srcDirs) {
|
||||
if (!Files.exists(srcDir.toAbsolutePath())) {
|
||||
throw new PlaywrightException("Source location specified in PLAYWRIGHT_JAVA_SRC doesn't exist: '" + srcDir.toAbsolutePath() + "'");
|
||||
throw new PlaywrightException("Source location specified in " + PLAYWRIGHT_JAVA_SRC + " doesn't exist: '" + srcDir.toAbsolutePath() + "'");
|
||||
}
|
||||
}
|
||||
return new StackTraceCollector(srcDirs);
|
||||
|
||||
@@ -26,7 +26,6 @@ import java.nio.file.Path;
|
||||
import static com.microsoft.playwright.impl.Serialization.gson;
|
||||
|
||||
class TracingImpl extends ChannelOwner implements Tracing {
|
||||
LocalUtils localUtils;
|
||||
boolean isRemote;
|
||||
|
||||
TracingImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) {
|
||||
@@ -60,7 +59,7 @@ class TracingImpl extends ChannelOwner implements Tracing {
|
||||
// Add local sources to the remote trace if necessary.
|
||||
if (isRemote && json.has("sourceEntries")) {
|
||||
JsonArray entries = json.getAsJsonArray("sourceEntries");
|
||||
localUtils.zip(path, entries);
|
||||
connection.localUtils.zip(path, entries);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -97,4 +97,13 @@ class UrlMatcher {
|
||||
public int hashCode() {
|
||||
return Objects.hash(rawSource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
if (rawSource == null)
|
||||
return "<any>";
|
||||
if (rawSource instanceof Predicate)
|
||||
return "matching predicate";
|
||||
return rawSource.toString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,11 +176,18 @@ class Utils {
|
||||
} catch (IOException e) {
|
||||
throw new PlaywrightException("Failed to copy file to remote server.", e);
|
||||
}
|
||||
jsonStreams.add(temp.toProtocol());
|
||||
jsonStreams.add(temp.toProtocolRef());
|
||||
}
|
||||
params.add("streams", jsonStreams);
|
||||
} else {
|
||||
params.add("localPaths", toJsonArray(files));
|
||||
Path[] absolute = Arrays.stream(files).map(f -> {
|
||||
try {
|
||||
return f.toRealPath();
|
||||
} catch (IOException e) {
|
||||
throw new PlaywrightException("Cannot get absolute file path", e);
|
||||
}
|
||||
}).toArray(Path[]::new);
|
||||
params.add("localPaths", toJsonArray(absolute));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,6 +277,17 @@ class Utils {
|
||||
return map;
|
||||
}
|
||||
|
||||
static List<HttpHeader> toHeadersList(Map<String, String> headers) {
|
||||
List<HttpHeader> list = new ArrayList<>();
|
||||
for (Map.Entry<String, String> entry: headers.entrySet()) {
|
||||
HttpHeader header = new HttpHeader();
|
||||
header.name = entry.getKey();
|
||||
header.value = entry.getValue();
|
||||
list.add(header);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
static String toJsRegexFlags(Pattern pattern) {
|
||||
String regexFlags = "";
|
||||
if ((pattern.flags() & Pattern.CASE_INSENSITIVE) != 0) {
|
||||
@@ -289,4 +307,18 @@ class Utils {
|
||||
}
|
||||
return regexFlags;
|
||||
}
|
||||
|
||||
static int fromJsRegexFlags(String regexFlags) {
|
||||
int flags = 0;
|
||||
if (regexFlags.contains("i")) {
|
||||
flags |= Pattern.CASE_INSENSITIVE;
|
||||
}
|
||||
if (regexFlags.contains("s")) {
|
||||
flags |= Pattern.DOTALL;
|
||||
}
|
||||
if (regexFlags.contains("m")) {
|
||||
flags |= Pattern.MULTILINE;
|
||||
}
|
||||
return flags;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,6 +72,9 @@ class VideoImpl implements Video {
|
||||
@Override
|
||||
public void saveAs(Path path) {
|
||||
page.withLogging("Video.saveAs", () -> {
|
||||
if (!page.isClosed()) {
|
||||
throw new PlaywrightException("Page is not yet closed. Close the page prior to calling saveAs");
|
||||
}
|
||||
try {
|
||||
waitForArtifact().saveAs(path);
|
||||
} catch (PlaywrightException e) {
|
||||
|
||||
@@ -18,38 +18,52 @@ package com.microsoft.playwright.impl;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static com.microsoft.playwright.impl.Utils.createGuid;
|
||||
|
||||
public class WaitForEventLogger<T> implements Supplier<T> {
|
||||
private final Supplier<T> supplier;
|
||||
public class WaitForEventLogger<T> implements Supplier<T>, Logger {
|
||||
private final Function<Logger, T> supplier;
|
||||
private final ChannelOwner channel;
|
||||
private final String waitId;
|
||||
private final String apiName;
|
||||
|
||||
WaitForEventLogger(ChannelOwner channelOwner, String apiName, Supplier<T> supplier) {
|
||||
WaitForEventLogger(ChannelOwner channelOwner, String apiName, Function<Logger, T> supplier) {
|
||||
this.supplier = supplier;
|
||||
this.channel = channelOwner;
|
||||
this.apiName = apiName;
|
||||
this.waitId = createGuid();
|
||||
JsonObject info = new JsonObject();
|
||||
info.addProperty("phase", "before");
|
||||
sendWaitForEventInfo(info);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T get() {
|
||||
return channel.withLogging(apiName, () -> {
|
||||
{
|
||||
JsonObject info = new JsonObject();
|
||||
info.addProperty("phase", "before");
|
||||
sendWaitForEventInfo(info);
|
||||
}
|
||||
JsonObject info = new JsonObject();
|
||||
info.addProperty("phase", "after");
|
||||
try {
|
||||
return supplier.apply(this);
|
||||
} catch (RuntimeException e) {
|
||||
info.addProperty("error", e.getMessage());
|
||||
throw e;
|
||||
} finally {
|
||||
sendWaitForEventInfo(info);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void log(String message) {
|
||||
LoggingSupport.logApiIfEnabled(message);
|
||||
JsonObject info = new JsonObject();
|
||||
info.addProperty("phase", "after");
|
||||
try {
|
||||
return supplier.get();
|
||||
} catch (RuntimeException e) {
|
||||
info.addProperty("error", e.getMessage());
|
||||
throw e;
|
||||
} finally {
|
||||
sendWaitForEventInfo(info);
|
||||
}
|
||||
info.addProperty("phase", "log");
|
||||
info.addProperty("message", message);
|
||||
sendWaitForEventInfo(info);
|
||||
}
|
||||
|
||||
private void sendWaitForEventInfo(JsonObject info) {
|
||||
@@ -57,6 +71,6 @@ public class WaitForEventLogger<T> implements Supplier<T> {
|
||||
info.addProperty("waitId", waitId);
|
||||
JsonObject params = new JsonObject();
|
||||
params.add("info", info);
|
||||
channel.withLogging(apiName, () -> channel.sendMessageAsync("waitForEventInfo", params));
|
||||
channel.sendMessageAsync("waitForEventInfo", params);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ class WebSocketImpl extends ChannelOwner implements WebSocket {
|
||||
|
||||
@Override
|
||||
public WebSocketFrame waitForFrameReceived(WaitForFrameReceivedOptions options, Runnable code) {
|
||||
return withWaitLogging("WebSocket.waitForFrameReceived", () -> waitForFrameReceivedImpl(options, code));
|
||||
return withWaitLogging("WebSocket.waitForFrameReceived", logger -> waitForFrameReceivedImpl(options, code));
|
||||
}
|
||||
|
||||
private WebSocketFrame waitForFrameReceivedImpl(WaitForFrameReceivedOptions options, Runnable code) {
|
||||
@@ -99,7 +99,7 @@ class WebSocketImpl extends ChannelOwner implements WebSocket {
|
||||
|
||||
@Override
|
||||
public WebSocketFrame waitForFrameSent(WaitForFrameSentOptions options, Runnable code) {
|
||||
return withWaitLogging("WebSocket.waitForFrameSent", () -> waitForFrameSentImpl(options, code));
|
||||
return withWaitLogging("WebSocket.waitForFrameSent", logger -> waitForFrameSentImpl(options, code));
|
||||
}
|
||||
|
||||
private WebSocketFrame waitForFrameSentImpl(WaitForFrameSentOptions options, Runnable code) {
|
||||
|
||||
@@ -59,7 +59,7 @@ class WorkerImpl extends ChannelOwner implements Worker {
|
||||
|
||||
@Override
|
||||
public Worker waitForClose(WaitForCloseOptions options, Runnable code) {
|
||||
return withWaitLogging("Worker.waitForClose", () -> waitForCloseImpl(options, code));
|
||||
return withWaitLogging("Worker.waitForClose", logger -> waitForCloseImpl(options, code));
|
||||
}
|
||||
|
||||
private Worker waitForCloseImpl(WaitForCloseOptions options, Runnable code) {
|
||||
|
||||
@@ -30,10 +30,4 @@ class WritableStream extends ChannelOwner {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
JsonObject toProtocol() {
|
||||
JsonObject json = new JsonObject();
|
||||
json.addProperty("guid", guid);
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* 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.options;
|
||||
|
||||
public enum HarContentPolicy {
|
||||
OMIT,
|
||||
EMBED,
|
||||
ATTACH
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* 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.options;
|
||||
|
||||
public enum HarMode {
|
||||
FULL,
|
||||
MINIMAL
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* 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.options;
|
||||
|
||||
public enum HarNotFound {
|
||||
ABORT,
|
||||
FALLBACK
|
||||
}
|
||||
@@ -19,7 +19,8 @@ package com.microsoft.playwright.options;
|
||||
import com.microsoft.playwright.impl.RequestOptionsImpl;
|
||||
|
||||
/**
|
||||
* The {@code RequestOptions} allows to create form data to be sent via {@code APIRequestContext}.
|
||||
* The {@code RequestOptions} allows to create form data to be sent via {@code APIRequestContext}. Playwright will automatically
|
||||
* determine content type of the request.
|
||||
* <pre>{@code
|
||||
* context.request().post(
|
||||
* "https://example.com/submit",
|
||||
@@ -27,6 +28,33 @@ import com.microsoft.playwright.impl.RequestOptionsImpl;
|
||||
* .setQueryParam("page", 1)
|
||||
* .setData("My data"));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> **Uploading html form data**
|
||||
*
|
||||
* <p> {@code FormData} class can be used to send a form to the server, by default the request will use
|
||||
* {@code application/x-www-form-urlencoded} encoding:
|
||||
* <pre>{@code
|
||||
* context.request().post("https://example.com/signup", RequestOptions.create().setForm(
|
||||
* FormData.create()
|
||||
* .set("firstName", "John")
|
||||
* .set("lastName", "Doe")));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> You can also send files as fields of an html form. The data will be encoded using <a
|
||||
* href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST">{@code multipart/form-data}</a>:
|
||||
* <pre>{@code
|
||||
* Path path = Paths.get("members.csv");
|
||||
* APIResponse response = context.request().post("https://example.com/upload_members",
|
||||
* RequestOptions.create().setMultipart(FormData.create().set("membersList", path)));
|
||||
* }</pre>
|
||||
*
|
||||
* <p> Alternatively, you can build the file payload manually:
|
||||
* <pre>{@code
|
||||
* FilePayload filePayload = new FilePayload("members.csv", "text/csv",
|
||||
* "Alice, 33\nJohn, 35\n".getBytes(StandardCharsets.UTF_8));
|
||||
* APIResponse response = context.request().post("https://example.com/upload_members",
|
||||
* RequestOptions.create().setMultipart(FormData.create().set("membersList", filePayload)));
|
||||
* }</pre>
|
||||
*/
|
||||
public interface RequestOptions {
|
||||
/**
|
||||
@@ -87,6 +115,13 @@ public interface RequestOptions {
|
||||
* @param ignoreHTTPSErrors Whether to ignore HTTPS errors when sending network requests.
|
||||
*/
|
||||
RequestOptions setIgnoreHTTPSErrors(boolean ignoreHTTPSErrors);
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @param maxRedirects 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.
|
||||
*/
|
||||
RequestOptions setMaxRedirects(int maxRedirects);
|
||||
/**
|
||||
* Changes the request method (e.g. <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT">PUT</a> or <a
|
||||
* href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST">POST</a>).
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* 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.options;
|
||||
|
||||
public enum ServiceWorkerPolicy {
|
||||
ALLOW,
|
||||
BLOCK
|
||||
}
|
||||
@@ -195,6 +195,7 @@ public class Server implements HttpHandler {
|
||||
String resourcePath = "resources" + path;
|
||||
InputStream resource = getClass().getClassLoader().getResourceAsStream(resourcePath);
|
||||
if (resource == null) {
|
||||
exchange.getResponseHeaders().add("Content-Type", "text/plain");
|
||||
exchange.sendResponseHeaders(404, 0);
|
||||
try (Writer writer = new OutputStreamWriter(exchange.getResponseBody())) {
|
||||
writer.write("File not found: " + resourcePath);
|
||||
|
||||
@@ -19,8 +19,11 @@ package com.microsoft.playwright;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.opentest4j.AssertionFailedError;
|
||||
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.Writer;
|
||||
|
||||
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestAPIResponseAssertions extends TestBase {
|
||||
@Test
|
||||
@@ -38,14 +41,62 @@ public class TestAPIResponseAssertions extends TestBase {
|
||||
@Test
|
||||
void fail() {
|
||||
APIResponse res = page.request().get(server.PREFIX + "/unknown");
|
||||
boolean didThrow = false;
|
||||
try {
|
||||
assertThat(res).isOK();
|
||||
} catch (AssertionFailedError e) {
|
||||
didThrow = true;
|
||||
assertTrue(e.getMessage().contains("→ GET " + server.PREFIX + "/unknown"), "Actual error: " + e.toString());
|
||||
assertTrue(e.getMessage().contains("← 404 Not Found"), "Actual error: " + e.toString());
|
||||
AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(res).isOK());
|
||||
assertTrue(e.getMessage().contains("→ GET " + server.PREFIX + "/unknown"), "Actual error: " + e.toString());
|
||||
assertTrue(e.getMessage().contains("← 404 Not Found"), "Actual error: " + e.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldPrintResponseTextIfIdOkFails() {
|
||||
APIResponse res = page.request().get(server.PREFIX + "/unknown");
|
||||
AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(res).isOK());
|
||||
assertTrue(e.getMessage().contains("File not found"), "Actual error: " + e.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldOnlyPrintResponseWithTextContentTypeIfIsOkFails() {
|
||||
{
|
||||
server.setRoute("/text-content-type", exchange -> {
|
||||
exchange.getResponseHeaders().set("Content-type", "text/plain");
|
||||
exchange.sendResponseHeaders(404, 0);
|
||||
try (Writer writer = new OutputStreamWriter(exchange.getResponseBody())) {
|
||||
writer.write("Text error");
|
||||
}
|
||||
});
|
||||
AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(page.request().get(server.PREFIX + "/text-content-type")).isOK());
|
||||
assertTrue(e.getMessage().contains("Text error"), "Actual error: " + e);
|
||||
}
|
||||
{
|
||||
server.setRoute("/svg-xml-content-type", exchange -> {
|
||||
exchange.getResponseHeaders().set("Content-type", "image/svg+xml");
|
||||
exchange.sendResponseHeaders(404, 0);
|
||||
try (Writer writer = new OutputStreamWriter(exchange.getResponseBody())) {
|
||||
writer.write("Json error");
|
||||
}
|
||||
});
|
||||
AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(page.request().get(server.PREFIX + "/svg-xml-content-type")).isOK());
|
||||
assertTrue(e.getMessage().contains("Json error"), "Actual error: " + e);
|
||||
}
|
||||
{
|
||||
server.setRoute("/no-content-type", exchange -> {
|
||||
exchange.sendResponseHeaders(404, 0);
|
||||
try (Writer writer = new OutputStreamWriter(exchange.getResponseBody())) {
|
||||
writer.write("No content type error");
|
||||
}
|
||||
});
|
||||
AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(page.request().get(server.PREFIX + "/no-content-type")).isOK());
|
||||
assertFalse(e.getMessage().contains("No content type error"), "Actual error: " + e);
|
||||
}
|
||||
{
|
||||
server.setRoute("/image-content-type", exchange -> {
|
||||
exchange.getResponseHeaders().set("Content-type", "image/bmp");
|
||||
exchange.sendResponseHeaders(404, 0);
|
||||
try (Writer writer = new OutputStreamWriter(exchange.getResponseBody())) {
|
||||
writer.write("Image type error");
|
||||
}
|
||||
});
|
||||
AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(page.request().get(server.PREFIX + "/image-content-type")).isOK());
|
||||
assertFalse(e.getMessage().contains("Image type error"), "Actual error: " + e);
|
||||
}
|
||||
assertTrue(didThrow);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ package com.microsoft.playwright;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
|
||||
import com.microsoft.playwright.options.SameSiteAttribute;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static com.microsoft.playwright.Utils.getBrowserNameFromEnv;
|
||||
@@ -35,9 +37,11 @@ public class TestBase {
|
||||
static final boolean isMac = Utils.getOS() == Utils.OS.MAC;
|
||||
static final boolean isWindows = Utils.getOS() == Utils.OS.WINDOWS;
|
||||
static final boolean headful;
|
||||
static final SameSiteAttribute defaultSameSiteCookieValue;
|
||||
static {
|
||||
String headfulEnv = System.getenv("HEADFUL");
|
||||
headful = headfulEnv != null && !"0".equals(headfulEnv) && !"false".equals(headfulEnv);
|
||||
defaultSameSiteCookieValue = initSameSiteAttribute();
|
||||
}
|
||||
|
||||
// Fields reset before each test.
|
||||
@@ -72,8 +76,12 @@ public class TestBase {
|
||||
return options;
|
||||
}
|
||||
|
||||
Playwright.CreateOptions playwrightOptions() {
|
||||
return null;
|
||||
}
|
||||
|
||||
void initBrowserType() {
|
||||
playwright = Playwright.create();
|
||||
playwright = Playwright.create(playwrightOptions());
|
||||
browserType = Utils.getBrowserTypeFromEnv(playwright);
|
||||
}
|
||||
|
||||
@@ -141,4 +149,11 @@ public class TestBase {
|
||||
page = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static SameSiteAttribute initSameSiteAttribute() {
|
||||
if (isChromium()) return SameSiteAttribute.LAX;
|
||||
if (isWebKit()) return SameSiteAttribute.NONE;
|
||||
// for firefox version >= 103 'None' is used.
|
||||
return SameSiteAttribute.NONE;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,12 +48,8 @@ public class TestBrowser extends TestBase {
|
||||
@Test
|
||||
void shouldThrowUponSecondCreateNewPage() {
|
||||
Page page = browser.newPage();
|
||||
try {
|
||||
page.context().newPage();
|
||||
fail("newPage should throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Please use browser.newContext()"));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.context().newPage());
|
||||
assertTrue(e.getMessage().contains("Please use browser.newContext()"));
|
||||
page.close();
|
||||
}
|
||||
|
||||
@@ -97,4 +93,9 @@ public class TestBrowser extends TestBase {
|
||||
assertNotNull(browser);
|
||||
browser.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnBrowserType() {
|
||||
assertEquals(browserType, browser.browserType());
|
||||
}
|
||||
}
|
||||
|
||||
+13
-27
@@ -16,7 +16,6 @@
|
||||
|
||||
package com.microsoft.playwright;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.microsoft.playwright.options.Cookie;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -27,7 +26,6 @@ import java.util.concurrent.Future;
|
||||
|
||||
import static com.microsoft.playwright.Utils.assertJsonEquals;
|
||||
import static java.util.Arrays.asList;
|
||||
import static java.util.Collections.emptyList;
|
||||
import static java.util.Collections.singletonList;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@@ -51,15 +49,11 @@ public class TestBrowserContextAddCookies extends TestBase {
|
||||
"}");
|
||||
assertEquals("username=John Doe", documentCookie);
|
||||
List<Cookie> cookies = context.cookies();
|
||||
assertEquals(1, cookies.size());
|
||||
context.clearCookies();
|
||||
assertEquals(emptyList(), context.cookies());
|
||||
context.addCookies(asList(new Cookie(cookies.get(0).name, cookies.get(0).value)
|
||||
.setDomain(cookies.get(0).domain)
|
||||
.setPath(cookies.get(0).path)
|
||||
.setExpires(cookies.get(0).expires)
|
||||
.setSameSite(cookies.get(0).sameSite)
|
||||
));
|
||||
assertJsonEquals(new Gson().toJson(cookies), context.cookies());
|
||||
assertEquals(0, context.cookies().size());
|
||||
context.addCookies(cookies);
|
||||
assertJsonEquals(cookies, context.cookies());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -248,27 +242,19 @@ public class TestBrowserContextAddCookies extends TestBase {
|
||||
|
||||
@Test
|
||||
void shouldNotSetACookieWithBlankPageURL() {
|
||||
try {
|
||||
context.addCookies(asList(
|
||||
new Cookie("example-cookie", "best").setUrl(server.EMPTY_PAGE),
|
||||
new Cookie("example-cookie-blank", "best").setUrl("about:blank")
|
||||
));
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Blank page can not have cookie \"example-cookie-blank\""));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> context.addCookies(asList(
|
||||
new Cookie("example-cookie", "best").setUrl(server.EMPTY_PAGE),
|
||||
new Cookie("example-cookie-blank", "best").setUrl("about:blank")
|
||||
)));
|
||||
assertTrue(e.getMessage().contains("Blank page can not have cookie \"example-cookie-blank\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotSetACookieOnADataURLPage() {
|
||||
try {
|
||||
context.addCookies(asList(
|
||||
new Cookie("example-cookie", "best").setUrl("data:,Hello%2C%20World!")
|
||||
));
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Data URL page can not have cookie \"example-cookie\""));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> context.addCookies(asList(
|
||||
new Cookie("example-cookie", "best").setUrl("data:,Hello%2C%20World!")
|
||||
)));
|
||||
assertTrue(e.getMessage().contains("Data URL page can not have cookie \"example-cookie\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -116,22 +116,18 @@ public class TestBrowserContextBasic extends TestBase {
|
||||
|
||||
@Test
|
||||
void shouldNotAllowDeviceScaleFactorWithNullViewport() {
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
browser.newContext(new Browser.NewContextOptions().setDeviceScaleFactor(1.0).setViewportSize(null));
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("\"deviceScaleFactor\" option is not supported with null \"viewport\""));
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("\"deviceScaleFactor\" option is not supported with null \"viewport\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotAllowIsMobileWithNullViewport() {
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
browser.newContext(new Browser.NewContextOptions().setIsMobile(true).setViewportSize(null));
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("\"isMobile\" option is not supported with null \"viewport\""));
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("\"isMobile\" option is not supported with null \"viewport\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -143,12 +139,10 @@ public class TestBrowserContextBasic extends TestBase {
|
||||
@Test
|
||||
void closeShouldAbortFutureEvent() {
|
||||
BrowserContext context = browser.newContext();
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
context.waitForPage(() -> context.close());
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Context closed"));
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("Context closed"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -211,15 +205,11 @@ public class TestBrowserContextBasic extends TestBase {
|
||||
BrowserContext context = browser.newContext(new Browser.NewContextOptions().setJavaScriptEnabled(false));
|
||||
Page page = context.newPage();
|
||||
page.navigate("data:text/html, <script>var something = 'forbidden'</script>");
|
||||
try {
|
||||
page.evaluate("something");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
if (isWebKit())
|
||||
assertTrue(e.getMessage().contains("Can\'t find variable: something"));
|
||||
else
|
||||
assertTrue(e.getMessage().contains("something is not defined"));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.evaluate("something"));
|
||||
if (isWebKit())
|
||||
assertTrue(e.getMessage().contains("Can\'t find variable: something"));
|
||||
else
|
||||
assertTrue(e.getMessage().contains("something is not defined"));
|
||||
context.close();
|
||||
}
|
||||
|
||||
@@ -244,11 +234,7 @@ public class TestBrowserContextBasic extends TestBase {
|
||||
void shouldWorkWithOfflineOption() {
|
||||
BrowserContext context = browser.newContext(new Browser.NewContextOptions().setOffline(true));
|
||||
Page page = context.newPage();
|
||||
try {
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
}
|
||||
assertThrows(PlaywrightException.class, () -> page.navigate(server.EMPTY_PAGE));
|
||||
|
||||
context.setOffline(false);
|
||||
Response response = page.navigate(server.EMPTY_PAGE);
|
||||
|
||||
@@ -20,7 +20,6 @@ import com.microsoft.playwright.options.Cookie;
|
||||
import com.microsoft.playwright.options.SameSiteAttribute;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.DisabledIf;
|
||||
import org.junit.jupiter.api.condition.EnabledIf;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
@@ -29,8 +28,7 @@ import java.util.stream.Collectors;
|
||||
import static com.microsoft.playwright.Utils.assertJsonEquals;
|
||||
import static com.microsoft.playwright.Utils.getOS;
|
||||
import static java.util.Arrays.asList;
|
||||
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 TestBrowserContextCookies extends TestBase {
|
||||
@Test
|
||||
@@ -60,25 +58,28 @@ public class TestBrowserContextCookies extends TestBase {
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
// @see https://en.wikipedia.org/wiki/Year_2038_problem
|
||||
Object documentCookie = page.evaluate("() => {\n" +
|
||||
" const date= new Date('1/1/2038');\n" +
|
||||
" document.cookie = `username=John Doe;expires=${date.toUTCString()}`;\n" +
|
||||
" return document.cookie;\n" +
|
||||
" }");
|
||||
" const date = new Date('1/1/2038');\n" +
|
||||
" document.cookie = `username=John Doe;expires=${date.toUTCString()}`;\n" +
|
||||
" return document.cookie;\n" +
|
||||
"}");
|
||||
assertEquals("username=John Doe", documentCookie);
|
||||
int timestamp = (Integer) page.evaluate("+(new Date('1/1/2038'))/1000");
|
||||
Cookie cookie = context.cookies().get(0);
|
||||
assertEquals("username", cookie.name);
|
||||
assertEquals("John Doe", cookie.value);
|
||||
assertEquals("localhost", cookie.domain);
|
||||
assertEquals("/", cookie.path);
|
||||
assertEquals(timestamp, cookie.expires);
|
||||
assertEquals(false, cookie.httpOnly);
|
||||
assertEquals(false, cookie.secure);
|
||||
if (isChromium()) {
|
||||
assertEquals(SameSiteAttribute.LAX, cookie.sameSite);
|
||||
} else {
|
||||
assertEquals(SameSiteAttribute.NONE, cookie.sameSite);
|
||||
}
|
||||
List<Cookie> cookies = context.cookies();
|
||||
assertEquals(1, cookies.size());
|
||||
assertEquals("username", cookies.get(0).name);
|
||||
assertEquals("John Doe", cookies.get(0).value);
|
||||
assertEquals("localhost", cookies.get(0).domain);
|
||||
assertEquals("/", cookies.get(0).path);
|
||||
assertFalse(cookies.get(0).httpOnly);
|
||||
assertFalse(cookies.get(0).secure);
|
||||
assertEquals(defaultSameSiteCookieValue, cookies.get(0).sameSite);
|
||||
|
||||
// Browsers start to cap cookies with 400 days max expires value.
|
||||
// See https://github.com/httpwg/http-extensions/pull/1732
|
||||
// Chromium patch: https://chromium.googlesource.com/chromium/src/+/aaa5d2b55478eac2ee642653dcd77a50ac3faff6
|
||||
// We want to make sure that expires date is at least 400 days in future.
|
||||
int FOUR_HUNDRED_DAYS = 1000 * 60 * 60 * 24 * 400;
|
||||
int FIVE_MINUTES = 1000 * 60 * 5; // relax condition a bit to make sure test is not flaky.
|
||||
assertTrue(cookies.get(0).expires > ((System.currentTimeMillis() + FOUR_HUNDRED_DAYS - FIVE_MINUTES) / 1000));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+6
-18
@@ -58,28 +58,16 @@ public class TestBrowserContextExposeFunction extends TestBase {
|
||||
void shouldThrowForDuplicateRegistrations() {
|
||||
context.exposeFunction("foo", args -> null);
|
||||
context.exposeFunction("bar", args -> null);
|
||||
try {
|
||||
context.exposeFunction("foo", args -> null);
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Function \"foo\" has been already registered"));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> context.exposeFunction("foo", args -> null));
|
||||
assertTrue(e.getMessage().contains("Function \"foo\" has been already registered"));
|
||||
|
||||
Page page = context.newPage();
|
||||
try {
|
||||
page.exposeFunction("foo", args -> null);
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Function \"foo\" has been already registered in the browser context"));
|
||||
}
|
||||
e = assertThrows(PlaywrightException.class, () -> page.exposeFunction("foo", args -> null));
|
||||
assertTrue(e.getMessage().contains("Function \"foo\" has been already registered in the browser context"));
|
||||
|
||||
page.exposeFunction("baz", args -> null);
|
||||
try {
|
||||
context.exposeFunction("baz", args -> null);
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Function \"baz\" has been already registered in one of the pages"));
|
||||
}
|
||||
e = assertThrows(PlaywrightException.class, () -> context.exposeFunction("baz", args -> null));
|
||||
assertTrue(e.getMessage().contains("Function \"baz\" has been already registered in one of the pages"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -51,24 +51,16 @@ public class TestBrowserContextFetch extends TestBase {
|
||||
@Test
|
||||
void shouldThrowOnNetworkError() {
|
||||
server.setRoute("/test", exchange -> exchange.getResponseBody().close());
|
||||
try {
|
||||
context.request().get(server.PREFIX + "/test");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("socket hang up"), e.getMessage());
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> context.request().get(server.PREFIX + "/test"));
|
||||
assertTrue(e.getMessage().contains("socket hang up"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldThrowOnNetworkErrorAfterRedirect() {
|
||||
server.setRedirect("/redirect", "/test");
|
||||
server.setRoute("/test", exchange -> exchange.getResponseBody().close());
|
||||
try {
|
||||
context.request().get(server.PREFIX + "/redirect");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("socket hang up"), e.getMessage());
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> context.request().get(server.PREFIX + "/redirect"));
|
||||
assertTrue(e.getMessage().contains("socket hang up"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -80,12 +72,8 @@ public class TestBrowserContextFetch extends TestBase {
|
||||
writer.write("<title>A");
|
||||
}
|
||||
});
|
||||
try {
|
||||
context.request().get(server.PREFIX + "/test");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("aborted"), e.getMessage());
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> context.request().get(server.PREFIX + "/test"));
|
||||
assertTrue(e.getMessage().contains("aborted"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -98,12 +86,8 @@ public class TestBrowserContextFetch extends TestBase {
|
||||
writer.write("<title>A");
|
||||
}
|
||||
});
|
||||
try {
|
||||
context.request().get(server.PREFIX + "/redirect");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("aborted"), e.getMessage());
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> context.request().get(server.PREFIX + "/redirect"));
|
||||
assertTrue(e.getMessage().contains("aborted"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -134,12 +118,10 @@ public class TestBrowserContextFetch extends TestBase {
|
||||
|
||||
@Test
|
||||
void getShouldSupportFailOnStatusCode() {
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
context.request().get(server.PREFIX + "/does-not-exist.html", RequestOptions.create().setFailOnStatusCode(true));
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("404 Not Found"), e.getMessage());
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("404 Not Found"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -385,29 +367,20 @@ public class TestBrowserContextFetch extends TestBase {
|
||||
|
||||
@Test
|
||||
void shouldThrowOnInvalidHeaderValue() {
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
context.request().get(server.EMPTY_PAGE, RequestOptions.create()
|
||||
.setHeader("foo", "недопустимое значение"));
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Invalid character in header content"), e.getMessage());
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("Invalid character in header content"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldThrowOnNonHttpSProtocol() {
|
||||
try {
|
||||
context.request().get("data:text/plain,test");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Protocol \"data:\" not supported"), e.getMessage());
|
||||
}
|
||||
try {
|
||||
context.request().get("file:///tmp/foo");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Protocol \"file:\" not supported"), e.getMessage());
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> context.request().get("data:text/plain,test"));
|
||||
assertTrue(e.getMessage().contains("Protocol \"data:\" not supported"), e.getMessage());
|
||||
|
||||
e = assertThrows(PlaywrightException.class, () -> context.request().get("file:///tmp/foo"));
|
||||
assertTrue(e.getMessage().contains("Protocol \"file:\" not supported"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -417,12 +390,10 @@ public class TestBrowserContextFetch extends TestBase {
|
||||
exchange.sendResponseHeaders(200, 4096);
|
||||
});
|
||||
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
context.request().get(server.PREFIX + "/slow", RequestOptions.create().setTimeout(100));
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Request timed out after 100ms"), e.getMessage());
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("Request timed out after 100ms"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -453,12 +424,8 @@ public class TestBrowserContextFetch extends TestBase {
|
||||
});
|
||||
|
||||
context.setDefaultTimeout(100);
|
||||
try {
|
||||
context.request().get(server.PREFIX + "/redirect");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Request timed out after 100ms"), e.getMessage());
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> context.request().get(server.PREFIX + "/redirect"));
|
||||
assertTrue(e.getMessage().contains("Request timed out after 100ms"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -466,12 +433,8 @@ public class TestBrowserContextFetch extends TestBase {
|
||||
APIResponse response = context.request().get(server.PREFIX + "/simple.json");
|
||||
assertEquals("{\"foo\": \"bar\"}\n", response.text());
|
||||
response.dispose();
|
||||
try {
|
||||
response.body();
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Response has been disposed"), e.getMessage());
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> response.body());
|
||||
assertTrue(e.getMessage().contains("Response has been disposed"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -479,13 +442,9 @@ public class TestBrowserContextFetch extends TestBase {
|
||||
APIResponse response = context.request().get(server.PREFIX + "/simple.json");
|
||||
assertEquals("{\"foo\": \"bar\"}\n", response.text());
|
||||
context.close();
|
||||
try {
|
||||
response.body();
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Response has been disposed") ||
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> response.body());
|
||||
assertTrue(e.getMessage().contains("Response has been disposed") ||
|
||||
e.getMessage().contains("Target page, context or browser has been closed"), e.getMessage());
|
||||
}
|
||||
}
|
||||
@Test
|
||||
void shouldOverrideRequestParameters() throws ExecutionException, InterruptedException {
|
||||
@@ -614,17 +573,11 @@ public class TestBrowserContextFetch extends TestBase {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldThrowWhenDataPassedForUnsupportedRequest() {
|
||||
try {
|
||||
context.request().fetch(server.EMPTY_PAGE, RequestOptions.create()
|
||||
.setMethod("GET").setData("bar"));
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Method GET does not accept post data"), e.getMessage());
|
||||
}
|
||||
void shouldNotThrowWhenDataPassedForUnsupportedRequest() {
|
||||
context.request().fetch(server.EMPTY_PAGE, RequestOptions.create()
|
||||
.setMethod("GET").setData("bar"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void contextRequestShouldExportSameStorageStateAsContext() {
|
||||
server.setRoute("/setcookie.html", exchange -> {
|
||||
@@ -666,18 +619,10 @@ public class TestBrowserContextFetch extends TestBase {
|
||||
return null;
|
||||
});
|
||||
page.evaluate("() => setTimeout(closeContext, 1000);");
|
||||
try {
|
||||
context.request().get(server.EMPTY_PAGE);
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Request context disposed"), e.getMessage());
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> context.request().get(server.EMPTY_PAGE));
|
||||
assertTrue(e.getMessage().contains("Request context disposed"), e.getMessage());
|
||||
|
||||
try {
|
||||
context.request().post(server.EMPTY_PAGE);
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Target page, context or browser has been closed"), e.getMessage());
|
||||
}
|
||||
e = assertThrows(PlaywrightException.class, () -> context.request().post(server.EMPTY_PAGE));
|
||||
assertTrue(e.getMessage().contains("Target page, context or browser has been closed"), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,449 @@
|
||||
/*
|
||||
* 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.options.HarContentPolicy;
|
||||
import com.microsoft.playwright.options.HarMode;
|
||||
import com.microsoft.playwright.options.HarNotFound;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.DisabledIf;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static com.microsoft.playwright.Utils.copy;
|
||||
import static com.microsoft.playwright.Utils.extractZip;
|
||||
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
|
||||
import static com.microsoft.playwright.options.HarContentPolicy.ATTACH;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestBrowserContextHar extends TestBase {
|
||||
@Test
|
||||
void shouldContextRouteFromHARMatchingTheMethodAndFollowingRedirects() {
|
||||
Path path = Paths.get("src/test/resources/har-fulfill.har");
|
||||
context.routeFromHAR(path);
|
||||
Page page = context.newPage();
|
||||
page.navigate("http://no.playwright/");
|
||||
// HAR contains a redirect for the script that should be followed automatically.
|
||||
assertEquals("foo", page.evaluate("window.value"));
|
||||
// HAR contains a POST for the css file that should not be used.
|
||||
assertThat(page.locator("body")).hasCSS("background-color", "rgb(255, 0, 0)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldPageRouteFromHARMatchingTheMethodAndFollowingRedirects() {
|
||||
Path path = Paths.get("src/test/resources/har-fulfill.har");
|
||||
Page page = context.newPage();
|
||||
page.routeFromHAR(path);
|
||||
page.navigate("http://no.playwright/");
|
||||
// HAR contains a redirect for the script that should be followed automatically.
|
||||
assertEquals("foo", page.evaluate("window.value"));
|
||||
// HAR contains a POST for the css file that should not be used.
|
||||
assertThat(page.locator("body")).hasCSS("background-color", "rgb(255, 0, 0)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallbackContinueShouldContinueWhenNotFoundInHar() {
|
||||
Path path = Paths.get("src/test/resources/har-fulfill.har");
|
||||
context.routeFromHAR(path, new BrowserContext.RouteFromHAROptions().setNotFound(HarNotFound.FALLBACK));
|
||||
Page page = context.newPage();
|
||||
page.navigate(server.PREFIX + "/one-style.html");
|
||||
assertThat(page.locator("body")).hasCSS("background-color", "rgb(255, 192, 203)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void byDefaultShouldAbortRequestsNotFoundInHar() {
|
||||
Path path = Paths.get("src/test/resources/har-fulfill.har");
|
||||
context.routeFromHAR(path);
|
||||
Page page = context.newPage();
|
||||
assertThrows(PlaywrightException.class, () -> page.navigate(server.EMPTY_PAGE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallbackContinueShouldContinueRequestsOnBadHar(@TempDir Path tmpDir) throws IOException {
|
||||
Path path = tmpDir.resolve("test.har");
|
||||
try (Writer stream = new OutputStreamWriter(Files.newOutputStream(path))) {
|
||||
stream.write("{ \"log\" : {} }");
|
||||
}
|
||||
context.routeFromHAR(path, new BrowserContext.RouteFromHAROptions().setNotFound(HarNotFound.FALLBACK));
|
||||
Page page = context.newPage();
|
||||
page.navigate(server.PREFIX + "/one-style.html");
|
||||
assertThat(page.locator("body")).hasCSS("background-color", "rgb(255, 192, 203)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldOnlyHandleRequestsMatchingUrlFilter() {
|
||||
Path path = Paths.get("src/test/resources/har-fulfill.har");
|
||||
context.routeFromHAR(path, new BrowserContext.RouteFromHAROptions().setNotFound(HarNotFound.FALLBACK).setUrl("**/*.js"));
|
||||
Page page = context.newPage();
|
||||
context.route("http://no.playwright/", route -> {
|
||||
assertEquals("http://no.playwright/", route.request().url());
|
||||
route.fulfill(new Route.FulfillOptions()
|
||||
.setStatus(200)
|
||||
.setContentType("text/html")
|
||||
.setBody("<script src='./script.js'></script><div>hello</div>"));
|
||||
});
|
||||
page.navigate("http://no.playwright/");
|
||||
// HAR contains a redirect for the script that should be followed automatically.
|
||||
assertEquals("foo", page.evaluate("window.value"));
|
||||
assertThat(page.locator("body")).hasCSS("background-color", "rgba(0, 0, 0, 0)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldOnlyContextRouteFromHARRequestsMatchingUrlFilter() {
|
||||
Path path = Paths.get("src/test/resources/har-fulfill.har");
|
||||
context.routeFromHAR(path, new BrowserContext.RouteFromHAROptions().setUrl("**/*.js"));
|
||||
Page page = context.newPage();
|
||||
context.route("http://no.playwright/", route -> {
|
||||
assertEquals("http://no.playwright/", route.request().url());
|
||||
route.fulfill(new Route.FulfillOptions()
|
||||
.setStatus(200)
|
||||
.setContentType("text/html")
|
||||
.setBody("<script src='./script.js'></script><div>hello</div>"));
|
||||
});
|
||||
page.navigate("http://no.playwright/");
|
||||
// HAR contains a redirect for the script that should be followed automatically.
|
||||
assertEquals("foo", page.evaluate("window.value"));
|
||||
assertThat(page.locator("body")).hasCSS("background-color", "rgba(0, 0, 0, 0)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldOnlyPageRouteFromHARRequestsMatchingUrlFilter() {
|
||||
Path path = Paths.get("src/test/resources/har-fulfill.har");
|
||||
Page page = context.newPage();
|
||||
page.routeFromHAR(path, new Page.RouteFromHAROptions().setUrl("**/*.js"));
|
||||
context.route("http://no.playwright/", route -> {
|
||||
assertEquals("http://no.playwright/", route.request().url());
|
||||
route.fulfill(new Route.FulfillOptions()
|
||||
.setStatus(200)
|
||||
.setContentType("text/html")
|
||||
.setBody("<script src='./script.js'></script><div>hello</div>"));
|
||||
});
|
||||
page.navigate("http://no.playwright/");
|
||||
// HAR contains a redirect for the script that should be followed automatically.
|
||||
assertEquals("foo", page.evaluate("window.value"));
|
||||
assertThat(page.locator("body")).hasCSS("background-color", "rgba(0, 0, 0, 0)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSupportRegexFilter() {
|
||||
Path path = Paths.get("src/test/resources/har-fulfill.har");
|
||||
context.routeFromHAR(path, new BrowserContext.RouteFromHAROptions().setUrl(Pattern.compile(".*(\\.js|.*\\.css|no.playwright\\/)$")));
|
||||
Page page = context.newPage();
|
||||
page.navigate("http://no.playwright/");
|
||||
assertEquals("foo", page.evaluate("window.value"));
|
||||
assertThat(page.locator("body")).hasCSS("background-color", "rgb(255, 0, 0)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void newPageShouldFulfillFromHarMatchingTheMethodAndFollowingRedirects() {
|
||||
Path path = Paths.get("src/test/resources/har-fulfill.har");
|
||||
Page page = browser.newPage();
|
||||
page.routeFromHAR(path);
|
||||
page.navigate("http://no.playwright/");
|
||||
// HAR contains a redirect for the script that should be followed automatically.
|
||||
assertEquals("foo", page.evaluate("window.value"));
|
||||
// HAR contains a POST for the css file that should not be used.
|
||||
assertThat(page.locator("body")).hasCSS("background-color", "rgb(255, 0, 0)");
|
||||
page.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldChangeDocumentURLAfterRedirectedNavigation() {
|
||||
Path path = Paths.get("src/test/resources/har-redirect.har");
|
||||
context.routeFromHAR(path);
|
||||
Page page = context.newPage();
|
||||
Response response = page.waitForNavigation(() -> {
|
||||
page.navigate("https://theverge.com/");
|
||||
page.waitForURL("https://www.theverge.com/");
|
||||
});
|
||||
assertThat(page).hasURL("https://www.theverge.com/");
|
||||
assertEquals("https://www.theverge.com/", response.request().url());
|
||||
assertEquals("https://www.theverge.com/", page.evaluate("location.href"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldChangeDocumentURLAfterRedirectedNavigationOnClick() {
|
||||
Path path = Paths.get("src/test/resources/har-redirect.har");
|
||||
context.routeFromHAR(path, new BrowserContext.RouteFromHAROptions().setUrl(Pattern.compile(".*theverge.*")));
|
||||
Page page = context.newPage();
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
page.setContent("<a href='https://theverge.com/'>click me</a>");
|
||||
Response response = page.waitForNavigation(() -> page.click("text=click me"));
|
||||
assertThat(page).hasURL("https://www.theverge.com/");
|
||||
assertEquals("https://www.theverge.com/", response.request().url());
|
||||
assertEquals("https://www.theverge.com/", page.evaluate("location.href"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldGoBackToRedirectedNavigation() {
|
||||
Path path = Paths.get("src/test/resources/har-redirect.har");
|
||||
context.routeFromHAR(path, new BrowserContext.RouteFromHAROptions().setUrl(Pattern.compile(".*theverge.*")));
|
||||
Page page = context.newPage();
|
||||
page.navigate("https://theverge.com/");
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
assertThat(page).hasURL(server.EMPTY_PAGE);
|
||||
Response response = page.goBack();
|
||||
assertThat(page).hasURL("https://www.theverge.com/");
|
||||
assertEquals("https://www.theverge.com/", response.request().url());
|
||||
assertEquals("https://www.theverge.com/", page.evaluate("location.href"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisabledIf(value="isFirefox", disabledReason="Flaky in Firefox, upstream as well")
|
||||
void shouldGoForwardToRedirectedNavigation() {
|
||||
Path path = Paths.get("src/test/resources/har-redirect.har");
|
||||
context.routeFromHAR(path, new BrowserContext.RouteFromHAROptions().setUrl(Pattern.compile(".*theverge.*")));
|
||||
Page page = context.newPage();
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
assertThat(page).hasURL(server.EMPTY_PAGE);
|
||||
page.navigate("https://theverge.com/");
|
||||
assertThat(page).hasURL("https://www.theverge.com/");
|
||||
page.goBack();
|
||||
assertThat(page).hasURL(server.EMPTY_PAGE);
|
||||
Response response = page.goForward();
|
||||
assertThat(page).hasURL("https://www.theverge.com/");
|
||||
assertEquals("https://www.theverge.com/", response.request().url());
|
||||
assertEquals("https://www.theverge.com/", page.evaluate("() => location.href"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReloadRedirectedNavigation() {
|
||||
Path path = Paths.get("src/test/resources/har-redirect.har");
|
||||
context.routeFromHAR(path, new BrowserContext.RouteFromHAROptions().setUrl(Pattern.compile(".*theverge.*")));
|
||||
Page page = context.newPage();
|
||||
page.navigate("https://theverge.com/");
|
||||
assertThat(page).hasURL("https://www.theverge.com/");
|
||||
Response response = page.reload();
|
||||
assertThat(page).hasURL("https://www.theverge.com/");
|
||||
assertEquals("https://www.theverge.com/", response.request().url());
|
||||
assertEquals("https://www.theverge.com/", page.evaluate("() => location.href"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFulfillFromHarWithContentInAFile() {
|
||||
Path path = Paths.get("src/test/resources/har-sha1.har");
|
||||
context.routeFromHAR(path);
|
||||
Page page = context.newPage();
|
||||
page.navigate("http://no.playwright/");
|
||||
assertEquals("<html><head></head><body>Hello, world</body></html>", page.content());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRoundTripHarZip(@TempDir Path tmpDir) {
|
||||
Path harPath = tmpDir.resolve("har.zip");
|
||||
try (BrowserContext context1 = browser.newContext(new Browser.NewContextOptions()
|
||||
.setRecordHarPath(harPath)
|
||||
.setRecordHarMode(HarMode.MINIMAL))) {
|
||||
Page page1 = context1.newPage();
|
||||
page1.navigate(server.PREFIX + "/one-style.html");
|
||||
}
|
||||
try (BrowserContext context2 = browser.newContext()) {
|
||||
context2.routeFromHAR(harPath, new BrowserContext.RouteFromHAROptions().setNotFound(HarNotFound.ABORT));
|
||||
Page page2 = context2.newPage();
|
||||
page2.navigate(server.PREFIX + "/one-style.html");
|
||||
assertTrue(page2.content().contains("hello, world!"));
|
||||
assertThat(page2.locator("body")).hasCSS("background-color", "rgb(255, 192, 203)");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldProduceExtractedZip(@TempDir Path tmpDir) throws IOException {
|
||||
Path harPath = tmpDir.resolve("har.har");
|
||||
try (BrowserContext context1 = browser.newContext(new Browser.NewContextOptions()
|
||||
.setRecordHarPath(harPath)
|
||||
.setRecordHarMode(HarMode.MINIMAL)
|
||||
.setRecordHarContent(ATTACH))) {
|
||||
Page page1 = context1.newPage();
|
||||
page1.navigate(server.PREFIX + "/one-style.html");
|
||||
}
|
||||
assertTrue(Files.exists(harPath));
|
||||
String har = new String(Files.readAllBytes(harPath), StandardCharsets.UTF_8);
|
||||
assertFalse(har.contains("background-color"));
|
||||
try (BrowserContext context2 = browser.newContext()) {
|
||||
context2.routeFromHAR(harPath, new BrowserContext.RouteFromHAROptions().setNotFound(HarNotFound.ABORT));
|
||||
Page page2 = context2.newPage();
|
||||
page2.navigate(server.PREFIX + "/one-style.html");
|
||||
assertTrue(page2.content().contains("hello, world!"));
|
||||
assertThat(page2.locator("body")).hasCSS("background-color", "rgb(255, 192, 203)");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRoundTripExtractedHarZip(@TempDir Path tmpDir) throws IOException {
|
||||
Path harPath = tmpDir.resolve("har.zip");
|
||||
try (BrowserContext context1 = browser.newContext(new Browser.NewContextOptions()
|
||||
.setRecordHarPath(harPath)
|
||||
.setRecordHarMode(HarMode.MINIMAL))) {
|
||||
Page page1 = context1.newPage();
|
||||
page1.navigate(server.PREFIX + "/one-style.html");
|
||||
}
|
||||
|
||||
Path harDir = tmpDir.resolve("hardir");
|
||||
extractZip(harPath, harDir);
|
||||
|
||||
try (BrowserContext context2 = browser.newContext()) {
|
||||
context2.routeFromHAR(harDir.resolve("har.har"));
|
||||
Page page2 = context2.newPage();
|
||||
page2.navigate(server.PREFIX + "/one-style.html");
|
||||
assertTrue(page2.content().contains("hello, world!"));
|
||||
assertThat(page2.locator("body")).hasCSS("background-color", "rgb(255, 192, 203)");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRoundTripHarWithPostData(@TempDir Path tmpDir) {
|
||||
server.setRoute("/echo", exchange -> {
|
||||
exchange.sendResponseHeaders(200, 0);
|
||||
try (OutputStream out = exchange.getResponseBody()) {
|
||||
copy(exchange.getRequestBody(), out);
|
||||
}
|
||||
});
|
||||
|
||||
String fetchFunction = "async body => {\n" +
|
||||
" const response = await fetch('/echo', { method: 'POST', body });\n" +
|
||||
" return await response.text();\n" +
|
||||
" }\n";
|
||||
Path harPath = tmpDir.resolve("har.zip");
|
||||
try (BrowserContext context1 = browser.newContext(new Browser.NewContextOptions()
|
||||
.setRecordHarPath(harPath)
|
||||
.setRecordHarMode(HarMode.MINIMAL))) {
|
||||
Page page1 = context1.newPage();
|
||||
page1.navigate(server.EMPTY_PAGE);
|
||||
assertEquals("1", page1.evaluate(fetchFunction, "1"));
|
||||
assertEquals("2", page1.evaluate(fetchFunction, "2"));
|
||||
assertEquals("3", page1.evaluate(fetchFunction, "3"));
|
||||
}
|
||||
server.reset();
|
||||
try (BrowserContext context2 = browser.newContext()) {
|
||||
context2.routeFromHAR(harPath);
|
||||
Page page2 = context2.newPage();
|
||||
page2.navigate(server.EMPTY_PAGE);
|
||||
assertEquals("1", page2.evaluate(fetchFunction, "1"));
|
||||
assertEquals("2", page2.evaluate(fetchFunction, "2"));
|
||||
assertEquals("3", page2.evaluate(fetchFunction, "3"));
|
||||
assertEquals("3", page2.evaluate(fetchFunction, "3"));
|
||||
assertThrows(PlaywrightException.class, () -> page2.evaluate(fetchFunction, "4"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDisambiguateByHeader(@TempDir Path tmpDir) {
|
||||
server.setRoute("/echo", exchange -> {
|
||||
exchange.sendResponseHeaders(200, 0);
|
||||
try (OutputStream out = exchange.getResponseBody()) {
|
||||
List<String> values = exchange.getRequestHeaders().get("baz");
|
||||
try (OutputStreamWriter writer = new OutputStreamWriter(exchange.getResponseBody())) {
|
||||
writer.write(values == null ? "<no header>" : String.join(", ", values));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
String fetchFunction = "async bazValue => {\n" +
|
||||
" const response = await fetch('/echo', {\n" +
|
||||
" method: 'POST',\n" +
|
||||
" body: '',\n" +
|
||||
" headers: {\n" +
|
||||
" foo: 'foo-value',\n" +
|
||||
" bar: 'bar-value',\n" +
|
||||
" baz: bazValue,\n" +
|
||||
" }\n" +
|
||||
" });\n" +
|
||||
" return await response.text();\n" +
|
||||
" }\n";
|
||||
Path harPath = tmpDir.resolve("har.zip");
|
||||
try (BrowserContext context1 = browser.newContext(new Browser.NewContextOptions()
|
||||
.setRecordHarPath(harPath)
|
||||
.setRecordHarMode(HarMode.MINIMAL))) {
|
||||
Page page1 = context1.newPage();
|
||||
page1.navigate(server.EMPTY_PAGE);
|
||||
assertEquals("baz1", page1.evaluate(fetchFunction, "baz1"));
|
||||
assertEquals("baz2", page1.evaluate(fetchFunction, "baz2"));
|
||||
assertEquals("baz3", page1.evaluate(fetchFunction, "baz3"));
|
||||
}
|
||||
server.reset();
|
||||
try (BrowserContext context2 = browser.newContext()) {
|
||||
context2.routeFromHAR(harPath);
|
||||
Page page2 = context2.newPage();
|
||||
page2.navigate(server.EMPTY_PAGE);
|
||||
assertEquals("baz1", page2.evaluate(fetchFunction, "baz1"));
|
||||
assertEquals("baz2", page2.evaluate(fetchFunction, "baz2"));
|
||||
assertEquals("baz3", page2.evaluate(fetchFunction, "baz3"));
|
||||
assertEquals("baz1", page2.evaluate(fetchFunction, "baz4"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldUpdateHarZipForContext(@TempDir Path tmpDir) {
|
||||
Path harPath = tmpDir.resolve("har.zip");
|
||||
try (BrowserContext context1 = browser.newContext()) {
|
||||
context1.routeFromHAR(harPath, new BrowserContext.RouteFromHAROptions().setUpdate(true));
|
||||
Page page1 = context1.newPage();
|
||||
page1.navigate(server.PREFIX + "/one-style.html");
|
||||
}
|
||||
try (BrowserContext context2 = browser.newContext()) {
|
||||
context2.routeFromHAR(harPath, new BrowserContext.RouteFromHAROptions().setNotFound(HarNotFound.ABORT));
|
||||
Page page2 = context2.newPage();
|
||||
page2.navigate(server.PREFIX + "/one-style.html");
|
||||
assertTrue(page2.content().contains("hello, world!"));
|
||||
assertThat(page2.locator("body")).hasCSS("background-color", "rgb(255, 192, 203)");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldUpdateHarZipForPage(@TempDir Path tmpDir) {
|
||||
Path harPath = tmpDir.resolve("har.zip");
|
||||
try (BrowserContext context1 = browser.newContext()) {
|
||||
Page page1 = context1.newPage();
|
||||
page1.routeFromHAR(harPath, new Page.RouteFromHAROptions().setUpdate(true));
|
||||
page1.navigate(server.PREFIX + "/one-style.html");
|
||||
}
|
||||
try (BrowserContext context2 = browser.newContext()) {
|
||||
Page page2 = context2.newPage();
|
||||
page2.routeFromHAR(harPath, new Page.RouteFromHAROptions().setNotFound(HarNotFound.ABORT));
|
||||
page2.navigate(server.PREFIX + "/one-style.html");
|
||||
assertTrue(page2.content().contains("hello, world!"));
|
||||
assertThat(page2.locator("body")).hasCSS("background-color", "rgb(255, 192, 203)");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldUpdateExtractedHarZipForPage(@TempDir Path tmpDir) {
|
||||
Path harPath = tmpDir.resolve("har.har");
|
||||
try (BrowserContext context1 = browser.newContext()) {
|
||||
Page page1 = context1.newPage();
|
||||
page1.routeFromHAR(harPath, new Page.RouteFromHAROptions().setUpdate(true));
|
||||
page1.navigate(server.PREFIX + "/one-style.html");
|
||||
}
|
||||
try (BrowserContext context2 = browser.newContext()) {
|
||||
Page page2 = context2.newPage();
|
||||
page2.routeFromHAR(harPath, new Page.RouteFromHAROptions().setNotFound(HarNotFound.ABORT));
|
||||
page2.navigate(server.PREFIX + "/one-style.html");
|
||||
assertTrue(page2.content().contains("hello, world!"));
|
||||
assertThat(page2.locator("body")).hasCSS("background-color", "rgb(255, 192, 203)");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,19 +28,19 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
public class TestBrowserContextLocale extends TestBase {
|
||||
@Test
|
||||
void shouldAffectAcceptLanguageHeader() throws ExecutionException, InterruptedException {
|
||||
BrowserContext context = browser.newContext(new Browser.NewContextOptions().setLocale("fr-CH"));
|
||||
BrowserContext context = browser.newContext(new Browser.NewContextOptions().setLocale("fr-FR"));
|
||||
Page page = context.newPage();
|
||||
Future<Server.Request> request = server.futureRequest("/empty.html");
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
assertEquals("fr-CH", request.get().headers.get("accept-language").get(0).substring(0, 5));
|
||||
assertEquals("fr-FR", request.get().headers.get("accept-language").get(0).substring(0, 5));
|
||||
context.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldAffectNavigatorLanguage() {
|
||||
BrowserContext context = browser.newContext(new Browser.NewContextOptions().setLocale("fr-CH"));
|
||||
BrowserContext context = browser.newContext(new Browser.NewContextOptions().setLocale("fr-FR"));
|
||||
Page page = context.newPage();
|
||||
assertEquals("fr-CH", page.evaluate("() => navigator.language"));
|
||||
assertEquals("fr-FR", page.evaluate("() => navigator.language"));
|
||||
context.close();
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ public class TestBrowserContextLocale extends TestBase {
|
||||
context.close();
|
||||
}
|
||||
{
|
||||
BrowserContext context = browser.newContext(new Browser.NewContextOptions().setLocale("fr-CH"));
|
||||
BrowserContext context = browser.newContext(new Browser.NewContextOptions().setLocale("fr-FR"));
|
||||
Page page = context.newPage();
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
assertEquals("1 000 000,5", page.evaluate("() => (1000000.50).toLocaleString().replace(/\\s/g, ' ')"));
|
||||
@@ -87,7 +87,7 @@ public class TestBrowserContextLocale extends TestBase {
|
||||
|
||||
@Test
|
||||
void shouldFormatNumberInPopups() {
|
||||
BrowserContext context = browser.newContext(new Browser.NewContextOptions().setLocale("fr-CH"));
|
||||
BrowserContext context = browser.newContext(new Browser.NewContextOptions().setLocale("fr-FR"));
|
||||
Page page = context.newPage();
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
Page popup = page.waitForPopup(() -> page.evaluate(
|
||||
@@ -100,14 +100,14 @@ public class TestBrowserContextLocale extends TestBase {
|
||||
|
||||
@Test
|
||||
void shouldAffectNavigatorLanguageInPopups() {
|
||||
BrowserContext context = browser.newContext(new Browser.NewContextOptions().setLocale("fr-CH"));
|
||||
BrowserContext context = browser.newContext(new Browser.NewContextOptions().setLocale("fr-FR"));
|
||||
Page page = context.newPage();
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
Page popup = page.waitForPopup(() -> page.evaluate(
|
||||
"url => window.open(url)", server.PREFIX + "/formatted-number.html"));
|
||||
popup.waitForLoadState(LoadState.DOMCONTENTLOADED);
|
||||
Object result = popup.evaluate("window.initialNavigatorLanguage");
|
||||
assertEquals("fr-CH", result);
|
||||
assertEquals("fr-FR", result);
|
||||
context.close();
|
||||
}
|
||||
|
||||
@@ -155,7 +155,7 @@ public class TestBrowserContextLocale extends TestBase {
|
||||
defaultLocale = getContextLocale.apply(context);
|
||||
context.close();
|
||||
}
|
||||
String localeOverride = "ru-RU".equals(defaultLocale) ? "de-DE" : "ru-RU";
|
||||
String localeOverride = "es-MX".equals(defaultLocale) ? "de-DE" : "es-MX";
|
||||
{
|
||||
BrowserContext context = browser.newContext(new Browser.NewContextOptions().setLocale(localeOverride));
|
||||
assertEquals(localeOverride, getContextLocale.apply(context));
|
||||
|
||||
@@ -47,9 +47,9 @@ public class TestBrowserContextProxy extends TestBase {
|
||||
@EnabledIf(value="isChromiumWindows", disabledReason="Platform-specific")
|
||||
void shouldThrowForMissingGlobalProxyOnChromiumWindows() {
|
||||
try (Browser browser = browserType.launch(createLaunchOptions())) {
|
||||
browser.newContext(new Browser.NewContextOptions().setProxy("localhost:" + server.PORT));
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
browser.newContext(new Browser.NewContextOptions().setProxy("localhost:" + server.PORT));
|
||||
});
|
||||
assertTrue(e.getMessage().contains("Browser needs to be launched with the global proxy"));
|
||||
}
|
||||
}
|
||||
@@ -179,23 +179,9 @@ public class TestBrowserContextProxy extends TestBase {
|
||||
page.navigate("http://0.non.existent.domain.for.the.test/target.html");
|
||||
assertEquals("Served by the proxy", page.title());
|
||||
|
||||
try {
|
||||
page.navigate("http://1.non.existent.domain.for.the.test/target.html");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException exception) {
|
||||
}
|
||||
|
||||
try {
|
||||
page.navigate("http://2.non.existent.domain.for.the.test/target.html");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
}
|
||||
|
||||
try {
|
||||
page.navigate("http://foo.is.the.another.test/target.html");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
}
|
||||
assertThrows(PlaywrightException.class, () -> page.navigate("http://1.non.existent.domain.for.the.test/target.html"));
|
||||
assertThrows(PlaywrightException.class, () -> page.navigate("http://2.non.existent.domain.for.the.test/target.html"));
|
||||
assertThrows(PlaywrightException.class, () -> page.navigate("http://foo.is.the.another.test/target.html"));
|
||||
|
||||
page.navigate("http://3.non.existent.domain.for.the.test/target.html");
|
||||
assertEquals("Served by the proxy", page.title());
|
||||
|
||||
@@ -19,6 +19,7 @@ package com.microsoft.playwright;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
@@ -62,28 +63,28 @@ public class TestBrowserContextRoute extends TestBase {
|
||||
List<Integer> intercepted = new ArrayList<>();
|
||||
context.route("**/*", route -> {
|
||||
intercepted.add(1);
|
||||
route.resume();
|
||||
route.fallback();
|
||||
});
|
||||
context.route("**/empty.html", route -> {
|
||||
intercepted.add(2);
|
||||
route.resume();
|
||||
route.fallback();
|
||||
});
|
||||
context.route("**/empty.html", route -> {
|
||||
intercepted.add(3);
|
||||
route.resume();
|
||||
route.fallback();
|
||||
});
|
||||
Consumer<Route> handler4 = route -> {
|
||||
intercepted.add(4);
|
||||
route.resume();
|
||||
route.fallback();
|
||||
};
|
||||
context.route("**/empty.html", handler4);
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
assertEquals(asList(4), intercepted);
|
||||
assertEquals(asList(4, 3, 2, 1), intercepted);
|
||||
|
||||
intercepted.clear();
|
||||
context.unroute("**/empty.html", handler4);
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
assertEquals(asList(3), intercepted);
|
||||
assertEquals(asList(3, 2, 1), intercepted);
|
||||
|
||||
intercepted.clear();
|
||||
context.unroute("**/empty.html");
|
||||
@@ -168,12 +169,8 @@ public class TestBrowserContextRoute extends TestBase {
|
||||
throw new RuntimeException("My Exception");
|
||||
});
|
||||
|
||||
try {
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
fail("did not throw");
|
||||
} catch (RuntimeException e) {
|
||||
assertTrue(e.getMessage().contains("My Exception"), e.getMessage());
|
||||
}
|
||||
RuntimeException e = assertThrows(RuntimeException.class, () -> page.navigate(server.EMPTY_PAGE));
|
||||
assertTrue(e.getMessage().contains("My Exception"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -186,12 +183,8 @@ public class TestBrowserContextRoute extends TestBase {
|
||||
// Fulfilling with dsiposed response will lead to a server-side exception.
|
||||
route.fulfill(new Route.FulfillOptions().setResponse(response));
|
||||
});
|
||||
try {
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
fail("did not throw");
|
||||
} catch (RuntimeException e) {
|
||||
assertTrue(e.getMessage().contains("Fetch response has been disposed"), e.getMessage());
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.navigate(server.EMPTY_PAGE));
|
||||
assertTrue(e.getMessage().contains("Fetch response has been disposed"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -200,11 +193,116 @@ public class TestBrowserContextRoute extends TestBase {
|
||||
page.route("**/*", route -> {
|
||||
route.resume(new Route.ResumeOptions().setUrl("file:///tmp"));
|
||||
});
|
||||
try {
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
fail("did not throw");
|
||||
} catch (RuntimeException e) {
|
||||
assertTrue(e.getMessage().contains("New URL must have same protocol as overridden URL"), e.getMessage());
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.navigate(server.EMPTY_PAGE));
|
||||
assertTrue(e.getMessage().contains("New URL must have same protocol as overridden URL"), e.getMessage());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void shouldChainFallback() {
|
||||
List<Integer> intercepted = new ArrayList<>();
|
||||
context.route("**/empty.html", route -> {
|
||||
intercepted.add(1);
|
||||
route.fallback();
|
||||
});
|
||||
context.route("**/empty.html", route -> {
|
||||
intercepted.add(2);
|
||||
route.fallback();
|
||||
});
|
||||
context.route("**/empty.html", route -> {
|
||||
intercepted.add(3);
|
||||
route.fallback();
|
||||
});
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
assertEquals(asList(3, 2, 1), intercepted);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotChainFulfill() {
|
||||
boolean[] failed = {false};
|
||||
context.route("**/empty.html", route -> {
|
||||
failed[0] = true;
|
||||
});
|
||||
context.route("**/empty.html", route -> {
|
||||
route.fulfill(new Route.FulfillOptions().setStatus(200).setBody("fulfilled"));
|
||||
});
|
||||
context.route("**/empty.html", route -> {
|
||||
route.fallback();
|
||||
});
|
||||
Response response = page.navigate(server.EMPTY_PAGE);
|
||||
byte[] body = response.body();
|
||||
assertEquals("fulfilled", new String(body, StandardCharsets.UTF_8));
|
||||
assertFalse(failed[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotChainAbort() {
|
||||
boolean[] failed = {false};
|
||||
context.route("**/empty.html", route -> {
|
||||
failed[0] = true;
|
||||
});
|
||||
context.route("**/empty.html", route -> {
|
||||
route.abort();
|
||||
});
|
||||
context.route("**/empty.html", route -> {
|
||||
route.fallback();
|
||||
});
|
||||
|
||||
assertThrows(PlaywrightException.class, () -> page.navigate(server.EMPTY_PAGE));
|
||||
assertFalse(failed[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldChainFallbackIntoPage() {
|
||||
List<Integer> intercepted = new ArrayList<>();
|
||||
context.route("**/empty.html", route -> {
|
||||
intercepted.add(1);
|
||||
route.fallback();
|
||||
});
|
||||
context.route("**/empty.html", route -> {
|
||||
intercepted.add(2);
|
||||
route.fallback();
|
||||
});
|
||||
context.route("**/empty.html", route -> {
|
||||
intercepted.add(3);
|
||||
route.fallback();
|
||||
});
|
||||
page.route("**/empty.html", route -> {
|
||||
intercepted.add(4);
|
||||
route.fallback();
|
||||
});
|
||||
page.route("**/empty.html", route -> {
|
||||
intercepted.add(5);
|
||||
route.fallback();
|
||||
});
|
||||
page.route("**/empty.html", route -> {
|
||||
intercepted.add(6);
|
||||
route.fallback();
|
||||
});
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
assertEquals(asList(6, 5, 4, 3, 2, 1), intercepted);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallBackAsync() {
|
||||
List<Integer> intercepted = new ArrayList<>();
|
||||
context.route("**/empty.html", route -> {
|
||||
intercepted.add(1);
|
||||
page.waitForTimeout(50);
|
||||
route.fallback();
|
||||
});
|
||||
context.route("**/empty.html", route -> {
|
||||
intercepted.add(2);
|
||||
page.waitForTimeout(100);
|
||||
route.fallback();
|
||||
});
|
||||
context.route("**/empty.html", route -> {
|
||||
intercepted.add(3);
|
||||
page.waitForTimeout(150);
|
||||
route.fallback();
|
||||
});
|
||||
page.navigate(server.EMPTY_PAGE);
|
||||
assertEquals(asList(3, 2, 1), intercepted);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* 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.options.ServiceWorkerPolicy;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
public class TestBrowserContextServiceWorkerPolicy extends TestBase {
|
||||
@Test
|
||||
void shouldAllowServiceWorkersByDefault() {
|
||||
page.navigate(server.PREFIX + "/serviceworkers/empty/sw.html");
|
||||
assertNotNull(page.evaluate("() => window['registrationPromise']"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blocksServiceWorkerRegistration() {
|
||||
try (BrowserContext context = browser.newContext(new Browser.NewContextOptions().setServiceWorkers(ServiceWorkerPolicy.BLOCK))) {
|
||||
Page page = context.newPage();
|
||||
ConsoleMessage message = page.waitForConsoleMessage(new Page.WaitForConsoleMessageOptions()
|
||||
.setPredicate(m -> "Service Worker registration blocked by Playwright".equals(m.text())),
|
||||
() -> page.navigate(server.PREFIX + "/serviceworkers/empty/sw.html"));
|
||||
assertNotNull(message);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -38,12 +38,8 @@ public class TestBrowserContextStrict extends TestBase {
|
||||
@Test
|
||||
void shouldFailPageTextContentInStrictMode() {
|
||||
page.setContent("<span>span1</span><div><span>target</span></div>");
|
||||
try {
|
||||
page.textContent("span");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("strict mode violation"));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.textContent("span"));
|
||||
assertTrue(e.getMessage().contains("strict mode violation"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -43,11 +43,7 @@ public class TestBrowserTypeBasic extends TestBase {
|
||||
@Test
|
||||
@DisabledIf(value="com.microsoft.playwright.TestBase#isChromium", disabledReason="Non-chromium behavior")
|
||||
void shouldThrowWhenTryingToConnectWithNotChromium() {
|
||||
try {
|
||||
browserType.connectOverCDP("foo");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Connecting over CDP is only supported in Chromium."));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> browserType.connectOverCDP("foo"));
|
||||
assertTrue(e.getMessage().contains("Connecting over CDP is only supported in Chromium."));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,8 +16,7 @@
|
||||
|
||||
package com.microsoft.playwright;
|
||||
|
||||
import com.microsoft.playwright.impl.Driver;
|
||||
import com.microsoft.playwright.options.WaitForSelectorState;
|
||||
import com.microsoft.playwright.impl.driver.Driver;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
@@ -61,8 +60,8 @@ public class TestBrowserTypeConnect extends TestBase {
|
||||
|
||||
private static BrowserServer launchBrowserServer(BrowserType browserType) {
|
||||
try {
|
||||
Path driver = Driver.ensureDriverInstalled(Collections.emptyMap(), false);
|
||||
Path dir = driver.getParent();
|
||||
Driver driver = Driver.ensureDriverInstalled(Collections.emptyMap(), false);
|
||||
Path dir = driver.driverPath().getParent();
|
||||
String node = dir.resolve(isWindows ? "node.exe" : "node").toString();
|
||||
String cliJs = dir.resolve("package/lib/cli/cli.js").toString();
|
||||
// We launch node process directly instead of using playwright.sh script as killing the script
|
||||
@@ -193,12 +192,8 @@ public class TestBrowserTypeConnect extends TestBase {
|
||||
|
||||
remote.kill();
|
||||
assertEquals(1, disconnected1[0]);
|
||||
try {
|
||||
// Tickle connection so that it gets a chance to dispatch disconnect event.
|
||||
page2.title();
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
}
|
||||
// Tickle connection so that it gets a chance to dispatch disconnect event.
|
||||
assertThrows(PlaywrightException.class, () -> page2.title());
|
||||
assertEquals(1, disconnected2[0]);
|
||||
}
|
||||
|
||||
@@ -239,11 +234,8 @@ public class TestBrowserTypeConnect extends TestBase {
|
||||
}
|
||||
}
|
||||
assertFalse(remote.isConnected());
|
||||
try {
|
||||
page.evaluate("1 + 1");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Browser has been closed"), e.getMessage());
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.evaluate("1 + 1"));
|
||||
assertTrue(e.getMessage().contains("Browser has been closed"), e.getMessage());
|
||||
assertFalse(remote.isConnected());
|
||||
}
|
||||
|
||||
@@ -263,12 +255,8 @@ public class TestBrowserTypeConnect extends TestBase {
|
||||
}
|
||||
}
|
||||
assertFalse(browser.isConnected());
|
||||
try {
|
||||
page.waitForNavigation(() -> {});
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Page closed") || e.getMessage().contains("Browser has been closed"), e.getMessage());
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.waitForNavigation(() -> {}));
|
||||
assertTrue(e.getMessage().contains("Page closed") || e.getMessage().contains("Browser has been closed"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -278,12 +266,10 @@ public class TestBrowserTypeConnect extends TestBase {
|
||||
|
||||
server.setRoute("/one-style.css", r -> {});
|
||||
page.onRequest(r -> remote.close());
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
page.navigate(server.PREFIX + "/one-style.html", new Page.NavigateOptions().setTimeout(60000));
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Browser has been closed"));
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("Browser has been closed"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -409,12 +395,8 @@ public class TestBrowserTypeConnect extends TestBase {
|
||||
Path savedAsPath = tempDir.resolve("my-video.webm");
|
||||
page.video().saveAs(savedAsPath);
|
||||
assertTrue(Files.exists(savedAsPath));
|
||||
try {
|
||||
page.video().path();
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Path is not available when using browserType.connect(). Use saveAs() to save a local copy."));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.video().path());
|
||||
assertTrue(e.getMessage().contains("Path is not available when using browserType.connect(). Use saveAs() to save a local copy."));
|
||||
}
|
||||
|
||||
|
||||
@@ -436,12 +418,8 @@ public class TestBrowserTypeConnect extends TestBase {
|
||||
download.saveAs(nestedPath);
|
||||
assertTrue(Files.exists(nestedPath));
|
||||
assertEquals("Hello world", new String(Files.readAllBytes(nestedPath), StandardCharsets.UTF_8));
|
||||
try {
|
||||
download.path();
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Path is not available when using browserType.connect(). Use download.saveAs() to save a local copy."));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> download.path());
|
||||
assertTrue(e.getMessage().contains("Path is not available when using browserType.connect(). Use download.saveAs() to save a local copy."));
|
||||
page.close();
|
||||
}
|
||||
|
||||
@@ -460,12 +438,8 @@ public class TestBrowserTypeConnect extends TestBase {
|
||||
Download download = page.waitForDownload(() -> page.click("a"));
|
||||
Path userPath = tempDir.resolve("download.txt");
|
||||
download.delete();
|
||||
try {
|
||||
download.saveAs(userPath);
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Target page, context or browser has been closed"));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> download.saveAs(userPath));
|
||||
assertTrue(e.getMessage().contains("Target page, context or browser has been closed"));
|
||||
page.close();
|
||||
}
|
||||
|
||||
@@ -499,7 +473,7 @@ public class TestBrowserTypeConnect extends TestBase {
|
||||
Path trace = tmpDir.resolve("trace1.zip");
|
||||
context.tracing().stop(new Tracing.StopOptions().setPath(trace));
|
||||
|
||||
Map<String, byte[]> entries = parseTrace(trace);
|
||||
Map<String, byte[]> entries = parseZip(trace);
|
||||
Map<String, byte[]> sources = entries.entrySet().stream().filter(e -> e.getKey().endsWith(".txt")).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
assertEquals(1, sources.size());
|
||||
|
||||
|
||||
@@ -80,12 +80,10 @@ public class TestChromiumTracing extends TestBase {
|
||||
browser.startTracing(page, new Browser.StartTracingOptions()
|
||||
.setPath(outputTraceFile));
|
||||
Page newPage = browser.newPage();
|
||||
try {
|
||||
assertThrows(PlaywrightException.class, () -> {
|
||||
browser.startTracing(newPage, new Browser.StartTracingOptions()
|
||||
.setPath(outputTraceFile));
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
}
|
||||
});
|
||||
newPage.close();
|
||||
browser.stopTracing();
|
||||
}
|
||||
|
||||
@@ -172,14 +172,10 @@ public class TestClick extends TestBase {
|
||||
void shouldNotWaitWithForce() {
|
||||
page.navigate(server.PREFIX + "/input/button.html");
|
||||
page.evalOnSelector("button", "b => b.style.display = 'none'");
|
||||
Exception exception = null;
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
page.click("button", new Page.ClickOptions().setForce(true));
|
||||
} catch (PlaywrightException e) {
|
||||
exception = e;
|
||||
}
|
||||
assertNotNull(exception);
|
||||
assertTrue(exception.getMessage().contains("Element is not visible"));
|
||||
});
|
||||
assertTrue(e.getMessage().contains("Element is not visible"));
|
||||
assertEquals("Was not clicked", page.evaluate("result"));
|
||||
}
|
||||
|
||||
@@ -428,8 +424,8 @@ public class TestClick extends TestBase {
|
||||
int expectedY = 18;
|
||||
if (isWebKit()) {
|
||||
// WebKit rounds up during css -> dip -> css conversion.
|
||||
expectedX = 29;
|
||||
expectedY = 19;
|
||||
expectedX = 26;
|
||||
expectedY = 17;
|
||||
} else if (isChromium() && !headful) {
|
||||
// Headless Chromium rounds down during css -> dip -> css conversion.
|
||||
expectedX = 27;
|
||||
@@ -564,12 +560,10 @@ public class TestClick extends TestBase {
|
||||
page.evaluate("addButton()");
|
||||
ElementHandle handle = page.querySelector("button");
|
||||
page.evaluate("stopButton(true)");
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
handle.click(new ElementHandle.ClickOptions().setForce(true));
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Element is not attached to the DOM"));
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("Element is not attached to the DOM"));
|
||||
assertEquals(null, page.evaluate("window.clicked"));
|
||||
}
|
||||
|
||||
|
||||
@@ -82,8 +82,8 @@ public class TestDefaultBrowserContext2 extends TestBase {
|
||||
@Test
|
||||
void shouldSupportLocaleOption() {
|
||||
Page page = launchPersistent(new BrowserType.LaunchPersistentContextOptions()
|
||||
.setLocale("fr-CH"));
|
||||
assertEquals("fr-CH", page.evaluate("navigator.language"));
|
||||
.setLocale("fr-FR"));
|
||||
assertEquals("fr-FR", page.evaluate("navigator.language"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -192,12 +192,10 @@ public class TestDefaultBrowserContext2 extends TestBase {
|
||||
BrowserType.LaunchPersistentContextOptions options = new BrowserType.LaunchPersistentContextOptions()
|
||||
.setArgs(asList(server.EMPTY_PAGE));
|
||||
Path userDataDir = Files.createTempDirectory("user-data-dir-");
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
browserType.launchPersistentContext(userDataDir, options);
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("can not specify page"));
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("can not specify page"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -102,9 +102,8 @@ public class TestDownload extends TestBase {
|
||||
assertTrue(error[0].getMessage().contains("Download is starting"));
|
||||
assertEquals("about:blank", page.url());
|
||||
} else {
|
||||
assertNotNull(response[0]);
|
||||
assertEquals(200, response[0].status());
|
||||
assertEquals(server.PREFIX + "/download", page.url());
|
||||
assertNotNull(error[0]);
|
||||
assertTrue(error[0].getMessage().contains("Download is starting"));
|
||||
}
|
||||
page.close();
|
||||
}
|
||||
@@ -116,13 +115,9 @@ public class TestDownload extends TestBase {
|
||||
Download download = page.waitForDownload(() -> page.click("a"));
|
||||
assertEquals(server.PREFIX + "/downloadWithFilename", download.url());
|
||||
assertEquals("file.txt", download.suggestedFilename());
|
||||
try {
|
||||
download.path();
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(download.failure().contains("acceptDownloads"));
|
||||
assertTrue(e.getMessage().contains("acceptDownloads: true"));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> download.path());
|
||||
assertTrue(download.failure().contains("acceptDownloads"));
|
||||
assertTrue(e.getMessage().contains("acceptDownloads: true"));
|
||||
}
|
||||
}
|
||||
@Test
|
||||
@@ -243,12 +238,8 @@ public class TestDownload extends TestBase {
|
||||
Download download = page.waitForDownload(() -> page.click("a"));
|
||||
|
||||
Path userPath = Files.createTempFile("download-", ".txt");
|
||||
try {
|
||||
download.saveAs(userPath);
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Pass { acceptDownloads: true } when you are creating your browser context"));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> download.saveAs(userPath));
|
||||
assertTrue(e.getMessage().contains("Pass { acceptDownloads: true } when you are creating your browser context"));
|
||||
page.close();
|
||||
}
|
||||
|
||||
@@ -260,12 +251,8 @@ public class TestDownload extends TestBase {
|
||||
|
||||
Path userPath = Files.createTempFile("download-", ".txt");
|
||||
download.delete();
|
||||
try {
|
||||
download.saveAs(userPath);
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Target page, context or browser has been closed"), e.getMessage());
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> download.saveAs(userPath));
|
||||
assertTrue(e.getMessage().contains("Target page, context or browser has been closed"), e.getMessage());
|
||||
page.close();
|
||||
}
|
||||
|
||||
|
||||
@@ -60,12 +60,8 @@ public class TestElementHandleClick extends TestBase {
|
||||
page.navigate(server.PREFIX + "/input/button.html");
|
||||
ElementHandle button = page.querySelector("button");
|
||||
page.evaluate("button => button.remove()", button);
|
||||
try {
|
||||
button.click();
|
||||
fail("click should throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Element is not attached to the DOM"));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> button.click());
|
||||
assertTrue(e.getMessage().contains("Element is not attached to the DOM"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -73,12 +69,10 @@ public class TestElementHandleClick extends TestBase {
|
||||
page.navigate(server.PREFIX + "/input/button.html");
|
||||
ElementHandle button = page.querySelector("button");
|
||||
page.evaluate("button => button.style.display = 'none'", button);
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
button.click(new ElementHandle.ClickOptions().setForce(true));
|
||||
fail("click should throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Element is not visible"));
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("Element is not visible"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -86,24 +80,20 @@ public class TestElementHandleClick extends TestBase {
|
||||
page.navigate(server.PREFIX + "/input/button.html");
|
||||
ElementHandle button = page.querySelector("button");
|
||||
page.evaluate("button => button.parentElement.style.display = 'none'", button);
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
button.click(new ElementHandle.ClickOptions().setForce(true));
|
||||
fail("click should throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Element is not visible"));
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("Element is not visible"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldThrowForBrElementsWithForce() {
|
||||
page.setContent("hello<br>goodbye");
|
||||
ElementHandle br = page.querySelector("br");
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
br.click(new ElementHandle.ClickOptions().setForce(true));
|
||||
fail("click should throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Element is outside of the viewport"));
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("Element is outside of the viewport"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+11
-30
@@ -57,19 +57,12 @@ public class TestElementHandleConvenience extends TestBase {
|
||||
ElementHandle handle = page.querySelector("#input");
|
||||
assertEquals("input value", handle.inputValue());
|
||||
|
||||
try {
|
||||
page.inputValue("#inner");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Node is not an <input>, <textarea> or <select> element"), e.getMessage());
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.inputValue("#inner"));
|
||||
assertTrue(e.getMessage().contains("Node is not an <input>, <textarea> or <select> element"), e.getMessage());
|
||||
|
||||
ElementHandle handle2 = page.querySelector("#inner");
|
||||
try {
|
||||
handle2.inputValue();
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Node is not an <input>, <textarea> or <select> element"), e.getMessage());
|
||||
}
|
||||
e = assertThrows(PlaywrightException.class, () -> handle2.inputValue());
|
||||
assertTrue(e.getMessage().contains("Node is not an <input>, <textarea> or <select> element"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -91,19 +84,11 @@ public class TestElementHandleConvenience extends TestBase {
|
||||
@Test
|
||||
void innerTextShouldThrow() {
|
||||
page.setContent("<svg>text</svg>");
|
||||
try {
|
||||
page.innerText("svg");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Node is not an HTMLElement"), e.getMessage());
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.innerText("svg"));
|
||||
assertTrue(e.getMessage().contains("Node is not an HTMLElement"), e.getMessage());
|
||||
ElementHandle handle = page.querySelector("svg");
|
||||
try {
|
||||
handle.innerText();
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Node is not an HTMLElement"), e.getMessage());
|
||||
}
|
||||
e = assertThrows(PlaywrightException.class, () -> handle.innerText());
|
||||
assertTrue(e.getMessage().contains("Node is not an HTMLElement"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -267,11 +252,7 @@ public class TestElementHandleConvenience extends TestBase {
|
||||
handle.evaluate("input => input.checked = false");
|
||||
assertFalse(handle.isChecked());
|
||||
assertFalse(page.isChecked("input"));
|
||||
try {
|
||||
page.isChecked("div");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Not a checkbox or radio button"));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.isChecked("div"));
|
||||
assertTrue(e.getMessage().contains("Not a checkbox or radio button"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,12 +47,10 @@ public class TestElementHandleSelectText extends TestBase {
|
||||
page.navigate(server.PREFIX + "/input/textarea.html");
|
||||
ElementHandle textarea = page.querySelector("textarea");
|
||||
textarea.evaluate("e => e.style.display = 'none'");
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
textarea.selectText(new ElementHandle.SelectTextOptions().setTimeout(3000));
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("element is not visible"));
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("element is not visible"));
|
||||
}
|
||||
|
||||
// @Test
|
||||
|
||||
+8
-19
@@ -20,8 +20,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.DisabledIf;
|
||||
|
||||
import static com.microsoft.playwright.options.ElementState.*;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestElementHandleWaitForElementState extends TestBase {
|
||||
|
||||
@@ -51,12 +50,10 @@ public class TestElementHandleWaitForElementState extends TestBase {
|
||||
void shouldTimeoutWaitingForVisible() {
|
||||
page.setContent("<div style='display:none'>content</div>");
|
||||
ElementHandle div = page.querySelector("div");
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
div.waitForElementState(VISIBLE, new ElementHandle.WaitForElementStateOptions().setTimeout(1000));
|
||||
fail("did not throw");
|
||||
} catch (TimeoutError e) {
|
||||
assertTrue(e.getMessage().contains("Timeout 1000ms exceeded"));
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("Timeout 1000ms exceeded"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -64,12 +61,8 @@ public class TestElementHandleWaitForElementState extends TestBase {
|
||||
page.setContent("<div style='display:none'>content</div>");
|
||||
ElementHandle div = page.querySelector("div");
|
||||
div.evaluate("div => div.remove()");
|
||||
try {
|
||||
div.waitForElementState(VISIBLE);
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Element is not attached to the DOM"));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> div.waitForElementState(VISIBLE));
|
||||
assertTrue(e.getMessage().contains("Element is not attached to the DOM"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -111,12 +104,8 @@ public class TestElementHandleWaitForElementState extends TestBase {
|
||||
page.setContent("<button disabled>Target</button>");
|
||||
ElementHandle button = page.querySelector("button");
|
||||
button.evaluate("button => button.remove()");
|
||||
try {
|
||||
button.waitForElementState(ENABLED);
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Element is not attached to the DOM"));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> button.waitForElementState(ENABLED));
|
||||
assertTrue(e.getMessage().contains("Element is not attached to the DOM"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -119,12 +119,10 @@ public class TestEvalOnSelector extends TestBase {
|
||||
|
||||
@Test
|
||||
void shouldThrowErrorIfNoElementIsFound() {
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
page.evalOnSelector("section", "e => e.id");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("failed to find element matching selector \"section\""));
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("failed to find element matching selector \"section\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -166,23 +164,20 @@ public class TestEvalOnSelector extends TestBase {
|
||||
|
||||
@Test
|
||||
void shouldThrowOnMultipleCaptures() {
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
page.evalOnSelector("*css=div >> *css=span", "e => e.outerHTML");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Only one of the selectors can capture using * modifier"));
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("Only one of the selectors can capture using * modifier"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldThrowOnMalformedCapture() {
|
||||
try {
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> {
|
||||
page.evalOnSelector("*=div", "e => e.outerHTML");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("Unknown engine \"\" while parsing selector *=div"));
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("Unknown engine \"\" while parsing selector *=div"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldWorkWithSpacesInCssAttributes() {
|
||||
page.setContent("<div><input placeholder='Select date'></div>");
|
||||
|
||||
@@ -21,8 +21,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIf;
|
||||
|
||||
import static com.microsoft.playwright.Utils.mapOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestFirefoxLauncher extends TestBase {
|
||||
|
||||
@@ -47,11 +46,7 @@ public class TestFirefoxLauncher extends TestBase {
|
||||
"network.proxy.http_port", 3333));
|
||||
launchBrowser(options);
|
||||
Page page = browser.newPage();
|
||||
try {
|
||||
page.navigate("http://example.com");
|
||||
fail("did not throw");
|
||||
} catch (PlaywrightException e) {
|
||||
assertTrue(e.getMessage().contains("NS_ERROR_PROXY_CONNECTION_REFUSED"));
|
||||
}
|
||||
PlaywrightException e = assertThrows(PlaywrightException.class, () -> page.navigate("http://example.com"));
|
||||
assertTrue(e.getMessage().contains("NS_ERROR_PROXY_CONNECTION_REFUSED"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,8 +19,7 @@ package com.microsoft.playwright;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static com.microsoft.playwright.options.WaitUntilState.NETWORKIDLE;
|
||||
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 TestFrameNavigate extends TestBase {
|
||||
|
||||
@@ -43,12 +42,11 @@ public class TestFrameNavigate extends TestBase {
|
||||
void shouldContinueAfterClientRedirect() {
|
||||
server.setRoute("/frames/script.js", (httpExchange) -> {});
|
||||
String url = server.PREFIX + "/frames/child-redirect.html";
|
||||
try {
|
||||
TimeoutError e = assertThrows(TimeoutError.class, () -> {
|
||||
page.navigate(url, new Page.NavigateOptions().setTimeout(5000).setWaitUntil(NETWORKIDLE));
|
||||
} catch (TimeoutError e) {
|
||||
assertTrue(e.getMessage().contains("Timeout 5000ms exceeded."));
|
||||
assertTrue(e.getMessage().contains("navigating to \"" + url +"\", waiting until \"networkidle\""));
|
||||
}
|
||||
});
|
||||
assertTrue(e.getMessage().contains("Timeout 5000ms exceeded."));
|
||||
assertTrue(e.getMessage().contains("navigating to \"" + url +"\", waiting until \"networkidle\""));
|
||||
}
|
||||
|
||||
// TODO: not supported in sync api
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user