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
10 changes: 10 additions & 0 deletions playwright/src/main/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ Java code around the place it goes to, and write the new lines the same way.
One upstream file can have several Java files, one per class (`network.ts` is `RequestImpl`,
`ResponseImpl`, `RouteImpl`, `WebSocketImpl`, ...). A new upstream file is a new Java file
with that header.
- The assertions are the port of `packages/playwright/src/matchers`: `matchers.ts` is
`LocatorAssertionsImpl`, `PageAssertionsImpl` and `APIResponseAssertionsImpl`; `toBeTruthy.ts`,
`toEqual.ts`, `toMatchText.ts`, `toMatchAriaSnapshot.ts` and `matcherHint.ts` are the classes
of the same name; `AssertionsBase` is the call of a matcher from `expect.ts`. The `utils` of a
matcher are `MatcherUtils`: jest is not ported: the values are printed in the same layout, and
where upstream prints a diff both values are printed in full. A failure message has the upstream layout with the
Java call: `assertThat(locator).not().hasText(expected) failed` for
`expect(locator).not.toHaveText(expected) failed`, and the title `Assert "hasText"`.
- `isomorphic/locatorGenerators.ts` and the selector parser are not ported: `Locator.toString()`
asks the driver (`LocalUtils.asLocatorDescription`, language `java`).
- A class that implements a public interface is `<Name>Impl` (`Page` is `PageImpl`). A
helper class keeps the upstream name (`Waiter`, `HarRouter`, `TimeoutSettings`).
- The members keep the upstream order. A new upstream member goes where it is in the `.ts` file,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,26 @@
* limitations under the License.
*/

// Port of matchers.ts.
package com.microsoft.playwright.impl;

import com.microsoft.playwright.impl.protocol.*;
import com.microsoft.playwright.APIResponse;
import com.microsoft.playwright.assertions.APIResponseAssertions;
import org.opentest4j.AssertionFailedError;
import com.microsoft.playwright.impl.MatcherHint.MatcherMessageDetails;
import com.microsoft.playwright.impl.MatcherHint.MatcherResult;

import java.util.List;
import java.util.regex.Pattern;

