Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -57,6 +58,8 @@ public APIRequestContextImpl newContext(NewContextOptions options) {
}
PlaywrightNewRequestParams.PlaywrightNewRequestParamsStorageState storageState = storageStateJson == null ? null :
gson().fromJson(storageStateJson, PlaywrightNewRequestParams.PlaywrightNewRequestParamsStorageState.class);
Path defaultTracesDir = playwright.defaultLaunchOptions != null ? playwright.defaultLaunchOptions.tracesDir : null;
Path tracesDir = defaultTracesDir != null ? defaultTracesDir.toAbsolutePath().normalize() : null;
Map<String, String> extraHTTPHeaders = options.extraHTTPHeaders;
List<ClientCertificate> clientCertificates = options.clientCertificates;
Object httpCredentials = options.httpCredentials;
Expand All @@ -69,15 +72,14 @@ public APIRequestContextImpl newContext(NewContextOptions options) {
PlaywrightNewRequestParams params = Utils.toProtocol(options, PlaywrightNewRequestParams.class);
params.extraHTTPHeaders = extraHTTPHeaders != null ? Headers.headersObjectToArray(extraHTTPHeaders) : null;
params.storageState = storageState;
// We do not expose tracesDir in the API, so do not allow options to accidentally override it.
params.tracesDir = playwright.defaultLaunchOptions != null && playwright.defaultLaunchOptions.tracesDir != null ? playwright.defaultLaunchOptions.tracesDir.toString() : null;
params.tracesDir = tracesDir != null ? tracesDir.toString() : null;
params.clientCertificates = BrowserContextImpl.toClientCertificatesProtocol(clientCertificates);
params.httpCredentials = BrowserContextImpl.toHttpCredentialsProtocol(httpCredentials);
APIRequestContextImpl context = playwright.channel.newRequest(params, NO_TIMEOUT).request;
contexts.add(context);
context.request = this;
context.timeoutSettings.setDefaultTimeout(options.timeout != null ? options.timeout : playwright.defaultContextTimeout);
context.tracing.tracesDir = playwright.defaultLaunchOptions != null ? playwright.defaultLaunchOptions.tracesDir : null;
context.tracing.tracesDir = tracesDir;
context.instrumentation.runAfterCreateRequestContext(context);
return context;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,16 @@ public String name() {

@Override
public BrowserImpl launch(LaunchOptions options) {
LaunchOptions userOptions = options == null ? new LaunchOptions() : options;
LaunchOptions userOptions = options == null ? new LaunchOptions() : Utils.clone(options);
return wrapApiCall(() -> {
// java: the userDataDir and port asserts are not ported, LaunchOptions has no such fields.

// java: LaunchOptions has no logger, so options.logger and _defaultLaunchOptions?.logger are always unset.
Object logger = null;
LaunchOptions launchOptions = withDefaults(playwright.defaultLaunchOptions, userOptions, LaunchOptions.class);
if (launchOptions.tracesDir != null) {
launchOptions.tracesDir = launchOptions.tracesDir.toAbsolutePath().normalize();
}
BrowserTypeLaunchParams params = toLaunchParams(launchOptions);
BrowserImpl browser = channel.launch(params, new TimeoutSettings().launchTimeout(launchOptions.timeout)).browser;
browser.connectToBrowserType(this, launchOptions, logger);
Expand All @@ -108,11 +111,14 @@ BrowserServer launchServer(LaunchOptions options) {

@Override
public BrowserContextImpl launchPersistentContext(Path userDataDir, LaunchPersistentContextOptions options) {
LaunchPersistentContextOptions userOptions = options == null ? new LaunchPersistentContextOptions() : options;
LaunchPersistentContextOptions userOptions = options == null ? new LaunchPersistentContextOptions() : Utils.clone(options);
return wrapApiCall(() -> {
// java: the port assert is not ported, LaunchPersistentContextOptions has no such field.
// java: _withSelectorOptions, the Java options have no selector fields, so they are set on the params below.
LaunchPersistentContextOptions persistentOptions = withDefaults(playwright.defaultLaunchOptions, userOptions, LaunchPersistentContextOptions.class);
if (persistentOptions.tracesDir != null) {
persistentOptions.tracesDir = persistentOptions.tracesDir.toAbsolutePath().normalize();
}
instrumentation.runBeforeCreateBrowserContext(persistentOptions);

// java: LaunchPersistentContextOptions has no logger, so options.logger and _defaultLaunchOptions?.logger are always unset.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import com.microsoft.playwright.options.HttpHeader;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
Expand All @@ -49,7 +50,7 @@ class HarRouter {

static HarRouter create(LocalUtils localUtils, String file, HarNotFound notFoundAction, Object urlMatch) {
LocalUtilsHarOpenParams params = new LocalUtilsHarOpenParams();
params.file = file;
params.file = Paths.get(file).toAbsolutePath().normalize().toString();
LocalUtilsHarOpenResult result = localUtils.harOpen(params);
if (result.error != null) {
throw new PlaywrightException(result.error);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ class LongStandingScope {
private final ChannelOwner owner;
private PlaywrightException terminateError;
private PlaywrightException closeError;
// java: the frames are a Java stack trace.
private final Map<WaitableResult<PlaywrightException>, StackTraceElement[]> terminatePromises = new LinkedHashMap<>();
// java: captured errors hold a Java stack trace.
private final Map<WaitableResult<PlaywrightException>, Exception> terminatePromises = new LinkedHashMap<>();
private boolean isClosed = false;

LongStandingScope(ChannelOwner owner) {
Expand All @@ -52,7 +52,7 @@ void reject(PlaywrightException error) {
void close(PlaywrightException error) {
isClosed = true;
closeError = error;
for (Map.Entry<WaitableResult<PlaywrightException>, StackTraceElement[]> entry : new ArrayList<>(terminatePromises.entrySet()))
for (Map.Entry<WaitableResult<PlaywrightException>, Exception> entry : new ArrayList<>(terminatePromises.entrySet()))
entry.getKey().complete(cloneError(error, entry.getValue()));
}

Expand Down Expand Up @@ -92,12 +92,12 @@ <T> T safeRace(Waitable<T> promise, T defaultValue) {

private <T> Waitable<T> race(List<Waitable<T>> promises, boolean safe, T defaultValue) {
WaitableResult<PlaywrightException> terminatePromise = new WaitableResult<>();
StackTraceElement[] frames = new Exception().getStackTrace();
Exception capturedError = new Exception();
if (terminateError != null)
terminatePromise.complete(terminateError);
if (closeError != null)
terminatePromise.complete(cloneError(closeError, frames));
terminatePromises.put(terminatePromise, frames);
terminatePromise.complete(cloneError(closeError, capturedError));
terminatePromises.put(terminatePromise, capturedError);
List<Waitable<T>> race = new ArrayList<>();
// java: the promises go first, a settled promise wins over a closed scope as its reaction runs first upstream.
race.addAll(promises);
Expand Down Expand Up @@ -125,7 +125,8 @@ public void dispose() {
// java: no signalToPromise, it serves AbortSignal.

// java: a new exception of the same type, with the frames of the race as its stack trace.
private static PlaywrightException cloneError(PlaywrightException error, StackTraceElement[] frames) {
private static PlaywrightException cloneError(PlaywrightException error, Exception capturedError) {
StackTraceElement[] frames = capturedError.getStackTrace();
PlaywrightException clone = error instanceof TargetClosedError ? new TargetClosedError(error.getMessage()) : new PlaywrightException(error.getMessage());
clone.setStackTrace(frames);
return clone;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,15 +161,15 @@ public void stop(StopOptions options) {
}

@Override
public AutoCloseable startHar(Path path, StartHarOptions options) {
public AutoCloseable startHar(Path harPath, StartHarOptions options) {
StartHarOptions o = options == null ? new StartHarOptions() : options;
return wrapApiCall(() -> {
if (harId != null) {
throw new PlaywrightException("HAR recording has already been started");
}
// java: StartHarOptions has no resourcesDir, so there is no check of resourcesDir with a .zip har file.
HarContentPolicy defaultContent = isZip(path) ? HarContentPolicy.ATTACH : HarContentPolicy.EMBED;
harId = recordIntoHAR(path, null,
HarContentPolicy defaultContent = isZip(harPath) ? HarContentPolicy.ATTACH : HarContentPolicy.EMBED;
harId = recordIntoHAR(harPath, null,
o.urlFilter,
o.content != null ? o.content : defaultContent,
o.mode != null ? o.mode : HarMode.FULL,
Expand All @@ -192,6 +192,8 @@ public void stopHar() {

// java: the options object of upstream is positional, url is a String glob or a Pattern.
String recordIntoHAR(Path har, PageImpl page, Object url, HarContentPolicy updateContent, HarMode updateMode, Path resourcesDir) {
har = har.toAbsolutePath().normalize();
resourcesDir = resourcesDir != null ? resourcesDir.toAbsolutePath().normalize() : null;
boolean isZip = isZip(har);
TracingHarStartParams params = new TracingHarStartParams();
params.page = page;
Expand Down Expand Up @@ -309,6 +311,7 @@ private void saveChunk(Path filePath, String stacksId, List<String> additionalSo
throw new PlaywrightException("Cannot save trace in thin clients");
}

filePath = filePath.toAbsolutePath().normalize();
boolean isLocal = !connection.isRemote();

if (isLocal) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,9 @@ void shouldSetCookiesWithSameSiteAttributeAndNoSecureAttribute(BrowserContext co
if (!(browserName == BrowserName.CHROMIUM || (browserName == BrowserName.WEBKIT && (Env.isLinux || "webkit-wsl".equals(Env.channel()))) || Env.isBidi()))
expected.add(cookie("same-site-none", "1", "foo.com", "/", -1.0, false, false, SameSiteAttribute.NONE));
expected.add(cookie("same-site-lax", "1", "foo.com", "/", -1.0, false, false,
(browserName == BrowserName.WEBKIT && Env.isWindows && !"webkit-wsl".equals(Env.channel())) ? SameSiteAttribute.NONE : SameSiteAttribute.LAX));
SameSiteAttribute.LAX));
expected.add(cookie("same-site-strict", "1", "foo.com", "/", -1.0, false, false,
(browserName == BrowserName.WEBKIT && Env.isWindows && !"webkit-wsl".equals(Env.channel())) ? SameSiteAttribute.NONE : SameSiteAttribute.STRICT));
SameSiteAttribute.STRICT));
assertCookiesAnyOrder(expected, cookies);
}

Expand Down Expand Up @@ -378,11 +378,17 @@ void shouldSetCookieWithReasonableDefaults(BrowserContext context, TestServer se
List<Cookie> cookies = context.cookies();
cookies.sort((a, b) -> a.name.compareTo(b.name));
assertCookies(Arrays.asList(cookie("defaults", "123456", server.HOSTNAME, "/", -1.0, false, false, defaultSameSiteCookieValue)), cookies);

context.addCookies(Arrays.asList(
new Cookie("default-path", "test").setUrl(server.PREFIX + "/foo/bar")));
assertEquals("/foo", context.cookies().stream().filter(cookie -> cookie.name.equals("default-path")).findFirst().get().path);
assertEquals(Arrays.asList("default-path", "defaults"),
context.cookies(server.PREFIX + "/foo").stream().map(cookie -> cookie.name).sorted().collect(java.util.stream.Collectors.toList()));
}

@PlaywrightTest
@DisplayName("CO-033 should set a cookie with a path")
void shouldSetACookieWithAPath(BrowserContext context, Page page, TestServer server, BrowserName browserName) {
void shouldSetACookieWithAPath(BrowserContext context, Page page, TestServer server) {
page.navigate(server.PREFIX + "/grid.html");
context.addCookies(Arrays.asList(
new Cookie("gridcookie", "GRID")
Expand All @@ -391,7 +397,7 @@ void shouldSetACookieWithAPath(BrowserContext context, Page page, TestServer ser
.setSameSite(SameSiteAttribute.LAX)));
assertCookies(Arrays.asList(
cookie("gridcookie", "GRID", server.HOSTNAME, "/grid.html", -1.0, false, false,
(browserName == BrowserName.WEBKIT && Env.isWindows && !"webkit-wsl".equals(Env.channel())) ? SameSiteAttribute.NONE : SameSiteAttribute.LAX)),
SameSiteAttribute.LAX)),
context.cookies());
assertEquals("gridcookie=GRID", page.evaluate("document.cookie"));
page.navigate(server.EMPTY_PAGE);
Expand Down Expand Up @@ -450,7 +456,7 @@ void shouldBeAbleToSetUnsecureCookieForHTTPWebsite(BrowserContext context, Page

@PlaywrightTest
@DisplayName("CO-038 should set a cookie on a different domain")
void shouldSetACookieOnADifferentDomain(BrowserContext context, Page page, TestServer server, BrowserName browserName) {
void shouldSetACookieOnADifferentDomain(BrowserContext context, Page page, TestServer server) {
page.navigate(server.EMPTY_PAGE);
context.addCookies(Arrays.asList(
new Cookie("example-cookie", "best")
Expand All @@ -459,7 +465,7 @@ void shouldSetACookieOnADifferentDomain(BrowserContext context, Page page, TestS
assertEquals("", page.evaluate("document.cookie"));
assertCookies(Arrays.asList(
cookie("example-cookie", "best", "www.example.com", "/", -1.0, false, true,
(browserName == BrowserName.WEBKIT && Env.isWindows && !"webkit-wsl".equals(Env.channel())) ? SameSiteAttribute.NONE : SameSiteAttribute.LAX)),
SameSiteAttribute.LAX)),
context.cookies("https://www.example.com"));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,9 +197,7 @@ void shouldProperlyReportHttpOnlyCookie(BrowserContext context, Page page, TestS

@PlaywrightTest
@DisplayName("CO-006 should properly report \"Strict\" sameSite cookie")
void shouldProperlyReportStrictSameSiteCookie(BrowserContext context, Page page, TestServer server, BrowserName browserName) {
assumeFalse(browserName == BrowserName.WEBKIT && Env.platform().equals("win32") && !"webkit-wsl".equals(Env.channel()), "fail: webkit on Windows reports the sameSite attribute differently");

void shouldProperlyReportStrictSameSiteCookie(BrowserContext context, Page page, TestServer server) {
server.setRoute("/empty.html", (req, res) -> {
res.setHeader("Set-Cookie", "name=value;SameSite=Strict");
res.end();
Expand All @@ -212,9 +210,7 @@ void shouldProperlyReportStrictSameSiteCookie(BrowserContext context, Page page,

@PlaywrightTest
@DisplayName("CO-007 should properly report \"Lax\" sameSite cookie")
void shouldProperlyReportLaxSameSiteCookie(BrowserContext context, Page page, TestServer server, BrowserName browserName) {
assumeFalse(browserName == BrowserName.WEBKIT && Env.platform().equals("win32") && !"webkit-wsl".equals(Env.channel()), "fail: webkit on Windows reports the sameSite attribute differently");

void shouldProperlyReportLaxSameSiteCookie(BrowserContext context, Page page, TestServer server) {
server.setRoute("/empty.html", (req, res) -> {
res.setHeader("Set-Cookie", "name=value;SameSite=Lax");
res.end();
Expand Down Expand Up @@ -244,21 +240,21 @@ void shouldGetMultipleCookies(BrowserContext context, Page page, TestServer serv

@PlaywrightTest
@DisplayName("CO-009 should get cookies from multiple urls")
void shouldGetCookiesFromMultipleUrls(BrowserContext context, BrowserName browserName) {
void shouldGetCookiesFromMultipleUrls(BrowserContext context) {
context.addCookies(Arrays.asList(
new Cookie("doggo", "woofs").setUrl("https://foo.com").setSameSite(SameSiteAttribute.NONE),
new Cookie("catto", "purrs").setUrl("https://bar.com").setSameSite(SameSiteAttribute.LAX),
new Cookie("birdo", "tweets").setUrl("https://baz.com").setSameSite(SameSiteAttribute.LAX)));
List<Cookie> cookies = context.cookies(Arrays.asList("https://foo.com", "https://baz.com"));
assertCookiesAnyOrder(Arrays.asList(
cookie("birdo", "tweets", "baz.com", "/", -1.0, false, true,
(browserName == BrowserName.WEBKIT && Env.isWindows && !"webkit-wsl".equals(Env.channel())) ? SameSiteAttribute.NONE : SameSiteAttribute.LAX),
SameSiteAttribute.LAX),
cookie("doggo", "woofs", "foo.com", "/", -1.0, false, true, SameSiteAttribute.NONE)), cookies);
}

@PlaywrightTest
@DisplayName("CO-010 should work with subdomain cookie")
void shouldWorkWithSubdomainCookie(BrowserContext context, BrowserName browserName) {
void shouldWorkWithSubdomainCookie(BrowserContext context) {
context.addCookies(Arrays.asList(
new Cookie("doggo", "woofs")
.setDomain(".foo.com")
Expand All @@ -267,11 +263,11 @@ void shouldWorkWithSubdomainCookie(BrowserContext context, BrowserName browserNa
.setSecure(true)));
assertCookies(Arrays.asList(
cookie("doggo", "woofs", ".foo.com", "/", -1.0, false, true,
(browserName == BrowserName.WEBKIT && Env.isWindows && !"webkit-wsl".equals(Env.channel())) ? SameSiteAttribute.NONE : SameSiteAttribute.LAX)),
SameSiteAttribute.LAX)),
context.cookies("https://foo.com"));
assertCookies(Arrays.asList(
cookie("doggo", "woofs", ".foo.com", "/", -1.0, false, true,
(browserName == BrowserName.WEBKIT && Env.isWindows && !"webkit-wsl".equals(Env.channel())) ? SameSiteAttribute.NONE : SameSiteAttribute.LAX)),
SameSiteAttribute.LAX)),
context.cookies("https://sub.foo.com"));
}

Expand Down Expand Up @@ -311,19 +307,19 @@ void shouldReturnCookiesWithEmptyValue(BrowserContext context, Page page, TestSe

@PlaywrightTest
@DisplayName("CO-013 should return secure cookies based on HTTP(S) protocol")
void shouldReturnSecureCookiesBasedOnHTTPSProtocol(BrowserContext context, BrowserName browserName) {
void shouldReturnSecureCookiesBasedOnHTTPSProtocol(BrowserContext context) {
context.addCookies(Arrays.asList(
new Cookie("doggo", "woofs").setUrl("https://foo.com").setSameSite(SameSiteAttribute.LAX).setSecure(true),
new Cookie("catto", "purrs").setUrl("http://foo.com").setSameSite(SameSiteAttribute.LAX).setSecure(false)));
List<Cookie> cookies = context.cookies("https://foo.com");
assertCookiesAnyOrder(Arrays.asList(
cookie("catto", "purrs", "foo.com", "/", -1.0, false, false,
(browserName == BrowserName.WEBKIT && Env.isWindows && !"webkit-wsl".equals(Env.channel())) ? SameSiteAttribute.NONE : SameSiteAttribute.LAX),
SameSiteAttribute.LAX),
cookie("doggo", "woofs", "foo.com", "/", -1.0, false, true,
(browserName == BrowserName.WEBKIT && Env.isWindows && !"webkit-wsl".equals(Env.channel())) ? SameSiteAttribute.NONE : SameSiteAttribute.LAX)), cookies);
SameSiteAttribute.LAX)), cookies);
assertCookies(Arrays.asList(
cookie("catto", "purrs", "foo.com", "/", -1.0, false, false,
(browserName == BrowserName.WEBKIT && Env.isWindows && !"webkit-wsl".equals(Env.channel())) ? SameSiteAttribute.NONE : SameSiteAttribute.LAX)),
SameSiteAttribute.LAX)),
context.cookies("http://foo.com/"));
}

Expand Down
Loading
Loading