public class APIResponseAssertionsImpl implements APIResponseAssertions {
private final APIResponse actual;
private final boolean isNot;
import static com.microsoft.playwright.impl.MatcherHint.formatMatcherMessage;

// java: the matcher of an APIResponse, see LocatorAssertionsImpl.
public class APIResponseAssertionsImpl extends AssertionsBase implements APIResponseAssertions {
private final APIResponseImpl actual;

APIResponseAssertionsImpl(APIResponse response, boolean isNot) {
this.actual = response;
this.isNot = isNot;
super(isNot);
this.actual = (APIResponseImpl) response;
}

public APIResponseAssertionsImpl(APIResponse response) {
Expand All @@ -44,31 +47,39 @@ public APIResponseAssertions not() {

@Override
public void isOK() {
if (actual.ok() == !isNot) {
return;
}
String message = "Response status expected to be within [200..299] range, was " + actual.status();
if (isNot) {
message = message.replace("expected to", "expected not to");
}
List<String> logList = ((APIResponseImpl) actual).fetchLog();
String log = String.join("\n", logList);
if (!log.isEmpty()) {
log = "\nCall log:\n" + log;
}
callMatcherAsStep("isOK", state -> {
APIResponseImpl response = actual;
String matcherName = "isOK";

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);
String contentType = response.headers().get("content-type");
boolean isTextEncoding = contentType != null && !contentType.isEmpty() && isTextualMimeType(contentType);
List<String> log = null;
String text = null;
if (state.isNot == response.ok()) {
log = response.fetchLog();
text = isTextEncoding ? response.text() : null;
}
}

throw new AssertionFailedError(message + log + responseText);
List<String> finalLog = log;
String finalText = text;
MatcherResult result = new MatcherResult();
result.message = () -> {
MatcherMessageDetails details = new MatcherMessageDetails();
details.isNot = state.isNot;
details.promise = state.promise;
details.matcherName = matcherName;
details.receiver = "response";
details.expectation = "";
details.log = finalLog;
return formatMatcherMessage(details) + (finalText == null ? "" : "\nResponse text:\n" + (finalText.length() > 1000 ? finalText.substring(0, 1000) : finalText));
};

result.pass = response.ok();
return result;
});
}

// java: isTextualMimeType of isomorphic/mimeType.ts.
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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,105 +14,82 @@
* limitations under the License.
*/

// Port of expect.ts.
package com.microsoft.playwright.impl;

import com.microsoft.playwright.impl.protocol.*;
import com.microsoft.playwright.impl.MatcherHint.MatcherResult;
import org.opentest4j.AssertionFailedError;
import org.opentest4j.ValueWrapper;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.microsoft.playwright.impl.Utils.toJsRegexFlags;
import static java.util.Arrays.asList;

// java: only the call of a matcher is ported: callMatcherAsStep and invokeMatcher. The expect function, its
// configuration, the custom, soft, poll and promise matchers and the steps belong to the test runner.
abstract class AssertionsBase {
final boolean isNot;

AssertionsBase(boolean isNot) {
this.isNot = isNot;
}

void expectImpl(String expression, ExpectedTextValue textValue, Object expected, String message, FrameExpectOptions options, String title) {
expectImpl(expression, asList(textValue), expected, message, options, title);
// java: the fields of ExpectMatcherStateInternal that the matchers read, utils is MatcherUtils.
static class ExpectMatcherState {
boolean isNot;
String promise;
double timeout;
String title;
}

void expectImpl(String expression, List<ExpectedTextValue> expectedText, Object expected, String message, FrameExpectOptions options, String title) {
if (options == null) {
options = new FrameExpectOptions();
}
options.expectedText = expectedText;
expectImpl(expression, options, expected, message, title);
// java: the type of a matcher bound to its receiver and arguments.
interface RawMatcherFn {
MatcherResult call(ExpectMatcherState state);
}

void expectImpl(String expression, FrameExpectOptions expectOptions, Object expected, String message, String title) {
if (expectOptions.timeout == null) {
expectOptions.timeout = AssertionsTimeout.defaultTimeout;
}
expectOptions.isNot = isNot;
if (isNot) {
message = message.replace("expected to", "expected not to");
}
FrameExpectResult result = doExpect(expression, expectOptions, title);
if (result.matches == isNot) {
Object actual;
if (result.received == null) {
actual = null;
} else if (result.received.value != null) {
actual = Serialization.deserialize(result.received.value);
} else {
actual = result.received.ariaSnapshot;
}
String log = (result.log == null) ? "" : String.join("\n", result.log);
if (!log.isEmpty()) {
log = "\nCall log:\n" + log;
}
if (result.errorMessage != null) {
message += "\n" + result.errorMessage;
}
if (expected == null) {
throw new AssertionFailedError(message + log);
}
ValueWrapper expectedValue = formatValue(expected);
ValueWrapper actualValue = formatValue(actual);
message += "\nExpected: " + expectedValue.getStringRepresentation() + "\nReceived: " + actualValue.getStringRepresentation() + "\n";
throw new AssertionFailedError(message + log, expectedValue, actualValue);
// java: the type of the query argument of toBeTruthy, toEqual and toMatchText.
interface Query {
FrameExpectResult query(boolean isNot, double timeout);
}

void callMatcherAsStep(String matcherName, RawMatcherFn matcher) {
// java: no custom message and no title suffix, escapeWithQuotes has nothing to escape in a matcher name.
String defaultTitle = (isNot ? "not " : "") + matcherName;
// java: the title of the Java client is Assert, with the Java name of the matcher.
String title = "Assert \"" + defaultTitle + "\"";

MatcherResult result = invokeMatcher(matcherName, matcher, title);
if (result.pass == isNot) {
// java: ExpectError is an AssertionFailedError with the expected and the actual value of the result.
String message = result.message.get();
if (result.expected == null && (result.actual == null || result.actual == MatcherUtils.UNDEFINED))
throw new AssertionFailedError(message);
throw new AssertionFailedError(message, formatValue(result.expected), formatValue(result.actual));
}
}

abstract FrameExpectResult doExpect(String expression, FrameExpectOptions expectOptions, String title);
private MatcherResult invokeMatcher(String matcherName, RawMatcherFn matcher, String title) {
double timeout = AssertionsTimeout.defaultTimeout;
ExpectMatcherState matcherContext = new ExpectMatcherState();
matcherContext.isNot = isNot;
matcherContext.promise = "";
matcherContext.timeout = timeout;
matcherContext.title = title;

return matcher.call(matcherContext);
}

// java: a helper with no counterpart upstream, the value of an AssertionFailedError.
protected static ValueWrapper formatValue(Object value) {
if (value == MatcherUtils.UNDEFINED) {
return ValueWrapper.create(null);
}
if (value == null || !value.getClass().isArray()) {
return ValueWrapper.create(value);
}
Collection<String> values = asList((Object[]) value).stream().map(e -> e.toString()).collect(Collectors.toList());
String stringRepresentation = "[" + String.join(", ", values) + "]";
return ValueWrapper.create(value, stringRepresentation);
}

static ExpectedTextValue expectedRegex(Pattern pattern) {
ExpectedTextValue expected = new ExpectedTextValue();
expected.regexSource = pattern.pattern();
if (pattern.flags() != 0) {
expected.regexFlags = toJsRegexFlags(pattern);
}
return expected;
}

static Boolean shouldIgnoreCase(Object options) {
if (options == null) {
return null;
}
try {
Field fromField = options.getClass().getDeclaredField("ignoreCase");
Object value = fromField.get(options);
return (Boolean) value;
} catch (NoSuchFieldException | IllegalAccessException e) {
return null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,20 @@
package com.microsoft.playwright.impl;

import com.microsoft.playwright.impl.protocol.ExpectedTextValue;
import com.microsoft.playwright.impl.protocol.SerializedArgument;
import com.microsoft.playwright.options.PseudoElement;

import java.util.List;

// java: the options of Frame._expect, FrameExpectParams of types.ts.
// java: the options of Frame._expect: FrameExpectParams of types.ts with the timeout and the title.
class FrameExpectOptions {
Object expressionArg;
List<ExpectedTextValue> expectedText;
String selector;
Double expectedNumber;
SerializedArgument expectedValue;
Object expectedValue;
Boolean useInnerText;
PseudoElement pseudo;
boolean isNot;
Double timeout;
double timeout;
String title;
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,18 @@

package com.microsoft.playwright.impl;

import com.microsoft.playwright.impl.protocol.FrameExpectErrorDetails;

import java.util.List;

// java: ExpectResult of frame.ts; the command has no result, a mismatch arrives as an error with FrameExpectErrorDetails.
// java: ExpectResult and ExpectReceived of frame.ts.
class FrameExpectResult {
boolean matches;
FrameExpectErrorDetails.FrameExpectErrorDetailsReceived received;
String errorMessage;
ExpectReceived received;
List<String> log;
Boolean timedOut;
String errorMessage;

static class ExpectReceived {
Object value;
String ariaSnapshot;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import static com.microsoft.playwright.impl.isomorphic.LocatorUtils.*;
import static com.microsoft.playwright.impl.Serialization.deserialize;
import static com.microsoft.playwright.impl.Serialization.gson;
import static com.microsoft.playwright.impl.Serialization.parseResult;
import static com.microsoft.playwright.impl.Serialization.assertEvaluateOptions;
import static com.microsoft.playwright.impl.Serialization.serializeArgument;
import static com.microsoft.playwright.impl.Serialization.serializeArgumentWithCallbacks;
Expand Down Expand Up @@ -915,25 +916,42 @@ public String title() {
return channel.title(NO_TIMEOUT).value;
}

// java: the title is a parameter, the options are the seed FrameExpectOptions, the result the seed FrameExpectResult.
FrameExpectResult expect(String expression, FrameExpectOptions options, String title) {
// java: the options are FrameExpectOptions, the result is FrameExpectResult.
FrameExpectResult expect(String expression, FrameExpectOptions options) {
double timeout = options.timeout;
String title = options.title;
return wrapApiCall(() -> {
FrameExpectParams params = toProtocol(this, options, FrameExpectParams.class);
// java: ...rest is one assignment per field, expectedValue is not a protocol value before it is serialized.
FrameExpectParams params = new FrameExpectParams();
params.expression = expression;
params.selector = options.selector;
params.expressionArg = options.expressionArg == null ? null : gson().toJsonTree(options.expressionArg);
params.pseudo = options.pseudo == null ? null : gson().toJsonTree(options.pseudo).getAsString();
params.expectedText = options.expectedText;
params.expectedNumber = options.expectedNumber;
params.useInnerText = options.useInnerText;
params.isNot = options.isNot;
// java: expectedValue is serialized by the assertion classes.
FrameExpectResult result = new FrameExpectResult();
params.expectedValue = serializeArgument(options.expectedValue);
try {
channel.expect(params, options.timeout);
channel.expect(params, timeout);
FrameExpectResult result = new FrameExpectResult();
result.matches = !params.isNot;
return result;
} catch (ServerErrorWithDetails e) {
// java: no AbortSignal, so no AbortError branch; only errors with details are expect mismatches.
// java: no AbortSignal, so no AbortError branch; only an error with details is a PlaywrightError of the server.
FrameExpectErrorDetails details = gson().fromJson(e.errorDetails(), FrameExpectErrorDetails.class);
FrameExpectResult.ExpectReceived received = null;
if (details.received != null) {
received = new FrameExpectResult.ExpectReceived();
// java: an undefined value is MatcherUtils.UNDEFINED, null is the JavaScript null.
received.value = details.received.value != null && !"undefined".equals(details.received.value.v) ? parseResult(details.received.value) : MatcherUtils.UNDEFINED;
received.ariaSnapshot = details.received.ariaSnapshot;
}
FrameExpectResult result = new FrameExpectResult();
result.matches = params.isNot;
// java: AssertionsBase parses the received value, FrameExpectResult has no timedOut.
result.received = details.received;
result.received = received;
result.log = e.log();
result.timedOut = details.timedOut;
result.errorMessage = details.customErrorMessage != null ? "Error: " + details.customErrorMessage : null;
return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,14 @@ JsonArray deviceDescriptors() {
return initializer.getAsJsonArray("deviceDescriptors");
}

// java: the locator generators run on the driver, with the Java language.
String asLocatorDescription(String selector) {
LocalUtilsAsLocatorDescriptionParams params = new LocalUtilsAsLocatorDescriptionParams();
params.selector = selector;
params.sdkLanguage = "java";
return wrapApiCall(() -> channel.asLocatorDescription(params, NO_TIMEOUT).description, null, true);
}

// java: the Java API matches globs on the driver.
public Pattern globToRegex(String glob, String baseURL, boolean webSocketUrl) {
LocalUtilsGlobToRegexParams params = new LocalUtilsGlobToRegexParams();
Expand Down
Loading
Loading