From 91e6148da76612cca6a3f47915c910bd9e996cc4 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Mon, 23 Nov 2026 12:22:11 -0800 Subject: [PATCH 1/6] chore: port the locator generators Locator.toString() prints the Java locator code from the selector, without a server round trip. --- .../playwright/impl/LocatorImpl.java | 32 +- .../playwright/impl/isomorphic/CssParser.java | 363 +++++++ .../impl/isomorphic/CssTokenizer.java | 995 ++++++++++++++++++ .../impl/isomorphic/LocatorGenerators.java | 559 ++++++++++ .../playwright/impl/isomorphic/RegExp.java | 92 ++ .../impl/isomorphic/SelectorParser.java | 529 ++++++++++ .../impl/isomorphic/StringUtils.java | 52 +- .../playwright/TestLocatorConvenience.java | 8 +- .../playwright/TestLocatorGenerators.java | 288 +++++ .../tests/page/TestLocatorAnyFrame.java | 2 +- .../tests/page/TestLocatorConvenience.java | 4 +- 11 files changed, 2891 insertions(+), 33 deletions(-) create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssParser.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssTokenizer.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorGenerators.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/RegExp.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/SelectorParser.java create mode 100644 playwright/src/test/java/com/microsoft/playwright/TestLocatorGenerators.java diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java index 0bfca68f2..99731bbb2 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java @@ -34,6 +34,8 @@ import java.util.regex.Pattern; import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; +import static com.microsoft.playwright.impl.isomorphic.LocatorGenerators.asLocatorDescription; +import static com.microsoft.playwright.impl.isomorphic.LocatorGenerators.locatorCustomDescription; import static com.microsoft.playwright.impl.isomorphic.LocatorUtils.*; import static com.microsoft.playwright.impl.Serialization.gson; import static com.microsoft.playwright.impl.Serialization.serializeArgument; @@ -355,18 +357,10 @@ public Locator describe(String description) { return new LocatorImpl(frame, selector + " >> internal:describe=" + gson().toJson(description)); } - // java: there is no port of the selector parser; this matches the trailing internal:describe part - // that upstream locatorCustomDescription() reads. @Override public String description() { - Matcher matcher = Pattern.compile(" >> internal:describe=(\"(?:[^\"\\\\]|\\\\.)*\")$").matcher(selector); - if (!matcher.find()) - return null; - try { - return gson().fromJson(matcher.group(1), String.class); - } catch (RuntimeException e) { - return null; - } + String description = locatorCustomDescription(selector); + return description == null || description.isEmpty() ? null : description; } @Override @@ -420,16 +414,12 @@ public int count() { return frame.queryCount(selector); } - // java: sends sdkLanguage so that toString() prints the Java locator code the server returns. @Override public Locator normalize() { FrameResolveSelectorParams params = new FrameResolveSelectorParams(); params.selector = selector; - params.sdkLanguage = "java"; FrameResolveSelectorResult result = frame.channel.resolveSelector(params, NO_TIMEOUT); - LocatorImpl locator = new LocatorImpl(frame, result.resolvedSelector); - locator.stringRepresentation = result.locatorCode; - return locator; + return new LocatorImpl(frame, result.resolvedSelector); } @Override @@ -709,16 +699,10 @@ FrameExpectResult expect(String expression, FrameExpectOptions options, String t // java: no _inspect, it serves inspect.custom. - // java: there is no port of the locator generators. The text of the old Java client is kept, - // tests pin it: the server's Java locator code after normalize(), the description, or Locator@. + // java: the language is java, not javascript: the Java client prints Java locator code. @Override public String toString() { - if (stringRepresentation != null) - return stringRepresentation; - String description = description(); - if (description != null) - return description; - return "Locator@" + selector; + return asLocatorDescription("java", selector); } // java: the module-level _testIdAttributeName is SelectorsImpl.testIdAttributeName of the Playwright instance, @@ -754,8 +738,6 @@ static String cssObjectToString(Map style) { } // java: helpers and members with no upstream counterpart. - private String stringRepresentation; - private Frame.SelectOptionOptions frameSelectOptionOptions(SelectOptionOptions options) { if (options == null) options = new SelectOptionOptions(); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssParser.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssParser.java new file mode 100644 index 000000000..1afaefe59 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssParser.java @@ -0,0 +1,363 @@ +/* + * 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. + */ + +// Port of isomorphic/cssParser.ts. +package com.microsoft.playwright.impl.isomorphic; + +import com.microsoft.playwright.PlaywrightException; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +// java: the types of the file are nested classes. A CSSFunctionArgument is an Object holding a CSSComplexSelector, +// a Double or a String. serializeSelector is not ported, the locator generators do not use it. +public final class CssParser { + private CssParser() { + } + + public static class InvalidSelectorError extends PlaywrightException { + public InvalidSelectorError(String message) { + super(message); + } + } + + public static boolean isInvalidSelectorError(Throwable error) { + return error instanceof InvalidSelectorError; + } + + public static class CSSFunction { + public String name; + public List args; + + CSSFunction(String name, List args) { + this.name = name; + this.args = args; + } + } + + public static class CSSSimpleSelector { + public String css; + public List functions; + + CSSSimpleSelector(String css, List functions) { + this.css = css; + this.functions = functions; + } + } + + // java: the type of an item of CSSComplexSelector.simples. + public static class CSSSimple { + public CSSSimpleSelector selector; + public String combinator; + + CSSSimple(CSSSimpleSelector selector, String combinator) { + this.selector = selector; + this.combinator = combinator; + } + } + + public static class CSSComplexSelector { + public List simples = new ArrayList<>(); + } + + // java: the object that parseCSS() returns. + public static class ParsedCSS { + public List selector; + public List names; + } + + public static ParsedCSS parseCSS(String selector, Set customNames) { + List tokens; + try { + tokens = CssTokenizer.tokenize(selector); + // java: the item before the first one of an empty list is undefined upstream. + if (tokens.isEmpty() || !(tokens.get(tokens.size() - 1) instanceof CssTokenizer.EOFToken)) + tokens.add(new CssTokenizer.EOFToken()); + } catch (RuntimeException e) { + // java: the message of an exception is final, so a new exception with the new message wraps the caught one. + String newMessage = e.getMessage() + " while parsing css selector \"" + selector + "\". Did you mean to CSS.escape it?"; + throw new PlaywrightException(newMessage, e); + } + CssTokenizer.CSSTokenInterface unsupportedToken = null; + for (CssTokenizer.CSSTokenInterface token : tokens) { + if ((token instanceof CssTokenizer.AtKeywordToken) || + (token instanceof CssTokenizer.BadStringToken) || + (token instanceof CssTokenizer.BadURLToken) || + (token instanceof CssTokenizer.ColumnToken) || + (token instanceof CssTokenizer.CDOToken) || + (token instanceof CssTokenizer.CDCToken) || + (token instanceof CssTokenizer.SemicolonToken) || + (token instanceof CssTokenizer.OpenCurlyToken) || + (token instanceof CssTokenizer.CloseCurlyToken) || + (token instanceof CssTokenizer.URLToken) || + (token instanceof CssTokenizer.PercentageToken)) { + unsupportedToken = token; + break; + } + } + if (unsupportedToken != null) + throw new InvalidSelectorError("Unsupported token \"" + unsupportedToken.toSource() + "\" while parsing css selector \"" + selector + "\". Did you mean to CSS.escape it?"); + + Parser parser = new Parser(selector, customNames, tokens); + List result = parser.consumeFunctionArguments(); + if (!parser.isEOF()) + throw parser.unexpected(); + List complexSelectors = new ArrayList<>(); + for (Object arg : result) { + if (!(arg instanceof CSSComplexSelector)) + throw new InvalidSelectorError("Error while parsing css selector \"" + selector + "\". Did you mean to CSS.escape it?"); + complexSelectors.add((CSSComplexSelector) arg); + } + ParsedCSS parsed = new ParsedCSS(); + parsed.selector = complexSelectors; + parsed.names = new ArrayList<>(parser.names); + return parsed; + } + + // java: the local variables and the nested functions of parseCSS() are the fields and the methods of this class. + private static class Parser { + private final String selector; + private final Set customNames; + private final List tokens; + private int pos = 0; + private final Set names = new LinkedHashSet<>(); + + Parser(String selector, Set customNames, List tokens) { + this.selector = selector; + this.customNames = customNames; + this.tokens = tokens; + } + + InvalidSelectorError unexpected() { + return new InvalidSelectorError("Unexpected token \"" + tokens.get(pos).toSource() + "\" while parsing css selector \"" + selector + "\". Did you mean to CSS.escape it?"); + } + + void skipWhitespace() { + while (tokens.get(pos) instanceof CssTokenizer.WhitespaceToken) + pos++; + } + + boolean isIdent() { + return isIdent(pos); + } + + boolean isIdent(int p) { + return tokens.get(p) instanceof CssTokenizer.IdentToken; + } + + boolean isString() { + return isString(pos); + } + + boolean isString(int p) { + return tokens.get(p) instanceof CssTokenizer.StringToken; + } + + boolean isNumber() { + return isNumber(pos); + } + + boolean isNumber(int p) { + return tokens.get(p) instanceof CssTokenizer.NumberToken; + } + + boolean isComma() { + return isComma(pos); + } + + boolean isComma(int p) { + return tokens.get(p) instanceof CssTokenizer.CommaToken; + } + + boolean isOpenParen() { + return isOpenParen(pos); + } + + boolean isOpenParen(int p) { + return tokens.get(p) instanceof CssTokenizer.OpenParenToken; + } + + boolean isCloseParen() { + return isCloseParen(pos); + } + + boolean isCloseParen(int p) { + return tokens.get(p) instanceof CssTokenizer.CloseParenToken; + } + + boolean isFunction() { + return isFunction(pos); + } + + boolean isFunction(int p) { + return tokens.get(p) instanceof CssTokenizer.FunctionToken; + } + + boolean isStar() { + return isStar(pos); + } + + boolean isStar(int p) { + return (tokens.get(p) instanceof CssTokenizer.DelimToken) && "*".equals(tokens.get(p).value()); + } + + boolean isEOF() { + return isEOF(pos); + } + + boolean isEOF(int p) { + return tokens.get(p) instanceof CssTokenizer.EOFToken; + } + + boolean isClauseCombinator() { + return isClauseCombinator(pos); + } + + boolean isClauseCombinator(int p) { + return (tokens.get(p) instanceof CssTokenizer.DelimToken) && (Arrays.asList(">", "+", "~").contains((String) tokens.get(p).value())); + } + + boolean isSelectorClauseEnd() { + return isSelectorClauseEnd(pos); + } + + boolean isSelectorClauseEnd(int p) { + return isComma(p) || isCloseParen(p) || isEOF(p) || isClauseCombinator(p) || (tokens.get(p) instanceof CssTokenizer.WhitespaceToken); + } + + List consumeFunctionArguments() { + List result = new ArrayList<>(); + result.add(consumeArgument()); + while (true) { + skipWhitespace(); + if (!isComma()) + break; + pos++; + result.add(consumeArgument()); + } + return result; + } + + Object consumeArgument() { + skipWhitespace(); + if (isNumber()) + return tokens.get(pos++).value(); + if (isString()) + return tokens.get(pos++).value(); + return consumeComplexSelector(); + } + + CSSComplexSelector consumeComplexSelector() { + CSSComplexSelector result = new CSSComplexSelector(); + skipWhitespace(); + if (isClauseCombinator()) { + List functions = new ArrayList<>(); + functions.add(new CSSFunction("scope", new ArrayList<>())); + result.simples.add(new CSSSimple(new CSSSimpleSelector(null, functions), "")); + } else { + result.simples.add(new CSSSimple(consumeSimpleSelector(), "")); + } + while (true) { + skipWhitespace(); + if (isClauseCombinator()) { + result.simples.get(result.simples.size() - 1).combinator = (String) tokens.get(pos++).value(); + skipWhitespace(); + } else if (isSelectorClauseEnd()) { + break; + } + result.simples.add(new CSSSimple(consumeSimpleSelector(), "")); + } + return result; + } + + CSSSimpleSelector consumeSimpleSelector() { + String rawCSSString = ""; + List functions = new ArrayList<>(); + + while (!isSelectorClauseEnd()) { + if (isIdent() || isStar()) { + rawCSSString += tokens.get(pos++).toSource(); + } else if (tokens.get(pos) instanceof CssTokenizer.HashToken) { + rawCSSString += tokens.get(pos++).toSource(); + } else if ((tokens.get(pos) instanceof CssTokenizer.DelimToken) && ".".equals(tokens.get(pos).value())) { + pos++; + if (isIdent()) + rawCSSString += "." + tokens.get(pos++).toSource(); + else + throw unexpected(); + } else if (tokens.get(pos) instanceof CssTokenizer.ColonToken) { + pos++; + if (isIdent()) { + if (!customNames.contains(((String) tokens.get(pos).value()).toLowerCase(Locale.ROOT))) { + rawCSSString += ":" + tokens.get(pos++).toSource(); + } else { + String name = ((String) tokens.get(pos++).value()).toLowerCase(Locale.ROOT); + functions.add(new CSSFunction(name, new ArrayList<>())); + names.add(name); + } + } else if (isFunction()) { + String name = ((String) tokens.get(pos++).value()).toLowerCase(Locale.ROOT); + if (!customNames.contains(name)) { + rawCSSString += ":" + name + "(" + consumeBuiltinFunctionArguments() + ")"; + } else { + functions.add(new CSSFunction(name, consumeFunctionArguments())); + names.add(name); + } + skipWhitespace(); + if (!isCloseParen()) + throw unexpected(); + pos++; + } else { + throw unexpected(); + } + } else if (tokens.get(pos) instanceof CssTokenizer.OpenSquareToken) { + rawCSSString += "["; + pos++; + while (!(tokens.get(pos) instanceof CssTokenizer.CloseSquareToken) && !isEOF()) + rawCSSString += tokens.get(pos++).toSource(); + if (!(tokens.get(pos) instanceof CssTokenizer.CloseSquareToken)) + throw unexpected(); + rawCSSString += "]"; + pos++; + } else { + throw unexpected(); + } + } + if (rawCSSString.isEmpty() && functions.isEmpty()) + throw unexpected(); + return new CSSSimpleSelector(rawCSSString.isEmpty() ? null : rawCSSString, functions); + } + + String consumeBuiltinFunctionArguments() { + String s = ""; + int balance = 1; + while (!isEOF()) { + if (isOpenParen() || isFunction()) + balance++; + if (isCloseParen()) + balance--; + if (balance == 0) + break; + s += tokens.get(pos++).toSource(); + } + return s; + } + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssTokenizer.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssTokenizer.java new file mode 100644 index 000000000..5d1d01d2e --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssTokenizer.java @@ -0,0 +1,995 @@ +/* + * The code in this file is licensed under the CC0 license. + * http://creativecommons.org/publicdomain/zero/1.0/ + * It is free to use for any purpose. No attribution, permission, or reproduction of this license is required. + */ + +// Port of isomorphic/cssTokenizer.ts. +package com.microsoft.playwright.impl.isomorphic; + +import com.microsoft.playwright.PlaywrightException; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +// java: the token classes are nested classes of this class. A code point is an int, -1 where upstream reads NaN. +// A number value is a Double. toJSON is not ported. +public final class CssTokenizer { + private CssTokenizer() { + } + + // java: the value property is a method. + public interface CSSTokenInterface { + String toSource(); + Object value(); + } + + private static boolean between(int num, int first, int last) { return num >= first && num <= last; } + private static boolean digit(int code) { return between(code, 0x30, 0x39); } + private static boolean hexdigit(int code) { return digit(code) || between(code, 0x41, 0x46) || between(code, 0x61, 0x66); } + private static boolean uppercaseletter(int code) { return between(code, 0x41, 0x5a); } + private static boolean lowercaseletter(int code) { return between(code, 0x61, 0x7a); } + private static boolean letter(int code) { return uppercaseletter(code) || lowercaseletter(code); } + private static boolean nonascii(int code) { return code >= 0x80; } + private static boolean namestartchar(int code) { return letter(code) || nonascii(code) || code == 0x5f; } + private static boolean namechar(int code) { return namestartchar(code) || digit(code) || code == 0x2d; } + private static boolean nonprintable(int code) { return between(code, 0, 8) || code == 0xb || between(code, 0xe, 0x1f) || code == 0x7f; } + private static boolean newline(int code) { return code == 0xa; } + private static boolean whitespace(int code) { return newline(code) || code == 9 || code == 0x20; } + + private static final int maximumallowedcodepoint = 0x10ffff; + + public static class InvalidCharacterError extends PlaywrightException { + public InvalidCharacterError(String message) { + super(message); + } + } + + private static List preprocess(String str) { + List codepoints = new ArrayList<>(); + for (int i = 0; i < str.length(); i++) { + int code = charCodeAt(str, i); + if (code == 0xd && charCodeAt(str, i + 1) == 0xa) { + code = 0xa; i++; + } + if (code == 0xd || code == 0xc) + code = 0xa; + if (code == 0x0) + code = 0xfffd; + if (between(code, 0xd800, 0xdbff) && between(charCodeAt(str, i + 1), 0xdc00, 0xdfff)) { + int lead = code - 0xd800; + int trail = charCodeAt(str, i + 1) - 0xdc00; + code = (1 << 16) + lead * (1 << 10) + trail; + i++; + } + codepoints.add(code); + } + return codepoints; + } + + private static String stringFromCode(int code) { + if (code <= 0xffff) + return String.valueOf((char) code); + code -= 1 << 16; + int lead = code / (1 << 10) + 0xd800; + int trail = code % (1 << 10) + 0xdc00; + return String.valueOf((char) lead) + String.valueOf((char) trail); + } + + public static List tokenize(String str1) { + return new Tokenizer(str1).tokenize(); + } + + // java: the local variables and the closures of tokenize() are the fields and the methods of this class. + private static class Tokenizer { + private final List str; + private int i = -1; + private final List tokens = new ArrayList<>(); + private int code; + + private int line = 0; + private int column = 0; + private int lastLineLength = 0; + // java: locStart is two fields. + private int locStartLine = line; + private int locStartColumn = column; + + Tokenizer(String str1) { + str = preprocess(str1); + } + + private void incrLineno() { + line += 1; + lastLineLength = column; + column = 0; + } + + private int codepoint(int i) { + if (i >= str.size()) + return -1; + + return str.get(i); + } + + private int next() { + return next(1); + } + + private int next(int num) { + if (num > 3) + throw new PlaywrightException("Spec Error: no more than three codepoints of lookahead."); + return codepoint(i + num); + } + + private boolean consume() { + return consume(1); + } + + private boolean consume(int num) { + i += num; + code = codepoint(i); + if (newline(code)) + incrLineno(); + else + column += num; + return true; + } + + private boolean reconsume() { + i -= 1; + if (newline(code)) { + line -= 1; + column = lastLineLength; + } else { + column -= 1; + } + locStartLine = line; + locStartColumn = column; + return true; + } + + private boolean eof() { + return eof(code); + } + + private boolean eof(int codepoint) { + return codepoint == -1; + } + + private void donothing() { + } + + private void parseerror() { + } + + private CSSTokenInterface consumeAToken() { + consumeComments(); + consume(); + if (whitespace(code)) { + while (whitespace(next())) + consume(); + return new WhitespaceToken(); + } else if (code == 0x22) {return consumeAStringToken();} else if (code == 0x23) { + if (namechar(next()) || areAValidEscape(next(1), next(2))) { + HashToken token = new HashToken(""); + if (wouldStartAnIdentifier(next(1), next(2), next(3))) + token.type = "id"; + token.value = consumeAName(); + return token; + } else { + return new DelimToken(code); + } + } else if (code == 0x24) { + if (next() == 0x3d) { + consume(); + return new SuffixMatchToken(); + } else { + return new DelimToken(code); + } + } else if (code == 0x27) {return consumeAStringToken();} else if (code == 0x28) {return new OpenParenToken();} else if (code == 0x29) {return new CloseParenToken();} else if (code == 0x2a) { + if (next() == 0x3d) { + consume(); + return new SubstringMatchToken(); + } else { + return new DelimToken(code); + } + } else if (code == 0x2b) { + if (startsWithANumber()) { + reconsume(); + return consumeANumericToken(); + } else { + return new DelimToken(code); + } + } else if (code == 0x2c) {return new CommaToken();} else if (code == 0x2d) { + if (startsWithANumber()) { + reconsume(); + return consumeANumericToken(); + } else if (next(1) == 0x2d && next(2) == 0x3e) { + consume(2); + return new CDCToken(); + } else if (startsWithAnIdentifier()) { + reconsume(); + return consumeAnIdentlikeToken(); + } else { + return new DelimToken(code); + } + } else if (code == 0x2e) { + if (startsWithANumber()) { + reconsume(); + return consumeANumericToken(); + } else { + return new DelimToken(code); + } + } else if (code == 0x3a) {return new ColonToken();} else if (code == 0x3b) {return new SemicolonToken();} else if (code == 0x3c) { + if (next(1) == 0x21 && next(2) == 0x2d && next(3) == 0x2d) { + consume(3); + return new CDOToken(); + } else { + return new DelimToken(code); + } + } else if (code == 0x40) { + if (wouldStartAnIdentifier(next(1), next(2), next(3))) + return new AtKeywordToken(consumeAName()); + else + return new DelimToken(code); + + } else if (code == 0x5b) {return new OpenSquareToken();} else if (code == 0x5c) { + if (startsWithAValidEscape()) { + reconsume(); + return consumeAnIdentlikeToken(); + } else { + parseerror(); + return new DelimToken(code); + } + } else if (code == 0x5d) {return new CloseSquareToken();} else if (code == 0x5e) { + if (next() == 0x3d) { + consume(); + return new PrefixMatchToken(); + } else { + return new DelimToken(code); + } + } else if (code == 0x7b) {return new OpenCurlyToken();} else if (code == 0x7c) { + if (next() == 0x3d) { + consume(); + return new DashMatchToken(); + } else if (next() == 0x7c) { + consume(); + return new ColumnToken(); + } else { + return new DelimToken(code); + } + } else if (code == 0x7d) {return new CloseCurlyToken();} else if (code == 0x7e) { + if (next() == 0x3d) { + consume(); + return new IncludeMatchToken(); + } else { + return new DelimToken(code); + } + } else if (digit(code)) { + reconsume(); + return consumeANumericToken(); + } else if (namestartchar(code)) { + reconsume(); + return consumeAnIdentlikeToken(); + } else if (eof()) {return new EOFToken();} else {return new DelimToken(code);} + } + + private void consumeComments() { + while (next(1) == 0x2f && next(2) == 0x2a) { + consume(2); + while (true) { + consume(); + if (code == 0x2a && next() == 0x2f) { + consume(); + break; + } else if (eof()) { + parseerror(); + return; + } + } + } + } + + private CSSTokenInterface consumeANumericToken() { + ConsumedNumber num = consumeANumber(); + if (wouldStartAnIdentifier(next(1), next(2), next(3))) { + DimensionToken token = new DimensionToken(); + token.value = num.value; + token.repr = num.repr; + token.type = num.type; + token.unit = consumeAName(); + return token; + } else if (next() == 0x25) { + consume(); + PercentageToken token = new PercentageToken(); + token.value = num.value; + token.repr = num.repr; + return token; + } else { + NumberToken token = new NumberToken(); + token.value = num.value; + token.repr = num.repr; + token.type = num.type; + return token; + } + } + + private CSSTokenInterface consumeAnIdentlikeToken() { + String str = consumeAName(); + if (str.toLowerCase(Locale.ROOT).equals("url") && next() == 0x28) { + consume(); + while (whitespace(next(1)) && whitespace(next(2))) + consume(); + if (next() == 0x22 || next() == 0x27) + return new FunctionToken(str); + else if (whitespace(next()) && (next(2) == 0x22 || next(2) == 0x27)) + return new FunctionToken(str); + else + return consumeAURLToken(); + + } else if (next() == 0x28) { + consume(); + return new FunctionToken(str); + } else { + return new IdentToken(str); + } + } + + private CSSParserToken consumeAStringToken() { + return consumeAStringToken(code); + } + + private CSSParserToken consumeAStringToken(int endingCodePoint) { + String string = ""; + while (consume()) { + if (code == endingCodePoint || eof()) { + return new StringToken(string); + } else if (newline(code)) { + parseerror(); + reconsume(); + return new BadStringToken(); + } else if (code == 0x5c) { + if (eof(next())) + donothing(); + else if (newline(next())) + consume(); + else + string += stringFromCode(consumeEscape()); + + } else { + string += stringFromCode(code); + } + } + throw new PlaywrightException("Internal error"); + } + + private CSSTokenInterface consumeAURLToken() { + URLToken token = new URLToken(""); + while (whitespace(next())) + consume(); + if (eof(next())) + return token; + while (consume()) { + if (code == 0x29 || eof()) { + return token; + } else if (whitespace(code)) { + while (whitespace(next())) + consume(); + if (next() == 0x29 || eof(next())) { + consume(); + return token; + } else { + consumeTheRemnantsOfABadURL(); + return new BadURLToken(); + } + } else if (code == 0x22 || code == 0x27 || code == 0x28 || nonprintable(code)) { + parseerror(); + consumeTheRemnantsOfABadURL(); + return new BadURLToken(); + } else if (code == 0x5c) { + if (startsWithAValidEscape()) { + token.value = token.value + stringFromCode(consumeEscape()); + } else { + parseerror(); + consumeTheRemnantsOfABadURL(); + return new BadURLToken(); + } + } else { + token.value = token.value + stringFromCode(code); + } + } + throw new PlaywrightException("Internal error"); + } + + private int consumeEscape() { + consume(); + if (hexdigit(code)) { + List digits = new ArrayList<>(); + digits.add(code); + for (int total = 0; total < 5; total++) { + if (hexdigit(next())) { + consume(); + digits.add(code); + } else { + break; + } + } + if (whitespace(next())) + consume(); + StringBuilder joined = new StringBuilder(); + for (int x : digits) + joined.append((char) x); + int value = Integer.parseInt(joined.toString(), 16); + if (value > maximumallowedcodepoint) + value = 0xfffd; + return value; + } else if (eof()) { + return 0xfffd; + } else { + return code; + } + } + + private boolean areAValidEscape(int c1, int c2) { + if (c1 != 0x5c) + return false; + if (newline(c2)) + return false; + return true; + } + + private boolean startsWithAValidEscape() { + return areAValidEscape(code, next()); + } + + private boolean wouldStartAnIdentifier(int c1, int c2, int c3) { + if (c1 == 0x2d) + return namestartchar(c2) || c2 == 0x2d || areAValidEscape(c2, c3); + else if (namestartchar(c1)) + return true; + else if (c1 == 0x5c) + return areAValidEscape(c1, c2); + else + return false; + + } + + private boolean startsWithAnIdentifier() { + return wouldStartAnIdentifier(code, next(1), next(2)); + } + + private boolean wouldStartANumber(int c1, int c2, int c3) { + if (c1 == 0x2b || c1 == 0x2d) { + if (digit(c2)) + return true; + if (c2 == 0x2e && digit(c3)) + return true; + return false; + } else if (c1 == 0x2e) { + if (digit(c2)) + return true; + return false; + } else if (digit(c1)) { + return true; + } else { + return false; + } + } + + private boolean startsWithANumber() { + return wouldStartANumber(code, next(1), next(2)); + } + + private String consumeAName() { + String result = ""; + while (consume()) { + if (namechar(code)) { + result += stringFromCode(code); + } else if (startsWithAValidEscape()) { + result += stringFromCode(consumeEscape()); + } else { + reconsume(); + return result; + } + } + throw new PlaywrightException("Internal parse error"); + } + + private ConsumedNumber consumeANumber() { + String repr = ""; + String type = "integer"; + if (next() == 0x2b || next() == 0x2d) { + consume(); + repr += stringFromCode(code); + } + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + if (next(1) == 0x2e && digit(next(2))) { + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + type = "number"; + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + } + int c1 = next(1); + int c2 = next(2); + int c3 = next(3); + if ((c1 == 0x45 || c1 == 0x65) && digit(c2)) { + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + type = "number"; + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + } else if ((c1 == 0x45 || c1 == 0x65) && (c2 == 0x2b || c2 == 0x2d) && digit(c3)) { + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + type = "number"; + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + } + double value = convertAStringToANumber(repr); + ConsumedNumber result = new ConsumedNumber(); + result.type = type; + result.value = value; + result.repr = repr; + return result; + } + + // java: the repr is a decimal literal with a digit after the dot, which Double.parseDouble reads like the unary plus. + private double convertAStringToANumber(String string) { + return Double.parseDouble(string); + } + + private void consumeTheRemnantsOfABadURL() { + while (consume()) { + if (code == 0x29 || eof()) { + return; + } else if (startsWithAValidEscape()) { + consumeEscape(); + donothing(); + } else { + donothing(); + } + } + } + + List tokenize() { + int iterationCount = 0; + while (!eof(next())) { + tokens.add(consumeAToken()); + iterationCount++; + if (iterationCount > str.size() * 2) + throw new PlaywrightException("I'm infinite-looping!"); + } + return tokens; + } + } + + // java: the object that consumeANumber() returns. + private static class ConsumedNumber { + String type; + double value; + String repr; + } + + // java: a subclass sets tokenType and value in an initializer block or in its constructor. + public static class CSSParserToken implements CSSTokenInterface { + String tokenType = ""; + Object value; + @Override + public String toString() { return tokenType; } + @Override + public String toSource() { return "" + this; } + @Override + public Object value() { return value; } + } + + public static class BadStringToken extends CSSParserToken { + { tokenType = "BADSTRING"; } + } + + public static class BadURLToken extends CSSParserToken { + { tokenType = "BADURL"; } + } + + public static class WhitespaceToken extends CSSParserToken { + { tokenType = "WHITESPACE"; } + @Override + public String toString() { return "WS"; } + @Override + public String toSource() { return " "; } + } + + public static class CDOToken extends CSSParserToken { + { tokenType = "CDO"; } + @Override + public String toSource() { return ""; } + } + + public static class ColonToken extends CSSParserToken { + { tokenType = ":"; } + } + + public static class SemicolonToken extends CSSParserToken { + { tokenType = ";"; } + } + + public static class CommaToken extends CSSParserToken { + { tokenType = ","; } + } + + public static class GroupingToken extends CSSParserToken { + { value = ""; } + String mirror = ""; + } + + public static class OpenCurlyToken extends GroupingToken { + { tokenType = "{"; } + public OpenCurlyToken() { + super(); + this.value = "{"; + this.mirror = "}"; + } + } + + public static class CloseCurlyToken extends GroupingToken { + { tokenType = "}"; } + public CloseCurlyToken() { + super(); + this.value = "}"; + this.mirror = "{"; + } + } + + public static class OpenSquareToken extends GroupingToken { + { tokenType = "["; } + public OpenSquareToken() { + super(); + this.value = "["; + this.mirror = "]"; + } + } + + public static class CloseSquareToken extends GroupingToken { + { tokenType = "]"; } + public CloseSquareToken() { + super(); + this.value = "]"; + this.mirror = "["; + } + } + + public static class OpenParenToken extends GroupingToken { + { tokenType = "("; } + public OpenParenToken() { + super(); + this.value = "("; + this.mirror = ")"; + } + } + + public static class CloseParenToken extends GroupingToken { + { tokenType = ")"; } + public CloseParenToken() { + super(); + this.value = ")"; + this.mirror = "("; + } + } + + public static class IncludeMatchToken extends CSSParserToken { + { tokenType = "~="; } + } + + public static class DashMatchToken extends CSSParserToken { + { tokenType = "|="; } + } + + public static class PrefixMatchToken extends CSSParserToken { + { tokenType = "^="; } + } + + public static class SuffixMatchToken extends CSSParserToken { + { tokenType = "$="; } + } + + public static class SubstringMatchToken extends CSSParserToken { + { tokenType = "*="; } + } + + public static class ColumnToken extends CSSParserToken { + { tokenType = "||"; } + } + + public static class EOFToken extends CSSParserToken { + { tokenType = "EOF"; } + @Override + public String toSource() { return ""; } + } + + public static class DelimToken extends CSSParserToken { + { tokenType = "DELIM"; } + + public DelimToken(int code) { + super(); + this.value = stringFromCode(code); + } + + @Override + public String toString() { return "DELIM(" + this.value + ")"; } + + @Override + public String toSource() { + if (this.value.equals("\\")) + return "\\\n"; + else + return (String) this.value; + } + } + + public abstract static class StringValuedToken extends CSSParserToken { + { value = ""; } + public boolean ASCIIMatch(String str) { + return ((String) this.value).toLowerCase(Locale.ROOT).equals(str.toLowerCase(Locale.ROOT)); + } + } + + public static class IdentToken extends StringValuedToken { + public IdentToken(String val) { + super(); + this.value = val; + } + + { tokenType = "IDENT"; } + @Override + public String toString() { return "IDENT(" + this.value + ")"; } + @Override + public String toSource() { + return escapeIdent((String) this.value); + } + } + + public static class FunctionToken extends StringValuedToken { + { tokenType = "FUNCTION"; } + String mirror; + public FunctionToken(String val) { + super(); + this.value = val; + this.mirror = ")"; + } + + @Override + public String toString() { return "FUNCTION(" + this.value + ")"; } + + @Override + public String toSource() { + return escapeIdent((String) this.value) + "("; + } + } + + public static class AtKeywordToken extends StringValuedToken { + { tokenType = "AT-KEYWORD"; } + public AtKeywordToken(String val) { + super(); + this.value = val; + } + @Override + public String toString() { return "AT(" + this.value + ")"; } + @Override + public String toSource() { + return "@" + escapeIdent((String) this.value); + } + } + + public static class HashToken extends StringValuedToken { + { tokenType = "HASH"; } + String type; + public HashToken(String val) { + super(); + this.value = val; + this.type = "unrestricted"; + } + + @Override + public String toString() { return "HASH(" + this.value + ")"; } + + @Override + public String toSource() { + if (this.type.equals("id")) + return "#" + escapeIdent((String) this.value); + else + return "#" + escapeHash((String) this.value); + + } + } + + public static class StringToken extends StringValuedToken { + { tokenType = "STRING"; } + public StringToken(String val) { + super(); + this.value = val; + } + + @Override + public String toString() { + return "\"" + escapeString((String) this.value) + "\""; + } + } + + public static class URLToken extends StringValuedToken { + { tokenType = "URL"; } + public URLToken(String val) { + super(); + this.value = val; + } + @Override + public String toString() { return "URL(" + this.value + ")"; } + @Override + public String toSource() { + return "url(\"" + escapeString((String) this.value) + "\")"; + } + } + + public static class NumberToken extends CSSParserToken { + { tokenType = "NUMBER"; } + String type; + String repr; + + public NumberToken() { + super(); + this.type = "integer"; + this.repr = ""; + } + + @Override + public String toString() { + if (this.type.equals("integer")) + return "INT(" + this.value + ")"; + return "NUMBER(" + this.value + ")"; + } + @Override + public String toSource() { return this.repr; } + } + + + public static class PercentageToken extends CSSParserToken { + { tokenType = "PERCENTAGE"; } + String repr; + public PercentageToken() { + super(); + this.repr = ""; + } + @Override + public String toString() { return "PERCENTAGE(" + this.value + ")"; } + @Override + public String toSource() { return this.repr + "%"; } + } + + public static class DimensionToken extends CSSParserToken { + { tokenType = "DIMENSION"; } + String type; + String repr; + String unit; + + public DimensionToken() { + super(); + this.type = "integer"; + this.repr = ""; + this.unit = ""; + } + + @Override + public String toString() { return "DIM(" + this.value + "," + this.unit + ")"; } + @Override + public String toSource() { + String source = this.repr; + String unit = escapeIdent(this.unit); + if (unit.substring(0, 1).toLowerCase(Locale.ROOT).equals("e") && (charCodeAt(unit, 1) == '-' || between(charCodeAt(unit, 1), 0x30, 0x39))) { + unit = "\\65 " + unit.substring(1, unit.length()); + } + return source + unit; + } + } + + private static String escapeIdent(String string) { + String result = ""; + int firstcode = charCodeAt(string, 0); + for (int i = 0; i < string.length(); i++) { + int code = charCodeAt(string, i); + if (code == 0x0) + throw new InvalidCharacterError("Invalid character: the input contains U+0000."); + + if ( + between(code, 0x1, 0x1f) || code == 0x7f || + (i == 0 && between(code, 0x30, 0x39)) || + (i == 1 && between(code, 0x30, 0x39) && firstcode == 0x2d) + ) + result += "\\" + Integer.toString(code, 16) + " "; + else if ( + code >= 0x80 || + code == 0x2d || + code == 0x5f || + between(code, 0x30, 0x39) || + between(code, 0x41, 0x5a) || + between(code, 0x61, 0x7a) + ) + result += string.charAt(i); + else + result += "\\" + string.charAt(i); + + } + return result; + } + + private static String escapeHash(String string) { + String result = ""; + for (int i = 0; i < string.length(); i++) { + int code = charCodeAt(string, i); + if (code == 0x0) + throw new InvalidCharacterError("Invalid character: the input contains U+0000."); + + if ( + code >= 0x80 || + code == 0x2d || + code == 0x5f || + between(code, 0x30, 0x39) || + between(code, 0x41, 0x5a) || + between(code, 0x61, 0x7a) + ) + result += string.charAt(i); + else + result += "\\" + Integer.toString(code, 16) + " "; + + } + return result; + } + + private static String escapeString(String string) { + String result = ""; + for (int i = 0; i < string.length(); i++) { + int code = charCodeAt(string, i); + + if (code == 0x0) + throw new InvalidCharacterError("Invalid character: the input contains U+0000."); + + if (between(code, 0x1, 0x1f) || code == 0x7f) + result += "\\" + Integer.toString(code, 16) + " "; + else if (code == 0x22 || code == 0x5c) + result += "\\" + string.charAt(i); + else + result += string.charAt(i); + + } + return result; + } + + // java: helpers with no counterpart upstream. + + // java: String.prototype.charCodeAt, -1 where it returns NaN. + private static int charCodeAt(String string, int index) { + return index < string.length() ? string.charAt(index) : -1; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorGenerators.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorGenerators.java new file mode 100644 index 000000000..a010a770a --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorGenerators.java @@ -0,0 +1,559 @@ +/* + * 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. + */ + +// Port of isomorphic/locatorGenerators.ts. +package com.microsoft.playwright.impl.isomorphic; + +import com.google.gson.JsonElement; +import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.impl.isomorphic.SelectorParser.AttributeSelector; +import com.microsoft.playwright.impl.isomorphic.SelectorParser.AttributeSelectorPart; +import com.microsoft.playwright.impl.isomorphic.SelectorParser.NestedSelectorBody; +import com.microsoft.playwright.impl.isomorphic.SelectorParser.ParsedSelector; +import com.microsoft.playwright.impl.isomorphic.SelectorParser.ParsedSelectorPart; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.function.Supplier; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.microsoft.playwright.impl.isomorphic.SelectorParser.parseAttributeSelector; +import static com.microsoft.playwright.impl.isomorphic.SelectorParser.parseSelector; +import static com.microsoft.playwright.impl.isomorphic.SelectorParser.stringifySelector; +import static com.microsoft.playwright.impl.isomorphic.SelectorParser.valueToString; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.escapeWithQuotes; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.jsonParse; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.normalizeEscapedRegexQuotes; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.toNumber; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.toSnakeCase; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.toTitleCase; + +// java: only the JavaLocatorFactory is ported, the JavaScript, Python, CSharp and Jsonl factories are not: the client +// prints Java code. Language, LocatorType and LocatorBase are a String. A string | RegExp is an Object holding +// a String or a RegExp. There is no preferredQuote parameter, only the JavaScript factory reads it. +public final class LocatorGenerators { + private LocatorGenerators() { + } + + // java: the type of an item of LocatorOptions.attrs. The value is a String, a Boolean, a Double, a RegExp or null. + static class LocatorOptionsAttr { + String name; + Object value; + + LocatorOptionsAttr(String name, Object value) { + this.name = name; + this.value = value; + } + } + + static class LocatorOptions { + List attrs; + Boolean exact; + Object name; + Object description; + Object hasText; + Object hasNotText; + } + + public interface LocatorFactory { + String generateLocator(String base, String kind, Object body, LocatorOptions options); + String chainLocators(List locators); + // java: the overload for the optional options parameter. + default String generateLocator(String base, String kind, Object body) { + return generateLocator(base, kind, body, null); + } + } + + public static String asLocatorDescription(String lang, String selector) { + try { + ParsedSelector parsed = parseSelector(selector); + String customDescription = parseCustomDescription(parsed); + if (customDescription != null && !customDescription.isEmpty()) + return customDescription; + return innerAsLocators(generators.get(lang).get(), parsed, false, 1).get(0); + } catch (RuntimeException e) { + return selector; + } + } + + public static String locatorCustomDescription(String selector) { + try { + ParsedSelector parsed = parseSelector(selector); + return parseCustomDescription(parsed); + } catch (RuntimeException e) { + return null; + } + } + + private static String parseCustomDescription(ParsedSelector parsed) { + ParsedSelectorPart lastPart = parsed.parts.get(parsed.parts.size() - 1); + if (lastPart.name.equals("internal:describe")) { + JsonElement description = jsonParse((String) lastPart.body); + if (description.isJsonPrimitive() && description.getAsJsonPrimitive().isString()) + return description.getAsString(); + } + return null; + } + + public static String asLocator(String lang, String selector) { + return asLocator(lang, selector, false); + } + + public static String asLocator(String lang, String selector, boolean isFrameLocator) { + return asLocators(lang, selector, isFrameLocator, 1).get(0); + } + + public static List asLocators(String lang, String selector) { + return asLocators(lang, selector, false, 20); + } + + public static List asLocators(String lang, String selector, boolean isFrameLocator, int maxOutputSize) { + try { + return innerAsLocators(generators.get(lang).get(), parseSelector(selector), isFrameLocator, maxOutputSize); + } catch (RuntimeException e) { + return new ArrayList<>(Collections.singletonList(selector)); + } + } + + private static List innerAsLocators(LocatorFactory factory, ParsedSelector parsed, boolean isFrameLocator, int maxOutputSize) { + List parts = new ArrayList<>(parsed.parts); + List> tokens = new ArrayList<>(); + String nextBase = isFrameLocator ? "frame-locator" : "page"; + for (int index = 0; index < parts.size(); index++) { + ParsedSelectorPart part = parts.get(index); + String base = nextBase; + nextBase = "locator"; + + if (part.name.equals("internal:describe")) + continue; + if (part.name.equals("nth")) { + if ("0".equals(part.body)) + tokens.add(listOf(factory.generateLocator(base, "first", ""), factory.generateLocator(base, "nth", "0"))); + else if ("-1".equals(part.body)) + tokens.add(listOf(factory.generateLocator(base, "last", ""), factory.generateLocator(base, "nth", "-1"))); + else + tokens.add(listOf(factory.generateLocator(base, "nth", (String) part.body))); + continue; + } + if (part.name.equals("visible")) { + List tokenList = new ArrayList<>(); + if ("true".equals(part.body)) + tokenList.add(factory.generateLocator(base, "visible", "")); + tokenList.add(factory.generateLocator(base, "filter-visible", (String) part.body)); + tokenList.add(factory.generateLocator(base, "default", "visible=" + part.body)); + tokens.add(tokenList); + continue; + } + if (part.name.equals("internal:text")) { + DetectedExact detected = detectExact((String) part.body); + LocatorOptions options = new LocatorOptions(); + options.exact = detected.exact; + tokens.add(listOf(factory.generateLocator(base, "text", detected.text, options))); + continue; + } + if (part.name.equals("internal:has-text")) { + DetectedExact detected = detectExact((String) part.body); + if (!(detected.exact != null && detected.exact)) { + LocatorOptions options = new LocatorOptions(); + options.exact = detected.exact; + tokens.add(listOf(factory.generateLocator(base, "has-text", detected.text, options))); + continue; + } + } + if (part.name.equals("internal:has-not-text")) { + DetectedExact detected = detectExact((String) part.body); + if (!(detected.exact != null && detected.exact)) { + LocatorOptions options = new LocatorOptions(); + options.exact = detected.exact; + tokens.add(listOf(factory.generateLocator(base, "has-not-text", detected.text, options))); + continue; + } + } + if (part.name.equals("internal:has")) { + List inners = innerAsLocators(factory, ((NestedSelectorBody) part.body).parsed, false, maxOutputSize); + List mapped = new ArrayList<>(); + for (String inner : inners) + mapped.add(factory.generateLocator(base, "has", inner)); + tokens.add(mapped); + continue; + } + if (part.name.equals("internal:has-not")) { + List inners = innerAsLocators(factory, ((NestedSelectorBody) part.body).parsed, false, maxOutputSize); + List mapped = new ArrayList<>(); + for (String inner : inners) + mapped.add(factory.generateLocator(base, "hasNot", inner)); + tokens.add(mapped); + continue; + } + if (part.name.equals("internal:and")) { + List inners = innerAsLocators(factory, ((NestedSelectorBody) part.body).parsed, false, maxOutputSize); + List mapped = new ArrayList<>(); + for (String inner : inners) + mapped.add(factory.generateLocator(base, "and", inner)); + tokens.add(mapped); + continue; + } + if (part.name.equals("internal:or")) { + List inners = innerAsLocators(factory, ((NestedSelectorBody) part.body).parsed, false, maxOutputSize); + List mapped = new ArrayList<>(); + for (String inner : inners) + mapped.add(factory.generateLocator(base, "or", inner)); + tokens.add(mapped); + continue; + } + if (part.name.equals("internal:chain")) { + List inners = innerAsLocators(factory, ((NestedSelectorBody) part.body).parsed, false, maxOutputSize); + List mapped = new ArrayList<>(); + for (String inner : inners) + mapped.add(factory.generateLocator(base, "chain", inner)); + tokens.add(mapped); + continue; + } + if (part.name.equals("internal:label")) { + DetectedExact detected = detectExact((String) part.body); + LocatorOptions options = new LocatorOptions(); + options.exact = detected.exact; + tokens.add(listOf(factory.generateLocator(base, "label", detected.text, options))); + continue; + } + if (part.name.equals("internal:role")) { + AttributeSelector attrSelector = parseAttributeSelector((String) part.body, true); + LocatorOptions options = new LocatorOptions(); + options.attrs = new ArrayList<>(); + for (AttributeSelectorPart attr : attrSelector.attributes) { + if (attr.name.equals("name") || attr.name.equals("description")) { + if (attr.value instanceof String) { + if (options.exact != null && options.exact != attr.caseSensitive) + throw new PlaywrightException("Conflicting exactness in internal:role selector: " + stringifySelector(new ParsedSelector(listOf(part)))); + options.exact = attr.caseSensitive; + } + if (attr.name.equals("name")) + options.name = attr.value; + else + options.description = attr.value; + } else { + if (attr.name.equals("level") && attr.value instanceof String) + attr.value = toNumber((String) attr.value); + options.attrs.add(new LocatorOptionsAttr(attr.name.equals("include-hidden") ? "includeHidden" : attr.name, attr.value)); + } + } + tokens.add(listOf(factory.generateLocator(base, "role", attrSelector.name, options))); + continue; + } + if (part.name.equals("internal:testid")) { + AttributeSelector attrSelector = parseAttributeSelector((String) part.body, true); + Object value = attrSelector.attributes.get(0).value; + tokens.add(listOf(factory.generateLocator(base, "test-id", value))); + continue; + } + if (part.name.equals("internal:attr")) { + AttributeSelector attrSelector = parseAttributeSelector((String) part.body, true); + String name = attrSelector.attributes.get(0).name; + Object text = attrSelector.attributes.get(0).value; + boolean exact = attrSelector.attributes.get(0).caseSensitive; + LocatorOptions options = new LocatorOptions(); + options.exact = exact; + if (name.equals("placeholder")) { + tokens.add(listOf(factory.generateLocator(base, "placeholder", text, options))); + continue; + } + if (name.equals("alt")) { + tokens.add(listOf(factory.generateLocator(base, "alt", text, options))); + continue; + } + if (name.equals("title")) { + tokens.add(listOf(factory.generateLocator(base, "title", text, options))); + continue; + } + } + if (part.name.equals("internal:control") && "any-frame".equals(part.body)) { + tokens.add(listOf(factory.generateLocator(base, "any-frame", ""))); + nextBase = "frame-locator"; + continue; + } + if (part.name.equals("internal:control") && "enter-frame".equals(part.body)) { + List lastTokens = tokens.get(tokens.size() - 1); + ParsedSelectorPart lastPart = parts.get(index - 1); + + List transformed = new ArrayList<>(); + for (String token : lastTokens) + transformed.add(factory.chainLocators(listOf(token, factory.generateLocator(base, "frame", "")))); + if (Arrays.asList("xpath", "css").contains(lastPart.name)) { + transformed.add(factory.generateLocator(base, "frame-locator", stringifySelector(new ParsedSelector(listOf(lastPart))))); + transformed.add(factory.generateLocator(base, "frame-locator", stringifySelector(new ParsedSelector(listOf(lastPart)), true))); + } + + lastTokens.clear(); + lastTokens.addAll(transformed); + nextBase = "frame-locator"; + continue; + } + + ParsedSelectorPart nextPart = index + 1 < parts.size() ? parts.get(index + 1) : null; + + String selectorPart = stringifySelector(new ParsedSelector(listOf(part))); + String locatorPart = factory.generateLocator(base, "default", selectorPart); + + if (nextPart != null && Arrays.asList("internal:has-text", "internal:has-not-text").contains(nextPart.name)) { + DetectedExact detected = detectExact((String) nextPart.body); + if (!(detected.exact != null && detected.exact)) { + LocatorOptions nextOptions = new LocatorOptions(); + nextOptions.exact = detected.exact; + String nextLocatorPart = factory.generateLocator("locator", nextPart.name.equals("internal:has-text") ? "has-text" : "has-not-text", detected.text, nextOptions); + LocatorOptions options = new LocatorOptions(); + if (nextPart.name.equals("internal:has-text")) + options.hasText = detected.text; + else + options.hasNotText = detected.text; + String combinedPart = factory.generateLocator(base, "default", selectorPart, options); + tokens.add(listOf(factory.chainLocators(listOf(locatorPart, nextLocatorPart)), combinedPart)); + index++; + continue; + } + } + + String locatorPartWithEngine = null; + if (Arrays.asList("xpath", "css").contains(part.name)) { + String selectorPartWithEngine = stringifySelector(new ParsedSelector(listOf(part)), true); + locatorPartWithEngine = factory.generateLocator(base, "default", selectorPartWithEngine); + } + + List tokenList = new ArrayList<>(); + for (String token : Arrays.asList(locatorPart, locatorPartWithEngine)) { + if (token != null && !token.isEmpty()) + tokenList.add(token); + } + tokens.add(tokenList); + } + + return combineTokens(factory, tokens, maxOutputSize); + } + + private static List combineTokens(LocatorFactory factory, List> tokens, int maxOutputSize) { + List currentTokens = new ArrayList<>(); + for (int i = 0; i < tokens.size(); i++) + currentTokens.add(""); + List result = new ArrayList<>(); + + visit(factory, tokens, maxOutputSize, currentTokens, result, 0); + return result; + } + + // java: the visit closure of combineTokens() is a method, the variables it captures are parameters. + private static boolean visit(LocatorFactory factory, List> tokens, int maxOutputSize, List currentTokens, List result, int index) { + if (index == tokens.size()) { + result.add(factory.chainLocators(currentTokens)); + return result.size() < maxOutputSize; + } + for (String taken : tokens.get(index)) { + currentTokens.set(index, taken); + if (!visit(factory, tokens, maxOutputSize, currentTokens, result, index + 1)) + return false; + } + return true; + } + + // java: the object that detectExact() returns. + private static class DetectedExact { + Boolean exact; + Object text; + + DetectedExact(Boolean exact, Object text) { + this.exact = exact; + this.text = text; + } + } + + // java: the dot of a JS RegExp does not match the line terminators, and its $ only matches at the end. + private static DetectedExact detectExact(String text) { + boolean exact = false; + Matcher match = Pattern.compile("/([^\\n\\r\\u2028\\u2029]*)/([dgimsuvy]*)").matcher(text); + if (match.matches()) + return new DetectedExact(null, new RegExp(match.group(1), match.group(2))); + if (text.endsWith("\"")) { + text = jsonParse(text).getAsString(); + exact = true; + } else if (text.endsWith("\"s")) { + text = jsonParse(text.substring(0, text.length() - 1)).getAsString(); + exact = true; + } else if (text.endsWith("\"i")) { + text = jsonParse(text.substring(0, text.length() - 1)).getAsString(); + exact = false; + } + return new DetectedExact(exact, text); + } + + // java: a body that is not a String or a RegExp (a boolean, a number or null attribute value) fails the cast to + // String, so asLocator() returns the selector; upstream quotes a part of JSON.stringify(body), "ru" for true. + public static class JavaLocatorFactory implements LocatorFactory { + @Override + public String generateLocator(String base, String kind, Object body, LocatorOptions options) { + if (options == null) + options = new LocatorOptions(); + String clazz = null; + switch (base) { + case "page": clazz = "Page"; break; + case "frame-locator": clazz = "FrameLocator"; break; + case "locator": clazz = "Locator"; break; + } + switch (kind) { + case "default": + if (options.hasText != null) + return "locator(" + this.quote((String) body) + ", new " + clazz + ".LocatorOptions().setHasText(" + this.toHasText(options.hasText) + "))"; + if (options.hasNotText != null) + return "locator(" + this.quote((String) body) + ", new " + clazz + ".LocatorOptions().setHasNotText(" + this.toHasText(options.hasNotText) + "))"; + return "locator(" + this.quote((String) body) + ")"; + case "frame-locator": + return "frameLocator(" + this.quote((String) body) + ")"; + case "frame": + return "contentFrame()"; + case "any-frame": + return "frameLocator()"; + case "nth": + return "nth(" + body + ")"; + case "first": + return "first()"; + case "last": + return "last()"; + case "visible": + return "visible()"; + case "filter-visible": + return "filter(new " + clazz + ".FilterOptions().setVisible(" + ("true".equals(body) ? "true" : "false") + "))"; + case "role": + List attrs = new ArrayList<>(); + if (isRegExp(options.name)) + attrs.add(".setName(" + this.regexToString((RegExp) options.name) + ")"); + else if (options.name instanceof String) + attrs.add(".setName(" + this.quote((String) options.name) + ")"); + if (isRegExp(options.description)) + attrs.add(".setDescription(" + this.regexToString((RegExp) options.description) + ")"); + else if (options.description instanceof String) + attrs.add(".setDescription(" + this.quote((String) options.description) + ")"); + if (options.exact != null && options.exact && (options.name instanceof String || options.description instanceof String)) + attrs.add(".setExact(true)"); + for (LocatorOptionsAttr attr : options.attrs) + attrs.add(".set" + toTitleCase(attr.name) + "(" + (attr.value instanceof String ? this.quote((String) attr.value) : valueToString(attr.value)) + ")"); + String attrString = !attrs.isEmpty() ? ", new " + clazz + ".GetByRoleOptions()" + String.join("", attrs) : ""; + return "getByRole(AriaRole." + toSnakeCase((String) body).toUpperCase(Locale.ROOT) + attrString + ")"; + case "has-text": + return "filter(new " + clazz + ".FilterOptions().setHasText(" + this.toHasText(body) + "))"; + case "has-not-text": + return "filter(new " + clazz + ".FilterOptions().setHasNotText(" + this.toHasText(body) + "))"; + case "has": + return "filter(new " + clazz + ".FilterOptions().setHas(" + body + "))"; + case "hasNot": + return "filter(new " + clazz + ".FilterOptions().setHasNot(" + body + "))"; + case "and": + return "and(" + body + ")"; + case "or": + return "or(" + body + ")"; + case "chain": + return "locator(" + body + ")"; + case "test-id": + return "getByTestId(" + this.toTestIdValue(body) + ")"; + case "text": + return this.toCallWithExact(clazz, "getByText", body, options.exact != null && options.exact); + case "alt": + return this.toCallWithExact(clazz, "getByAltText", body, options.exact != null && options.exact); + case "placeholder": + return this.toCallWithExact(clazz, "getByPlaceholder", body, options.exact != null && options.exact); + case "label": + return this.toCallWithExact(clazz, "getByLabel", body, options.exact != null && options.exact); + case "title": + return this.toCallWithExact(clazz, "getByTitle", body, options.exact != null && options.exact); + default: + throw new PlaywrightException("Unknown selector kind " + kind); + } + } + + @Override + public String chainLocators(List locators) { + return String.join(".", locators); + } + + private String regexToString(RegExp body) { + String suffix = regexFlagsSuffix(body, "Pattern", regexFlagNames.get("java")); + return "Pattern.compile(" + this.quote(normalizeEscapedRegexQuotes(body.source)) + suffix + ")"; + } + + private String toCallWithExact(String clazz, String method, Object body, boolean exact) { + if (isRegExp(body)) + return method + "(" + this.regexToString((RegExp) body) + ")"; + if (exact) + return method + "(" + this.quote((String) body) + ", new " + clazz + "." + toTitleCase(method) + "Options().setExact(true))"; + return method + "(" + this.quote((String) body) + ")"; + } + + private String toHasText(Object body) { + if (isRegExp(body)) + return this.regexToString((RegExp) body); + return this.quote((String) body); + } + + private String toTestIdValue(Object value) { + if (isRegExp(value)) + return this.regexToString((RegExp) value); + return this.quote((String) value); + } + + private String quote(String text) { + return escapeWithQuotes(text, "\""); + } + } + + // java: only the java generator. + private static final Map> generators = new LinkedHashMap<>(); + static { + generators.put("java", JavaLocatorFactory::new); + } + + // java: only the java flag names. + public static final Map> regexFlagNames = new LinkedHashMap<>(); + static { + Map java = new LinkedHashMap<>(); + java.put("i", "CASE_INSENSITIVE"); + java.put("m", "MULTILINE"); + java.put("s", "DOTALL"); + regexFlagNames.put("java", java); + } + + private static String regexFlagsSuffix(RegExp body, String flagsEnum, Map names) { + List flags = new ArrayList<>(); + for (char flag : body.flags.toCharArray()) { + if (names.containsKey(String.valueOf(flag))) + flags.add(flagsEnum + "." + names.get(String.valueOf(flag))); + } + return !flags.isEmpty() ? ", " + String.join(" | ", flags) : ""; + } + + private static boolean isRegExp(Object obj) { + return obj instanceof RegExp; + } + + // java: helpers with no counterpart upstream. + + // java: an array literal, as a list that can be changed. + @SafeVarargs + private static List listOf(T... items) { + return new ArrayList<>(Arrays.asList(items)); + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/RegExp.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/RegExp.java new file mode 100644 index 000000000..2ebc11a2e --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/RegExp.java @@ -0,0 +1,92 @@ +/* + * 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. + */ + +// java: no counterpart upstream. A JS RegExp of a selector, as its source and flags. It is never compiled: +// a Java Pattern does not accept every JS regular expression, and the generators only print it. +package com.microsoft.playwright.impl.isomorphic; + +import com.microsoft.playwright.PlaywrightException; + +public final class RegExp { + public final String source; + public final String flags; + + // java: the constructor of a JS RegExp throws on an invalid flag or a repeated one, and on an invalid source; + // the source is not checked here. + public RegExp(String source, String flags) { + StringBuilder canonicalFlags = new StringBuilder(); + for (char flag : "dgimsuvy".toCharArray()) { + int index = flags.indexOf(flag); + if (index == -1) + continue; + if (flags.indexOf(flag, index + 1) != -1) + throw new PlaywrightException("Invalid flags supplied to RegExp constructor '" + flags + "'"); + canonicalFlags.append(flag); + } + if (canonicalFlags.length() != flags.length() || (flags.contains("u") && flags.contains("v"))) + throw new PlaywrightException("Invalid flags supplied to RegExp constructor '" + flags + "'"); + this.source = escapeSource(source); + this.flags = canonicalFlags.toString(); + } + + // java: RegExp.prototype.source escapes a slash outside of a character class and the line terminators, + // and is (?:) for an empty pattern. + private static String escapeSource(String pattern) { + if (pattern.isEmpty()) + return "(?:)"; + StringBuilder result = new StringBuilder(); + boolean inClass = false; + for (int i = 0; i < pattern.length(); i++) { + char c = pattern.charAt(i); + if (c == '\\' && i + 1 < pattern.length()) { + char escaped = pattern.charAt(++i); + if (escaped == '\n') + result.append("\\n"); + else if (escaped == '\r') + result.append("\\r"); + else if (escaped == '
') + result.append("\\u2028"); + else if (escaped == '
') + result.append("\\u2029"); + else + result.append(c).append(escaped); + continue; + } + if (c == '[') + inClass = true; + else if (c == ']') + inClass = false; + if (c == '/' && !inClass) + result.append("\\/"); + else if (c == '\n') + result.append("\\n"); + else if (c == '\r') + result.append("\\r"); + else if (c == '
') + result.append("\\u2028"); + else if (c == '
') + result.append("\\u2029"); + else + result.append(c); + } + return result.toString(); + } + + @Override + public String toString() { + return "/" + source + "/" + flags; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/SelectorParser.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/SelectorParser.java new file mode 100644 index 000000000..af62ab7c5 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/SelectorParser.java @@ -0,0 +1,529 @@ +/* + * 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. + */ + +// Port of isomorphic/selectorParser.ts. +package com.microsoft.playwright.impl.isomorphic; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.microsoft.playwright.impl.isomorphic.CssParser.InvalidSelectorError; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.microsoft.playwright.impl.isomorphic.CssParser.parseCSS; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.JS_WHITESPACE; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.jsTrim; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.jsonParse; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.numberToString; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.toNumber; + +// java: the types of the file are nested classes. kAnyFrameSelector, splitSelectorByFrame and visitAllSelectorParts +// are not ported, the locator generators do not use them. +public final class SelectorParser { + private SelectorParser() { + } + + public static class NestedSelectorBody { + public ParsedSelector parsed; + public Double distance; + } + + private static final Set kNestedSelectorNames = new HashSet<>(Arrays.asList("internal:has", "internal:has-not", "internal:and", "internal:or", "internal:chain", "left-of", "right-of", "above", "below", "near")); + private static final Set kNestedSelectorNamesWithDistance = new HashSet<>(Arrays.asList("left-of", "right-of", "above", "below", "near")); + + // java: the body is an Object holding a String, a List or a NestedSelectorBody. + public static class ParsedSelectorPart { + public String name; + public Object body; + public String source; + + ParsedSelectorPart(String name, Object body, String source) { + this.name = name; + this.body = body; + this.source = source; + } + } + + public static class ParsedSelector { + public List parts; + public Integer capture; + + ParsedSelector(List parts) { + this.parts = parts; + } + } + + // java: the type of an item of ParsedSelectorStrings.parts. + private static class ParsedSelectorStringPart { + String name; + String body; + + ParsedSelectorStringPart(String name, String body) { + this.name = name; + this.body = body; + } + } + + private static class ParsedSelectorStrings { + List parts = new ArrayList<>(); + Integer capture; + } + + public static final Set customCSSNames = new HashSet<>(Arrays.asList("not", "is", "where", "has", "scope", "light", "visible", "text", "text-matches", "text-is", "has-text", "above", "below", "right-of", "left-of", "near", "nth-match")); + + public static ParsedSelector parseSelector(String selector) { + ParsedSelectorStrings parsedStrings = parseSelectorString(selector); + List parts = new ArrayList<>(); + for (ParsedSelectorStringPart part : parsedStrings.parts) { + if (part.name.equals("css") || part.name.equals("css:light")) { + if (part.name.equals("css:light")) + part.body = ":light(" + part.body + ")"; + CssParser.ParsedCSS parsedCSS = parseCSS(part.body, customCSSNames); + parts.add(new ParsedSelectorPart( + "css", + parsedCSS.selector, + part.body + )); + continue; + } + if (kNestedSelectorNames.contains(part.name)) { + String innerSelector; + Double distance = null; + try { + JsonElement unescaped = jsonParse("[" + part.body + "]"); + if (!unescaped.isJsonArray() || unescaped.getAsJsonArray().size() < 1 || unescaped.getAsJsonArray().size() > 2 || !isJsonString(unescaped.getAsJsonArray().get(0))) + throw new InvalidSelectorError("Malformed selector: " + part.name + "=" + part.body); + JsonArray array = unescaped.getAsJsonArray(); + innerSelector = array.get(0).getAsString(); + if (array.size() == 2) { + if (!(array.get(1).isJsonPrimitive() && array.get(1).getAsJsonPrimitive().isNumber()) || !kNestedSelectorNamesWithDistance.contains(part.name)) + throw new InvalidSelectorError("Malformed selector: " + part.name + "=" + part.body); + distance = array.get(1).getAsDouble(); + } + } catch (RuntimeException e) { + throw new InvalidSelectorError("Malformed selector: " + part.name + "=" + part.body); + } + NestedSelectorBody nestedBody = new NestedSelectorBody(); + nestedBody.parsed = parseSelector(innerSelector); + nestedBody.distance = distance; + ParsedSelectorPart nested = new ParsedSelectorPart(part.name, nestedBody, part.body); + ParsedSelectorPart lastFrame = null; + for (int i = nestedBody.parsed.parts.size() - 1; i >= 0; i--) { + ParsedSelectorPart p = nestedBody.parsed.parts.get(i); + if (p.name.equals("internal:control") && "enter-frame".equals(p.body)) { + lastFrame = p; + break; + } + } + int lastFrameIndex = lastFrame != null ? nestedBody.parsed.parts.indexOf(lastFrame) : -1; + List outerParts = !parts.isEmpty() && parts.get(0).name.equals("internal:control") && "any-frame".equals(parts.get(0).body) ? slice(parts, 1, parts.size()) : parts; + if (lastFrameIndex != -1 && selectorPartsEqual(slice(nestedBody.parsed.parts, 0, lastFrameIndex + 1), slice(outerParts, 0, lastFrameIndex + 1))) { + nestedBody.parsed.parts.subList(0, lastFrameIndex + 1).clear(); + if (nestedBody.parsed.capture != null) { + if (nestedBody.parsed.capture <= lastFrameIndex) + throw new InvalidSelectorError("Can not capture the selector before diving into the frame. Only use * after the last frame has been selected"); + nestedBody.parsed.capture -= lastFrameIndex + 1; + } + } + parts.add(nested); + continue; + } + parts.add(new ParsedSelectorPart(part.name, part.body, part.body)); + } + if (kNestedSelectorNames.contains(parts.get(0).name)) + throw new InvalidSelectorError("\"" + parts.get(0).name + "\" selector cannot be first"); + ParsedSelector result = new ParsedSelector(parts); + result.capture = parsedStrings.capture; + return result; + } + + private static boolean selectorPartsEqual(List list1, List list2) { + return stringifySelector(new ParsedSelector(list1)).equals(stringifySelector(new ParsedSelector(list2))); + } + + public static String stringifySelector(String selector) { + return selector; + } + + public static String stringifySelector(ParsedSelector selector) { + return stringifySelector(selector, false); + } + + public static String stringifySelector(ParsedSelector selector, boolean forceEngineName) { + List result = new ArrayList<>(); + for (int i = 0; i < selector.parts.size(); i++) { + ParsedSelectorPart p = selector.parts.get(i); + boolean isCapture = selector.capture != null && i == selector.capture; + boolean includeEngine = true; + if (!forceEngineName && !isCapture) { + if (p.name.equals("css")) + includeEngine = false; + else if (p.name.equals("xpath") && (p.source.startsWith("//") || p.source.startsWith(".."))) + includeEngine = false; + } + String prefix = includeEngine ? p.name + "=" : ""; + result.add((isCapture ? "*" : "") + prefix + p.source); + } + return String.join(" >> ", result); + } + + private static ParsedSelectorStrings parseSelectorString(String selector) { + return new SelectorStringParser(selector).parse(); + } + + // java: the local variables and the closures of parseSelectorString() are the fields and the methods of this class. + private static class SelectorStringParser { + private final String selector; + private int index = 0; + private String quote; + private int start = 0; + private final ParsedSelectorStrings result = new ParsedSelectorStrings(); + + SelectorStringParser(String selector) { + this.selector = selector; + } + + private void append() { + String part = jsTrim(selector.substring(start, index)); + int eqIndex = part.indexOf('='); + String name; + String body; + if (eqIndex != -1 && jsTrim(part.substring(0, eqIndex)).matches("[a-zA-Z_0-9\\-+:*]+")) { + name = jsTrim(part.substring(0, eqIndex)); + body = part.substring(eqIndex + 1); + } else if (part.length() > 1 && part.charAt(0) == '"' && part.charAt(part.length() - 1) == '"') { + name = "text"; + body = part; + } else if (part.length() > 1 && part.charAt(0) == '\'' && part.charAt(part.length() - 1) == '\'') { + name = "text"; + body = part; + } else if (Pattern.compile("^\\(*//").matcher(part).find() || part.startsWith("..")) { + name = "xpath"; + body = part; + } else { + name = "css"; + body = part; + } + boolean capture = false; + if (name.charAt(0) == '*') { + capture = true; + name = name.substring(1); + } + result.parts.add(new ParsedSelectorStringPart(name, body)); + if (capture) { + if (result.capture != null) + throw new InvalidSelectorError("Only one of the selectors can capture using * modifier"); + result.capture = result.parts.size() - 1; + } + } + + // java: the dot of a JS RegExp does not match the line terminators, and its $ only matches at the end. + private boolean shouldIgnoreTextSelectorQuote() { + String prefix = selector.substring(start, index); + Matcher match = Pattern.compile(JS_WHITESPACE + "*text" + JS_WHITESPACE + "*=([^\\n\\r\\u2028\\u2029]*)").matcher(prefix); + return match.matches() && !match.group(1).isEmpty(); + } + + ParsedSelectorStrings parse() { + if (!selector.contains(">>")) { + index = selector.length(); + append(); + return result; + } + + while (index < selector.length()) { + String c = selector.substring(index, index + 1); + if (c.equals("\\") && index + 1 < selector.length()) { + index += 2; + } else if (c.equals(quote)) { + quote = null; + index++; + } else if (quote == null && (c.equals("\"") || c.equals("'") || c.equals("`")) && !shouldIgnoreTextSelectorQuote()) { + quote = c; + index++; + } else if (quote == null && c.equals(">") && index + 1 < selector.length() && selector.charAt(index + 1) == '>') { + append(); + index += 2; + start = index; + } else { + index++; + } + } + append(); + return result; + } + } + + // java: the value is an Object holding a String, a Boolean, a Double, a RegExp or null. + public static class AttributeSelectorPart { + public String name; + public List jsonPath; + public String op; + public Object value; + public boolean caseSensitive; + + AttributeSelectorPart(String name, List jsonPath, String op, Object value, boolean caseSensitive) { + this.name = name; + this.jsonPath = jsonPath; + this.op = op; + this.value = value; + this.caseSensitive = caseSensitive; + } + } + + public static class AttributeSelector { + public String name = ""; + public List attributes = new ArrayList<>(); + } + + + public static AttributeSelector parseAttributeSelector(String selector, boolean allowUnquotedStrings) { + return new AttributeSelectorParser(selector, allowUnquotedStrings).parse(); + } + + // java: the local variables and the nested functions of parseAttributeSelector() are the fields and the methods of + // this class. A character is a String of one char, empty at the end of the selector. + private static class AttributeSelectorParser { + private final String selector; + private final boolean allowUnquotedStrings; + private int wp = 0; + private boolean EOL; + + AttributeSelectorParser(String selector, boolean allowUnquotedStrings) { + this.selector = selector; + this.allowUnquotedStrings = allowUnquotedStrings; + EOL = selector.length() == 0; + } + + private String next() { + return wp < selector.length() ? selector.substring(wp, wp + 1) : ""; + } + + private String eat1() { + String result = next(); + ++wp; + EOL = wp >= selector.length(); + return result; + } + + private void syntaxError(String stage) { + if (EOL) + throw new InvalidSelectorError("Unexpected end of selector while parsing selector `" + selector + "`"); + throw new InvalidSelectorError("Error while parsing selector `" + selector + "` - unexpected symbol \"" + next() + "\" at position " + wp + (stage != null ? " during " + stage : "")); + } + + private void skipSpaces() { + while (!EOL && next().matches(JS_WHITESPACE)) + eat1(); + } + + // java: an empty string is not a name char; upstream compares it with the range bounds, which gives false. + private boolean isCSSNameChar(String ch) { + if (ch.isEmpty()) + return false; + char c = ch.charAt(0); + return (c >= '\u0080') + || (c >= '0' && c <= '9') + || (c >= 'A' && c <= 'Z') + || (c >= 'a' && c <= 'z') + || (c >= '0' && c <= '9') + || c == '_' + || c == '-'; + } + + private String readIdentifier() { + String result = ""; + skipSpaces(); + while (!EOL && isCSSNameChar(next())) + result += eat1(); + return result; + } + + private String readQuotedString(String quote) { + String result = eat1(); + if (!result.equals(quote)) + syntaxError("parsing quoted string"); + while (!EOL && !next().equals(quote)) { + if (next().equals("\\")) + eat1(); + result += eat1(); + } + if (!next().equals(quote)) + syntaxError("parsing quoted string"); + result += eat1(); + return result; + } + + private RegExp readRegularExpression() { + if (!eat1().equals("/")) + syntaxError("parsing regular expression"); + String source = ""; + boolean inClass = false; + while (!EOL) { + if (next().equals("\\")) { + source += eat1(); + if (EOL) + syntaxError("parsing regular expression"); + } else if (inClass && next().equals("]")) { + inClass = false; + } else if (!inClass && next().equals("[")) { + inClass = true; + } else if (!inClass && next().equals("/")) { + break; + } + source += eat1(); + } + if (!eat1().equals("/")) + syntaxError("parsing regular expression"); + String flags = ""; + while (!EOL && next().matches("[dgimsuvy]")) + flags += eat1(); + try { + return new RegExp(source, flags); + } catch (RuntimeException e) { + throw new InvalidSelectorError("Error while parsing selector `" + selector + "`: " + e.getMessage()); + } + } + + private String readAttributeToken() { + String token = ""; + skipSpaces(); + if (next().equals("'") || next().equals("\"")) { + String quoted = readQuotedString(next()); + token = quoted.substring(1, quoted.length() - 1); + } else { + token = readIdentifier(); + } + if (token.isEmpty()) + syntaxError("parsing property path"); + return token; + } + + private String readOperator() { + skipSpaces(); + String op = ""; + if (!EOL) + op += eat1(); + if (!EOL && (!op.equals("="))) + op += eat1(); + if (!Arrays.asList("=", "*=", "^=", "$=", "|=", "~=").contains(op)) + syntaxError("parsing operator"); + return op; + } + + private AttributeSelectorPart readAttribute() { + eat1(); + + List jsonPath = new ArrayList<>(); + jsonPath.add(readAttributeToken()); + skipSpaces(); + while (next().equals(".")) { + eat1(); + jsonPath.add(readAttributeToken()); + skipSpaces(); + } + if (next().equals("]")) { + eat1(); + return new AttributeSelectorPart(String.join(".", jsonPath), jsonPath, "", null, false); + } + + String operator = readOperator(); + + Object value = null; + boolean caseSensitive = true; + skipSpaces(); + if (next().equals("/")) { + if (!operator.equals("=")) + throw new InvalidSelectorError("Error while parsing selector `" + selector + "` - cannot use " + operator + " in attribute with regular expression"); + value = readRegularExpression(); + } else if (next().equals("'") || next().equals("\"")) { + String quoted = readQuotedString(next()); + value = quoted.substring(1, quoted.length() - 1); + skipSpaces(); + if (next().equals("i") || next().equals("I")) { + caseSensitive = false; + eat1(); + } else if (next().equals("s") || next().equals("S")) { + caseSensitive = true; + eat1(); + } + } else { + String unquoted = ""; + while (!EOL && (isCSSNameChar(next()) || next().equals("+") || next().equals("."))) + unquoted += eat1(); + value = unquoted; + if (unquoted.equals("true")) { + value = true; + } else if (unquoted.equals("false")) { + value = false; + } else { + if (!allowUnquotedStrings) { + value = toNumber(unquoted); + if (Double.isNaN((Double) value)) + syntaxError("parsing attribute value"); + } + } + } + skipSpaces(); + if (!next().equals("]")) + syntaxError("parsing attribute value"); + + eat1(); + if (!operator.equals("=") && !(value instanceof String)) + throw new InvalidSelectorError("Error while parsing selector `" + selector + "` - cannot use " + operator + " in attribute with non-string matching value - " + valueToString(value)); + return new AttributeSelectorPart(String.join(".", jsonPath), jsonPath, operator, value, caseSensitive); + } + + AttributeSelector parse() { + AttributeSelector result = new AttributeSelector(); + result.name = readIdentifier(); + skipSpaces(); + while (next().equals("[")) { + result.attributes.add(readAttribute()); + skipSpaces(); + } + if (!EOL) + syntaxError(null); + if (result.name.isEmpty() && result.attributes.isEmpty()) + throw new InvalidSelectorError("Error while parsing selector `" + selector + "` - selector cannot be empty"); + return result; + } + } + + // java: helpers with no counterpart upstream. + + private static boolean isJsonString(JsonElement element) { + return element.isJsonPrimitive() && element.getAsJsonPrimitive().isString(); + } + + // java: Array.prototype.slice, which clamps the indexes to the length. + private static List slice(List list, int start, int end) { + return new ArrayList<>(list.subList(Math.min(start, list.size()), Math.min(end, list.size()))); + } + + // java: String(value) of an attribute value. + static String valueToString(Object value) { + if (value instanceof Double) + return numberToString((Double) value); + return String.valueOf(value); + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java index cde6ffca1..0e3ec729e 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java @@ -19,8 +19,15 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import com.google.gson.Strictness; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; import com.microsoft.playwright.PlaywrightException; +import java.io.IOException; +import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -314,13 +321,56 @@ public static String jsonStringify(String value) { return gson.toJson(value); } + // java: JSON.parse; throws on malformed JSON. + public static JsonElement jsonParse(String text) { + try { + JsonReader reader = new JsonReader(new StringReader(text)); + reader.setStrictness(Strictness.STRICT); + JsonElement result = gson.getAdapter(JsonElement.class).read(reader); + if (reader.peek() != JsonToken.END_DOCUMENT) + throw new PlaywrightException("Unexpected non-whitespace character after JSON"); + return result; + } catch (IOException | IllegalStateException | JsonParseException e) { + throw new PlaywrightException("Malformed JSON: " + text, e); + } + } + + // java: String.prototype.trim, which removes the \s characters of a JS RegExp. + public static String jsTrim(String text) { + return text.replaceAll("^" + JS_WHITESPACE + "+|" + JS_WHITESPACE + "+$", ""); + } + + // java: the unary plus on a string. A hexadecimal literal and a decimal literal are converted, anything else is NaN. + public static double toNumber(String text) { + String trimmed = jsTrim(text); + if (trimmed.isEmpty()) + return 0; + if (trimmed.matches("0[xX][0-9a-fA-F]+")) + return new java.math.BigInteger(trimmed.substring(2), 16).doubleValue(); + if (trimmed.matches("[+-]?(Infinity|(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?)")) + return Double.parseDouble(trimmed); + return Double.NaN; + } + + // java: String(value) of a JS number. A whole number prints without a fraction; other numbers print as + // Double.toString() does, which differs from JS in the exponent form. + public static String numberToString(double value) { + if (Double.isNaN(value)) + return "NaN"; + if (Double.isInfinite(value)) + return value > 0 ? "Infinity" : "-Infinity"; + if (value == Math.rint(value) && Math.abs(value) < 1e15) + return String.valueOf((long) value); + return Double.toString(value); + } + // java: String(re) of a JS RegExp. private static String toJsRegExp(Pattern pattern) { return "/" + pattern.pattern() + "/" + toJsRegexFlags(pattern); } // java: the \s character class of a JS RegExp. - private static final String JS_WHITESPACE = "[\\t\\n\\u000B\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]"; + static final String JS_WHITESPACE = "[\\t\\n\\u000B\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]"; // java: String.prototype.replace with a global RegExp and a function that looks the match up in escaped. private static String replaceEach(String s, Pattern pattern) { diff --git a/playwright/src/test/java/com/microsoft/playwright/TestLocatorConvenience.java b/playwright/src/test/java/com/microsoft/playwright/TestLocatorConvenience.java index 15ccf26cd..c52e4a5a1 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestLocatorConvenience.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestLocatorConvenience.java @@ -30,10 +30,10 @@ void shouldHaveANicePreview(Page page, Server server) { Locator check = page.locator("#check"); JSHandle text = inner.evaluateHandle("e => e.firstChild"); page.evaluate("() => 1"); // Give them a chance to calculate the preview. - assertEquals("Locator@#outer", outer.toString()); - assertEquals("Locator@#outer >> #inner", inner.toString()); + assertEquals("locator(\"#outer\")", outer.toString()); + assertEquals("locator(\"#outer\").locator(\"#inner\")", inner.toString()); assertEquals("JSHandle@#text=Text,↵more text", text.toString()); - assertEquals("Locator@#check", check.toString()); + assertEquals("locator(\"#check\")", check.toString()); } @PlaywrightTest @@ -226,7 +226,7 @@ void descriptionShouldReturnLastDescriptionForMultipleCalls(Page page) { void toStringShouldReturnFormattedLocator(Page page) { page.setContent("
Hello
"); Locator locator = page.locator("div"); - assertTrue(locator.toString().startsWith("Locator@")); + assertEquals("locator(\"div\")", locator.toString()); } @PlaywrightTest diff --git a/playwright/src/test/java/com/microsoft/playwright/TestLocatorGenerators.java b/playwright/src/test/java/com/microsoft/playwright/TestLocatorGenerators.java new file mode 100644 index 000000000..53514c167 --- /dev/null +++ b/playwright/src/test/java/com/microsoft/playwright/TestLocatorGenerators.java @@ -0,0 +1,288 @@ +/* + * 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.fixtures.PlaywrightTest; +import com.microsoft.playwright.options.AriaRole; + +import java.util.regex.Pattern; + +import static com.microsoft.playwright.impl.isomorphic.LocatorGenerators.asLocator; +import static com.microsoft.playwright.impl.isomorphic.LocatorGenerators.asLocatorDescription; +import static com.microsoft.playwright.impl.isomorphic.LocatorGenerators.asLocators; +import static java.util.Arrays.asList; +import static org.junit.jupiter.api.Assertions.assertEquals; + +// The java expectations of upstream tests/library/locator-generator.spec.ts. +public class TestLocatorGenerators { + private static String generate(Locator locator) { + return locator.toString(); + } + + @PlaywrightTest + void reverseEngineerLocators(Page page) { + assertEquals("getByTestId(\"Hello\")", generate(page.getByTestId("Hello"))); + assertEquals("getByTestId(\"He\\\"llo\")", generate(page.getByTestId("He\"llo"))); + assertEquals("getByTestId(Pattern.compile(\"He\\\"llo\"))", generate(page.getByTestId(Pattern.compile("He\"llo")))); + assertEquals("getByTestId(Pattern.compile(\"He\\\\\\\\\\\"llo\"))", generate(page.getByTestId(Pattern.compile("He\\\\\"llo")))); + assertEquals("getByText(\"Hello\", new Page.GetByTextOptions().setExact(true))", generate(page.getByText("Hello", new Page.GetByTextOptions().setExact(true)))); + assertEquals("getByText(\"Hello\")", generate(page.getByText("Hello"))); + assertEquals("getByText(Pattern.compile(\"Hello\"))", generate(page.getByText(Pattern.compile("Hello")))); + assertEquals("getByLabel(\"Name\")", generate(page.getByLabel("Name"))); + assertEquals("getByLabel(\"Last Name\", new Page.GetByLabelOptions().setExact(true))", generate(page.getByLabel("Last Name", new Page.GetByLabelOptions().setExact(true)))); + assertEquals("getByLabel(Pattern.compile(\"Last\\\\s+name\", Pattern.CASE_INSENSITIVE))", generate(page.getByLabel(Pattern.compile("Last\\s+name", Pattern.CASE_INSENSITIVE)))); + // Only JavaScript can express these flags, other languages drop them. + for (String flags : asList("u", "s", "y", "d", "v", "gm")) { + for (String[] engineAndMethod : asList(new String[] {"text", "getByText"}, new String[] {"label", "getByLabel"})) { + String selector = "internal:" + engineAndMethod[0] + "=/Hello/" + flags; + String suffix = ""; + if (flags.contains("s")) + suffix = ", Pattern.DOTALL"; + if (flags.contains("m")) + suffix = ", Pattern.MULTILINE"; + assertEquals(engineAndMethod[1] + "(Pattern.compile(\"Hello\"" + suffix + "))", asLocator("java", selector), selector); + } + } + + assertEquals("getByPlaceholder(\"hello\")", generate(page.getByPlaceholder("hello"))); + assertEquals("getByPlaceholder(\"Hello\", new Page.GetByPlaceholderOptions().setExact(true))", generate(page.getByPlaceholder("Hello", new Page.GetByPlaceholderOptions().setExact(true)))); + assertEquals("getByPlaceholder(Pattern.compile(\"wor\", Pattern.CASE_INSENSITIVE))", generate(page.getByPlaceholder(Pattern.compile("wor", Pattern.CASE_INSENSITIVE)))); + + assertEquals("getByAltText(\"hello\")", generate(page.getByAltText("hello"))); + assertEquals("getByAltText(\"Hello\", new Page.GetByAltTextOptions().setExact(true))", generate(page.getByAltText("Hello", new Page.GetByAltTextOptions().setExact(true)))); + assertEquals("getByAltText(Pattern.compile(\"wor\", Pattern.CASE_INSENSITIVE))", generate(page.getByAltText(Pattern.compile("wor", Pattern.CASE_INSENSITIVE)))); + + assertEquals("getByTitle(\"hello\")", generate(page.getByTitle("hello"))); + assertEquals("getByTitle(\"Hello\", new Page.GetByTitleOptions().setExact(true))", generate(page.getByTitle("Hello", new Page.GetByTitleOptions().setExact(true)))); + assertEquals("getByTitle(Pattern.compile(\"wor\", Pattern.CASE_INSENSITIVE))", generate(page.getByTitle(Pattern.compile("wor", Pattern.CASE_INSENSITIVE)))); + assertEquals("getByPlaceholder(\"hello my\\nwo\\\"rld\")", generate(page.getByPlaceholder("hello my\nwo\"rld"))); + assertEquals("getByAltText(\"hello my\\nwo\\\"rld\")", generate(page.getByAltText("hello my\nwo\"rld"))); + assertEquals("getByTitle(\"hello my\\nwo\\\"rld\")", generate(page.getByTitle("hello my\nwo\"rld"))); + } + + @PlaywrightTest + void reverseEngineerGetByRole(Page page) { + assertEquals("getByRole(AriaRole.BUTTON)", generate(page.getByRole(AriaRole.BUTTON))); + assertEquals("getByRole(AriaRole.HEADING)", generate(page.getByRole(AriaRole.HEADING, new Page.GetByRoleOptions()))); + assertEquals("getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Hello\"))", generate(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Hello")))); + assertEquals("getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(Pattern.compile(\"Hello\")))", generate(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(Pattern.compile("Hello"))))); + assertEquals("getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"He\\\"llo\").setExact(true))", generate(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("He\"llo").setExact(true)))); + assertEquals("getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setChecked(true).setLevel(3).setPressed(false))", generate(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setChecked(true).setPressed(false).setLevel(3)))); + assertEquals("getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setName(\"Upload\").setDescription(\"doc.pdf\"))", generate(page.getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setName("Upload").setDescription("doc.pdf")))); + assertEquals("getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setDescription(\"doc.pdf\"))", generate(page.getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setDescription("doc.pdf")))); + assertEquals("getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setDescription(Pattern.compile(\"doc\\\\.pdf\")))", generate(page.getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setDescription(Pattern.compile("doc\\.pdf"))))); + assertEquals("getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setName(\"Upload\").setDescription(\"doc.pdf\").setExact(true))", generate(page.getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setName("Upload").setDescription("doc.pdf").setExact(true)))); + } + + @PlaywrightTest + void refusesToTranslateInternalRoleWithConflictingNameDescriptionExactness() { + // https://github.com/microsoft/playwright/issues/41032 + String conflicting = "internal:role=row[name=\"abc\"i][description=\"d\"s]"; + String conflictingReversed = "internal:role=row[name=\"abc\"s][description=\"d\"i]"; + assertEquals(conflicting, asLocator("java", conflicting)); + assertEquals(conflictingReversed, asLocator("java", conflictingReversed)); + } + + @PlaywrightTest + void reverseEngineerInternalRoleWithRegexAndStringNameDescription() { + assertEquals("getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setName(Pattern.compile(\"Upload\")).setDescription(\"doc.pdf\"))", + asLocator("java", "internal:role=alert[name=/Upload/][description=\"doc.pdf\"i]")); + assertEquals("getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setName(\"Upload\").setDescription(Pattern.compile(\"doc\\\\.pdf\")))", + asLocator("java", "internal:role=alert[name=\"Upload\"i][description=/doc\\.pdf/]")); + } + + @PlaywrightTest + void reverseEngineerIgnoreCaseLocators(Page page) { + assertEquals("getByText(\"hello my\\nwo\\\"rld\")", generate(page.getByText("hello my\nwo\"rld"))); + assertEquals("getByText(\"hello my wo\\\"rld\")", generate(page.getByText("hello my wo\"rld"))); + assertEquals("getByLabel(\"hello my\\nwo\\\"rld\")", generate(page.getByLabel("hello my\nwo\"rld"))); + } + + @PlaywrightTest + void reverseEngineerOrderedLocators(Page page) { + assertEquals("locator(\"div\").nth(3).first().last()", generate(page.locator("div").nth(3).first().last())); + } + + @PlaywrightTest + void reverseEngineerLocatorsWithRegex(Page page) { + assertEquals("getByText(Pattern.compile(\"he\\\\/\\\\sl\\\\nlo\"))", generate(page.getByText(Pattern.compile("he\\/\\sl\\nlo")))); + assertEquals("getByPlaceholder(Pattern.compile(\"he\\\\/\\\\sl\\\\nlo\"))", generate(page.getByPlaceholder(Pattern.compile("he\\/\\sl\\nlo")))); + assertEquals("getByText(Pattern.compile(\"hel\\\"lo\"))", generate(page.getByText(Pattern.compile("hel\"lo")))); + assertEquals("getByPlaceholder(Pattern.compile(\"hel\\\"lo\"))", generate(page.getByPlaceholder(Pattern.compile("hel\"lo")))); + } + + @PlaywrightTest + void reverseEngineerHasText(Page page) { + assertEquals("getByText(\"Hello\").filter(new Locator.FilterOptions().setHasText(\"wo\\\"rld\\n\"))", + generate(page.getByText("Hello").filter(new Locator.FilterOptions().setHasText("wo\"rld\n")))); + assertEquals("getByText(\"Hello\").filter(new Locator.FilterOptions().setHasText(Pattern.compile(\"wo\\\\/\\\\srld\\\\n\")))", + generate(page.getByText("Hello").filter(new Locator.FilterOptions().setHasText(Pattern.compile("wo\\/\\srld\\n"))))); + assertEquals("getByText(\"Hello\").filter(new Locator.FilterOptions().setHasText(Pattern.compile(\"wor\\\"ld\")))", + generate(page.getByText("Hello").filter(new Locator.FilterOptions().setHasText(Pattern.compile("wor\"ld"))))); + } + + @PlaywrightTest + void reverseEngineerHasNotText(Page page) { + assertEquals("getByText(\"Hello\").filter(new Locator.FilterOptions().setHasNotText(\"wo\\\"rld\\n\"))", + generate(page.getByText("Hello").filter(new Locator.FilterOptions().setHasNotText("wo\"rld\n")))); + } + + @PlaywrightTest + void reverseEngineerVisible(Page page) { + assertEquals("getByText(\"Hello\").visible().locator(\"div\")", generate(page.getByText("Hello").visible().locator("div"))); + assertEquals("getByText(\"Hello\").filter(new Locator.FilterOptions().setVisible(false)).locator(\"div\")", + generate(page.getByText("Hello").filter(new Locator.FilterOptions().setVisible(false)).locator("div"))); + } + + @PlaywrightTest + void reverseEngineerHas(Page page) { + assertEquals("getByText(\"Hello\").filter(new Locator.FilterOptions().setHas(locator(\"div\").getByText(\"bye\")))", + generate(page.getByText("Hello").filter(new Locator.FilterOptions().setHas(page.locator("div").getByText("bye"))))); + + Locator locator = page + .locator("section") + .filter(new Locator.FilterOptions().setHas(page.locator("div").filter(new Locator.FilterOptions().setHas(page.locator("span"))))) + .filter(new Locator.FilterOptions().setHasText("foo")) + .filter(new Locator.FilterOptions().setHas(page.locator("a"))); + assertEquals("locator(\"section\").filter(new Locator.FilterOptions().setHas(locator(\"div\").filter(new Locator.FilterOptions().setHas(locator(\"span\"))))).filter(new Locator.FilterOptions().setHasText(\"foo\")).filter(new Locator.FilterOptions().setHas(locator(\"a\")))", + generate(locator)); + } + + @PlaywrightTest + void reverseEngineerHasNot(Page page) { + assertEquals("getByText(\"Hello\").filter(new Locator.FilterOptions().setHasNot(locator(\"div\").getByText(\"bye\")))", + generate(page.getByText("Hello").filter(new Locator.FilterOptions().setHasNot(page.locator("div").getByText("bye"))))); + + Locator locator = page + .locator("section") + .filter(new Locator.FilterOptions().setHas(page.locator("div").filter(new Locator.FilterOptions().setHasNot(page.locator("span"))))) + .filter(new Locator.FilterOptions().setHasText("foo")) + .filter(new Locator.FilterOptions().setHasNot(page.locator("a"))); + assertEquals("locator(\"section\").filter(new Locator.FilterOptions().setHas(locator(\"div\").filter(new Locator.FilterOptions().setHasNot(locator(\"span\"))))).filter(new Locator.FilterOptions().setHasText(\"foo\")).filter(new Locator.FilterOptions().setHasNot(locator(\"a\")))", + generate(locator)); + } + + @PlaywrightTest + void reverseEngineerHasAndHasText(Page page) { + Locator locator = page.locator("section").filter(new Locator.FilterOptions().setHasText("foo").setHas(page.locator("div"))).locator("a"); + assertEquals("locator(\"section\").filter(new Locator.FilterOptions().setHasText(\"foo\")).filter(new Locator.FilterOptions().setHas(locator(\"div\"))).locator(\"a\")", + generate(locator)); + } + + @PlaywrightTest + void reverseEngineerFrameLocator(Page page) { + Locator locator = page + .frameLocator("iframe") + .getByText("foo", new FrameLocator.GetByTextOptions().setExact(true)) + .frameLocator("frame").first() + .frameLocator("iframe") + .locator("span"); + assertEquals("locator(\"iframe\").contentFrame().getByText(\"foo\", new FrameLocator.GetByTextOptions().setExact(true)).locator(\"frame\").first().contentFrame().locator(\"iframe\").contentFrame().locator(\"span\")", + generate(locator)); + + // Note that frame locators with ">>" are not restored back due to ambiguity. + assertEquals("locator(\"div\").locator(\"iframe\").contentFrame().locator(\"span\")", generate(page.frameLocator("div >> iframe").locator("span"))); + + assertEquals(asList("getByTitle(\"iframe title\").contentFrame()"), asLocators("java", "internal:attr=[title=\"iframe title\"i] >> internal:control=enter-frame")); + } + + @PlaywrightTest + void reverseEngineerFrameLocatorWithoutASelector(Page page) { + assertEquals("frameLocator().getByText(\"foo\").locator(\"span\")", generate(page.frameLocator().getByText("foo").locator("span"))); + assertEquals("frameLocator()", asLocator("java", "internal:control=any-frame")); + } + + @PlaywrightTest + void generateMultipleLocators(Page page) { + String selector = "div >> internal:has-text=\"foo\"i >> nth=0 >> internal:has=\"span >> internal:has-not-text=\\\"bar\\\"i >> nth=-1\""; + Locator locator = page.locator("div", new Page.LocatorOptions().setHasText("foo")).nth(0).filter(new Locator.FilterOptions().setHas(page.locator("span", new Page.LocatorOptions().setHasNotText("bar")).nth(-1))); + assertEquals(asLocator("java", selector), generate(locator)); + assertEquals(asList( + "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).last()))", + "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).nth(-1)))", + "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).last()))", + "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).nth(-1)))", + "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).last()))", + "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).nth(-1)))", + "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).last()))", + "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).nth(-1)))", + "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).last()))", + "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).nth(-1)))", + "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).last()))", + "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).nth(-1)))", + "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).last()))", + "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).nth(-1)))", + "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).last()))", + "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).nth(-1)))" + ), asLocators("java", selector)); + } + + @PlaywrightTest + void reverseEngineerInternalHasTextLocators() { + assertEquals("locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"Goodbye world\")).locator(\"span\")", asLocator("java", "div >> internal:has-text=\"Goodbye world\"i >> span")); + assertEquals("locator(\"div\").locator(\"internal:has-text=\\\"foo\\\"s\")", asLocator("java", "div >> internal:has-text=\"foo\"s")); + assertEquals("locator(\"div\").locator(\"internal:has-not-text=\\\"foo\\\"s\")", asLocator("java", "div >> internal:has-not-text=\"foo\"s")); + } + + @PlaywrightTest + void asLocatorInternalAnd() { + assertEquals("locator(\"div\").and(locator(\"span\").locator(\"article\"))", asLocator("java", "div >> internal:and=\"span >> article\"")); + } + + @PlaywrightTest + void asLocatorInternalOr() { + assertEquals("locator(\"div\").or(locator(\"span\").locator(\"article\"))", asLocator("java", "div >> internal:or=\"span >> article\"")); + } + + @PlaywrightTest + void asLocatorInternalChain() { + assertEquals("locator(\"div\").locator(locator(\"span\").locator(\"article\"))", asLocator("java", "div >> internal:chain=\"span >> article\"")); + } + + @PlaywrightTest + void reverseEngineerNestedLocators(Page page) { + assertEquals("getByRole(AriaRole.ROW).locator(getByRole(AriaRole.CELL).nth(2))", generate(page.getByRole(AriaRole.ROW).locator(page.getByRole(AriaRole.CELL).nth(2)))); + assertEquals("locator(\"div\").and(getByText(\"foo\")).or(locator(\"span\").locator(locator(\"a\"))).first()", + generate(page.locator("div").and(page.getByText("foo")).or(page.locator("span").locator(page.locator("a"))).first())); + } + + @PlaywrightTest + void asLocatorXpath() { + String selector = "//*[contains(normalizer-text(), 'foo']"; + assertEquals("locator(\"//*[contains(normalizer-text(), 'foo']\")", asLocator("java", selector)); + } + + @PlaywrightTest + void reverseEngineerRegexFlags() { + assertEquals("getByText(Pattern.compile(\"a.b\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL))", asLocator("java", "internal:text=/a.b/ims")); + assertEquals("getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(Pattern.compile(\"a.b\", Pattern.DOTALL)))", asLocator("java", "internal:role=button[name=/a.b/s]")); + } + + @PlaywrightTest + void asLocatorDescriptionInvalidInput() { + assertEquals("desc", asLocatorDescription("java", "body >> internal:describe=\"desc\"")); + assertEquals("locator(\"body\")", asLocatorDescription("java", "body >> internal:describe=12")); + assertEquals("following-sibling::*[1]", asLocatorDescription("java", "following-sibling::*[1]")); + assertEquals("locator(\"body\").locator(\"div\")", asLocatorDescription("java", "body >> internal:describe=\"desc\" >> div")); + } + + @PlaywrightTest + void toStringShouldPrintTheDescription(Page page) { + assertEquals("Submit button", page.locator("#submit").describe("Submit button").toString()); + assertEquals("getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Submit\"))", page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Submit")).toString()); + } +} diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorAnyFrame.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorAnyFrame.java index e6764b9b6..97c661b0f 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorAnyFrame.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorAnyFrame.java @@ -577,7 +577,7 @@ void shouldSupportContentFrame(Page page, TestServer server) { @PlaywrightTest @DisplayName("LO-041 should render frameLocator() in the locator description") - @Fixme("java: Locator.toString() is 'Locator@internal:control=any-frame >> #x >> internal:control=enter-frame >> button', not \"frameLocator().locator('#x').contentFrame().locator('button')\"") + @Fixme("java: Locator.toString() prints Java code, frameLocator().locator(\"#x\").contentFrame().locator(\"button\"), not the JavaScript frameLocator().locator('#x').contentFrame().locator('button')") void shouldRenderFrameLocatorInTheLocatorDescription(Page page) { assertEquals("frameLocator().locator('#x').contentFrame().locator('button')", String.valueOf(page.frameLocator().frameLocator("#x").locator("button"))); assertEquals("frameLocator().locator('section').locator('iframe').contentFrame().getByText('foo')", String.valueOf(page.frameLocator().locator("section").frameLocator("iframe").getByText("foo"))); diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorConvenience.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorConvenience.java index cc31a32aa..d3b184cdc 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorConvenience.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorConvenience.java @@ -39,7 +39,7 @@ public class TestLocatorConvenience { @PlaywrightTest @DisplayName("LO-057 should have a nice preview") - @Fixme("java: Locator.toString() is 'Locator@#outer', not \"locator('#outer')\"; the JSHandle preview is 'JSHandle@node'") + @Fixme("java: Locator.toString() prints Java code, locator(\"#outer\"), not the JavaScript locator('#outer'); the JSHandle preview is 'JSHandle@node'") void shouldHaveANicePreview(Page page, TestServer server) { page.navigate(server.PREFIX + "/dom.html"); Locator outer = page.locator("#outer"); @@ -290,7 +290,7 @@ void descriptionShouldReturnDescriptionForLocatorWithMultipleDescribeCalls(Page @PlaywrightTest @DisplayName("LO-077 toString() returns formatted locator") - @Fixme("java: Locator.toString() is 'Locator@internal:role=button[name=\"Submit\"i]', not \"getByRole('button', { name: 'Submit' })\"") + @Fixme("java: Locator.toString() prints Java code, getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Submit\")), not the JavaScript getByRole('button', { name: 'Submit' })") void toStringReturnsFormattedLocator(Page page) { Locator locator = page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Submit")); assertEquals("getByRole('button', { name: 'Submit' })", locator.toString()); From ca3fe332d0497ffe864b4a298da39d639122a31f Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Mon, 23 Nov 2026 13:44:27 -0800 Subject: [PATCH 2/6] chore: port the assertions from the upstream matchers --- playwright/src/main/AGENTS.md | 8 + .../impl/APIResponseAssertionsImpl.java | 67 +- .../playwright/impl/AssertionsBase.java | 113 +- .../playwright/impl/DiffSequences.java | 415 ++++++ .../playwright/impl/FrameExpectOptions.java | 8 +- .../playwright/impl/FrameExpectResult.java | 14 +- .../microsoft/playwright/impl/FrameImpl.java | 36 +- .../microsoft/playwright/impl/JestDiff.java | 1234 +++++++++++++++++ .../playwright/impl/JestGetType.java | 68 + .../playwright/impl/JestMatcherUtils.java | 213 +++ .../impl/LocatorAssertionsImpl.java | 784 +++++++---- .../playwright/impl/LocatorImpl.java | 4 +- .../playwright/impl/MatcherHint.java | 146 ++ .../playwright/impl/PageAssertionsImpl.java | 84 +- .../playwright/impl/PrettyFormat.java | 407 ++++++ .../microsoft/playwright/impl/ToBeTruthy.java | 93 ++ .../microsoft/playwright/impl/ToEqual.java | 144 ++ .../playwright/impl/ToMatchAriaSnapshot.java | 139 ++ .../playwright/impl/ToMatchText.java | 145 ++ playwright/src/test/AGENTS.md | 5 + .../TestAssertThatIsInViewport.java | 2 +- .../microsoft/playwright/TestExpectMisc.java | 4 +- .../playwright/TestLocatorAssertions.java | 130 +- .../playwright/TestPageAriaSnapshot.java | 2 +- .../playwright/TestPageAssertions.java | 8 +- .../tests/page/TestExpectBoolean.java | 47 +- .../playwright/tests/page/TestExpectMisc.java | 120 +- .../tests/page/TestExpectTimeout.java | 27 +- .../tests/page/TestExpectToHaveText.java | 24 +- .../tests/page/TestExpectToHaveValue.java | 2 - .../tests/page/TestLocatorAnyFrame.java | 9 +- .../tests/page/TestToMatchAriaSnapshot.java | 85 +- 32 files changed, 3862 insertions(+), 725 deletions(-) create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/DiffSequences.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/JestDiff.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/JestGetType.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/JestMatcherUtils.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/MatcherHint.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/PrettyFormat.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/ToBeTruthy.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/ToEqual.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/ToMatchAriaSnapshot.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/ToMatchText.java diff --git a/playwright/src/main/AGENTS.md b/playwright/src/main/AGENTS.md index 7cc3afaee..1c75c1eb2 100644 --- a/playwright/src/main/AGENTS.md +++ b/playwright/src/main/AGENTS.md @@ -27,6 +27,14 @@ 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 `JestMatcherUtils`, with `JestDiff`, `DiffSequences`, `PrettyFormat` and `JestGetType`: ports of + the jest packages in `.upstream/node_modules/`, without colors. A failure message is the + upstream message with the Java call: `assertThat(locator).not().hasText(expected) failed` for + `expect(locator).not.toHaveText(expected) failed`, and the title `Assert "hasText"`. - A class that implements a public interface is `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, diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseAssertionsImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseAssertionsImpl.java index e3ad8aa0a..89951f8d7 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseAssertionsImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseAssertionsImpl.java @@ -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) { @@ -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 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 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 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); } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/AssertionsBase.java b/playwright/src/main/java/com/microsoft/playwright/impl/AssertionsBase.java index dd2cc0968..0f468f986 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/AssertionsBase.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/AssertionsBase.java @@ -14,21 +14,20 @@ * 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; @@ -36,56 +35,56 @@ abstract class AssertionsBase { 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 JestMatcherUtils. + static class ExpectMatcherState { + boolean isNot; + String promise; + double timeout; + String title; } - void expectImpl(String expression, List 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 == JestGetType.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 == JestGetType.UNDEFINED) { + return ValueWrapper.create(null); + } if (value == null || !value.getClass().isArray()) { return ValueWrapper.create(value); } @@ -93,26 +92,4 @@ protected static ValueWrapper formatValue(Object value) { 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; - } - } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/DiffSequences.java b/playwright/src/main/java/com/microsoft/playwright/impl/DiffSequences.java new file mode 100644 index 000000000..2bb01fc9c --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/DiffSequences.java @@ -0,0 +1,415 @@ +/* + * 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. + */ + +// Port of @jest/diff-sequences. +// java: the original is MIT licensed, Copyright (c) Meta Platforms, Inc. and affiliates. +package com.microsoft.playwright.impl; + +import com.microsoft.playwright.PlaywrightException; + +class DiffSequences { + // java: the types of the input and output callbacks. + interface IsCommon { + boolean isCommon(int aIndex, int bIndex); + } + + interface FoundSubsequence { + void foundSubsequence(int nCommon, int aCommon, int bCommon); + } + + // java: the type of an item of the callbacks array. + private static class Callbacks { + final FoundSubsequence foundSubsequence; + final IsCommon isCommon; + + Callbacks(FoundSubsequence foundSubsequence, IsCommon isCommon) { + this.foundSubsequence = foundSubsequence; + this.isCommon = isCommon; + } + } + + // java: the type of the division object. + private static class Division { + int aCommonFollowing = NOT_YET_SET; + int aCommonPreceding = NOT_YET_SET; + int aEndPreceding = NOT_YET_SET; + int aStartFollowing = NOT_YET_SET; + int bCommonFollowing = NOT_YET_SET; + int bCommonPreceding = NOT_YET_SET; + int bEndPreceding = NOT_YET_SET; + int bStartFollowing = NOT_YET_SET; + int nChangeFollowing = NOT_YET_SET; + int nChangePreceding = NOT_YET_SET; + int nCommonFollowing = NOT_YET_SET; + int nCommonPreceding = NOT_YET_SET; + } + + private static final String pkg = "@jest/diff-sequences"; + private static final int NOT_YET_SET = 0; + + private static int countCommonItemsF(int aIndex, int aEnd, int bIndex, int bEnd, IsCommon isCommon) { + int nCommon = 0; + while (aIndex < aEnd && bIndex < bEnd && isCommon.isCommon(aIndex, bIndex)) { + aIndex += 1; + bIndex += 1; + nCommon += 1; + } + return nCommon; + } + + private static int countCommonItemsR(int aStart, int aIndex, int bStart, int bIndex, IsCommon isCommon) { + int nCommon = 0; + while (aStart <= aIndex && bStart <= bIndex && isCommon.isCommon(aIndex, bIndex)) { + aIndex -= 1; + bIndex -= 1; + nCommon += 1; + } + return nCommon; + } + + private static int extendPathsF(int d, int aEnd, int bEnd, int bF, IsCommon isCommon, int[] aIndexesF, int iMaxF) { + int iF = 0; + int kF = -d; + int aFirst = aIndexesF[iF]; + int aIndexPrev1 = aFirst; + aIndexesF[iF] += countCommonItemsF(aFirst + 1, aEnd, bF + aFirst - kF + 1, bEnd, isCommon); + + int nF = Math.min(d, iMaxF); + + for (iF += 1, kF += 2; iF <= nF; iF += 1, kF += 2) { + if (iF != d && aIndexPrev1 < aIndexesF[iF]) { + aFirst = aIndexesF[iF]; + } else { + aFirst = aIndexPrev1 + 1; + + if (aEnd <= aFirst) { + return iF - 1; + } + } + + aIndexPrev1 = aIndexesF[iF]; + aIndexesF[iF] = aFirst + countCommonItemsF(aFirst + 1, aEnd, bF + aFirst - kF + 1, bEnd, isCommon); + } + return iMaxF; + } + + private static int extendPathsR(int d, int aStart, int bStart, int bR, IsCommon isCommon, int[] aIndexesR, int iMaxR) { + int iR = 0; + int kR = d; + int aFirst = aIndexesR[iR]; + int aIndexPrev1 = aFirst; + aIndexesR[iR] -= countCommonItemsR(aStart, aFirst - 1, bStart, bR + aFirst - kR - 1, isCommon); + + int nR = Math.min(d, iMaxR); + + for (iR += 1, kR -= 2; iR <= nR; iR += 1, kR -= 2) { + if (iR != d && aIndexesR[iR] < aIndexPrev1) { + aFirst = aIndexesR[iR]; + } else { + aFirst = aIndexPrev1 - 1; + + if (aFirst < aStart) { + return iR - 1; + } + } + + aIndexPrev1 = aIndexesR[iR]; + aIndexesR[iR] = aFirst - countCommonItemsR(aStart, aFirst - 1, bStart, bR + aFirst - kR - 1, isCommon); + } + return iMaxR; + } + + private static boolean extendOverlappablePathsF(int d, int aStart, int aEnd, int bStart, int bEnd, IsCommon isCommon, int[] aIndexesF, int iMaxF, int[] aIndexesR, int iMaxR, Division division) { + int bF = bStart - aStart; + int aLength = aEnd - aStart; + int bLength = bEnd - bStart; + int baDeltaLength = bLength - aLength; + + int kMinOverlapF = -baDeltaLength - (d - 1); + int kMaxOverlapF = -baDeltaLength + (d - 1); + + int aIndexPrev1 = NOT_YET_SET; + + int nF = Math.min(d, iMaxF); + + for (int iF = 0, kF = -d; iF <= nF; iF += 1, kF += 2) { + boolean insert = iF == 0 || iF != d && aIndexPrev1 < aIndexesF[iF]; + int aLastPrev = insert ? aIndexesF[iF] : aIndexPrev1; + int aFirst = insert ? aLastPrev + : aLastPrev + 1; + + int bFirst = bF + aFirst - kF; + int nCommonF = countCommonItemsF(aFirst + 1, aEnd, bFirst + 1, bEnd, isCommon); + int aLast = aFirst + nCommonF; + aIndexPrev1 = aIndexesF[iF]; + aIndexesF[iF] = aLast; + if (kMinOverlapF <= kF && kF <= kMaxOverlapF) { + int iR = (d - 1 - (kF + baDeltaLength)) / 2; + + if (iR <= iMaxR && aIndexesR[iR] - 1 <= aLast) { + int bLastPrev = bF + aLastPrev - (insert ? kF + 1 : kF - 1); + + int nCommonR = countCommonItemsR(aStart, aLastPrev, bStart, bLastPrev, isCommon); + int aIndexPrevFirst = aLastPrev - nCommonR; + int bIndexPrevFirst = bLastPrev - nCommonR; + int aEndPreceding = aIndexPrevFirst + 1; + int bEndPreceding = bIndexPrevFirst + 1; + division.nChangePreceding = d - 1; + if (d - 1 == aEndPreceding + bEndPreceding - aStart - bStart) { + division.aEndPreceding = aStart; + division.bEndPreceding = bStart; + } else { + division.aEndPreceding = aEndPreceding; + division.bEndPreceding = bEndPreceding; + } + division.nCommonPreceding = nCommonR; + if (nCommonR != 0) { + division.aCommonPreceding = aEndPreceding; + division.bCommonPreceding = bEndPreceding; + } + division.nCommonFollowing = nCommonF; + if (nCommonF != 0) { + division.aCommonFollowing = aFirst + 1; + division.bCommonFollowing = bFirst + 1; + } + int aStartFollowing = aLast + 1; + int bStartFollowing = bFirst + nCommonF + 1; + division.nChangeFollowing = d - 1; + if (d - 1 == aEnd + bEnd - aStartFollowing - bStartFollowing) { + division.aStartFollowing = aEnd; + division.bStartFollowing = bEnd; + } else { + division.aStartFollowing = aStartFollowing; + division.bStartFollowing = bStartFollowing; + } + return true; + } + } + } + return false; + } + + private static boolean extendOverlappablePathsR(int d, int aStart, int aEnd, int bStart, int bEnd, IsCommon isCommon, int[] aIndexesF, int iMaxF, int[] aIndexesR, int iMaxR, Division division) { + int bR = bEnd - aEnd; + int aLength = aEnd - aStart; + int bLength = bEnd - bStart; + int baDeltaLength = bLength - aLength; + + int kMinOverlapR = baDeltaLength - d; + int kMaxOverlapR = baDeltaLength + d; + + int aIndexPrev1 = NOT_YET_SET; + + int nR = Math.min(d, iMaxR); + + for (int iR = 0, kR = d; iR <= nR; iR += 1, kR -= 2) { + boolean insert = iR == 0 || iR != d && aIndexesR[iR] < aIndexPrev1; + int aLastPrev = insert ? aIndexesR[iR] : aIndexPrev1; + int aFirst = insert ? aLastPrev + : aLastPrev - 1; + + int bFirst = bR + aFirst - kR; + int nCommonR = countCommonItemsR(aStart, aFirst - 1, bStart, bFirst - 1, isCommon); + int aLast = aFirst - nCommonR; + aIndexPrev1 = aIndexesR[iR]; + aIndexesR[iR] = aLast; + if (kMinOverlapR <= kR && kR <= kMaxOverlapR) { + int iF = (d + (kR - baDeltaLength)) / 2; + + if (iF <= iMaxF && aLast - 1 <= aIndexesF[iF]) { + int bLast = bFirst - nCommonR; + division.nChangePreceding = d; + if (d == aLast + bLast - aStart - bStart) { + division.aEndPreceding = aStart; + division.bEndPreceding = bStart; + } else { + division.aEndPreceding = aLast; + division.bEndPreceding = bLast; + } + division.nCommonPreceding = nCommonR; + if (nCommonR != 0) { + division.aCommonPreceding = aLast; + division.bCommonPreceding = bLast; + } + division.nChangeFollowing = d - 1; + if (d == 1) { + division.nCommonFollowing = 0; + division.aStartFollowing = aEnd; + division.bStartFollowing = bEnd; + } else { + int bLastPrev = bR + aLastPrev - (insert ? kR - 1 : kR + 1); + + int nCommonF = countCommonItemsF(aLastPrev, aEnd, bLastPrev, bEnd, isCommon); + division.nCommonFollowing = nCommonF; + if (nCommonF != 0) { + division.aCommonFollowing = aLastPrev; + division.bCommonFollowing = bLastPrev; + } + int aStartFollowing = aLastPrev + nCommonF; + int bStartFollowing = bLastPrev + nCommonF; + + if (d - 1 == aEnd + bEnd - aStartFollowing - bStartFollowing) { + division.aStartFollowing = aEnd; + division.bStartFollowing = bEnd; + } else { + division.aStartFollowing = aStartFollowing; + division.bStartFollowing = bStartFollowing; + } + } + return true; + } + } + } + return false; + } + + private static void divide(int nChange, int aStart, int aEnd, int bStart, int bEnd, IsCommon isCommon, int[] aIndexesF, int[] aIndexesR, Division division) { + int bF = bStart - aStart; + int bR = bEnd - aEnd; + int aLength = aEnd - aStart; + int bLength = bEnd - bStart; + + int baDeltaLength = bLength - aLength; + + int iMaxF = aLength; + int iMaxR = aLength; + + aIndexesF[0] = aStart - 1; + aIndexesR[0] = aEnd; + + if (baDeltaLength % 2 == 0) { + int dMin = (nChange != 0 ? nChange : baDeltaLength) / 2; + int dMax = (aLength + bLength) / 2; + for (int d = 1; d <= dMax; d += 1) { + iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); + if (d < dMin) { + iMaxR = extendPathsR(d, aStart, bStart, bR, isCommon, aIndexesR, iMaxR); + } else if ( + extendOverlappablePathsR(d, aStart, aEnd, bStart, bEnd, isCommon, aIndexesF, iMaxF, aIndexesR, iMaxR, division)) { + return; + } + } + } else { + int dMin = ((nChange != 0 ? nChange : baDeltaLength) + 1) / 2; + int dMax = (aLength + bLength + 1) / 2; + + int d = 1; + iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); + for (d += 1; d <= dMax; d += 1) { + iMaxR = extendPathsR(d - 1, aStart, bStart, bR, isCommon, aIndexesR, iMaxR); + if (d < dMin) { + iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); + } else if ( + extendOverlappablePathsF(d, aStart, aEnd, bStart, bEnd, isCommon, aIndexesF, iMaxF, aIndexesR, iMaxR, division)) { + return; + } + } + } + + throw new PlaywrightException(pkg + ": no overlap aStart=" + aStart + " aEnd=" + aEnd + " bStart=" + bStart + " bEnd=" + bEnd); + } + + private static void findSubsequences(int nChange, int aStart, int aEnd, int bStart, int bEnd, boolean transposed, Callbacks[] callbacks, int[] aIndexesF, int[] aIndexesR, Division division) { + if (bEnd - bStart < aEnd - aStart) { + transposed = !transposed; + // java: the callbacks array has two slots, the second one is null until it is set. + if (transposed && callbacks[1] == null) { + FoundSubsequence foundSubsequence = callbacks[0].foundSubsequence; + IsCommon isCommon = callbacks[0].isCommon; + callbacks[1] = new Callbacks( + (nCommon, bCommon, aCommon) -> { + foundSubsequence.foundSubsequence(nCommon, aCommon, bCommon); + }, + (bIndex, aIndex) -> isCommon.isCommon(aIndex, bIndex)); + } + int tStart = aStart; + int tEnd = aEnd; + aStart = bStart; + aEnd = bEnd; + bStart = tStart; + bEnd = tEnd; + } + FoundSubsequence foundSubsequence = callbacks[transposed ? 1 : 0].foundSubsequence; + IsCommon isCommon = callbacks[transposed ? 1 : 0].isCommon; + + divide(nChange, aStart, aEnd, bStart, bEnd, isCommon, aIndexesF, aIndexesR, division); + int nChangePreceding = division.nChangePreceding; + int aEndPreceding = division.aEndPreceding; + int bEndPreceding = division.bEndPreceding; + int nCommonPreceding = division.nCommonPreceding; + int aCommonPreceding = division.aCommonPreceding; + int bCommonPreceding = division.bCommonPreceding; + int nCommonFollowing = division.nCommonFollowing; + int aCommonFollowing = division.aCommonFollowing; + int bCommonFollowing = division.bCommonFollowing; + int nChangeFollowing = division.nChangeFollowing; + int aStartFollowing = division.aStartFollowing; + int bStartFollowing = division.bStartFollowing; + + if (aStart < aEndPreceding && bStart < bEndPreceding) { + findSubsequences(nChangePreceding, aStart, aEndPreceding, bStart, bEndPreceding, transposed, callbacks, aIndexesF, aIndexesR, division); + } + + if (nCommonPreceding != 0) { + foundSubsequence.foundSubsequence(nCommonPreceding, aCommonPreceding, bCommonPreceding); + } + if (nCommonFollowing != 0) { + foundSubsequence.foundSubsequence(nCommonFollowing, aCommonFollowing, bCommonFollowing); + } + + if (aStartFollowing < aEnd && bStartFollowing < bEnd) { + findSubsequences(nChangeFollowing, aStartFollowing, aEnd, bStartFollowing, bEnd, transposed, callbacks, aIndexesF, aIndexesR, division); + } + } + + // java: validateLength and validateCallback are not ported, the Java types make these checks. + + static void diffSequence(int aLength, int bLength, IsCommon isCommon, FoundSubsequence foundSubsequence) { + int nCommonF = countCommonItemsF(0, aLength, 0, bLength, isCommon); + if (nCommonF != 0) { + foundSubsequence.foundSubsequence(nCommonF, 0, 0); + } + + if (aLength != nCommonF || bLength != nCommonF) { + int aStart = nCommonF; + int bStart = nCommonF; + + int nCommonR = countCommonItemsR(aStart, aLength - 1, bStart, bLength - 1, isCommon); + + int aEnd = aLength - nCommonR; + int bEnd = bLength - nCommonR; + + int nCommonFR = nCommonF + nCommonR; + if (aLength != nCommonFR && bLength != nCommonFR) { + int nChange = 0; + boolean transposed = false; + Callbacks[] callbacks = new Callbacks[] {new Callbacks(foundSubsequence, isCommon), null}; + + // java: a JavaScript array grows on assignment. The paths use the indexes from zero + // to the length of the shorter sequence, the Java arrays have that size from the start. + int[] aIndexesF = new int[Math.min(aEnd - aStart, bEnd - bStart) + 1]; + int[] aIndexesR = new int[Math.min(aEnd - aStart, bEnd - bStart) + 1]; + + Division division = new Division(); + + findSubsequences(nChange, aStart, aEnd, bStart, bEnd, transposed, callbacks, aIndexesF, aIndexesR, division); + } + if (nCommonR != 0) { + foundSubsequence.foundSubsequence(nCommonR, aEnd, bEnd); + } + } + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectOptions.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectOptions.java index 77f19a2e1..05000a149 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectOptions.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectOptions.java @@ -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 expectedText; String selector; Double expectedNumber; - SerializedArgument expectedValue; + Object expectedValue; Boolean useInnerText; PseudoElement pseudo; boolean isNot; - Double timeout; + double timeout; + String title; } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectResult.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectResult.java index 8a4d3477d..5bc4b4290 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectResult.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectResult.java @@ -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 log; + Boolean timedOut; + String errorMessage; + + static class ExpectReceived { + Object value; + String ariaSnapshot; + } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java index afbeca621..05e29d3b2 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java @@ -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; @@ -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 JestGetType.UNDEFINED, null is the JavaScript null. + received.value = details.received.value != null && !"undefined".equals(details.received.value.v) ? parseResult(details.received.value) : JestGetType.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; } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/JestDiff.java b/playwright/src/main/java/com/microsoft/playwright/impl/JestDiff.java new file mode 100644 index 000000000..0bb32bf23 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/JestDiff.java @@ -0,0 +1,1234 @@ +/* + * 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. + */ + +// Port of jest-diff. +// java: the original is MIT licensed, Copyright (c) Meta Platforms, Inc. and affiliates. +// java: cleanupSemantic.ts is from Diff Match and Patch, Copyright 2018 The diff-match-patch Authors, +// https://github.com/google/diff-match-patch, licensed under the Apache License, Version 2.0. +// java: the upstream files are in one class, in the order of the bundle: cleanupSemantic.ts, +// constants.ts, diffLines.ts, diffStrings.ts, escapeControlCharacters.ts, getAlignedDiffs.ts, +// joinAlignedDiffs.ts, normalizeDiffOptions.ts, printDiffs.ts, index.ts. +package com.microsoft.playwright.impl; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.microsoft.playwright.impl.DiffSequences.diffSequence; +import static com.microsoft.playwright.impl.JestGetType.getType; + +class JestDiff { + // java: no ANSI colors, the color functions return the text as is. + static class Chalk { + static String green(String text) { + return text; + } + + static String red(String text) { + return text; + } + + static String inverse(String text) { + return text; + } + + static String bold(String text) { + return text; + } + + static String dim(String text) { + return text; + } + + static String yellow(String text) { + return text; + } + + static String bgYellow(String text) { + return text; + } + } + + // java: the type of the options object. A null field is an option that is not set. + static class DiffOptions { + String aAnnotation; + Function aColor; + String aIndicator; + String bAnnotation; + Function bColor; + String bIndicator; + Function changeColor; + Function changeLineTrailingSpaceColor; + Function commonColor; + String commonIndicator; + Function commonLineTrailingSpaceColor; + Comparator compareKeys; + Integer contextLines; + String emptyFirstOrLastLinePlaceholder; + Boolean expand; + Boolean includeChangeCounts; + Boolean omitAnnotationLines; + Function patchColor; + } + + // java: the type of the result of countChanges. + private static class ChangeCounts { + int a; + int b; + } + + // java: helpers with no counterpart upstream, the ports of String.prototype.substring and + // String.prototype.charAt. They accept an index that is out of the string, as JavaScript does. + private static String substring(String string, int start) { + return substring(string, start, string.length()); + } + + private static String substring(String string, int start, int end) { + start = Math.max(0, Math.min(start, string.length())); + end = Math.max(0, Math.min(end, string.length())); + return string.substring(Math.min(start, end), Math.max(start, end)); + } + + private static String charAt(String string, int index) { + return index < 0 || index >= string.length() ? "" : string.substring(index, index + 1); + } + + // java: helper with no counterpart upstream, the port of String.prototype.repeat. + private static String repeat(String string, int count) { + StringBuilder result = new StringBuilder(); + for (int i = 0; i < count; i++) { + result.append(string); + } + return result.toString(); + } + + // java: helper with no counterpart upstream, the port of String.prototype.split: it keeps + // the empty strings at the end. + private static List split(String string, String separator) { + return new ArrayList<>(Arrays.asList(string.split(Pattern.quote(separator), -1))); + } + + // java: the whitespace characters of \s in a JavaScript regular expression. \s in Java + // matches the ASCII whitespace only. + static final String WHITESPACE = "[\\t\\n\\x0B\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]"; + + static final int DIFF_DELETE = -1; + static final int DIFF_INSERT = 1; + static final int DIFF_EQUAL = 0; + + // java: the items 0 and 1 of upstream are the fields op and text. + static class Diff { + int op; + String text; + + Diff(int op, String text) { + this.op = op; + this.text = text; + } + } + + private static int diff_commonPrefix(String text1, String text2) { + if (text1.isEmpty() || text2.isEmpty() || text1.charAt(0) != text2.charAt(0)) { + return 0; + } + int pointermin = 0; + int pointermax = Math.min(text1.length(), text2.length()); + int pointermid = pointermax; + int pointerstart = 0; + while (pointermin < pointermid) { + if (substring(text1, pointerstart, pointermid).equals(substring(text2, pointerstart, pointermid))) { + pointermin = pointermid; + pointerstart = pointermin; + } else { + pointermax = pointermid; + } + pointermid = (pointermax - pointermin) / 2 + pointermin; + } + return pointermid; + } + + private static int diff_commonSuffix(String text1, String text2) { + if (text1.isEmpty() || text2.isEmpty() || text1.charAt(text1.length() - 1) != text2.charAt(text2.length() - 1)) { + return 0; + } + int pointermin = 0; + int pointermax = Math.min(text1.length(), text2.length()); + int pointermid = pointermax; + int pointerend = 0; + while (pointermin < pointermid) { + if (substring(text1, text1.length() - pointermid, text1.length() - pointerend).equals(substring(text2, text2.length() - pointermid, text2.length() - pointerend))) { + pointermin = pointermid; + pointerend = pointermin; + } else { + pointermax = pointermid; + } + pointermid = (pointermax - pointermin) / 2 + pointermin; + } + return pointermid; + } + + private static int diff_commonOverlap_(String text1, String text2) { + int text1_length = text1.length(); + int text2_length = text2.length(); + if (text1_length == 0 || text2_length == 0) { + return 0; + } + if (text1_length > text2_length) { + text1 = substring(text1, text1_length - text2_length); + } else if (text1_length < text2_length) { + text2 = substring(text2, 0, text1_length); + } + int text_length = Math.min(text1_length, text2_length); + if (text1.equals(text2)) { + return text_length; + } + + int best = 0; + int length = 1; + while (true) { + String pattern = substring(text1, text_length - length); + int found = text2.indexOf(pattern); + if (found == -1) { + return best; + } + length += found; + if (found == 0 || substring(text1, text_length - length).equals(substring(text2, 0, length))) { + best = length; + length++; + } + } + } + + static void diff_cleanupSemantic(List diffs) { + boolean changes = false; + // java: the stack is a map, because upstream decreases equalitiesLength below zero and + // then writes and reads the property -1 of the JavaScript array. + Map equalities = new HashMap<>(); + int equalitiesLength = 0; + String lastEquality = null; + int pointer = 0; + int length_insertions1 = 0; + int length_deletions1 = 0; + int length_insertions2 = 0; + int length_deletions2 = 0; + while (pointer < diffs.size()) { + if (diffs.get(pointer).op == DIFF_EQUAL) { + equalities.put(equalitiesLength++, pointer); + length_insertions1 = length_insertions2; + length_deletions1 = length_deletions2; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = diffs.get(pointer).text; + } else { + if (diffs.get(pointer).op == DIFF_INSERT) { + length_insertions2 += diffs.get(pointer).text.length(); + } else { + length_deletions2 += diffs.get(pointer).text.length(); + } + if (lastEquality != null && !lastEquality.isEmpty() && lastEquality.length() <= Math.max(length_insertions1, length_deletions1) && lastEquality.length() <= Math.max(length_insertions2, length_deletions2)) { + diffs.add(equalities.get(equalitiesLength - 1), new Diff(DIFF_DELETE, lastEquality)); + diffs.get(equalities.get(equalitiesLength - 1) + 1).op = DIFF_INSERT; + equalitiesLength--; + equalitiesLength--; + pointer = equalitiesLength > 0 ? equalities.get(equalitiesLength - 1) : -1; + length_insertions1 = 0; + length_deletions1 = 0; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = null; + changes = true; + } + } + pointer++; + } + + if (changes) { + diff_cleanupMerge(diffs); + } + diff_cleanupSemanticLossless(diffs); + + pointer = 1; + while (pointer < diffs.size()) { + if (diffs.get(pointer - 1).op == DIFF_DELETE && diffs.get(pointer).op == DIFF_INSERT) { + String deletion = diffs.get(pointer - 1).text; + String insertion = diffs.get(pointer).text; + int overlap_length1 = diff_commonOverlap_(deletion, insertion); + int overlap_length2 = diff_commonOverlap_(insertion, deletion); + if (overlap_length1 >= overlap_length2) { + if (overlap_length1 >= deletion.length() / 2.0 || overlap_length1 >= insertion.length() / 2.0) { + diffs.add(pointer, new Diff(DIFF_EQUAL, substring(insertion, 0, overlap_length1))); + diffs.get(pointer - 1).text = substring(deletion, 0, deletion.length() - overlap_length1); + diffs.get(pointer + 1).text = substring(insertion, overlap_length1); + pointer++; + } + } else { + if (overlap_length2 >= deletion.length() / 2.0 || overlap_length2 >= insertion.length() / 2.0) { + diffs.add(pointer, new Diff(DIFF_EQUAL, substring(deletion, 0, overlap_length2))); + diffs.get(pointer - 1).op = DIFF_INSERT; + diffs.get(pointer - 1).text = substring(insertion, 0, insertion.length() - overlap_length2); + diffs.get(pointer + 1).op = DIFF_DELETE; + diffs.get(pointer + 1).text = substring(deletion, overlap_length2); + pointer++; + } + } + pointer++; + } + pointer++; + } + } + + // java: diff_cleanupSemanticScore_ is a function inside of diff_cleanupSemanticLossless upstream. + private static int diff_cleanupSemanticScore_(String one, String two) { + if (one.isEmpty() || two.isEmpty()) { + return 6; + } + + String char1 = charAt(one, one.length() - 1); + String char2 = charAt(two, 0); + boolean nonAlphaNumeric1 = nonAlphaNumericRegex_.matcher(char1).find(); + boolean nonAlphaNumeric2 = nonAlphaNumericRegex_.matcher(char2).find(); + boolean whitespace1 = nonAlphaNumeric1 && whitespaceRegex_.matcher(char1).find(); + boolean whitespace2 = nonAlphaNumeric2 && whitespaceRegex_.matcher(char2).find(); + boolean lineBreak1 = whitespace1 && linebreakRegex_.matcher(char1).find(); + boolean lineBreak2 = whitespace2 && linebreakRegex_.matcher(char2).find(); + boolean blankLine1 = lineBreak1 && blanklineEndRegex_.matcher(one).find(); + boolean blankLine2 = lineBreak2 && blanklineStartRegex_.matcher(two).find(); + if (blankLine1 || blankLine2) { + return 5; + } else if (lineBreak1 || lineBreak2) { + return 4; + } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { + return 3; + } else if (whitespace1 || whitespace2) { + return 2; + } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { + return 1; + } + return 0; + } + + private static void diff_cleanupSemanticLossless(List diffs) { + int pointer = 1; + while (pointer < diffs.size() - 1) { + if (diffs.get(pointer - 1).op == DIFF_EQUAL && diffs.get(pointer + 1).op == DIFF_EQUAL) { + String equality1 = diffs.get(pointer - 1).text; + String edit = diffs.get(pointer).text; + String equality2 = diffs.get(pointer + 1).text; + + int commonOffset = diff_commonSuffix(equality1, edit); + if (commonOffset != 0) { + String commonString = substring(edit, edit.length() - commonOffset); + equality1 = substring(equality1, 0, equality1.length() - commonOffset); + edit = commonString + substring(edit, 0, edit.length() - commonOffset); + equality2 = commonString + equality2; + } + + String bestEquality1 = equality1; + String bestEdit = edit; + String bestEquality2 = equality2; + int bestScore = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); + while (charAt(edit, 0).equals(charAt(equality2, 0))) { + equality1 += charAt(edit, 0); + edit = substring(edit, 1) + charAt(equality2, 0); + equality2 = substring(equality2, 1); + int score = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); + if (score >= bestScore) { + bestScore = score; + bestEquality1 = equality1; + bestEdit = edit; + bestEquality2 = equality2; + } + } + if (!diffs.get(pointer - 1).text.equals(bestEquality1)) { + if (!bestEquality1.isEmpty()) { + diffs.get(pointer - 1).text = bestEquality1; + } else { + diffs.remove(pointer - 1); + pointer--; + } + diffs.get(pointer).text = bestEdit; + if (!bestEquality2.isEmpty()) { + diffs.get(pointer + 1).text = bestEquality2; + } else { + diffs.remove(pointer + 1); + pointer--; + } + } + } + pointer++; + } + } + + private static final Pattern nonAlphaNumericRegex_ = Pattern.compile("[^a-zA-Z0-9]"); + private static final Pattern whitespaceRegex_ = Pattern.compile(WHITESPACE); + private static final Pattern linebreakRegex_ = Pattern.compile("[\\r\\n]"); + // java: \z is the end of the string. $ in Java matches before a line terminator at the end too. + private static final Pattern blanklineEndRegex_ = Pattern.compile("\\n\\r?\\n\\z"); + private static final Pattern blanklineStartRegex_ = Pattern.compile("^\\r?\\n\\r?\\n"); + + private static void diff_cleanupMerge(List diffs) { + diffs.add(new Diff(DIFF_EQUAL, "")); + int pointer = 0; + int count_delete = 0; + int count_insert = 0; + String text_delete = ""; + String text_insert = ""; + int commonlength; + while (pointer < diffs.size()) { + switch (diffs.get(pointer).op) { + case DIFF_INSERT: + count_insert++; + text_insert += diffs.get(pointer).text; + pointer++; + break; + case DIFF_DELETE: + count_delete++; + text_delete += diffs.get(pointer).text; + pointer++; + break; + case DIFF_EQUAL: + if (count_delete + count_insert > 1) { + if (count_delete != 0 && count_insert != 0) { + commonlength = diff_commonPrefix(text_insert, text_delete); + if (commonlength != 0) { + if (pointer - count_delete - count_insert > 0 && diffs.get(pointer - count_delete - count_insert - 1).op == DIFF_EQUAL) { + diffs.get(pointer - count_delete - count_insert - 1).text += substring(text_insert, 0, commonlength); + } else { + diffs.add(0, new Diff(DIFF_EQUAL, substring(text_insert, 0, commonlength))); + pointer++; + } + text_insert = substring(text_insert, commonlength); + text_delete = substring(text_delete, commonlength); + } + commonlength = diff_commonSuffix(text_insert, text_delete); + if (commonlength != 0) { + diffs.get(pointer).text = substring(text_insert, text_insert.length() - commonlength) + diffs.get(pointer).text; + text_insert = substring(text_insert, 0, text_insert.length() - commonlength); + text_delete = substring(text_delete, 0, text_delete.length() - commonlength); + } + } + pointer -= count_delete + count_insert; + // java: splice(pointer, n) removes n items. + for (int i = 0; i < count_delete + count_insert; i++) { + diffs.remove(pointer); + } + if (text_delete.length() != 0) { + diffs.add(pointer, new Diff(DIFF_DELETE, text_delete)); + pointer++; + } + if (text_insert.length() != 0) { + diffs.add(pointer, new Diff(DIFF_INSERT, text_insert)); + pointer++; + } + pointer++; + } else if (pointer != 0 && diffs.get(pointer - 1).op == DIFF_EQUAL) { + diffs.get(pointer - 1).text += diffs.get(pointer).text; + diffs.remove(pointer); + } else { + pointer++; + } + count_insert = 0; + count_delete = 0; + text_delete = ""; + text_insert = ""; + break; + } + } + if (diffs.get(diffs.size() - 1).text.equals("")) { + diffs.remove(diffs.size() - 1); + } + + boolean changes = false; + pointer = 1; + while (pointer < diffs.size() - 1) { + if (diffs.get(pointer - 1).op == DIFF_EQUAL && diffs.get(pointer + 1).op == DIFF_EQUAL) { + if (substring(diffs.get(pointer).text, diffs.get(pointer).text.length() - diffs.get(pointer - 1).text.length()).equals(diffs.get(pointer - 1).text)) { + diffs.get(pointer).text = diffs.get(pointer - 1).text + substring(diffs.get(pointer).text, 0, diffs.get(pointer).text.length() - diffs.get(pointer - 1).text.length()); + diffs.get(pointer + 1).text = diffs.get(pointer - 1).text + diffs.get(pointer + 1).text; + diffs.remove(pointer - 1); + changes = true; + } else if (substring(diffs.get(pointer).text, 0, diffs.get(pointer + 1).text.length()).equals(diffs.get(pointer + 1).text)) { + diffs.get(pointer - 1).text += diffs.get(pointer + 1).text; + diffs.get(pointer).text = substring(diffs.get(pointer).text, diffs.get(pointer + 1).text.length()) + diffs.get(pointer + 1).text; + diffs.remove(pointer + 1); + changes = true; + } + } + pointer++; + } + if (changes) { + diff_cleanupMerge(diffs); + } + } + + static final String NO_DIFF_MESSAGE = "Compared values have no visual difference."; + static final String SIMILAR_MESSAGE = "Compared values serialize to the same structure.\n" + "Printing internal object structure without calling `toJSON` instead."; + + private static boolean isEmptyString(List lines) { + return lines.size() == 1 && lines.get(0).length() == 0; + } + + private static ChangeCounts countChanges(List diffs) { + int a = 0; + int b = 0; + for (Diff diff : diffs) { + switch (diff.op) { + case DIFF_DELETE: + a += 1; + break; + case DIFF_INSERT: + b += 1; + break; + } + } + ChangeCounts changeCounts = new ChangeCounts(); + changeCounts.a = a; + changeCounts.b = b; + return changeCounts; + } + + private static String printAnnotation(DiffOptions options, ChangeCounts changeCounts) { + String aAnnotation = options.aAnnotation; + Function aColor = options.aColor; + String aIndicator = options.aIndicator; + String bAnnotation = options.bAnnotation; + Function bColor = options.bColor; + String bIndicator = options.bIndicator; + boolean includeChangeCounts = options.includeChangeCounts; + boolean omitAnnotationLines = options.omitAnnotationLines; + if (omitAnnotationLines) { + return ""; + } + String aRest = ""; + String bRest = ""; + if (includeChangeCounts) { + String aCount = String.valueOf(changeCounts.a); + String bCount = String.valueOf(changeCounts.b); + + int baAnnotationLengthDiff = bAnnotation.length() - aAnnotation.length(); + String aAnnotationPadding = repeat(" ", Math.max(0, baAnnotationLengthDiff)); + String bAnnotationPadding = repeat(" ", Math.max(0, -baAnnotationLengthDiff)); + + int baCountLengthDiff = bCount.length() - aCount.length(); + String aCountPadding = repeat(" ", Math.max(0, baCountLengthDiff)); + String bCountPadding = repeat(" ", Math.max(0, -baCountLengthDiff)); + aRest = aAnnotationPadding + " " + aIndicator + " " + aCountPadding + aCount; + bRest = bAnnotationPadding + " " + bIndicator + " " + bCountPadding + bCount; + } + String a = aIndicator + " " + aAnnotation + aRest; + String b = bIndicator + " " + bAnnotation + bRest; + return aColor.apply(a) + "\n" + bColor.apply(b) + "\n\n"; + } + + static String printDiffLines(List diffs, DiffOptions options) { + return printAnnotation(options, countChanges(diffs)) + (options.expand ? joinAlignedDiffsExpand(diffs, options) : joinAlignedDiffsNoExpand(diffs, options)); + } + + static String diffLinesUnified(List aLines, List bLines, DiffOptions options) { + return printDiffLines(diffLinesRaw(isEmptyString(aLines) ? new ArrayList<>() : map(aLines, JestDiff::escapeControlCharacters), isEmptyString(bLines) ? new ArrayList<>() : map(bLines, JestDiff::escapeControlCharacters)), normalizeDiffOptions(options)); + } + + // java: helper with no counterpart upstream, the port of Array.prototype.map. + private static List map(List lines, Function callback) { + List result = new ArrayList<>(); + for (String line : lines) { + result.add(callback.apply(line)); + } + return result; + } + + static String diffLinesUnified2(List aLinesDisplay, List bLinesDisplay, List aLinesCompare, List bLinesCompare, DiffOptions options) { + if (isEmptyString(aLinesDisplay) && isEmptyString(aLinesCompare)) { + aLinesDisplay = new ArrayList<>(); + aLinesCompare = new ArrayList<>(); + } + if (isEmptyString(bLinesDisplay) && isEmptyString(bLinesCompare)) { + bLinesDisplay = new ArrayList<>(); + bLinesCompare = new ArrayList<>(); + } + if (aLinesDisplay.size() != aLinesCompare.size() || bLinesDisplay.size() != bLinesCompare.size()) { + return diffLinesUnified(aLinesDisplay, bLinesDisplay, options); + } + List diffs = diffLinesRaw(aLinesCompare, bLinesCompare); + + int aIndex = 0; + int bIndex = 0; + for (Diff diff : diffs) { + switch (diff.op) { + case DIFF_DELETE: + diff.text = aLinesDisplay.get(aIndex); + aIndex += 1; + break; + case DIFF_INSERT: + diff.text = bLinesDisplay.get(bIndex); + bIndex += 1; + break; + default: + diff.text = bLinesDisplay.get(bIndex); + aIndex += 1; + bIndex += 1; + } + } + return printDiffLines(diffs, normalizeDiffOptions(options)); + } + + static List diffLinesRaw(List aLines, List bLines) { + int aLength = aLines.size(); + int bLength = bLines.size(); + DiffSequences.IsCommon isCommon = (aIndex, bIndex) -> aLines.get(aIndex).equals(bLines.get(bIndex)); + List diffs = new ArrayList<>(); + // java: a lambda cannot assign a local variable, aIndex and bIndex are arrays of one item. + int[] aIndex = {0}; + int[] bIndex = {0}; + DiffSequences.FoundSubsequence foundSubsequence = (nCommon, aCommon, bCommon) -> { + for (; aIndex[0] != aCommon; aIndex[0] += 1) { + diffs.add(new Diff(DIFF_DELETE, aLines.get(aIndex[0]))); + } + for (; bIndex[0] != bCommon; bIndex[0] += 1) { + diffs.add(new Diff(DIFF_INSERT, bLines.get(bIndex[0]))); + } + for (; nCommon != 0; nCommon -= 1, aIndex[0] += 1, bIndex[0] += 1) { + diffs.add(new Diff(DIFF_EQUAL, bLines.get(bIndex[0]))); + } + }; + diffSequence(aLength, bLength, isCommon, foundSubsequence); + + for (; aIndex[0] != aLength; aIndex[0] += 1) { + diffs.add(new Diff(DIFF_DELETE, aLines.get(aIndex[0]))); + } + for (; bIndex[0] != bLength; bIndex[0] += 1) { + diffs.add(new Diff(DIFF_INSERT, bLines.get(bIndex[0]))); + } + return diffs; + } + + private static List diffStrings(String a, String b) { + DiffSequences.IsCommon isCommon = (aIndex, bIndex) -> a.charAt(aIndex) == b.charAt(bIndex); + // java: a lambda cannot assign a local variable, aIndex and bIndex are arrays of one item. + int[] aIndex = {0}; + int[] bIndex = {0}; + List diffs = new ArrayList<>(); + DiffSequences.FoundSubsequence foundSubsequence = (nCommon, aCommon, bCommon) -> { + if (aIndex[0] != aCommon) { + diffs.add(new Diff(DIFF_DELETE, a.substring(aIndex[0], aCommon))); + } + if (bIndex[0] != bCommon) { + diffs.add(new Diff(DIFF_INSERT, b.substring(bIndex[0], bCommon))); + } + aIndex[0] = aCommon + nCommon; + bIndex[0] = bCommon + nCommon; + diffs.add(new Diff(DIFF_EQUAL, b.substring(bCommon, bIndex[0]))); + }; + diffSequence(a.length(), b.length(), isCommon, foundSubsequence); + + if (aIndex[0] != a.length()) { + diffs.add(new Diff(DIFF_DELETE, a.substring(aIndex[0]))); + } + if (bIndex[0] != b.length()) { + diffs.add(new Diff(DIFF_INSERT, b.substring(bIndex[0]))); + } + return diffs; + } + + private static final Pattern controlCharactersRegex = Pattern.compile("[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F-\\u009F]"); + + static String escapeControlCharacters(String str) { + // java: replaceAll with a callback is a loop over the matches. + Matcher matcher = controlCharactersRegex.matcher(str); + StringBuffer result = new StringBuffer(); + while (matcher.find()) { + String match = matcher.group(); + String replacement; + switch (match) { + case "\b": + replacement = "\\b"; + break; + case "\f": + replacement = "\\f"; + break; + case "\u000B": + replacement = "\\v"; + break; + default: { + int code = match.codePointAt(0); + replacement = "\\x" + (code < 16 ? "0" : "") + Integer.toString(code, 16); + } + } + matcher.appendReplacement(result, Matcher.quoteReplacement(replacement)); + } + matcher.appendTail(result); + return result.toString(); + } + + private static String concatenateRelevantDiffs(int op, List diffs, Function changeColor) { + String reduced = ""; + for (Diff diff : diffs) { + reduced = reduced + (diff.op == DIFF_EQUAL ? diff.text : diff.op == op && diff.text.length() > 0 + ? changeColor.apply(diff.text) : ""); + } + return reduced; + } + + private static class ChangeBuffer { + int op; + List line; + List lines; + Function changeColor; + + ChangeBuffer(int op, Function changeColor) { + this.op = op; + this.line = new ArrayList<>(); + this.lines = new ArrayList<>(); + this.changeColor = changeColor; + } + + void pushSubstring(String substring) { + this.pushDiff(new Diff(this.op, substring)); + } + + void pushLine() { + this.lines.add(this.line.size() == 1 ? this.line.get(0).op == this.op ? this.line.get(0) + : new Diff(this.op, this.line.get(0).text) : new Diff(this.op, concatenateRelevantDiffs(this.op, this.line, this.changeColor)) + ); + this.line.clear(); + } + + boolean isLineEmpty() { + return this.line.size() == 0; + } + + void pushDiff(Diff diff) { + this.line.add(diff); + } + + void align(Diff diff) { + String string = diff.text; + if (string.contains("\n")) { + List substrings = split(string, "\n"); + int iLast = substrings.size() - 1; + for (int i = 0; i < substrings.size(); i++) { + String substring = substrings.get(i); + if (i < iLast) { + this.pushSubstring(substring); + this.pushLine(); + } else if (substring.length() > 0) { + this.pushSubstring(substring); + } + } + } else { + this.pushDiff(diff); + } + } + + void moveLinesTo(List lines) { + if (!this.isLineEmpty()) { + this.pushLine(); + } + lines.addAll(this.lines); + this.lines.clear(); + } + } + + private static class CommonBuffer { + ChangeBuffer deleteBuffer; + ChangeBuffer insertBuffer; + List lines; + + CommonBuffer(ChangeBuffer deleteBuffer, ChangeBuffer insertBuffer) { + this.deleteBuffer = deleteBuffer; + this.insertBuffer = insertBuffer; + this.lines = new ArrayList<>(); + } + + void pushDiffCommonLine(Diff diff) { + this.lines.add(diff); + } + + void pushDiffChangeLines(Diff diff) { + boolean isDiffEmpty = diff.text.length() == 0; + + if (!isDiffEmpty || this.deleteBuffer.isLineEmpty()) { + this.deleteBuffer.pushDiff(diff); + } + if (!isDiffEmpty || this.insertBuffer.isLineEmpty()) { + this.insertBuffer.pushDiff(diff); + } + } + + void flushChangeLines() { + this.deleteBuffer.moveLinesTo(this.lines); + this.insertBuffer.moveLinesTo(this.lines); + } + + void align(Diff diff) { + int op = diff.op; + String string = diff.text; + if (string.contains("\n")) { + List substrings = split(string, "\n"); + int iLast = substrings.size() - 1; + for (int i = 0; i < substrings.size(); i++) { + String substring = substrings.get(i); + if (i == 0) { + Diff subdiff = new Diff(op, substring); + if (this.deleteBuffer.isLineEmpty() && this.insertBuffer.isLineEmpty()) { + this.flushChangeLines(); + this.pushDiffCommonLine(subdiff); + } else { + this.pushDiffChangeLines(subdiff); + this.flushChangeLines(); + } + } else if (i < iLast) { + this.pushDiffCommonLine(new Diff(op, substring)); + } else if (substring.length() > 0) { + this.pushDiffChangeLines(new Diff(op, substring)); + } + } + } else { + this.pushDiffChangeLines(diff); + } + } + + List getLines() { + this.flushChangeLines(); + return this.lines; + } + } + + private static List getAlignedDiffs(List diffs, Function changeColor) { + ChangeBuffer deleteBuffer = new ChangeBuffer(DIFF_DELETE, changeColor); + ChangeBuffer insertBuffer = new ChangeBuffer(DIFF_INSERT, changeColor); + CommonBuffer commonBuffer = new CommonBuffer(deleteBuffer, insertBuffer); + for (Diff diff : diffs) { + switch (diff.op) { + case DIFF_DELETE: + deleteBuffer.align(diff); + break; + case DIFF_INSERT: + insertBuffer.align(diff); + break; + default: + commonBuffer.align(diff); + } + } + return commonBuffer.getLines(); + } + + // java: \z is the end of the string. $ in Java matches before a line terminator at the end too. + private static final Pattern trailingSpacesRegex = Pattern.compile(WHITESPACE + "+\\z"); + + private static String formatTrailingSpaces(String line, Function trailingSpaceFormatter) { + // java: replace with a callback is the replacement of the first match. + Matcher matcher = trailingSpacesRegex.matcher(line); + if (!matcher.find()) { + return line; + } + return line.substring(0, matcher.start()) + trailingSpaceFormatter.apply(matcher.group()) + line.substring(matcher.end()); + } + + private static String printDiffLine(String line, boolean isFirstOrLast, Function color, String indicator, Function trailingSpaceFormatter, String emptyFirstOrLastLinePlaceholder) { + return line.length() == 0 ? indicator.equals(" ") ? isFirstOrLast && emptyFirstOrLastLinePlaceholder.length() > 0 ? color.apply(indicator + " " + emptyFirstOrLastLinePlaceholder) : "" : color.apply(indicator) : color.apply(indicator + " " + formatTrailingSpaces(line, trailingSpaceFormatter)); + } + + private static String printDeleteLine(String line, boolean isFirstOrLast, DiffOptions options) { + return printDiffLine(line, isFirstOrLast, options.aColor, options.aIndicator, options.changeLineTrailingSpaceColor, options.emptyFirstOrLastLinePlaceholder); + } + + private static String printInsertLine(String line, boolean isFirstOrLast, DiffOptions options) { + return printDiffLine(line, isFirstOrLast, options.bColor, options.bIndicator, options.changeLineTrailingSpaceColor, options.emptyFirstOrLastLinePlaceholder); + } + + private static String printCommonLine(String line, boolean isFirstOrLast, DiffOptions options) { + return printDiffLine(line, isFirstOrLast, options.commonColor, options.commonIndicator, options.commonLineTrailingSpaceColor, options.emptyFirstOrLastLinePlaceholder); + } + + private static String createPatchMark(int aStart, int aEnd, int bStart, int bEnd, DiffOptions options) { + return options.patchColor.apply("@@ -" + (aStart + 1) + "," + (aEnd - aStart) + " +" + (bStart + 1) + "," + (bEnd - bStart) + " @@"); + } + + private static String joinAlignedDiffsNoExpand(List diffs, DiffOptions options) { + int iLength = diffs.size(); + int nContextLines = options.contextLines; + int nContextLines2 = nContextLines + nContextLines; + + int jLength = iLength; + boolean hasExcessAtStartOrEnd = false; + int nExcessesBetweenChanges = 0; + int i = 0; + while (i != iLength) { + int iStart = i; + while (i != iLength && diffs.get(i).op == DIFF_EQUAL) { + i += 1; + } + if (iStart != i) { + if (iStart == 0) { + if (i > nContextLines) { + jLength -= i - nContextLines; + hasExcessAtStartOrEnd = true; + } + } else if (i == iLength) { + int n = i - iStart; + if (n > nContextLines) { + jLength -= n - nContextLines; + hasExcessAtStartOrEnd = true; + } + } else { + int n = i - iStart; + if (n > nContextLines2) { + jLength -= n - nContextLines2; + nExcessesBetweenChanges += 1; + } + } + } + while (i != iLength && diffs.get(i).op != DIFF_EQUAL) { + i += 1; + } + } + boolean hasPatch = nExcessesBetweenChanges != 0 || hasExcessAtStartOrEnd; + if (nExcessesBetweenChanges != 0) { + jLength += nExcessesBetweenChanges + 1; + } else if (hasExcessAtStartOrEnd) { + jLength += 1; + } + int jLast = jLength - 1; + List lines = new ArrayList<>(); + int jPatchMark = 0; + if (hasPatch) { + lines.add(""); + } + + // java: a lambda cannot assign a local variable, aEnd and bEnd are arrays of one item. + int aStart = 0; + int bStart = 0; + int[] aEnd = {0}; + int[] bEnd = {0}; + Consumer pushCommonLine = line -> { + int j = lines.size(); + lines.add(printCommonLine(line, j == 0 || j == jLast, options)); + aEnd[0] += 1; + bEnd[0] += 1; + }; + Consumer pushDeleteLine = line -> { + int j = lines.size(); + lines.add(printDeleteLine(line, j == 0 || j == jLast, options)); + aEnd[0] += 1; + }; + Consumer pushInsertLine = line -> { + int j = lines.size(); + lines.add(printInsertLine(line, j == 0 || j == jLast, options)); + bEnd[0] += 1; + }; + + i = 0; + while (i != iLength) { + int iStart = i; + while (i != iLength && diffs.get(i).op == DIFF_EQUAL) { + i += 1; + } + if (iStart != i) { + if (iStart == 0) { + if (i > nContextLines) { + iStart = i - nContextLines; + aStart = iStart; + bStart = iStart; + aEnd[0] = aStart; + bEnd[0] = bStart; + } + for (int iCommon = iStart; iCommon != i; iCommon += 1) { + pushCommonLine.accept(diffs.get(iCommon).text); + } + } else if (i == iLength) { + int iEnd = i - iStart > nContextLines ? iStart + nContextLines : i; + for (int iCommon = iStart; iCommon != iEnd; iCommon += 1) { + pushCommonLine.accept(diffs.get(iCommon).text); + } + } else { + int nCommon = i - iStart; + if (nCommon > nContextLines2) { + int iEnd = iStart + nContextLines; + for (int iCommon = iStart; iCommon != iEnd; iCommon += 1) { + pushCommonLine.accept(diffs.get(iCommon).text); + } + lines.set(jPatchMark, createPatchMark(aStart, aEnd[0], bStart, bEnd[0], options)); + jPatchMark = lines.size(); + lines.add(""); + + int nOmit = nCommon - nContextLines2; + aStart = aEnd[0] + nOmit; + bStart = bEnd[0] + nOmit; + aEnd[0] = aStart; + bEnd[0] = bStart; + for (int iCommon = i - nContextLines; iCommon != i; iCommon += 1) { + pushCommonLine.accept(diffs.get(iCommon).text); + } + } else { + for (int iCommon = iStart; iCommon != i; iCommon += 1) { + pushCommonLine.accept(diffs.get(iCommon).text); + } + } + } + } + while (i != iLength && diffs.get(i).op == DIFF_DELETE) { + pushDeleteLine.accept(diffs.get(i).text); + i += 1; + } + while (i != iLength && diffs.get(i).op == DIFF_INSERT) { + pushInsertLine.accept(diffs.get(i).text); + i += 1; + } + } + if (hasPatch) { + lines.set(jPatchMark, createPatchMark(aStart, aEnd[0], bStart, bEnd[0], options)); + } + return String.join("\n", lines); + } + + private static String joinAlignedDiffsExpand(List diffs, DiffOptions options) { + List lines = new ArrayList<>(); + for (int i = 0; i < diffs.size(); i++) { + Diff diff = diffs.get(i); + String line = diff.text; + boolean isFirstOrLast = i == 0 || i == diffs.size() - 1; + switch (diff.op) { + case DIFF_DELETE: + lines.add(printDeleteLine(line, isFirstOrLast, options)); + break; + case DIFF_INSERT: + lines.add(printInsertLine(line, isFirstOrLast, options)); + break; + default: + lines.add(printCommonLine(line, isFirstOrLast, options)); + } + } + return String.join("\n", lines); + } + + static String noColor(String string) { + return string; + } + + private static final int DIFF_CONTEXT_DEFAULT = 5; + private static final DiffOptions OPTIONS_DEFAULT = new DiffOptions(); + static { + OPTIONS_DEFAULT.aAnnotation = "Expected"; + OPTIONS_DEFAULT.aColor = Chalk::green; + OPTIONS_DEFAULT.aIndicator = "-"; + OPTIONS_DEFAULT.bAnnotation = "Received"; + OPTIONS_DEFAULT.bColor = Chalk::red; + OPTIONS_DEFAULT.bIndicator = "+"; + OPTIONS_DEFAULT.changeColor = Chalk::inverse; + OPTIONS_DEFAULT.changeLineTrailingSpaceColor = JestDiff::noColor; + OPTIONS_DEFAULT.commonColor = Chalk::dim; + OPTIONS_DEFAULT.commonIndicator = " "; + OPTIONS_DEFAULT.commonLineTrailingSpaceColor = JestDiff::noColor; + OPTIONS_DEFAULT.compareKeys = null; + OPTIONS_DEFAULT.contextLines = DIFF_CONTEXT_DEFAULT; + OPTIONS_DEFAULT.emptyFirstOrLastLinePlaceholder = ""; + OPTIONS_DEFAULT.expand = true; + OPTIONS_DEFAULT.includeChangeCounts = false; + OPTIONS_DEFAULT.omitAnnotationLines = false; + OPTIONS_DEFAULT.patchColor = Chalk::yellow; + } + + private static Comparator getCompareKeys(Comparator compareKeys) { + return compareKeys != null ? compareKeys : OPTIONS_DEFAULT.compareKeys; + } + + private static int getContextLines(Integer contextLines) { + return contextLines != null && contextLines >= 0 ? contextLines : DIFF_CONTEXT_DEFAULT; + } + + static DiffOptions normalizeDiffOptions(DiffOptions options) { + if (options == null) { + options = new DiffOptions(); + } + // java: the object spread is one assignment per field. + DiffOptions result = new DiffOptions(); + result.aAnnotation = options.aAnnotation != null ? options.aAnnotation : OPTIONS_DEFAULT.aAnnotation; + result.aColor = options.aColor != null ? options.aColor : OPTIONS_DEFAULT.aColor; + result.aIndicator = options.aIndicator != null ? options.aIndicator : OPTIONS_DEFAULT.aIndicator; + result.bAnnotation = options.bAnnotation != null ? options.bAnnotation : OPTIONS_DEFAULT.bAnnotation; + result.bColor = options.bColor != null ? options.bColor : OPTIONS_DEFAULT.bColor; + result.bIndicator = options.bIndicator != null ? options.bIndicator : OPTIONS_DEFAULT.bIndicator; + result.changeColor = options.changeColor != null ? options.changeColor : OPTIONS_DEFAULT.changeColor; + result.changeLineTrailingSpaceColor = options.changeLineTrailingSpaceColor != null ? options.changeLineTrailingSpaceColor : OPTIONS_DEFAULT.changeLineTrailingSpaceColor; + result.commonColor = options.commonColor != null ? options.commonColor : OPTIONS_DEFAULT.commonColor; + result.commonIndicator = options.commonIndicator != null ? options.commonIndicator : OPTIONS_DEFAULT.commonIndicator; + result.commonLineTrailingSpaceColor = options.commonLineTrailingSpaceColor != null ? options.commonLineTrailingSpaceColor : OPTIONS_DEFAULT.commonLineTrailingSpaceColor; + result.emptyFirstOrLastLinePlaceholder = options.emptyFirstOrLastLinePlaceholder != null ? options.emptyFirstOrLastLinePlaceholder : OPTIONS_DEFAULT.emptyFirstOrLastLinePlaceholder; + result.expand = options.expand != null ? options.expand : OPTIONS_DEFAULT.expand; + result.includeChangeCounts = options.includeChangeCounts != null ? options.includeChangeCounts : OPTIONS_DEFAULT.includeChangeCounts; + result.omitAnnotationLines = options.omitAnnotationLines != null ? options.omitAnnotationLines : OPTIONS_DEFAULT.omitAnnotationLines; + result.patchColor = options.patchColor != null ? options.patchColor : OPTIONS_DEFAULT.patchColor; + result.compareKeys = getCompareKeys(options.compareKeys); + result.contextLines = getContextLines(options.contextLines); + return result; + } + + private static boolean hasCommonDiff(List diffs, boolean isMultiline) { + if (isMultiline) { + int iLast = diffs.size() - 1; + for (int i = 0; i < diffs.size(); i++) { + Diff diff = diffs.get(i); + if (diff.op == DIFF_EQUAL && (i != iLast || !diff.text.equals("\n"))) { + return true; + } + } + return false; + } + for (Diff diff : diffs) { + if (diff.op == DIFF_EQUAL) { + return true; + } + } + return false; + } + + static String diffStringsUnified(String a, String b, DiffOptions options) { + if (!a.equals(b) && a.length() > 0 && b.length() > 0) { + boolean isMultiline = a.contains("\n") || b.contains("\n"); + + List diffs = diffStringsRaw(isMultiline ? a + "\n" : a, isMultiline ? b + "\n" : b, true + ); + if (hasCommonDiff(diffs, isMultiline)) { + DiffOptions optionsNormalized = normalizeDiffOptions(options); + List lines = getAlignedDiffs(diffs, optionsNormalized.changeColor); + return printDiffLines(lines, optionsNormalized); + } + } + + return diffLinesUnified(split(a, "\n"), split(b, "\n"), options); + } + + static List diffStringsRaw(String a, String b, boolean cleanup) { + List diffs = diffStrings(a, b); + if (cleanup) { + diff_cleanupSemantic(diffs); + } + return diffs; + } + + private static String getCommonMessage(String message, DiffOptions options) { + Function commonColor = normalizeDiffOptions(options).commonColor; + return commonColor.apply(message); + } + + // java: there are no plugins. + private static final PrettyFormat.Options FORMAT_OPTIONS = new PrettyFormat.Options(); + private static final PrettyFormat.Options FALLBACK_FORMAT_OPTIONS = new PrettyFormat.Options(); + static { + FALLBACK_FORMAT_OPTIONS.callToJSON = false; + FALLBACK_FORMAT_OPTIONS.maxDepth = 10; + } + + // java: helper with no counterpart upstream, the port of Object.is. + private static boolean objectIs(Object a, Object b) { + if (a instanceof Number && b instanceof Number) { + return Double.compare(((Number) a).doubleValue(), ((Number) b).doubleValue()) == 0; + } + if (a instanceof String || a instanceof Boolean) { + return a.equals(b); + } + return a == b; + } + + static String diff(Object a, Object b, DiffOptions options) { + if (objectIs(a, b)) { + return getCommonMessage(NO_DIFF_MESSAGE, options); + } + String aType = getType(a); + String expectedType = aType; + // java: there are no asymmetric matchers, omitDifference is always false. + if (!expectedType.equals(getType(b))) { + return " Comparing two different types of values." + " Expected " + Chalk.green(expectedType) + " but " + "received " + Chalk.red(getType(b)) + "."; + } + switch (aType) { + case "string": + return diffLinesUnified(split(escapeControlCharacters((String) a), "\n"), split(escapeControlCharacters((String) b), "\n"), options); + case "boolean": + case "number": + return comparePrimitive(a, b, options); + // java: the types map and set have no Java values, sortMap and sortSet are not ported. + default: + return compareObjects(a, b, options); + } + } + + private static String comparePrimitive(Object a, Object b, DiffOptions options) { + String aFormat = PrettyFormat.format(a, FORMAT_OPTIONS); + String bFormat = PrettyFormat.format(b, FORMAT_OPTIONS); + return aFormat.equals(bFormat) ? getCommonMessage(NO_DIFF_MESSAGE, options) : diffLinesUnified(split(aFormat, "\n"), split(bFormat, "\n"), options); + } + + private static String compareObjects(Object a, Object b, DiffOptions options) { + String difference = null; + boolean hasThrown = false; + try { + PrettyFormat.Options formatOptions = getFormatOptions(FORMAT_OPTIONS, options); + difference = getObjectsDifference(a, b, formatOptions, options); + } catch (RuntimeException e) { + hasThrown = true; + } + String noDiffMessage = getCommonMessage(NO_DIFF_MESSAGE, options); + if (difference == null || difference.equals(noDiffMessage)) { + PrettyFormat.Options formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options); + difference = getObjectsDifference(a, b, formatOptions, options); + if (!difference.equals(noDiffMessage) && !hasThrown) { + difference = getCommonMessage(SIMILAR_MESSAGE, options) + "\n\n" + difference; + } + } + return difference; + } + + private static PrettyFormat.Options getFormatOptions(PrettyFormat.Options formatOptions, DiffOptions options) { + Comparator compareKeys = normalizeDiffOptions(options).compareKeys; + // java: the object spread is one assignment per field. + PrettyFormat.Options result = new PrettyFormat.Options(); + result.callToJSON = formatOptions.callToJSON; + result.indent = formatOptions.indent; + result.maxDepth = formatOptions.maxDepth; + result.maxWidth = formatOptions.maxWidth; + result.min = formatOptions.min; + result.compareKeys = compareKeys; + return result; + } + + private static String getObjectsDifference(Object a, Object b, PrettyFormat.Options formatOptions, DiffOptions options) { + // java: the object spread is one assignment per field. + PrettyFormat.Options formatOptionsZeroIndent = new PrettyFormat.Options(); + formatOptionsZeroIndent.callToJSON = formatOptions.callToJSON; + formatOptionsZeroIndent.compareKeys = formatOptions.compareKeys; + formatOptionsZeroIndent.maxDepth = formatOptions.maxDepth; + formatOptionsZeroIndent.maxWidth = formatOptions.maxWidth; + formatOptionsZeroIndent.min = formatOptions.min; + formatOptionsZeroIndent.indent = 0; + String aCompare = PrettyFormat.format(a, formatOptionsZeroIndent); + String bCompare = PrettyFormat.format(b, formatOptionsZeroIndent); + if (aCompare.equals(bCompare)) { + return getCommonMessage(NO_DIFF_MESSAGE, options); + } else { + String aDisplay = PrettyFormat.format(a, formatOptions); + String bDisplay = PrettyFormat.format(b, formatOptions); + return diffLinesUnified2(split(aDisplay, "\n"), split(bDisplay, "\n"), split(aCompare, "\n"), split(bCompare, "\n"), options); + } + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/JestGetType.java b/playwright/src/main/java/com/microsoft/playwright/impl/JestGetType.java new file mode 100644 index 000000000..1d2e2695a --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/JestGetType.java @@ -0,0 +1,68 @@ +/* + * 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. + */ + +// Port of @jest/get-type. +// java: the original is MIT licensed, Copyright (c) Meta Platforms, Inc. and affiliates. +package com.microsoft.playwright.impl; + +import java.util.Date; +import java.util.List; +import java.util.regex.Pattern; + +class JestGetType { + // java: a Java value has one of these JavaScript types: null is null, a List or an array is + // an array, a Boolean is a boolean, a Number is a number, a String is a string, a Pattern is + // a regexp, a Date is a date. All other values, a Map too, are objects. The other types have no Java values. + // java: the undefined value is UNDEFINED: Frame.expect returns it for a received value that is undefined. + static final Object UNDEFINED = new Object() { + @Override + public String toString() { + return "undefined"; + } + }; + + static String getType(Object value) { + if (value == UNDEFINED) { + return "undefined"; + } else if (value == null) { + return "null"; + } else if (isArray(value)) { + return "array"; + } else if (value instanceof Boolean) { + return "boolean"; + } else if (value instanceof Number) { + return "number"; + } else if (value instanceof String) { + return "string"; + } else { + if (value instanceof Pattern) { + return "regexp"; + } else if (value instanceof Date) { + return "date"; + } + return "object"; + } + } + + static boolean isPrimitive(Object value) { + return value == null || value == UNDEFINED || value instanceof Boolean || value instanceof Number || value instanceof String; + } + + // java: helper with no counterpart upstream, the port of Array.isArray. + static boolean isArray(Object value) { + return value instanceof List || value != null && value.getClass().isArray(); + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/JestMatcherUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/JestMatcherUtils.java new file mode 100644 index 000000000..7f770b59d --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/JestMatcherUtils.java @@ -0,0 +1,213 @@ +/* + * 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. + */ + +// Port of jest-matcher-utils. +// java: the original is MIT licensed, Copyright (c) Meta Platforms, Inc. and affiliates. +package com.microsoft.playwright.impl; + +import java.util.List; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.microsoft.playwright.impl.JestDiff.DIFF_DELETE; +import static com.microsoft.playwright.impl.JestDiff.DIFF_EQUAL; +import static com.microsoft.playwright.impl.JestDiff.DIFF_INSERT; +import static com.microsoft.playwright.impl.JestDiff.diffStringsRaw; +import static com.microsoft.playwright.impl.JestDiff.diffStringsUnified; +import static com.microsoft.playwright.impl.JestGetType.getType; +import static com.microsoft.playwright.impl.JestGetType.isPrimitive; + +// java: the ensure functions, matcherHint, matcherErrorMessage, pluralize, highlightTrailingWhitespace, +// diff and shouldPrintDiff are not ported, the assertions do not call them. +class JestMatcherUtils { + // java: no ANSI colors, the color functions return the text as is. + static String EXPECTED_COLOR(String text) { + return JestDiff.Chalk.green(text); + } + + static String RECEIVED_COLOR(String text) { + return JestDiff.Chalk.red(text); + } + + static String INVERTED_COLOR(String text) { + return JestDiff.Chalk.inverse(text); + } + + static String BOLD_WEIGHT(String text) { + return JestDiff.Chalk.bold(text); + } + + static String DIM_COLOR(String text) { + return JestDiff.Chalk.dim(text); + } + + private static final Pattern MULTILINE_REGEXP = Pattern.compile("\\n"); + private static final String SPACE_SYMBOL = "·"; + + static String stringify(Object object) { + return stringify(object, 10, 10); + } + + static String stringify(Object object, int maxDepth, int maxWidth) { + int MAX_LENGTH = 10_000; + String result; + try { + PrettyFormat.Options options = new PrettyFormat.Options(); + options.maxDepth = maxDepth; + options.maxWidth = maxWidth; + options.min = true; + result = PrettyFormat.format(object, options); + } catch (RuntimeException e) { + PrettyFormat.Options options = new PrettyFormat.Options(); + options.callToJSON = false; + options.maxDepth = maxDepth; + options.maxWidth = maxWidth; + options.min = true; + result = PrettyFormat.format(object, options); + } + if (result.length() >= MAX_LENGTH && maxDepth > 1) { + return stringify(object, maxDepth / 2, maxWidth); + } else if (result.length() >= MAX_LENGTH && maxWidth > 1) { + return stringify(object, maxDepth, maxWidth / 2); + } else { + return result; + } + } + + // java: $ with the m flag in JavaScript is the position before \n, \r, 
, 
 or the + // end of the string. $ with MULTILINE in Java does not match between \r and \n, and it + // matches before \u0085. + private static final Pattern trailingSpacesRegex = Pattern.compile(JestDiff.WHITESPACE + "+(?=[\\n\\r\\u2028\\u2029]|\\z)"); + + private static String replaceTrailingSpaces(String text) { + // java: replaceAll with a callback is a loop over the matches. + Matcher matcher = trailingSpacesRegex.matcher(text); + StringBuffer result = new StringBuffer(); + while (matcher.find()) { + String spaces = matcher.group(); + matcher.appendReplacement(result, Matcher.quoteReplacement(repeat(SPACE_SYMBOL, spaces.length()))); + } + matcher.appendTail(result); + return result.toString(); + } + + // java: helper with no counterpart upstream, the port of String.prototype.repeat. + private static String repeat(String string, int count) { + StringBuilder result = new StringBuilder(); + for (int i = 0; i < count; i++) { + result.append(string); + } + return result.toString(); + } + + static String printReceived(Object object) { + return RECEIVED_COLOR(replaceTrailingSpaces(stringify(object))); + } + + static String printExpected(Object value) { + return EXPECTED_COLOR(replaceTrailingSpaces(stringify(value))); + } + + static String printWithType(String name, Object value, Function print) { + String type = getType(value); + String hasType = !type.equals("null") && !type.equals("undefined") ? name + " has type: " + type + "\n" : ""; + String hasValue = name + " has value: " + print.apply(value); + return hasType + hasValue; + } + + private static String getCommonAndChangedSubstrings(List diffs, int op, boolean hasCommonDiff) { + String reduced = ""; + for (JestDiff.Diff diff : diffs) { + reduced = reduced + (diff.op == DIFF_EQUAL ? diff.text : diff.op == op ? hasCommonDiff ? INVERTED_COLOR(diff.text) : diff.text : ""); + } + return reduced; + } + + private static boolean isLineDiffable(Object expected, Object received) { + String expectedType = getType(expected); + String receivedType = getType(received); + if (!expectedType.equals(receivedType)) { + return false; + } + if (isPrimitive(expected)) { + return expected instanceof String && received instanceof String && ((String) expected).length() > 0 && ((String) received).length() > 0 && (MULTILINE_REGEXP.matcher((String) expected).find() || MULTILINE_REGEXP.matcher((String) received).find()); + } + if (expectedType.equals("date") || expectedType.equals("function") || expectedType.equals("regexp")) { + return false; + } + // java: the value model has no Error values and no asymmetric matchers, these two + // checks are not ported. + return true; + } + + private static final int MAX_DIFF_STRING_LENGTH = 20_000; + + static String printDiffOrStringify(Object expected, Object received, String expectedLabel, String receivedLabel, boolean expand) { + if (expected instanceof String && received instanceof String && ((String) expected).length() > 0 && ((String) received).length() > 0 && ((String) expected).length() <= MAX_DIFF_STRING_LENGTH && ((String) received).length() <= MAX_DIFF_STRING_LENGTH && !expected.equals(received)) { + if (((String) expected).contains("\n") || ((String) received).contains("\n")) { + JestDiff.DiffOptions options = new JestDiff.DiffOptions(); + options.aAnnotation = expectedLabel; + options.bAnnotation = receivedLabel; + options.changeLineTrailingSpaceColor = JestDiff.Chalk::bgYellow; + options.commonLineTrailingSpaceColor = JestDiff.Chalk::bgYellow; + options.emptyFirstOrLastLinePlaceholder = "↵"; + options.expand = expand; + options.includeChangeCounts = true; + return diffStringsUnified((String) expected, (String) received, options); + } + List diffs = diffStringsRaw((String) expected, (String) received, true); + boolean hasCommonDiff = false; + for (JestDiff.Diff diff : diffs) { + if (diff.op == DIFF_EQUAL) { + hasCommonDiff = true; + } + } + Function printLabel = getLabelPrinter(expectedLabel, receivedLabel); + String expectedLine = printLabel.apply(expectedLabel) + printExpected(getCommonAndChangedSubstrings(diffs, DIFF_DELETE, hasCommonDiff)); + String receivedLine = printLabel.apply(receivedLabel) + printReceived(getCommonAndChangedSubstrings(diffs, DIFF_INSERT, hasCommonDiff)); + return expectedLine + "\n" + receivedLine; + } + if (isLineDiffable(expected, received)) { + // java: there are no asymmetric matchers, replaceMatchedToAsymmetricMatcher returns + // the values as they are and is not ported. + Object replacedExpected = expected; + Object replacedReceived = received; + JestDiff.DiffOptions options = new JestDiff.DiffOptions(); + options.aAnnotation = expectedLabel; + options.bAnnotation = receivedLabel; + options.expand = expand; + options.includeChangeCounts = true; + String difference = JestDiff.diff(replacedExpected, replacedReceived, options); + if (difference != null && difference.contains("- " + expectedLabel) && difference.contains("+ " + receivedLabel)) { + return difference; + } + } + Function printLabel = getLabelPrinter(expectedLabel, receivedLabel); + String expectedLine = printLabel.apply(expectedLabel) + printExpected(expected); + String receivedLine = printLabel.apply(receivedLabel) + (stringify(expected).equals(stringify(received)) ? "serializes to the same string" : printReceived(received)); + return expectedLine + "\n" + receivedLine; + } + + static Function getLabelPrinter(String... strings) { + int maxLength = 0; + for (String string : strings) { + maxLength = Math.max(string.length(), maxLength); + } + int finalMaxLength = maxLength; + return string -> string + ": " + repeat(" ", finalMaxLength - string.length()); + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorAssertionsImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorAssertionsImpl.java index fa481ef86..983d28dbe 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorAssertionsImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorAssertionsImpl.java @@ -14,24 +14,32 @@ * limitations under the License. */ +// Port of matchers.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; import com.microsoft.playwright.Locator; import com.microsoft.playwright.assertions.LocatorAssertions; +import com.microsoft.playwright.impl.protocol.ExpectedTextValue; import com.microsoft.playwright.options.AriaRole; import java.util.ArrayList; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.Serialization.serializeArgument; -import static com.microsoft.playwright.impl.Utils.convertType; +import static com.microsoft.playwright.impl.ToBeTruthy.toBeTruthy; +import static com.microsoft.playwright.impl.ToEqual.toEqual; +import static com.microsoft.playwright.impl.ToMatchAriaSnapshot.toMatchAriaSnapshot; +import static com.microsoft.playwright.impl.ToMatchText.toMatchText; +import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; +// java: the matchers of a Locator; those of a Page are in PageAssertionsImpl, toBeOK is in APIResponseAssertionsImpl. +// A matcher is the method of the public interface: it calls its upstream body through callMatcherAsStep, and its +// name in a message and in a title is the Java name (hasText for toHaveText). The +// options are read as options?.name, a matcher with a string, a pattern or an array has one overload per type. public class LocatorAssertionsImpl extends AssertionsBase implements LocatorAssertions { - LocatorImpl actualLocator; + final LocatorImpl actualLocator; public LocatorAssertionsImpl(Locator locator) { this(locator, false); @@ -43,445 +51,611 @@ private LocatorAssertionsImpl(Locator locator, boolean isNot) { } @Override - FrameExpectResult doExpect(String expression, FrameExpectOptions expectOptions, String title) { - return actualLocator.expect(expression, expectOptions, title); + public LocatorAssertions not() { + return new LocatorAssertionsImpl(actualLocator, !isNot); } + // java: items is an array of String or Pattern, the options are three parameters. + static List serializeExpectedTextValues(Object[] items, Boolean matchSubstring, Boolean normalizeWhiteSpace, Boolean ignoreCase) { + List result = new ArrayList<>(); + for (Object i : items) { + ExpectedTextValue value = new ExpectedTextValue(); + value.string = i instanceof String ? (String) i : null; + value.regexSource = i instanceof Pattern ? ((Pattern) i).pattern() : null; + value.regexFlags = i instanceof Pattern ? toJsRegexFlags((Pattern) i) : null; + value.matchSubstring = matchSubstring; + value.ignoreCase = ignoreCase; + value.normalizeWhiteSpace = normalizeWhiteSpace; + result.add(value); + } + return result; + } @Override - public void containsClass(String classname, ContainsClassOptions options) { - ExpectedTextValue expected = new ExpectedTextValue(); - expected.string = classname; - expectImpl("to.contain.class", expected, classname, "Locator expected to contain class", convertType(options, FrameExpectOptions.class), "Assert \"containsClass\""); + public void isAttached(IsAttachedOptions options) { + callMatcherAsStep("isAttached", state -> { + boolean attached = options == null || options.attached == null || options.attached; + String expected = attached ? "attached" : "detached"; + String arg = attached ? "" : "{ attached: false }"; + return toBeTruthy(state, "isAttached", actualLocator, "Locator", expected, arg, (isNot, timeout) -> { + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect(attached ? "to.be.attached" : "to.be.detached", expectOptions); + }, options == null ? null : options.timeout); + }); } @Override - public void containsClass(List classnames, ContainsClassOptions options) { - List list = new ArrayList<>(); - for (String text : classnames) { - ExpectedTextValue expected = new ExpectedTextValue(); - expected.string = text; - list.add(expected); - } - expectImpl("to.contain.class.array", list, classnames, "Locator expected to contain classes", convertType(options, FrameExpectOptions.class), "Assert \"containsClass\""); + public void isChecked(IsCheckedOptions options) { + callMatcherAsStep("isChecked", state -> { + Boolean checked = options == null ? null : options.checked; + Boolean indeterminate = options == null ? null : options.indeterminate; + // java: an undefined property is a missing key. + Map expectedValue = new LinkedHashMap<>(); + if (checked != null) + expectedValue.put("checked", checked); + if (indeterminate != null) + expectedValue.put("indeterminate", indeterminate); + String expected; + String arg; + if (options != null && options.indeterminate != null && options.indeterminate) { + expected = "indeterminate"; + arg = "{ indeterminate: true }"; + } else { + expected = options != null && options.checked != null && !options.checked ? "unchecked" : "checked"; + arg = options != null && options.checked != null && !options.checked ? "{ checked: false }" : ""; + } + return toBeTruthy(state, "isChecked", actualLocator, "Locator", expected, arg, (isNot, timeout) -> { + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.expectedValue = expectedValue; + expectOptions.title = state.title; + return actualLocator.expect("to.be.checked", expectOptions); + }, options == null ? null : options.timeout); + }); } @Override - 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), "Assert \"containsText\""); + public void isDisabled(IsDisabledOptions options) { + callMatcherAsStep("isDisabled", state -> { + return toBeTruthy(state, "isDisabled", actualLocator, "Locator", "disabled", "", (isNot, timeout) -> { + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.be.disabled", expectOptions); + }, options == null ? null : options.timeout); + }); } @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), "Assert \"containsText\""); + public void isEditable(IsEditableOptions options) { + callMatcherAsStep("isEditable", state -> { + boolean editable = options == null || options.editable == null || options.editable; + String expected = editable ? "editable" : "readOnly"; + String arg = editable ? "" : "{ editable: false }"; + return toBeTruthy(state, "isEditable", actualLocator, "Locator", expected, arg, (isNot, timeout) -> { + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect(editable ? "to.be.editable" : "to.be.readonly", expectOptions); + }, options == null ? null : options.timeout); + }); } @Override - public void containsText(String[] strings, ContainsTextOptions options) { - List list = new ArrayList<>(); - for (String text : strings) { - ExpectedTextValue expected = new ExpectedTextValue(); - expected.string = text; - expected.ignoreCase = shouldIgnoreCase(options); - expected.matchSubstring = true; - expected.normalizeWhiteSpace = true; - list.add(expected); - } - expectImpl("to.contain.text.array", list, strings, "Locator expected to contain text", convertType(options, FrameExpectOptions.class), "Assert \"containsText\""); + public void isEmpty(IsEmptyOptions options) { + callMatcherAsStep("isEmpty", state -> { + return toBeTruthy(state, "isEmpty", actualLocator, "Locator", "empty", "", (isNot, timeout) -> { + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.be.empty", expectOptions); + }, options == null ? null : options.timeout); + }); } @Override - public void containsText(Pattern[] patterns, ContainsTextOptions options) { - List list = new ArrayList<>(); - for (Pattern pattern : patterns) { - ExpectedTextValue expected = expectedRegex(pattern); - expected.ignoreCase = shouldIgnoreCase(options); - expected.matchSubstring = true; - expected.normalizeWhiteSpace = true; - list.add(expected); - } - expectImpl("to.contain.text.array", list, patterns, "Locator expected to contain text", convertType(options, FrameExpectOptions.class), "Assert \"containsText\""); + public void isEnabled(IsEnabledOptions options) { + callMatcherAsStep("isEnabled", state -> { + boolean enabled = options == null || options.enabled == null || options.enabled; + String expected = enabled ? "enabled" : "disabled"; + String arg = enabled ? "" : "{ enabled: false }"; + return toBeTruthy(state, "isEnabled", actualLocator, "Locator", expected, arg, (isNot, timeout) -> { + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect(enabled ? "to.be.enabled" : "to.be.disabled", expectOptions); + }, options == null ? null : options.timeout); + }); } @Override - public void hasAccessibleDescription(String description, HasAccessibleDescriptionOptions options) { - ExpectedTextValue expected = new ExpectedTextValue(); - expected.string = description; - expected.ignoreCase = shouldIgnoreCase(options); - expected.normalizeWhiteSpace = true; - expectImpl("to.have.accessible.description", expected, description, "Locator expected to have accessible description", convertType(options, FrameExpectOptions.class), "Assert \"hasAccessibleDescription\""); + public void isFocused(IsFocusedOptions options) { + callMatcherAsStep("isFocused", state -> { + return toBeTruthy(state, "isFocused", actualLocator, "Locator", "focused", "", (isNot, timeout) -> { + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.be.focused", expectOptions); + }, options == null ? null : options.timeout); + }); } @Override - public void hasAccessibleDescription(Pattern pattern, HasAccessibleDescriptionOptions options) { - ExpectedTextValue expected = expectedRegex(pattern); - expected.ignoreCase = shouldIgnoreCase(options); - expected.normalizeWhiteSpace = true; - expectImpl("to.have.accessible.description", expected, pattern, "Locator expected to have accessible description", convertType(options, FrameExpectOptions.class), "Assert \"hasAccessibleDescription\""); + public void isHidden(IsHiddenOptions options) { + callMatcherAsStep("isHidden", state -> { + return toBeTruthy(state, "isHidden", actualLocator, "Locator", "hidden", "", (isNot, timeout) -> { + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.be.hidden", expectOptions); + }, options == null ? null : options.timeout); + }); } @Override - public void hasAccessibleErrorMessage(String errorMessage, HasAccessibleErrorMessageOptions options) { - ExpectedTextValue expected = new ExpectedTextValue(); - expected.string = errorMessage; - expected.ignoreCase = shouldIgnoreCase(options); - expected.normalizeWhiteSpace = true; - expectImpl("to.have.accessible.error.message", expected, errorMessage, "Locator expected to have accessible error message", convertType(options, FrameExpectOptions.class), "Assert \"hasAccessibleErrorMessage\""); + public void isVisible(IsVisibleOptions options) { + callMatcherAsStep("isVisible", state -> { + boolean visible = options == null || options.visible == null || options.visible; + String expected = visible ? "visible" : "hidden"; + String arg = visible ? "" : "{ visible: false }"; + return toBeTruthy(state, "isVisible", actualLocator, "Locator", expected, arg, (isNot, timeout) -> { + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect(visible ? "to.be.visible" : "to.be.hidden", expectOptions); + }, options == null ? null : options.timeout); + }); } @Override - public void hasAccessibleErrorMessage(Pattern pattern, HasAccessibleErrorMessageOptions options) { - ExpectedTextValue expected = expectedRegex(pattern); - expected.ignoreCase = shouldIgnoreCase(options); - expected.normalizeWhiteSpace = true; - expectImpl("to.have.accessible.error.message", expected, pattern, "Locator expected to have accessible error message", convertType(options, FrameExpectOptions.class), "Assert \"hasAccessibleErrorMessage\""); + public void isInViewport(IsInViewportOptions options) { + callMatcherAsStep("isInViewport", state -> { + return toBeTruthy(state, "isInViewport", actualLocator, "Locator", "in viewport", "", (isNot, timeout) -> { + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.isNot = isNot; + expectOptions.expectedNumber = options == null ? null : options.ratio; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.be.in.viewport", expectOptions); + }, options == null ? null : options.timeout); + }); } @Override - public void hasAccessibleName(String name, HasAccessibleNameOptions options) { - ExpectedTextValue expected = new ExpectedTextValue(); - expected.string = name; - expected.ignoreCase = shouldIgnoreCase(options); - expected.normalizeWhiteSpace = true; - expectImpl("to.have.accessible.name", expected, name, "Locator expected to have accessible name", convertType(options, FrameExpectOptions.class), "Assert \"hasAccessibleName\""); + public void containsText(String expected, ContainsTextOptions options) { + toContainText(expected, options); } @Override - public void hasAccessibleName(Pattern pattern, HasAccessibleNameOptions options) { - ExpectedTextValue expected = expectedRegex(pattern); - expected.ignoreCase = shouldIgnoreCase(options); - expected.normalizeWhiteSpace = true; - expectImpl("to.have.accessible.name", expected, pattern, "Locator expected to have accessible name", convertType(options, FrameExpectOptions.class), "Assert \"hasAccessibleName\""); + public void containsText(Pattern expected, ContainsTextOptions options) { + toContainText(expected, options); } @Override - public void hasAttribute(String name, String text, HasAttributeOptions options) { - ExpectedTextValue expected = new ExpectedTextValue(); - expected.string = text; - expected.ignoreCase = shouldIgnoreCase(options); - hasAttribute(name, expected, text, options); + public void containsText(String[] expected, ContainsTextOptions options) { + toContainText(expected, options); } @Override - public void hasAttribute(String name, Pattern pattern, HasAttributeOptions options) { - ExpectedTextValue expected = expectedRegex(pattern); - expected.ignoreCase = shouldIgnoreCase(options); - hasAttribute(name, expected, pattern, options); + public void containsText(Pattern[] expected, ContainsTextOptions options) { + toContainText(expected, options); } - private void hasAttribute(String name, ExpectedTextValue expectedText, Object expectedValue, HasAttributeOptions options) { - if (options == null) { - options = new HasAttributeOptions(); - } - FrameExpectOptions commonOptions = convertType(options, FrameExpectOptions.class); - commonOptions.expressionArg = name; - String message = "Locator expected to have attribute '" + name + "'"; - if (expectedValue instanceof Pattern) { - message += " matching regex"; - } - expectImpl("to.have.attribute.value", expectedText, expectedValue, message, commonOptions, "Assert \"hasAttribute\""); + private void toContainText(Object expected, ContainsTextOptions options) { + callMatcherAsStep("containsText", state -> { + if (expected instanceof Object[]) { + return toEqual(state, "containsText", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues((Object[]) expected, true, true, options == null ? null : options.ignoreCase); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.useInnerText = options == null ? null : options.useInnerText; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.contain.text.array", expectOptions); + }, expected, options == null ? null : options.timeout); + } else { + return toMatchText(state, "containsText", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(new Object[] {expected}, true, true, options == null ? null : options.ignoreCase); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.useInnerText = options == null ? null : options.useInnerText; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.text", expectOptions); + }, expected, options == null ? null : options.timeout, true); + } + }); } @Override - public void hasClass(String text, HasClassOptions options) { - ExpectedTextValue expected = new ExpectedTextValue(); - expected.string = text; - expectImpl("to.have.class", expected, text, "Locator expected to have class", convertType(options, FrameExpectOptions.class), "Assert \"hasClass\""); + public void hasAccessibleDescription(String expected, HasAccessibleDescriptionOptions options) { + toHaveAccessibleDescription(expected, options); } @Override - public void hasClass(Pattern pattern, HasClassOptions options) { - ExpectedTextValue expected = expectedRegex(pattern); - expectImpl("to.have.class", expected, pattern, "Locator expected to have class matching regex", convertType(options, FrameExpectOptions.class), "Assert \"hasClass\""); + public void hasAccessibleDescription(Pattern expected, HasAccessibleDescriptionOptions options) { + toHaveAccessibleDescription(expected, options); } - @Override - public void hasClass(String[] strings, HasClassOptions options) { - List list = new ArrayList<>(); - for (String text : strings) { - ExpectedTextValue expected = new ExpectedTextValue(); - expected.string = text; - list.add(expected); - } - expectImpl("to.have.class.array", list, strings, "Locator expected to have class", convertType(options, FrameExpectOptions.class), "Assert \"hasClass\""); + private void toHaveAccessibleDescription(Object expected, HasAccessibleDescriptionOptions options) { + callMatcherAsStep("hasAccessibleDescription", state -> { + return toMatchText(state, "hasAccessibleDescription", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(new Object[] {expected}, null, true, options == null ? null : options.ignoreCase); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.accessible.description", expectOptions); + }, expected, options == null ? null : options.timeout, false); + }); } @Override - public void hasClass(Pattern[] patterns, HasClassOptions options) { - List list = new ArrayList<>(); - for (Pattern pattern : patterns) { - ExpectedTextValue expected = expectedRegex(pattern); - list.add(expected); - } - expectImpl("to.have.class.array", list, patterns, "Locator expected to have class matching regex", convertType(options, FrameExpectOptions.class), "Assert \"hasClass\""); + public void hasAccessibleName(String expected, HasAccessibleNameOptions options) { + toHaveAccessibleName(expected, options); } @Override - public void hasCount(int count, HasCountOptions options) { - if (options == null) { - options = new HasCountOptions(); - } - FrameExpectOptions commonOptions = convertType(options, FrameExpectOptions.class); - commonOptions.expectedNumber = (double) count; - List expectedText = null; - expectImpl("to.have.count", expectedText, count, "Locator expected to have count", commonOptions, "Assert \"hasCount\""); + public void hasAccessibleName(Pattern expected, HasAccessibleNameOptions options) { + toHaveAccessibleName(expected, options); + } + + private void toHaveAccessibleName(Object expected, HasAccessibleNameOptions options) { + callMatcherAsStep("hasAccessibleName", state -> { + return toMatchText(state, "hasAccessibleName", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(new Object[] {expected}, null, true, options == null ? null : options.ignoreCase); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.accessible.name", expectOptions); + }, expected, options == null ? null : options.timeout, false); + }); } @Override - public void hasCSS(String name, String value, HasCSSOptions options) { - ExpectedTextValue expected = new ExpectedTextValue(); - expected.string = value; - hasCSS(name, expected, value, options); + public void hasAccessibleErrorMessage(String expected, HasAccessibleErrorMessageOptions options) { + toHaveAccessibleErrorMessage(expected, options); } @Override - public void hasCSS(String name, Pattern pattern, HasCSSOptions options) { - ExpectedTextValue expected = expectedRegex(pattern); - hasCSS(name, expected, pattern, options); + public void hasAccessibleErrorMessage(Pattern expected, HasAccessibleErrorMessageOptions options) { + toHaveAccessibleErrorMessage(expected, options); } - private void hasCSS(String name, ExpectedTextValue expectedText, Object expectedValue, HasCSSOptions options) { - if (options == null) { - options = new HasCSSOptions(); - } - FrameExpectOptions commonOptions = convertType(options, FrameExpectOptions.class); - commonOptions.expressionArg = name; - String message = "Locator expected to have CSS property '" + name + "'"; - if (expectedValue instanceof Pattern) { - message += " matching regex"; - } - expectImpl("to.have.css", expectedText, expectedValue, message, commonOptions, "Assert \"hasCSS\""); + private void toHaveAccessibleErrorMessage(Object expected, HasAccessibleErrorMessageOptions options) { + callMatcherAsStep("hasAccessibleErrorMessage", state -> { + return toMatchText(state, "hasAccessibleErrorMessage", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(new Object[] {expected}, null, true, options == null ? null : options.ignoreCase); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.accessible.error.message", expectOptions); + }, expected, options == null ? null : options.timeout, false); + }); } @Override - public void hasId(String id, HasIdOptions options) { - ExpectedTextValue expected = new ExpectedTextValue(); - expected.string = id; - expectImpl("to.have.id", expected, id, "Locator expected to have ID", convertType(options, FrameExpectOptions.class), "Assert \"hasId\""); + public void hasAttribute(String name, String expected, HasAttributeOptions options) { + toHaveAttribute(name, expected, options); } @Override - public void hasId(Pattern pattern, HasIdOptions options) { - ExpectedTextValue expected = expectedRegex(pattern); - expectImpl("to.have.id", expected, pattern, "Locator expected to have ID matching regex", convertType(options, FrameExpectOptions.class), "Assert \"hasId\""); + public void hasAttribute(String name, Pattern expected, HasAttributeOptions options) { + toHaveAttribute(name, expected, options); } - @Override - public void hasJSProperty(String name, Object value, HasJSPropertyOptions options) { - if (options == null) { - options = new HasJSPropertyOptions(); - } - FrameExpectOptions commonOptions = convertType(options, FrameExpectOptions.class); - commonOptions.expressionArg = name; - commonOptions.expectedValue = serializeArgument(value); - List list = null; - expectImpl("to.have.property", list, value, "Locator expected to have JavaScript property '" + name + "'", commonOptions, "Assert \"hasJSProperty\""); + // java: the public API has no hasAttribute(name), so there is no toBeTruthy branch for a missing expected value. + private void toHaveAttribute(String name, Object expected, HasAttributeOptions options) { + callMatcherAsStep("hasAttribute", state -> { + return toMatchText(state, "hasAttribute", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(new Object[] {expected}, null, null, options == null ? null : options.ignoreCase); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expressionArg = name; + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.attribute.value", expectOptions); + }, expected, options == null ? null : options.timeout, false); + }); } @Override - public void hasRole(AriaRole role, HasRoleOptions options) { - ExpectedTextValue expected = new ExpectedTextValue(); - expected.string = role.toString().toLowerCase(); - expectImpl("to.have.role", expected, expected.string, "Locator expected to have role", convertType(options, FrameExpectOptions.class), "Assert \"hasRole\""); + public void hasClass(String expected, HasClassOptions options) { + toHaveClass(expected, options); } @Override - 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), "Assert \"hasText\""); + public void hasClass(Pattern expected, HasClassOptions options) { + toHaveClass(expected, options); } @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; - expectImpl("to.have.text", expected, pattern, "Locator expected to have text matching regex", convertType(options, FrameExpectOptions.class), "Assert \"hasText\""); + public void hasClass(String[] expected, HasClassOptions options) { + toHaveClass(expected, options); } @Override - public void hasText(String[] strings, HasTextOptions options) { - List list = new ArrayList<>(); - for (String text : strings) { - ExpectedTextValue expected = new ExpectedTextValue(); - expected.string = text; - expected.ignoreCase = shouldIgnoreCase(options); - expected.matchSubstring = false; - expected.normalizeWhiteSpace = true; - list.add(expected); - } - expectImpl("to.have.text.array", list, strings, "Locator expected to have text", convertType(options, FrameExpectOptions.class), "Assert \"hasText\""); + public void hasClass(Pattern[] expected, HasClassOptions options) { + toHaveClass(expected, options); } - @Override - public void hasText(Pattern[] patterns, HasTextOptions options) { - List list = new ArrayList<>(); - for (Pattern pattern : patterns) { - ExpectedTextValue expected = expectedRegex(pattern); - expected.ignoreCase = shouldIgnoreCase(options); - expected.matchSubstring = true; - expected.normalizeWhiteSpace = true; - list.add(expected); - } - expectImpl("to.have.text.array", list, patterns, "Locator expected to have text matching regex", convertType(options, FrameExpectOptions.class), "Assert \"hasText\""); + private void toHaveClass(Object expected, HasClassOptions options) { + callMatcherAsStep("hasClass", state -> { + if (expected instanceof Object[]) { + return toEqual(state, "hasClass", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues((Object[]) expected, null, null, null); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.class.array", expectOptions); + }, expected, options == null ? null : options.timeout); + } else { + return toMatchText(state, "hasClass", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(new Object[] {expected}, null, null, null); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.class", expectOptions); + }, expected, options == null ? null : options.timeout, false); + } + }); } @Override - public void hasValue(String value, HasValueOptions options) { - ExpectedTextValue expected = new ExpectedTextValue(); - expected.string = value; - expectImpl("to.have.value", expected, value, "Locator expected to have value", convertType(options, FrameExpectOptions.class), "Assert \"hasValue\""); + public void containsClass(String expected, ContainsClassOptions options) { + toContainClass(expected, options); } @Override - public void hasValue(Pattern pattern, HasValueOptions options) { - ExpectedTextValue expected = expectedRegex(pattern); - expectImpl("to.have.value", expected, pattern, "Locator expected to have value matching regex", convertType(options, FrameExpectOptions.class), "Assert \"hasValue\""); + public void containsClass(List expected, ContainsClassOptions options) { + toContainClass(expected, options); } - @Override - public void hasValues(String[] values, HasValuesOptions options) { - List 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), "Assert \"hasValues\""); + // java: expected is a String or a List of String, so there is no check for a RegExp. + private void toContainClass(Object expected, ContainsClassOptions options) { + callMatcherAsStep("containsClass", state -> { + if (expected instanceof List) { + return toEqual(state, "containsClass", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(((List) expected).toArray(), null, null, null); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.contain.class.array", expectOptions); + }, expected, options == null ? null : options.timeout); + } else { + return toMatchText(state, "containsClass", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(new Object[] {expected}, null, null, null); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.contain.class", expectOptions); + }, expected, options == null ? null : options.timeout, false); + } + }); } @Override - public void hasValues(Pattern[] patterns, HasValuesOptions options) { - List 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), "Assert \"hasValues\""); + public void hasCount(int expected, HasCountOptions options) { + callMatcherAsStep("hasCount", state -> { + return toEqual(state, "hasCount", actualLocator, "Locator", (isNot, timeout) -> { + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedNumber = (double) expected; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.count", expectOptions); + }, expected, options == null ? null : options.timeout); + }); } @Override - public void matchesAriaSnapshot(String expected, MatchesAriaSnapshotOptions snapshotOptions) { - if (snapshotOptions == null) { - snapshotOptions = new MatchesAriaSnapshotOptions(); - } - FrameExpectOptions options = convertType(snapshotOptions, FrameExpectOptions.class); - options.expectedValue = serializeArgument(expected); - expectImpl("to.match.aria", options, expected,"Locator expected to match Aria snapshot", "Assert \"matchesAriaSnapshot\""); + public void hasCSS(String name, String expected, HasCSSOptions options) { + toHaveCSS(name, expected, options); } @Override - public void isChecked(IsCheckedOptions options) { - if (options == null) { - options = new IsCheckedOptions(); - } - - Map expectedValue = new HashMap<>(); - if (options.indeterminate != null) { - expectedValue.put("indeterminate", options.indeterminate); - } - if (options.checked != null) { - expectedValue.put("checked", options.checked); - } + public void hasCSS(String name, Pattern expected, HasCSSOptions options) { + toHaveCSS(name, expected, options); + } - String expected; - if (options.indeterminate != null && options.indeterminate) { - expected = "indeterminate"; - } else { - boolean unchecked = options.checked != null && !options.checked; - expected = unchecked ? "unchecked" : "checked"; - } + private void toHaveCSS(String name, Object expected, HasCSSOptions options) { + callMatcherAsStep("hasCSS", state -> { + return toMatchText(state, "hasCSS", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(new Object[] {expected}, null, null, null); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expressionArg = name; + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.pseudo = options == null ? null : options.pseudo; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.css", expectOptions); + }, expected, options == null ? null : options.timeout, false); + }); + } + + @Override + public void hasId(String expected, HasIdOptions options) { + toHaveId(expected, options); + } + + @Override + public void hasId(Pattern expected, HasIdOptions options) { + toHaveId(expected, options); + } - String message = "Locator expected to be"; - FrameExpectOptions expectOptions = convertType(options, FrameExpectOptions.class); - expectOptions.expectedValue = serializeArgument(expectedValue); - expectImpl("to.be.checked", expectOptions, expected, message, "Assert \"isChecked\""); + private void toHaveId(Object expected, HasIdOptions options) { + callMatcherAsStep("hasId", state -> { + return toMatchText(state, "hasId", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(new Object[] {expected}, null, null, null); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.id", expectOptions); + }, expected, options == null ? null : options.timeout, false); + }); } @Override - public void isDisabled(IsDisabledOptions options) { - expectTrue("to.be.disabled", "Locator expected to be disabled", convertType(options, FrameExpectOptions.class), "Assert \"isDisabled\""); + public void hasJSProperty(String name, Object expected, HasJSPropertyOptions options) { + callMatcherAsStep("hasJSProperty", state -> { + return toEqual(state, "hasJSProperty", actualLocator, "Locator", (isNot, timeout) -> { + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expressionArg = name; + expectOptions.expectedValue = expected; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.property", expectOptions); + }, expected, options == null ? null : options.timeout); + }); } @Override - public void isEditable(IsEditableOptions options) { - FrameExpectOptions frameOptions = convertType(options, FrameExpectOptions.class); - boolean editable = options == null || options.editable == null || options.editable == true; - String message = "Locator expected to be " + (editable ? "editable" : "readonly"); - expectTrue(editable ? "to.be.editable" : "to.be.readonly", message, frameOptions, "Assert \"isEditable\""); + public void hasRole(AriaRole role, HasRoleOptions options) { + // java: the role is an enum, its string is the lower case name; there is no check that it is a string. + String expected = role.toString().toLowerCase(); + callMatcherAsStep("hasRole", state -> { + return toMatchText(state, "hasRole", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(new Object[] {expected}, null, null, null); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.role", expectOptions); + }, expected, options == null ? null : options.timeout, false); + }); } @Override - public void isEmpty(IsEmptyOptions options) { - expectTrue("to.be.empty", "Locator expected to be empty", convertType(options, FrameExpectOptions.class), "Assert \"isEmpty\""); + public void hasText(String expected, HasTextOptions options) { + toHaveText(expected, options); } @Override - public void isEnabled(IsEnabledOptions options) { - FrameExpectOptions frameOptions = convertType(options, FrameExpectOptions.class); - boolean enabled = options == null || options.enabled == null || options.enabled == true; - String message = "Locator expected to be " + (enabled ? "enabled" : "disabled"); - expectTrue(enabled ? "to.be.enabled" : "to.be.disabled", message, frameOptions, "Assert \"isEnabled\""); + public void hasText(Pattern expected, HasTextOptions options) { + toHaveText(expected, options); } @Override - public void isFocused(IsFocusedOptions options) { - expectTrue("to.be.focused", "Locator expected to be focused", convertType(options, FrameExpectOptions.class), "Assert \"isFocused\""); + public void hasText(String[] expected, HasTextOptions options) { + toHaveText(expected, options); } @Override - public void isHidden(IsHiddenOptions options) { - expectTrue("to.be.hidden", "Locator expected to be hidden", convertType(options, FrameExpectOptions.class), "Assert \"isHidden\""); + public void hasText(Pattern[] expected, HasTextOptions options) { + toHaveText(expected, options); + } + + private void toHaveText(Object expected, HasTextOptions options) { + callMatcherAsStep("hasText", state -> { + if (expected instanceof Object[]) { + return toEqual(state, "hasText", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues((Object[]) expected, null, true, options == null ? null : options.ignoreCase); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.useInnerText = options == null ? null : options.useInnerText; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.text.array", expectOptions); + }, expected, options == null ? null : options.timeout); + } else { + return toMatchText(state, "hasText", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(new Object[] {expected}, null, true, options == null ? null : options.ignoreCase); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.useInnerText = options == null ? null : options.useInnerText; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.text", expectOptions); + }, expected, options == null ? null : options.timeout, false); + } + }); } @Override - public void isInViewport(IsInViewportOptions options) { - FrameExpectOptions expectOptions = convertType(options, FrameExpectOptions.class); - if (options != null && options.ratio != null) { - expectOptions.expectedNumber = options.ratio; - } - expectTrue("to.be.in.viewport", "Locator expected to be in viewport", expectOptions, "Assert \"isInViewport\""); + public void hasValue(String expected, HasValueOptions options) { + toHaveValue(expected, options); } @Override - public void isVisible(IsVisibleOptions options) { - FrameExpectOptions frameOptions = convertType(options, FrameExpectOptions.class); - boolean visible = options == null || options.visible == null || options.visible == true; - String message = "Locator expected to be " + (visible ? "visible" : "hidden"); - expectTrue(visible ? "to.be.visible" : "to.be.hidden", message, frameOptions, "Assert \"isVisible\""); + public void hasValue(Pattern expected, HasValueOptions options) { + toHaveValue(expected, options); } - private void expectTrue(String expression, String message, FrameExpectOptions options, String title) { - List expectedText = null; - expectImpl(expression, expectedText, null, message, options, title); + private void toHaveValue(Object expected, HasValueOptions options) { + callMatcherAsStep("hasValue", state -> { + return toMatchText(state, "hasValue", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(new Object[] {expected}, null, null, null); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.value", expectOptions); + }, expected, options == null ? null : options.timeout, false); + }); } @Override - public LocatorAssertions not() { - return new LocatorAssertionsImpl(actualLocator, !isNot); + public void hasValues(String[] expected, HasValuesOptions options) { + toHaveValues(expected, options); } @Override - public void isAttached(IsAttachedOptions options) { - FrameExpectOptions frameOptions = convertType(options, FrameExpectOptions.class); - boolean attached = options == null || options.attached == null || options.attached == true; - String message = "Locator expected to be " + (attached ? "attached" : "detached"); - expectTrue(attached ? "to.be.attached" : "to.be.detached", message, frameOptions, "Assert \"isAttached\""); + public void hasValues(Pattern[] expected, HasValuesOptions options) { + toHaveValues(expected, options); + } + + private void toHaveValues(Object[] expected, HasValuesOptions options) { + callMatcherAsStep("hasValues", state -> { + return toEqual(state, "hasValues", actualLocator, "Locator", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(expected, null, null, null); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualLocator.expect("to.have.values", expectOptions); + }, expected, options == null ? null : options.timeout); + }); + } + + // java: toMatchAriaSnapshot of toMatchAriaSnapshot.ts. + @Override + public void matchesAriaSnapshot(String expected, MatchesAriaSnapshotOptions options) { + callMatcherAsStep("matchesAriaSnapshot", state -> toMatchAriaSnapshot(state, actualLocator, expected, options == null ? null : options.timeout)); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java index 99731bbb2..310ab068c 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java @@ -692,9 +692,9 @@ public void waitForFunction(String expression, Object arg, WaitForFunctionOption } // java: upstream options.title is the separate title parameter, as in FrameImpl.expect. - FrameExpectResult expect(String expression, FrameExpectOptions options, String title) { + FrameExpectResult expect(String expression, FrameExpectOptions options) { options.selector = selector; - return frame.expect(expression, options, title); + return frame.expect(expression, options); } // java: no _inspect, it serves inspect.custom. diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/MatcherHint.java b/playwright/src/main/java/com/microsoft/playwright/impl/MatcherHint.java new file mode 100644 index 000000000..1cea82b96 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/MatcherHint.java @@ -0,0 +1,146 @@ +/* + * 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. + */ + +// Port of matcherHint.ts. +package com.microsoft.playwright.impl; + +import java.util.List; +import java.util.function.Supplier; +import java.util.regex.Matcher; + +import static com.microsoft.playwright.impl.JestMatcherUtils.DIM_COLOR; +import static com.microsoft.playwright.impl.JestMatcherUtils.EXPECTED_COLOR; +import static com.microsoft.playwright.impl.JestMatcherUtils.INVERTED_COLOR; +import static com.microsoft.playwright.impl.JestMatcherUtils.RECEIVED_COLOR; +import static com.microsoft.playwright.impl.JestMatcherUtils.printReceived; + +class MatcherHint { + // java: no attachments, suggestedRebaseline, softError and shouldNotRetryTest, they belong to the test runner. + static class MatcherResult { + String name; + Object expected; + Supplier message; + boolean pass; + Object actual; + List log; + Double timeout; + String ariaSnapshot; + } + + // java: no ExpectError, AssertionsBase throws an AssertionFailedError of opentest4j. + + // java: no expectTypes, the receiver of a matcher is typed. + + // java: InternalMatcherUtils is JestMatcherUtils, its methods are static. + + private static String printSubstring(String val) { + return val.replaceAll("\"|\\\\", "\\\\$0"); + } + + static String printReceivedStringContainExpectedSubstring(String received, int start, int length) { + return RECEIVED_COLOR( + "\"" + + printSubstring(slice(received, 0, start)) + + INVERTED_COLOR(printSubstring(slice(received, start, start + length))) + + printSubstring(slice(received, start + length, received.length())) + + "\""); + } + + // java: result is the Matcher after a successful find(), or null. + static String printReceivedStringContainExpectedResult(String received, Matcher result) { + return result == null + ? printReceived(received) + : printReceivedStringContainExpectedSubstring( + received, + result.start(), + result.group().length()); + } + + static class MatcherMessageDetails { + String promise; + boolean isNot; + String receiver; + String matcherName; + String expectation; + String locator; + String printedExpected; + String printedReceived; + String printedDiff; + Boolean timedOut; + Double timeout; + String errorMessage; + List log; + } + + static String formatMatcherMessage(MatcherMessageDetails details) { + String receiver = details.receiver != null ? details.receiver : (details.locator != null && !details.locator.isEmpty() ? "locator" : "page"); + // java: the call is the Java one: assertThat(locator).not().hasText(expected). + String message = DIM_COLOR("assertThat(") + RECEIVED_COLOR(receiver) + + DIM_COLOR(")" + (details.promise != null && !details.promise.isEmpty() ? "." + details.promise : "") + (details.isNot ? ".not()" : "") + ".") + + details.matcherName + + DIM_COLOR("(") + EXPECTED_COLOR(details.expectation) + DIM_COLOR(")") + + " failed\n\n"; + + String[] diffLines = details.printedDiff == null ? null : details.printedDiff.split("\n", -1); + if (diffLines != null && diffLines.length == 2) { + details.printedExpected = diffLines[0]; + details.printedReceived = diffLines[1]; + details.printedDiff = null; + } + + boolean align = isEmpty(details.errorMessage) && details.printedExpected != null && details.printedExpected.startsWith("Expected:") + && (isEmpty(details.printedReceived) || details.printedReceived.startsWith("Received:")); + if (!isEmpty(details.locator)) + message += "Locator: " + (align ? " " : "") + details.locator + "\n"; + if (!isEmpty(details.printedExpected)) + message += details.printedExpected + "\n"; + if (!isEmpty(details.printedReceived)) + message += details.printedReceived + "\n"; + if (details.timedOut != null && details.timedOut && details.timeout != null && details.timeout != 0) + message += "Timeout: " + (align ? " " : "") + formatNumber(details.timeout) + "ms\n"; + if (!isEmpty(details.printedDiff)) + message += details.printedDiff + "\n"; + if (!isEmpty(details.errorMessage)) { + message += details.errorMessage; + if (!details.errorMessage.endsWith("\n")) + message += "\n"; + } + message += callLogText(details.log); + return message; + } + + static String callLogText(List log) { + if (log == null || !log.stream().anyMatch(l -> !isEmpty(l))) + return ""; + return "\nCall log:\n" + DIM_COLOR(String.join("\n", log)) + "\n"; + } + + // java: helpers with no counterpart upstream: String.prototype.slice, the truthiness of a string and the text of a number. + private static String slice(String string, int start, int end) { + int length = string.length(); + int from = start < 0 ? Math.max(length + start, 0) : Math.min(start, length); + int to = end < 0 ? Math.max(length + end, 0) : Math.min(end, length); + return from < to ? string.substring(from, to) : ""; + } + + private static boolean isEmpty(String string) { + return string == null || string.isEmpty(); + } + + static String formatNumber(double number) { + return number == Math.rint(number) && Math.abs(number) < 1e15 ? String.valueOf((long) number) : String.valueOf(number); + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PageAssertionsImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PageAssertionsImpl.java index 97e986886..07e1a1579 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageAssertionsImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageAssertionsImpl.java @@ -14,17 +14,22 @@ * limitations under the License. */ +// Port of matchers.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; import com.microsoft.playwright.Page; import com.microsoft.playwright.assertions.PageAssertions; +import com.microsoft.playwright.impl.protocol.ExpectedTextValue; +import java.util.List; import java.util.regex.Pattern; +import static com.microsoft.playwright.impl.LocatorAssertionsImpl.serializeExpectedTextValues; +import static com.microsoft.playwright.impl.ToMatchAriaSnapshot.toMatchAriaSnapshot; +import static com.microsoft.playwright.impl.ToMatchText.toMatchText; import static com.microsoft.playwright.impl.UrlMatcher.constructURLBasedOnBaseURL; -import static com.microsoft.playwright.impl.Utils.convertType; +// java: the matchers of a Page, see LocatorAssertionsImpl. public class PageAssertionsImpl extends AssertionsBase implements PageAssertions { private final PageImpl actualPage; @@ -38,55 +43,64 @@ private PageAssertionsImpl(Page page, boolean isNot) { } @Override - FrameExpectResult doExpect(String expression, FrameExpectOptions expectOptions, String title) { - FrameImpl frame = (FrameImpl) actualPage.mainFrame(); - return frame.expect(expression, expectOptions, title); + public PageAssertions not() { + return new PageAssertionsImpl(actualPage, !isNot); } @Override - public void hasTitle(String title, HasTitleOptions options) { - ExpectedTextValue expected = new ExpectedTextValue(); - expected.string = title; - expected.normalizeWhiteSpace = true; - expectImpl("to.have.title", expected, title, "Page title expected to be", convertType(options, FrameExpectOptions.class), "Assert \"hasTitle\""); + public void hasTitle(String expected, HasTitleOptions options) { + toHaveTitle(expected, options); } @Override - public void hasTitle(Pattern pattern, HasTitleOptions options) { - ExpectedTextValue expected = expectedRegex(pattern); - expectImpl("to.have.title", expected, pattern, "Page title expected to match regex", convertType(options, FrameExpectOptions.class), "Assert \"hasTitle\""); + public void hasTitle(Pattern expected, HasTitleOptions options) { + toHaveTitle(expected, options); } - @Override - public void hasURL(String url, HasURLOptions options) { - ExpectedTextValue expected = new ExpectedTextValue(); - if (actualPage.context().baseUrl() != null) { - url = constructURLBasedOnBaseURL(actualPage.context().baseUrl().toString(), url); - } - expected.string = url; - expected.ignoreCase = shouldIgnoreCase(options); - expectImpl("to.have.url", expected, url, "Page URL expected to be", convertType(options, FrameExpectOptions.class), "Assert \"hasURL\""); + private void toHaveTitle(Object expected, HasTitleOptions options) { + callMatcherAsStep("hasTitle", state -> { + return toMatchText(state, "hasTitle", actualPage, "Page", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(new Object[] {expected}, null, true, null); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualPage.mainFrame().expect("to.have.title", expectOptions); + }, expected, options == null ? null : options.timeout, false); + }); } @Override - public void hasURL(Pattern pattern, HasURLOptions options) { - ExpectedTextValue expected = expectedRegex(pattern); - expectImpl("to.have.url", expected, pattern, "Page URL expected to match regex", convertType(options, FrameExpectOptions.class), "Assert \"hasURL\""); + public void hasURL(String expected, HasURLOptions options) { + toHaveURL(expected, options); } @Override - public void matchesAriaSnapshot(String expected, MatchesAriaSnapshotOptions snapshotOptions) { - if (snapshotOptions == null) { - snapshotOptions = new MatchesAriaSnapshotOptions(); - } - FrameExpectOptions options = convertType(snapshotOptions, FrameExpectOptions.class); - options.expectedValue = Serialization.serializeArgument(expected); - expectImpl("to.match.aria", options, expected, "Page expected to match Aria snapshot", "Assert \"matchesAriaSnapshot\""); + public void hasURL(Pattern expected, HasURLOptions options) { + toHaveURL(expected, options); + } + + // java: the public API has no URLPattern and no predicate, so toHaveURLWithPredicate of toHaveURL.ts is not ported. + private void toHaveURL(Object expectedParam, HasURLOptions options) { + callMatcherAsStep("hasURL", state -> { + String baseURL = actualPage.context().options.baseURL; + Object expected = expectedParam instanceof String ? constructURLBasedOnBaseURL(baseURL, (String) expectedParam) : expectedParam; + return toMatchText(state, "hasURL", actualPage, "Page", (isNot, timeout) -> { + List expectedText = serializeExpectedTextValues(new Object[] {expected}, null, null, options == null ? null : options.ignoreCase); + FrameExpectOptions expectOptions = new FrameExpectOptions(); + expectOptions.expectedText = expectedText; + expectOptions.isNot = isNot; + expectOptions.timeout = timeout; + expectOptions.title = state.title; + return actualPage.mainFrame().expect("to.have.url", expectOptions); + }, expected, options == null ? null : options.timeout, false); + }); } + // java: toMatchAriaSnapshot of toMatchAriaSnapshot.ts. @Override - public PageAssertions not() { - return new PageAssertionsImpl(actualPage, !isNot); + public void matchesAriaSnapshot(String expected, MatchesAriaSnapshotOptions options) { + callMatcherAsStep("matchesAriaSnapshot", state -> toMatchAriaSnapshot(state, actualPage, expected, options == null ? null : options.timeout)); } } - diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PrettyFormat.java b/playwright/src/main/java/com/microsoft/playwright/impl/PrettyFormat.java new file mode 100644 index 000000000..7ad797872 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PrettyFormat.java @@ -0,0 +1,407 @@ +/* + * 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. + */ + +// Port of pretty-format. +// java: the original is MIT licensed, Copyright (c) Meta Platforms, Inc. and affiliates. +package com.microsoft.playwright.impl; + +import com.microsoft.playwright.PlaywrightException; + +import java.lang.reflect.Array; +import java.math.BigDecimal; +import java.math.MathContext; +import java.math.RoundingMode; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +import static com.microsoft.playwright.impl.JestGetType.isArray; +import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; + +// java: only the code that formats the Java values is ported: null, Boolean, Number, String, +// Pattern, List and arrays, Map. The plugins, callToJSON, the colors and the other JavaScript +// types are not ported. +class PrettyFormat { + // java: the type of the options object. A null field is an option that is not set. + static class Options { + Boolean callToJSON; + Comparator compareKeys; + Integer indent; + Integer maxDepth; + Integer maxWidth; + Boolean min; + } + + // java: the type of the config object. + static class Config { + boolean callToJSON; + Comparator compareKeys; + boolean escapeRegex; + boolean escapeString; + String indent; + int maxDepth; + int maxWidth; + boolean min; + boolean printBasicPrototype; + boolean printFunctionName; + String spacingInner; + String spacingOuter; + } + + // java: compareKeys is undefined or a function here. The null value of upstream, which + // keeps the order of the keys, is not ported. + private static List getKeysOfEnumerableProperties(Map object, Comparator compareKeys) { + // java: a key that is not a String is converted with String.valueOf, as a JavaScript + // object converts its keys. + List rawKeys = new ArrayList<>(); + for (Object key : object.keySet()) { + rawKeys.add(String.valueOf(key)); + } + // java: the default order of Array.prototype.sort is the order of the UTF-16 code units, + // which is the order of String.compareTo. + Collections.sort(rawKeys, compareKeys); + List keys = new ArrayList(rawKeys); + return keys; + } + + static String printListItems(List list, Config config, String indentation, int depth, List refs) { + String result = ""; + int length = list.size(); + if (length > 0) { + result += config.spacingOuter; + String indentationNext = indentation + config.indent; + for (int i = 0; i < length; i++) { + result += indentationNext; + if (i == config.maxWidth) { + result += "…"; + break; + } + result += printer(list.get(i), config, indentationNext, depth, refs, false); + if (i < length - 1) { + result += "," + config.spacingInner; + } else if (!config.min) { + result += ","; + } + } + result += config.spacingOuter + indentation; + } + return result; + } + + static String printObjectProperties(Map val, Config config, String indentation, int depth, List refs) { + String result = ""; + List keys = getKeysOfEnumerableProperties(val, config.compareKeys); + if (keys.size() > 0) { + result += config.spacingOuter; + String indentationNext = indentation + config.indent; + for (int i = 0; i < keys.size(); i++) { + Object key = keys.get(i); + String name = printer(key, config, indentationNext, depth, refs, false); + String value = printer(get(val, key), config, indentationNext, depth, refs, false); + result += indentationNext + name + ": " + value; + if (i < keys.size() - 1) { + result += "," + config.spacingInner; + } else if (!config.min) { + result += ","; + } + } + result += config.spacingOuter + indentation; + } + return result; + } + + // java: helper with no counterpart upstream, the port of val[key] for the converted keys. + private static Object get(Map val, Object key) { + if (val.containsKey(key)) { + return val.get(key); + } + for (Map.Entry entry : val.entrySet()) { + if (key.equals(String.valueOf(entry.getKey()))) { + return entry.getValue(); + } + } + return null; + } + + private static String printNumber(double val) { + return Double.compare(val, -0.0) == 0 ? "-0" : numberToString(val); + } + + // java: helper with no counterpart upstream, the port of String(val) for a number: the + // Number::toString algorithm of ECMAScript. Double.toString has another format, and before + // JDK 19 it does not always give the shortest digits. + private static String numberToString(double m) { + if (Double.isNaN(m)) { + return "NaN"; + } + if (m == 0) { + return "0"; + } + if (m < 0) { + return "-" + numberToString(-m); + } + if (Double.isInfinite(m)) { + return "Infinity"; + } + BigDecimal exact = new BigDecimal(m); + BigDecimal shortest = null; + for (int precision = 1; shortest == null; precision++) { + BigDecimal down = exact.round(new MathContext(precision, RoundingMode.DOWN)); + BigDecimal up = exact.round(new MathContext(precision, RoundingMode.UP)); + boolean isDown = down.doubleValue() == m; + boolean isUp = up.doubleValue() == m; + if (isDown && isUp) { + int order = exact.subtract(down).compareTo(up.subtract(exact)); + if (order == 0) { + shortest = down.unscaledValue().testBit(0) ? up : down; + } else { + shortest = order < 0 ? down : up; + } + } else if (isDown) { + shortest = down; + } else if (isUp) { + shortest = up; + } + } + shortest = shortest.stripTrailingZeros(); + String s = shortest.unscaledValue().toString(); + int k = s.length(); + int n = k - shortest.scale(); + if (k <= n && n <= 21) { + return s + repeat("0", n - k); + } + if (0 < n && n <= 21) { + return s.substring(0, n) + "." + s.substring(n); + } + if (-6 < n && n <= 0) { + return "0." + repeat("0", -n) + s; + } + String exponent = (n - 1 < 0 ? "-" : "+") + Math.abs(n - 1); + if (k == 1) { + return s + "e" + exponent; + } + return s.substring(0, 1) + "." + s.substring(1) + "e" + exponent; + } + + // java: helper with no counterpart upstream, the port of String.prototype.repeat. + private static String repeat(String string, int count) { + StringBuilder result = new StringBuilder(); + for (int i = 0; i < count; i++) { + result.append(string); + } + return result.toString(); + } + + // java: helper with no counterpart upstream, the port of RegExp.prototype.toString. The + // source is escaped as JavaScript escapes it: an empty source, a slash that is not in a + // character class and the line terminators. The syntax of the Java pattern stays as it is. + private static String regExpToString(Pattern val) { + String pattern = val.pattern(); + StringBuilder source = new StringBuilder(); + boolean inCharClass = false; + boolean previousCharWasBackslash = false; + for (int i = 0; i < pattern.length(); i++) { + char c = pattern.charAt(i); + String escaped = null; + if (c == '\n') { + escaped = "\\n"; + } else if (c == '\r') { + escaped = "\\r"; + } else if (c == '
') { + escaped = "\\u2028"; + } else if (c == '
') { + escaped = "\\u2029"; + } + if (previousCharWasBackslash) { + if (escaped != null) { + source.setLength(source.length() - 1); + source.append(escaped); + } else { + source.append(c); + } + previousCharWasBackslash = false; + continue; + } + if (escaped != null) { + source.append(escaped); + } else if (c == '/' && !inCharClass) { + source.append("\\/"); + } else { + if (c == '[') { + inCharClass = true; + } else if (c == ']') { + inCharClass = false; + } else if (c == '\\') { + previousCharWasBackslash = true; + } + source.append(c); + } + } + if (source.length() == 0) { + source.append("(?:)"); + } + // java: toJsRegexFlags gives the flags in the order "ism", JavaScript prints them in + // the alphabetical order. + char[] flags = toJsRegexFlags(val).toCharArray(); + Arrays.sort(flags); + return "/" + source + "/" + new String(flags); + } + + private static String printBasicValue(Object val, boolean printFunctionName, boolean escapeRegex, boolean escapeString) { + if (Boolean.TRUE.equals(val) || Boolean.FALSE.equals(val)) { + return "" + val; + } + if (val == JestGetType.UNDEFINED) { + return "undefined"; + } + if (val == null) { + return "null"; + } + if (val instanceof Number) { + // java: each Number is a JavaScript number, a double. + return printNumber(((Number) val).doubleValue()); + } + if (val instanceof String) { + if (escapeString) { + return "\"" + ((String) val).replaceAll("\"|\\\\", "\\\\$0") + "\""; + } + return "\"" + val + "\""; + } + if (val instanceof Date) { + // java: a java.util.Date is never invalid, so there is no "Date { NaN }". + return DateTimeFormatter.ISO_INSTANT.format(((Date) val).toInstant().truncatedTo(ChronoUnit.MILLIS)).replaceFirst("(:\\d\\d)Z$", "$1.000Z"); + } + if (val instanceof Pattern) { + if (escapeRegex) { + return regExpToString((Pattern) val).replaceAll("[$()*+.?\\[\\\\\\]^{|}]", "\\\\$0"); + } + return regExpToString((Pattern) val); + } + return null; + } + + private static String printComplexValue(Object val, Config config, String indentation, int depth, List refs, boolean hasCalledToJSON) { + // java: includes compares the objects by identity. + for (Object ref : refs) { + if (ref == val) { + return "[Circular]"; + } + } + refs = new ArrayList<>(refs); + refs.add(val); + boolean hitMaxDepth = ++depth > config.maxDepth; + boolean min = config.min; + if (isArray(val)) { + return hitMaxDepth ? "[Array]" : (min ? "" : !config.printBasicPrototype ? "" : "Array ") + "[" + printListItems(toList(val), config, indentation, depth, refs) + "]"; + } + if (!(val instanceof Map)) { + // java: a value that is not in the value model has no enumerable properties to print. + return String.valueOf(val); + } + + return hitMaxDepth ? "[Object]" : (min ? "" : !config.printBasicPrototype ? "" : "Object ") + "{" + printObjectProperties((Map) val, config, indentation, depth, refs) + "}"; + } + + // java: helper with no counterpart upstream, the items of a List or of an array. + private static List toList(Object val) { + if (val instanceof List) { + return (List) val; + } + List list = new ArrayList<>(); + for (int i = 0; i < Array.getLength(val); i++) { + list.add(Array.get(val, i)); + } + return list; + } + + private static String printer(Object val, Config config, String indentation, int depth, List refs, boolean hasCalledToJSON) { + String basicResult = printBasicValue(val, config.printFunctionName, config.escapeRegex, config.escapeString); + if (basicResult != null) { + return basicResult; + } + return printComplexValue(val, config, indentation, depth, refs, hasCalledToJSON); + } + + static final Options DEFAULT_OPTIONS = new Options(); + static { + DEFAULT_OPTIONS.callToJSON = true; + DEFAULT_OPTIONS.compareKeys = null; + DEFAULT_OPTIONS.indent = 2; + // java: an int has no infinity. + DEFAULT_OPTIONS.maxDepth = Integer.MAX_VALUE; + DEFAULT_OPTIONS.maxWidth = Integer.MAX_VALUE; + DEFAULT_OPTIONS.min = false; + } + + private static void validateOptions(Options options) { + if (options.min != null && options.min && options.indent != null && options.indent != 0) { + throw new PlaywrightException("pretty-format: Options \"min\" and \"indent\" cannot be used together."); + } + } + + // java: Options has no printFunctionName, escapeRegex and escapeString, the three getters + // return the default values. + private static boolean getPrintFunctionName(Options options) { + return true; + } + + private static boolean getEscapeRegex(Options options) { + return false; + } + + private static boolean getEscapeString(Options options) { + return true; + } + + private static Config getConfig(Options options) { + Config config = new Config(); + config.callToJSON = options != null && options.callToJSON != null ? options.callToJSON : DEFAULT_OPTIONS.callToJSON; + config.compareKeys = options != null && options.compareKeys != null ? options.compareKeys : DEFAULT_OPTIONS.compareKeys; + config.escapeRegex = getEscapeRegex(options); + config.escapeString = getEscapeString(options); + config.indent = options != null && options.min != null && options.min ? "" : createIndent(options != null && options.indent != null ? options.indent : DEFAULT_OPTIONS.indent); + config.maxDepth = options != null && options.maxDepth != null ? options.maxDepth : DEFAULT_OPTIONS.maxDepth; + config.maxWidth = options != null && options.maxWidth != null ? options.maxWidth : DEFAULT_OPTIONS.maxWidth; + config.min = options != null && options.min != null ? options.min : DEFAULT_OPTIONS.min; + config.printBasicPrototype = true; + config.printFunctionName = getPrintFunctionName(options); + config.spacingInner = options != null && options.min != null && options.min ? " " : "\n"; + config.spacingOuter = options != null && options.min != null && options.min ? "" : "\n"; + return config; + } + + private static String createIndent(int indent) { + return repeat(" ", indent); + } + + static String format(Object val, Options options) { + if (options != null) { + validateOptions(options); + } + String basicResult = printBasicValue(val, getPrintFunctionName(options), getEscapeRegex(options), getEscapeString(options)); + if (basicResult != null) { + return basicResult; + } + return printComplexValue(val, getConfig(options), "", 0, new ArrayList<>(), false); + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ToBeTruthy.java b/playwright/src/main/java/com/microsoft/playwright/impl/ToBeTruthy.java new file mode 100644 index 000000000..5caa2e171 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ToBeTruthy.java @@ -0,0 +1,93 @@ +/* + * 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. + */ + +// Port of toBeTruthy.ts. +package com.microsoft.playwright.impl; + +import com.microsoft.playwright.impl.AssertionsBase.ExpectMatcherState; +import com.microsoft.playwright.impl.AssertionsBase.Query; +import com.microsoft.playwright.impl.MatcherHint.MatcherMessageDetails; +import com.microsoft.playwright.impl.MatcherHint.MatcherResult; + +import java.util.List; + +import static com.microsoft.playwright.impl.MatcherHint.formatMatcherMessage; + +class ToBeTruthy { + // java: the options are their timeout, there is no AbortSignal. + static MatcherResult toBeTruthy( + ExpectMatcherState state, + String matcherName, + LocatorImpl locator, + String receiverType, + String expected, + String arg, + Query query, + Double optionsTimeout) { + double timeout = optionsTimeout != null ? optionsTimeout : state.timeout; + + FrameExpectResult queryResult = query.query(state.isNot, timeout); + boolean pass = queryResult.matches; + List log = queryResult.log; + Boolean timedOut = queryResult.timedOut; + FrameExpectResult.ExpectReceived received = queryResult.received; + String errorMessage = queryResult.errorMessage; + Object receivedValue = received == null ? JestGetType.UNDEFINED : received.value; + + if (pass == !state.isNot) { + MatcherResult result = new MatcherResult(); + result.name = matcherName; + result.message = () -> ""; + result.pass = pass; + result.expected = expected; + return result; + } + + String printedReceived; + String printedExpected; + if (pass) { + printedExpected = "Expected: not " + expected; + printedReceived = errorMessage != null ? "" : "Received: " + expected; + } else { + printedExpected = "Expected: " + expected; + printedReceived = errorMessage != null ? "" : "Received: " + receivedValue; + } + MatcherResult result = new MatcherResult(); + result.message = () -> { + MatcherMessageDetails details = new MatcherMessageDetails(); + details.isNot = state.isNot; + details.promise = state.promise; + details.matcherName = matcherName; + details.expectation = arg; + details.locator = locator.toString(); + details.timeout = timeout; + details.timedOut = timedOut; + details.printedExpected = printedExpected; + details.printedReceived = printedReceived; + details.errorMessage = errorMessage; + details.log = log; + return formatMatcherMessage(details); + }; + result.pass = pass; + result.actual = receivedValue; + result.name = matcherName; + result.expected = expected; + result.log = log; + result.timeout = timedOut != null && timedOut ? timeout : null; + result.ariaSnapshot = received == null ? null : received.ariaSnapshot; + return result; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ToEqual.java b/playwright/src/main/java/com/microsoft/playwright/impl/ToEqual.java new file mode 100644 index 000000000..051d4778a --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ToEqual.java @@ -0,0 +1,144 @@ +/* + * 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. + */ + +// Port of toEqual.ts. +package com.microsoft.playwright.impl; + +import com.microsoft.playwright.impl.AssertionsBase.ExpectMatcherState; +import com.microsoft.playwright.impl.AssertionsBase.Query; +import com.microsoft.playwright.impl.MatcherHint.MatcherMessageDetails; +import com.microsoft.playwright.impl.MatcherHint.MatcherResult; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Pattern; + +import static com.microsoft.playwright.impl.JestMatcherUtils.printDiffOrStringify; +import static com.microsoft.playwright.impl.JestMatcherUtils.printExpected; +import static com.microsoft.playwright.impl.JestMatcherUtils.printReceived; +import static com.microsoft.playwright.impl.MatcherHint.formatMatcherMessage; + +class ToEqual { + private static final String EXPECTED_LABEL = "Expected"; + private static final String RECEIVED_LABEL = "Received"; + + // java: the options are their timeout, contains is not read upstream and there is no AbortSignal. + static MatcherResult toEqual( + ExpectMatcherState state, + String matcherName, + LocatorImpl locator, + String receiverType, + Query query, + Object expected, + Double optionsTimeout) { + double timeout = optionsTimeout != null ? optionsTimeout : state.timeout; + + FrameExpectResult queryResult = query.query(state.isNot, timeout); + boolean pass = queryResult.matches; + FrameExpectResult.ExpectReceived received = queryResult.received; + List log = queryResult.log; + Boolean timedOut = queryResult.timedOut; + String errorMessage = queryResult.errorMessage; + Object receivedValue = received == null ? JestGetType.UNDEFINED : received.value; + + if (pass == !state.isNot) { + MatcherResult result = new MatcherResult(); + result.name = matcherName; + result.message = () -> ""; + result.pass = pass; + result.expected = expected; + return result; + } + + String printedReceived = null; + String printedExpected = null; + String printedDiff = null; + if (pass) { + printedExpected = "Expected: not " + printExpected(expected); + printedReceived = errorMessage != null ? "" : "Received: " + printReceived(receivedValue); + } else if (errorMessage != null) { + printedExpected = "Expected: " + printExpected(expected); + } else if (isArray(expected) && isArray(receivedValue)) { + List expectedList = toList(expected); + List receivedList = toList(receivedValue); + List normalizedExpected = new ArrayList<>(); + for (int index = 0; index < expectedList.size(); index++) { + Object exp = expectedList.get(index); + Object rec = index < receivedList.size() ? receivedList.get(index) : null; + if (exp instanceof Pattern) { + // java: RegExp.test() converts its argument to a string, a missing element is "undefined". + normalizedExpected.add(((Pattern) exp).matcher(rec == null ? "undefined" : String.valueOf(rec)).find() ? rec : exp); + continue; + } + + normalizedExpected.add(exp); + } + printedDiff = printDiffOrStringify( + normalizedExpected, + receivedValue, + EXPECTED_LABEL, + RECEIVED_LABEL, + false); + } else { + printedDiff = printDiffOrStringify( + expected, + receivedValue, + EXPECTED_LABEL, + RECEIVED_LABEL, + false); + } + String finalPrintedExpected = printedExpected; + String finalPrintedReceived = printedReceived; + String finalPrintedDiff = printedDiff; + MatcherResult result = new MatcherResult(); + result.message = () -> { + MatcherMessageDetails details = new MatcherMessageDetails(); + details.isNot = state.isNot; + details.promise = state.promise; + details.matcherName = matcherName; + details.expectation = "expected"; + details.locator = locator.toString(); + details.timeout = timeout; + details.timedOut = timedOut; + details.printedExpected = finalPrintedExpected; + details.printedReceived = finalPrintedReceived; + details.printedDiff = finalPrintedDiff; + details.errorMessage = errorMessage; + details.log = log; + return formatMatcherMessage(details); + }; + + result.actual = receivedValue; + result.expected = expected; + result.name = matcherName; + result.pass = pass; + result.log = log; + result.timeout = timedOut != null && timedOut ? timeout : null; + result.ariaSnapshot = received == null ? null : received.ariaSnapshot; + return result; + } + + // java: helpers with no counterpart upstream: a JS array is a List or a Java array. + private static boolean isArray(Object value) { + return value instanceof List || value instanceof Object[]; + } + + @SuppressWarnings("unchecked") + private static List toList(Object value) { + return value instanceof List ? (List) value : Arrays.asList((Object[]) value); + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchAriaSnapshot.java b/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchAriaSnapshot.java new file mode 100644 index 000000000..8e470c7db --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchAriaSnapshot.java @@ -0,0 +1,139 @@ +/* + * 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. + */ + +// Port of toMatchAriaSnapshot.ts. +package com.microsoft.playwright.impl; + +import com.microsoft.playwright.impl.AssertionsBase.ExpectMatcherState; +import com.microsoft.playwright.impl.MatcherHint.MatcherMessageDetails; +import com.microsoft.playwright.impl.MatcherHint.MatcherResult; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static com.microsoft.playwright.impl.JestMatcherUtils.printDiffOrStringify; +import static com.microsoft.playwright.impl.JestMatcherUtils.printExpected; +import static com.microsoft.playwright.impl.MatcherHint.formatMatcherMessage; +import static com.microsoft.playwright.impl.MatcherHint.printReceivedStringContainExpectedSubstring; + +class ToMatchAriaSnapshot { + // java: the receiver is a LocatorImpl or a PageImpl, expected is the snapshot text, the options are their timeout. + @SuppressWarnings("unchecked") + static MatcherResult toMatchAriaSnapshot( + ExpectMatcherState state, + Object receiver, + String expectedParam, + Double optionsTimeout) { + String matcherName = "matchesAriaSnapshot"; + LocatorImpl locator = receiver instanceof PageImpl ? null : (LocatorImpl) receiver; + + // java: there is no testInfo: no ignoreSnapshots, no updateSnapshots, no snapshot file, no baseline + // generation and no global children option. + String expected; + double timeout; + expected = expectedParam; + timeout = optionsTimeout != null ? optionsTimeout : state.timeout; + + expected = unshift(expected); + + FrameExpectOptions expectParams = new FrameExpectOptions(); + expectParams.expectedValue = expected; + expectParams.isNot = state.isNot; + expectParams.timeout = timeout; + expectParams.title = state.title; + FrameExpectResult queryResult = locator != null ? + locator.expect("to.match.aria", expectParams) : + ((PageImpl) receiver).mainFrame().expect("to.match.aria", expectParams); + boolean pass = queryResult.matches; + FrameExpectResult.ExpectReceived received = queryResult.received; + List log = queryResult.log; + Boolean timedOut = queryResult.timedOut; + String errorMessage = queryResult.errorMessage; + // java: MatcherReceived is the parsed object, a Map with raw and regex. + Map typedReceived = received == null || received.value == JestGetType.UNDEFINED ? null : (Map) received.value; + + String finalExpected = expected; + MatcherResult result = new MatcherResult(); + result.message = () -> { + String printedExpected = null; + String printedReceived = null; + String printedDiff = null; + if (errorMessage != null) { + printedExpected = "Expected: " + (state.isNot ? "not " : "") + printExpected(finalExpected); + } else if (pass) { + String raw = (String) typedReceived.get("raw"); + String receivedString = printReceivedStringContainExpectedSubstring(raw, raw.indexOf(finalExpected), finalExpected.length()); + printedExpected = "Expected: not " + printExpected(finalExpected); + printedReceived = "Received: " + receivedString; + } else { + printedDiff = printDiffOrStringify(finalExpected, typedReceived.get("raw"), "Expected", "Received", false); + } + MatcherMessageDetails details = new MatcherMessageDetails(); + details.isNot = state.isNot; + details.promise = state.promise; + details.matcherName = matcherName; + details.expectation = "expected"; + details.locator = locator == null ? null : locator.toString(); + details.timeout = timeout; + details.timedOut = timedOut; + details.printedExpected = printedExpected; + details.printedReceived = printedReceived; + details.printedDiff = printedDiff; + details.errorMessage = errorMessage; + details.log = log; + return formatMatcherMessage(details); + }; + + if (errorMessage != null) { + result.pass = state.isNot; + result.name = "matchesAriaSnapshot"; + result.expected = expected; + return result; + } + + result.name = matcherName; + result.expected = expected; + result.pass = pass; + result.actual = typedReceived == null ? null : typedReceived.get("raw"); + result.log = log; + result.timeout = timedOut != null && timedOut ? timeout : null; + return result; + } + + private static String unshift(String snapshot) { + String[] lines = snapshot.split("\n", -1); + int whitespacePrefixLength = 100; + for (String line : lines) { + if (line.trim().isEmpty()) + continue; + int length = 0; + while (length < line.length() && Character.isWhitespace(line.charAt(length))) + length++; + if (length < whitespacePrefixLength) + whitespacePrefixLength = length; + } + List result = new ArrayList<>(); + for (String line : lines) { + if (line.trim().isEmpty()) + continue; + result.add(line.substring(Math.min(whitespacePrefixLength, line.length()))); + } + return String.join("\n", result); + } + + // java: no indent, it formats the suggested rebaseline. +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchText.java b/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchText.java new file mode 100644 index 000000000..3f6a8d338 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchText.java @@ -0,0 +1,145 @@ +/* + * 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. + */ + +// Port of toMatchText.ts. +package com.microsoft.playwright.impl; + +import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.impl.AssertionsBase.ExpectMatcherState; +import com.microsoft.playwright.impl.AssertionsBase.Query; +import com.microsoft.playwright.impl.MatcherHint.MatcherMessageDetails; +import com.microsoft.playwright.impl.MatcherHint.MatcherResult; + +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.microsoft.playwright.impl.JestMatcherUtils.EXPECTED_COLOR; +import static com.microsoft.playwright.impl.JestMatcherUtils.printDiffOrStringify; +import static com.microsoft.playwright.impl.JestMatcherUtils.printExpected; +import static com.microsoft.playwright.impl.JestMatcherUtils.printWithType; +import static com.microsoft.playwright.impl.MatcherHint.formatMatcherMessage; +import static com.microsoft.playwright.impl.MatcherHint.printReceivedStringContainExpectedResult; +import static com.microsoft.playwright.impl.MatcherHint.printReceivedStringContainExpectedSubstring; + +class ToMatchText { + // java: the receiver is a LocatorImpl or a PageImpl, expected is a String or a Pattern; the options are their + // timeout and matchSubstring, there is no AbortSignal. + static MatcherResult toMatchText( + ExpectMatcherState state, + String matcherName, + Object receiver, + String receiverType, + Query query, + Object expected, + Double optionsTimeout, + boolean matchSubstring) { + LocatorImpl locator = "Locator".equals(receiverType) ? (LocatorImpl) receiver : null; + + if ( + !(expected instanceof String) && + !(expected instanceof Pattern) + ) { + String errorMessage = "Error: " + EXPECTED_COLOR("expected") + " value must be a string or regular expression\n" + printWithType("Expected", expected, JestMatcherUtils::printExpected); + MatcherMessageDetails details = new MatcherMessageDetails(); + details.promise = state.promise; + details.isNot = state.isNot; + details.locator = locator == null ? null : locator.toString(); + details.matcherName = matcherName; + details.expectation = "expected"; + details.errorMessage = errorMessage; + throw new PlaywrightException(formatMatcherMessage(details)); + } + + double timeout = optionsTimeout != null ? optionsTimeout : state.timeout; + + FrameExpectResult queryResult = query.query(state.isNot, timeout); + boolean pass = queryResult.matches; + FrameExpectResult.ExpectReceived received = queryResult.received; + List log = queryResult.log; + Boolean timedOut = queryResult.timedOut; + String errorMessage = queryResult.errorMessage; + + if (pass == !state.isNot) { + MatcherResult result = new MatcherResult(); + result.name = matcherName; + result.message = () -> ""; + result.pass = pass; + result.expected = expected; + return result; + } + + String expectedSuffix = expected instanceof String ? (matchSubstring ? " substring" : "") : " pattern"; + String receivedSuffix = expected instanceof String ? (matchSubstring ? " string" : "") : " string"; + // java: a received value that is not a string keeps its text. + String receivedValue = received == null || received.value == null || received.value == JestGetType.UNDEFINED ? null : String.valueOf(received.value); + String receivedString = receivedValue == null ? "" : receivedValue; + String printedReceived = null; + String printedExpected = null; + String printedDiff = null; + if (pass) { + if (expected instanceof String) { + printedExpected = "Expected" + expectedSuffix + ": not " + printExpected(expected); + if (errorMessage == null) { + String formattedReceived = printReceivedStringContainExpectedSubstring(receivedString, receivedString.indexOf((String) expected), ((String) expected).length()); + printedReceived = "Received" + receivedSuffix + ": " + formattedReceived; + } + } else { + printedExpected = "Expected" + expectedSuffix + ": not " + printExpected(expected); + if (errorMessage == null) { + Matcher matcher = ((Pattern) expected).matcher(receivedString); + String formattedReceived = printReceivedStringContainExpectedResult(receivedString, matcher.find() ? matcher : null); + printedReceived = "Received" + receivedSuffix + ": " + formattedReceived; + } + } + } else { + if (errorMessage != null) + printedExpected = "Expected" + expectedSuffix + ": " + printExpected(expected); + else + printedDiff = printDiffOrStringify(expected, receivedString, "Expected" + expectedSuffix, "Received" + receivedSuffix, false); + } + + String finalPrintedExpected = printedExpected; + String finalPrintedReceived = printedReceived; + String finalPrintedDiff = printedDiff; + MatcherResult result = new MatcherResult(); + result.message = () -> { + MatcherMessageDetails details = new MatcherMessageDetails(); + details.promise = state.promise; + details.isNot = state.isNot; + details.matcherName = matcherName; + details.expectation = "expected"; + details.locator = locator == null ? null : locator.toString(); + details.timeout = timeout; + details.timedOut = timedOut; + details.printedExpected = finalPrintedExpected; + details.printedReceived = finalPrintedReceived; + details.printedDiff = finalPrintedDiff; + details.log = log; + details.errorMessage = errorMessage; + return formatMatcherMessage(details); + }; + + result.name = matcherName; + result.expected = expected; + result.pass = pass; + result.actual = receivedValue; + result.log = log; + result.timeout = timedOut != null && timedOut ? timeout : null; + result.ariaSnapshot = received == null ? null : received.ariaSnapshot; + return result; + } +} diff --git a/playwright/src/test/AGENTS.md b/playwright/src/test/AGENTS.md index 2744cdbd7..f4bcf55c0 100644 --- a/playwright/src/test/AGENTS.md +++ b/playwright/src/test/AGENTS.md @@ -153,6 +153,11 @@ handler of the request has returned, as in the Node.js server, so a response sto `assertTrue(a instanceof X)`. A matcher on a locator, page or response (`await expect(locator).toHaveText(...)`) is the same matcher of the Java API: `assertThat(locator).hasText(...)` (`PlaywrightAssertions.assertThat`), `.not.` is `.not()`. + The text of a matcher failure is translated the same way: `expect(locator).not.toHaveText(expected) failed` + is `assertThat(locator).not().hasText(expected) failed`, and `Expect "not toHaveText"` in a call + log is `Assert "not hasText"`. A locator in that text is Java code: `locator('div')` is + `locator("div")`. The upstream test config sets the expect timeout to 10000ms, the Java default is + 5000ms: `with timeout 10000ms` of a matcher without a timeout is `with timeout 5000ms`. - `await expect(promise).rejects.toThrow('text')` and `const error = await promise.catch(e => e); expect(error.message).toContain('text')` are `PlaywrightException error = assertThrows(PlaywrightException.class, () -> ...)` then diff --git a/playwright/src/test/java/com/microsoft/playwright/TestAssertThatIsInViewport.java b/playwright/src/test/java/com/microsoft/playwright/TestAssertThatIsInViewport.java index cb631f72f..fe13518d4 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestAssertThatIsInViewport.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestAssertThatIsInViewport.java @@ -58,7 +58,7 @@ void shouldRespectRatioOption(Page page) { void shouldHaveGoodStack(Page page) { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("body")).not().isInViewport(new LocatorAssertions.IsInViewportOptions().setTimeout(100))); assertNotNull(error); - assertTrue(error.getMessage().contains("Locator expected not to be in viewport"), error.getMessage()); + assertTrue(error.getMessage().contains("assertThat(locator).not().isInViewport() failed"), error.getMessage()); } @PlaywrightTest diff --git a/playwright/src/test/java/com/microsoft/playwright/TestExpectMisc.java b/playwright/src/test/java/com/microsoft/playwright/TestExpectMisc.java index d348c046b..41d13c5b3 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestExpectMisc.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestExpectMisc.java @@ -30,7 +30,7 @@ void strictModeViolationErrorFormat(Page page) { page.setContent("
hello
hi
"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("div")).isVisible()); - assertTrue(error.getMessage().contains("Locator expected to be visible"), error.getMessage()); + assertTrue(error.getMessage().contains("assertThat(locator).isVisible() failed"), error.getMessage()); assertTrue(error.getMessage().contains("Error: strict mode violation: locator(\"div\") resolved to 2 elements:"), error.getMessage()); } @@ -39,7 +39,7 @@ void invalidSelectorErrorFormat(Page page) { page.setContent("
hello
hi
"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("##")).isVisible()); - assertTrue(error.getMessage().contains("Locator expected to be visible"), error.getMessage()); + assertTrue(error.getMessage().contains("assertThat(locator).isVisible() failed"), error.getMessage()); assertTrue(error.getMessage().contains("Error: Unexpected token \"#\" while parsing css selector \"##\"."), error.getMessage()); } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java index 204701aea..94704bb7e 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java @@ -69,7 +69,7 @@ void containsTextWRegexFail(Page page) { }); assertEquals("ex2", e.getExpected().getStringRepresentation()); assertEquals("Text content", e.getActual().getValue()); - assertTrue(e.getMessage().contains("Locator expected to contain regex"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).containsText(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -116,7 +116,7 @@ void hasTextWRegexFail(Page page) { }); assertEquals("Text 2", e.getExpected().getStringRepresentation()); assertEquals("Text content", e.getActual().getValue()); - assertTrue(e.getMessage().contains("Locator expected to have text matching regex"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasText(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -141,7 +141,7 @@ void hasTextWTextFail(Page page) { }); assertEquals("Text", e.getExpected().getStringRepresentation()); assertEquals("Text content", e.getActual().getValue()); - assertTrue(e.getMessage().contains("Locator expected to have text"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasText(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -195,7 +195,7 @@ void hasTextWTextArrayFailOnNotEmpty(Page page) { }); assertEquals("[]", e.getExpected().getStringRepresentation()); assertEquals("[]", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected not to have text"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).not().hasText(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -222,8 +222,8 @@ void hasTextWTextArrayFail(Page page) { }); assertEquals("[Text 1, Text 3, Extra]", e.getExpected().getStringRepresentation()); assertEquals("[Text 1, Text 3]", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have text\nExpected: [Text 1, Text 3, Extra]"), e.getMessage()); - assertTrue(e.getMessage().contains("Received: [Text 1, Text 3]"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasText(expected) failed"), e.getMessage()); + assertTrue(e.getMessage().contains("- \"Extra\","), e.getMessage()); } @PlaywrightTest @@ -244,7 +244,7 @@ void hasTextWRegExArrayFail(Page page) { }); assertEquals("[Text 1, Text \\d, Extra]", e.getExpected().getStringRepresentation()); assertEquals("[Text 1, Text 3]", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have text"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasText(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -271,7 +271,7 @@ void hasAttributeTextFail(Page page) { }); assertEquals("foo", e.getExpected().getStringRepresentation()); assertEquals("node", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have attribute 'id'\nExpected: foo\nReceived: node"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasAttribute(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -290,7 +290,7 @@ void hasAttributeRegExpFail(Page page) { }); assertEquals(".Nod..", e.getExpected().getStringRepresentation()); assertEquals("node", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have attribute 'id' matching regex\nExpected: .Nod..\nReceived: node"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasAttribute(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -309,7 +309,7 @@ void hasClassTextFail(Page page) { }); assertEquals("foo bar baz", e.getExpected().getStringRepresentation()); assertEquals("bar baz", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have class"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasClass(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -328,7 +328,7 @@ void hasClassRegExpFail(Page page) { }); assertEquals("foo Z.*", e.getExpected().getStringRepresentation()); assertEquals("bar baz", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have class matching regex"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasClass(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -347,7 +347,7 @@ void hasClassTextArrayFail(Page page) { }); assertEquals("[foo, bar, missing]", e.getExpected().getStringRepresentation()); assertEquals("[foo, bar, baz]", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have class"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasClass(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -366,7 +366,7 @@ void hasClassRegExpArrayFail(Page page) { }); assertEquals("[fo.*, .ar, baz, extra]", e.getExpected().getStringRepresentation()); assertEquals("[foo, bar, baz]", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have class matching regex"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasClass(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -385,7 +385,7 @@ void hasCountFail(Page page) { }); assertEquals("1", e.getExpected().getStringRepresentation()); assertEquals("2", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have count"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasCount(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -412,7 +412,7 @@ void hasCSSFail(Page page) { }); assertEquals("red", e.getExpected().getStringRepresentation()); assertEquals("rgb(255, 0, 0)", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have CSS property 'color'"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasCSS(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -431,7 +431,7 @@ void hasCSSRegExFail(Page page) { }); assertEquals("red", e.getExpected().getStringRepresentation()); assertEquals("rgb(255, 0, 0)", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have CSS property 'color' matching regex"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasCSS(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -450,7 +450,7 @@ void hasIdFail(Page page) { }); assertEquals("foo", e.getExpected().getStringRepresentation()); assertEquals("node", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have ID"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasId(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -480,7 +480,7 @@ void hasJSPropertyNumberFail(Page page) { }); assertEquals("1", e.getExpected().getStringRepresentation()); assertEquals("2021", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have JavaScript property 'foo'"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasJSProperty(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -493,7 +493,7 @@ void hasJSPropertyObjectFail(Page page) { }); assertEquals("{a=2}", e.getExpected().getStringRepresentation()); assertEquals("{a=1, b=string}", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have JavaScript property 'foo'"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasJSProperty(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -505,7 +505,7 @@ void hasJSPropertyStringFail(Page page) { }); assertEquals("foo", e.getExpected().getStringRepresentation()); assertEquals("node", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have JavaScript property 'id'"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasJSProperty(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -526,7 +526,7 @@ void hasValueTextFail(Page page) { }); assertEquals("Text2", e.getExpected().getStringRepresentation()); assertEquals("Text content", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have value"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasValue(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -555,7 +555,7 @@ void hasValueRegExpFail(Page page) { }); assertEquals("Text2", e.getExpected().getStringRepresentation()); assertEquals("Text content", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have value matching regex"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasValue(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -596,7 +596,7 @@ void hasValuesExactMatchWithText(Page page) { }); assertEquals("[R, G]", e.getExpected().getStringRepresentation()); assertEquals("[RR, GG]", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have values"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasValues(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -625,7 +625,7 @@ void hasValuesFailsWhenItemsNotSelected(Page page) { }); assertEquals("[R, G]", e.getExpected().getStringRepresentation()); assertEquals("[B]", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to have values matching regex"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).hasValues(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -669,7 +669,7 @@ void isCheckedFail(Page page) { }); assertEquals("checked", e.getExpected().getStringRepresentation()); assertEquals("unchecked", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected to be\nExpected: checked"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).isChecked() failed"), e.getMessage()); } @PlaywrightTest @@ -682,7 +682,7 @@ void notIsCheckedFail(Page page) { assertEquals("checked", e.getExpected().getStringRepresentation()); assertEquals("checked", e.getActual().getStringRepresentation()); - assertTrue(e.getMessage().contains("Locator expected not to be\nExpected: checked"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(locator).not().isChecked() failed"), e.getMessage()); } @PlaywrightTest @@ -698,7 +698,7 @@ void isCheckedFalseFail(Page page) { Locator locator = page.locator("input"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).isChecked(new LocatorAssertions.IsCheckedOptions().setChecked(false).setTimeout(1000))); - assertTrue(error.getMessage().contains("Locator expected to be\nExpected: unchecked"), error.getMessage()); + assertTrue(error.getMessage().contains("assertThat(locator).isChecked({ checked: false }) failed"), error.getMessage()); } @PlaywrightTest @@ -715,9 +715,8 @@ void isDisabledFail(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(locator).isDisabled(new LocatorAssertions.IsDisabledOptions().setTimeout(1000)); }); - assertNull(e.getExpected()); - assertNull(e.getActual()); - assertTrue(e.getMessage().contains("Locator expected to be disabled"), e.getMessage()); + assertEquals("disabled", e.getExpected().getValue()); + assertTrue(e.getMessage().contains("assertThat(locator).isDisabled() failed"), e.getMessage()); } @PlaywrightTest @@ -727,9 +726,8 @@ void notIsDisabledFail(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(locator).not().isDisabled(new LocatorAssertions.IsDisabledOptions().setTimeout(1000)); }); - assertNull(e.getExpected()); - assertNull(e.getActual()); - assertTrue(e.getMessage().contains("Locator expected not to be disabled"), e.getMessage()); + assertEquals("disabled", e.getExpected().getValue()); + assertTrue(e.getMessage().contains("assertThat(locator).not().isDisabled() failed"), e.getMessage()); } @PlaywrightTest @@ -746,9 +744,8 @@ void isEditableFail(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(locator).isEditable(new LocatorAssertions.IsEditableOptions().setTimeout(1000)); }); - assertNull(e.getExpected()); - assertNull(e.getActual()); - assertTrue(e.getMessage().contains("Locator expected to be editable"), e.getMessage()); + assertEquals("editable", e.getExpected().getValue()); + assertTrue(e.getMessage().contains("assertThat(locator).isEditable() failed"), e.getMessage()); } @PlaywrightTest @@ -757,7 +754,7 @@ void isEditableFalseFail(Page page) { Locator locator = page.locator("input"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).isEditable(new LocatorAssertions.IsEditableOptions().setEditable(false).setTimeout(1000))); - assertTrue(error.getMessage().contains("Locator expected to be readonly"), error.getMessage()); + assertTrue(error.getMessage().contains("assertThat(locator).isEditable({ editable: false }) failed"), error.getMessage()); } @PlaywrightTest @@ -767,9 +764,8 @@ void notIsEditableFail(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(locator).not().isEditable(new LocatorAssertions.IsEditableOptions().setTimeout(1000)); }); - assertNull(e.getExpected()); - assertNull(e.getActual()); - assertTrue(e.getMessage().contains("Locator expected not to be editable"), e.getMessage()); + assertEquals("editable", e.getExpected().getValue()); + assertTrue(e.getMessage().contains("assertThat(locator).not().isEditable() failed"), e.getMessage()); } @PlaywrightTest @@ -822,9 +818,8 @@ void isEmptyFail(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(locator).isEmpty(new LocatorAssertions.IsEmptyOptions().setTimeout(1000)); }); - assertNull(e.getExpected()); - assertNull(e.getActual()); - assertTrue(e.getMessage().contains("Locator expected to be empty"), e.getMessage()); + assertEquals("empty", e.getExpected().getValue()); + assertTrue(e.getMessage().contains("assertThat(locator).isEmpty() failed"), e.getMessage()); } @PlaywrightTest @@ -834,9 +829,8 @@ void notIsEmptyFail(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(locator).not().isEmpty(new LocatorAssertions.IsEmptyOptions().setTimeout(1000)); }); - assertNull(e.getExpected()); - assertNull(e.getActual()); - assertTrue(e.getMessage().contains("Locator expected not to be empty"), e.getMessage()); + assertEquals("empty", e.getExpected().getValue()); + assertTrue(e.getMessage().contains("assertThat(locator).not().isEmpty() failed"), e.getMessage()); } @PlaywrightTest @@ -853,9 +847,8 @@ void isEnabledFail(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(locator).isEnabled(new LocatorAssertions.IsEnabledOptions().setTimeout(1000)); }); - assertNull(e.getExpected()); - assertNull(e.getActual()); - assertTrue(e.getMessage().contains("Locator expected to be enabled"), e.getMessage()); + assertEquals("enabled", e.getExpected().getValue()); + assertTrue(e.getMessage().contains("assertThat(locator).isEnabled() failed"), e.getMessage()); } @PlaywrightTest @@ -865,9 +858,8 @@ void notIsEnabledFail(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(locator).not().isEnabled(new LocatorAssertions.IsEnabledOptions().setTimeout(1000)); }); - assertNull(e.getExpected()); - assertNull(e.getActual()); - assertTrue(e.getMessage().contains("Locator expected not to be enabled"), e.getMessage()); + assertEquals("enabled", e.getExpected().getValue()); + assertTrue(e.getMessage().contains("assertThat(locator).not().isEnabled() failed"), e.getMessage()); } @PlaywrightTest @@ -890,7 +882,7 @@ void isEnabledFalseFail(Page page) { Locator locator = page.locator("button"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).isEnabled(new LocatorAssertions.IsEnabledOptions().setEnabled(false).setTimeout(1000))); - assertTrue(error.getMessage().contains("Locator expected to be disabled"), error.getMessage()); + assertTrue(error.getMessage().contains("assertThat(locator).isEnabled({ enabled: false }) failed"), error.getMessage()); } @PlaywrightTest @@ -935,9 +927,8 @@ void isFocusedFail(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(locator).isFocused(new LocatorAssertions.IsFocusedOptions().setTimeout(1000)); }); - assertNull(e.getExpected()); - assertNull(e.getActual()); - assertTrue(e.getMessage().contains("Locator expected to be focused"), e.getMessage()); + assertEquals("focused", e.getExpected().getValue()); + assertTrue(e.getMessage().contains("assertThat(locator).isFocused() failed"), e.getMessage()); } @PlaywrightTest @@ -948,9 +939,8 @@ void notIsFocusedFail(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(locator).not().isFocused(new LocatorAssertions.IsFocusedOptions().setTimeout(1000)); }); - assertNull(e.getExpected()); - assertNull(e.getActual()); - assertTrue(e.getMessage().contains("Locator expected not to be focused"), e.getMessage()); + assertEquals("focused", e.getExpected().getValue()); + assertTrue(e.getMessage().contains("assertThat(locator).not().isFocused() failed"), e.getMessage()); } @PlaywrightTest @@ -967,9 +957,8 @@ void isHiddenFail(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(locator).isHidden(new LocatorAssertions.IsHiddenOptions().setTimeout(1000)); }); - assertNull(e.getExpected()); - assertNull(e.getActual()); - assertTrue(e.getMessage().contains("Locator expected to be hidden"), e.getMessage()); + assertEquals("hidden", e.getExpected().getValue()); + assertTrue(e.getMessage().contains("assertThat(locator).isHidden() failed"), e.getMessage()); } @PlaywrightTest @@ -979,9 +968,8 @@ void notIsHiddenFail(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(locator).not().isHidden(new LocatorAssertions.IsHiddenOptions().setTimeout(1000)); }); - assertNull(e.getExpected()); - assertNull(e.getActual()); - assertTrue(e.getMessage().contains("Locator expected not to be hidden"), e.getMessage()); + assertEquals("hidden", e.getExpected().getValue()); + assertTrue(e.getMessage().contains("assertThat(locator).not().isHidden() failed"), e.getMessage()); } @PlaywrightTest @@ -998,9 +986,8 @@ void isVisibleFail(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(locator).isVisible(new LocatorAssertions.IsVisibleOptions().setTimeout(1000)); }); - assertNull(e.getExpected()); - assertNull(e.getActual()); - assertTrue(e.getMessage().contains("Locator expected to be visible"), e.getMessage()); + assertEquals("visible", e.getExpected().getValue()); + assertTrue(e.getMessage().contains("assertThat(locator).isVisible() failed"), e.getMessage()); } @PlaywrightTest @@ -1009,7 +996,7 @@ void isVisibleFalseFail(Page page) { Locator locator = page.locator("input"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).isVisible(new LocatorAssertions.IsVisibleOptions().setVisible(false).setTimeout(1000))); - assertTrue(error.getMessage().contains("Locator expected to be hidden"), error.getMessage()); + assertTrue(error.getMessage().contains("assertThat(locator).isVisible({ visible: false }) failed"), error.getMessage()); } @PlaywrightTest @@ -1019,9 +1006,8 @@ void notIsVisibleFail(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> { assertThat(locator).not().isVisible(new LocatorAssertions.IsVisibleOptions().setTimeout(1000)); }); - assertNull(e.getExpected()); - assertNull(e.getActual()); - assertTrue(e.getMessage().contains("Locator expected not to be visible"), e.getMessage()); + assertEquals("visible", e.getExpected().getValue()); + assertTrue(e.getMessage().contains("assertThat(locator).not().isVisible() failed"), e.getMessage()); } @PlaywrightTest diff --git a/playwright/src/test/java/com/microsoft/playwright/TestPageAriaSnapshot.java b/playwright/src/test/java/com/microsoft/playwright/TestPageAriaSnapshot.java index a41cce6a0..a5e0d06dc 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestPageAriaSnapshot.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestPageAriaSnapshot.java @@ -344,7 +344,7 @@ void pageMatchesAriaSnapshot(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("- heading \"world\"", new com.microsoft.playwright.assertions.PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); - org.junit.jupiter.api.Assertions.assertTrue(e.getMessage().contains("Page expected to match Aria snapshot"), e.getMessage()); + org.junit.jupiter.api.Assertions.assertTrue(e.getMessage().contains("assertThat(page).matchesAriaSnapshot(expected) failed"), e.getMessage()); } } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestPageAssertions.java b/playwright/src/test/java/com/microsoft/playwright/TestPageAssertions.java index 786e44196..0658929cf 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestPageAssertions.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestPageAssertions.java @@ -40,7 +40,7 @@ void hasURLTextFail(Page page) { }); assertEquals("foo", e.getExpected().getValue()); assertEquals("data:text/html,
B
", e.getActual().getValue()); - assertTrue(e.getMessage().contains("Page URL expected to be"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(page).hasURL(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -78,7 +78,7 @@ void hasURLRegexFail(Page page, Server server) { }); assertEquals(".*foo.*", e.getExpected().getStringRepresentation()); assertEquals(server.EMPTY_PAGE, e.getActual().getValue()); - assertTrue(e.getMessage().contains("Page URL expected to match regex"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(page).hasURL(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -107,7 +107,7 @@ void hasTitleTextFail(Page page, Server server) { }); assertEquals("foo", e.getExpected().getValue()); assertEquals("Woof-Woof", e.getActual().getValue()); - assertTrue(e.getMessage().contains("Page title expected to be\nExpected: foo\nReceived: Woof-Woof"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(page).hasTitle(expected) failed"), e.getMessage()); } @PlaywrightTest @@ -124,7 +124,7 @@ void hasTitleRegexFail(Page page, Server server) { }); assertEquals("^foo[AB]", e.getExpected().getStringRepresentation()); assertEquals("Woof-Woof", e.getActual().getValue()); - assertTrue(e.getMessage().contains("Page title expected to match regex\nExpected: ^foo[AB]\nReceived: Woof-Woof"), e.getMessage()); + assertTrue(e.getMessage().contains("assertThat(page).hasTitle(expected) failed"), e.getMessage()); } @PlaywrightTest diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectBoolean.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectBoolean.java index 5614609f4..f55859850 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectBoolean.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectBoolean.java @@ -87,19 +87,18 @@ void withIndeterminateTrueAndChecked(Page page) { @PlaywrightTest @DisplayName("EX-006 fail") - @Fixme("java: the message is the Java assertion format, 'Locator expected to be\\nExpected: checked\\nReceived: unchecked\\n\\nCall log:\\n - Assert \"isChecked\" locator(\"input\") with timeout 1000ms ...', not the 'expect(locator).toBeChecked() failed' message of the Node.js client") void fail(Page page) { page.setContent(""); Locator locator = page.locator("input"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).isChecked(new LocatorAssertions.IsCheckedOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toBeChecked() failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).isChecked() failed\n" + "\n" + - "Locator: locator('input')\n" + + "Locator: locator(\"input\")\n" + "Expected: checked\n" + "Received: unchecked\n" + "Timeout: 1000ms")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"toBeChecked\" locator('input') with timeout 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"isChecked\" locator(\"input\") with timeout 1000ms")); } @PlaywrightTest @@ -120,75 +119,71 @@ void withNotAndCheckedFalse(Page page) { @PlaywrightTest @DisplayName("EX-009 fail with not") - @Fixme("java: the message is the Java assertion format, 'Locator expected to be\\nExpected: checked\\nReceived: unchecked\\n\\nCall log:\\n - Assert \"isChecked\" locator(\"input\") with timeout 1000ms ...', not the 'expect(locator).not.toBeChecked() failed' message of the Node.js client") void failWithNot(Page page) { page.setContent(""); Locator locator = page.locator("input"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).not().isChecked(new LocatorAssertions.IsCheckedOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).not.toBeChecked() failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).not().isChecked() failed\n" + "\n" + - "Locator: locator('input')\n" + + "Locator: locator(\"input\")\n" + "Expected: not checked\n" + "Received: checked\n" + "Timeout: 1000ms")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"not toBeChecked\" locator('input') with timeout 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"not isChecked\" locator(\"input\") with timeout 1000ms")); assertTrue(stripAnsi(error.getMessage()).contains("locator resolved to ")); } @PlaywrightTest @DisplayName("EX-010 fail with checked:false") - @Fixme("java: the message is the Java assertion format, 'Locator expected to be\\nExpected: checked\\nReceived: unchecked\\n\\nCall log:\\n - Assert \"isChecked\" locator(\"input\") with timeout 1000ms ...', not the 'expect(locator).toBeChecked({ checked: false }) failed' message of the Node.js client") void failWithCheckedFalse(Page page) { page.setContent(""); Locator locator = page.locator("input"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).isChecked(new LocatorAssertions.IsCheckedOptions().setChecked(false).setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toBeChecked({ checked: false }) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).isChecked({ checked: false }) failed\n" + "\n" + - "Locator: locator('input')\n" + + "Locator: locator(\"input\")\n" + "Expected: unchecked\n" + "Received: checked\n" + "Timeout: 1000ms")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"toBeChecked\" locator('input') with timeout 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"isChecked\" locator(\"input\") with timeout 1000ms")); assertTrue(stripAnsi(error.getMessage()).contains("locator resolved to ")); } @PlaywrightTest @DisplayName("EX-011 fail with indeterminate: true") - @Fixme("java: the message is the Java assertion format, 'Locator expected to be\\nExpected: checked\\nReceived: unchecked\\n\\nCall log:\\n - Assert \"isChecked\" locator(\"input\") with timeout 1000ms ...', not the 'expect(locator).toBeChecked({ indeterminate: true }) failed' message of the Node.js client") void failWithIndeterminateTrue(Page page) { page.setContent(""); Locator locator = page.locator("input"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).isChecked(new LocatorAssertions.IsCheckedOptions().setIndeterminate(true).setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toBeChecked({ indeterminate: true }) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).isChecked({ indeterminate: true }) failed\n" + "\n" + - "Locator: locator('input')\n" + + "Locator: locator(\"input\")\n" + "Expected: indeterminate\n" + "Received: unchecked\n" + "Timeout: 1000ms")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"toBeChecked\" locator('input') with timeout 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"isChecked\" locator(\"input\") with timeout 1000ms")); } @PlaywrightTest @DisplayName("EX-012 fail missing") - @Fixme("java: the message is the Java assertion format, 'Locator expected to be\\nExpected: checked\\nReceived: unchecked\\n\\nCall log:\\n - Assert \"isChecked\" locator(\"input\") with timeout 1000ms ...', not the 'expect(locator).not.toBeChecked() failed' message of the Node.js client") void failMissing(Page page) { page.setContent("
no inputs here
"); Locator locator2 = page.locator("input2"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator2).not().isChecked(new LocatorAssertions.IsCheckedOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).not.toBeChecked() failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).not().isChecked() failed\n" + "\n" + - "Locator: locator('input2')\n" + + "Locator: locator(\"input2\")\n" + "Expected: not checked\n" + "Timeout: 1000ms\n" + "Error: element(s) not found\n" + "\n" + "Call log:\n" + - " - Expect \"not toBeChecked\" locator('input2') with timeout 1000ms\n" + - " - waiting for locator('input2')\n")); + " - Assert \"not isChecked\" locator(\"input2\") with timeout 1000ms\n" + + " - waiting for locator(\"input2\")\n")); } @PlaywrightTest @@ -605,21 +600,20 @@ void failWithNot(Page page) { @PlaywrightTest @DisplayName("EX-059 fail with not when nothing matching") - @Fixme("java: the message is 'Locator expected not to be hidden\\nError: element(s) not found\\nCall log:\\n - Assert \"isHidden\" locator(\"button\") with timeout 1000ms ...', not the 'expect(locator).not.toBeHidden() failed' message of the Node.js client") void failWithNotWhenNothingMatching(Page page) { page.setContent("
"); Locator locator = page.locator("button"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).not().isHidden(new LocatorAssertions.IsHiddenOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).not.toBeHidden() failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).not().isHidden() failed\n" + "\n" + - "Locator: locator('button')\n" + + "Locator: locator(\"button\")\n" + "Expected: not hidden\n" + "Timeout: 1000ms\n" + "Error: element(s) not found\n" + "\n" + "Call log:\n" + - " - Expect \"not toBeHidden\" locator('button') with timeout 1000ms\n")); + " - Assert \"not isHidden\" locator(\"button\") with timeout 1000ms\n")); } @PlaywrightTest @@ -717,11 +711,10 @@ void beforeEach(TestServer server) { @PlaywrightTest @DisplayName("EX-070 text content type") - @Fixme("java: the message is 'Response status expected to be within [200..299] range, was 404\\nCall log:\\n→ GET ...', without the 'expect(response).toBeOK() failed' line of the Node.js client") void textContentType(Page page, TestServer server) { APIResponse res = page.request().get(server.PREFIX + "/text-content-type"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(res).isOK()); - assertTrue(stripAnsi(error.getMessage()).contains("expect(response).toBeOK() failed")); + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(response).isOK() failed")); assertTrue(error.getMessage().contains("→ GET " + server.PREFIX + "/text-content-type")); assertTrue(error.getMessage().contains("← 404 Not Found")); assertTrue(stripAnsi(error.getMessage()).contains("Response text:\nText error")); diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java index bfafaabd2..e6c85a4e0 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java @@ -99,36 +99,34 @@ void eventuallyPassNotNonZero(Page page) { @PlaywrightTest @DisplayName("EX-186 fail zero") - @Fixme("java: the assertion error has another format: 'Locator expected to have count\nExpected: 0\nReceived: 1\n\nCall log:\n- Assert \"hasCount\" locator(\"span\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void failZero(Page page) { page.setContent("
"); Locator locator = page.locator("span"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).hasCount(0, new LocatorAssertions.HasCountOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toHaveCount(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).hasCount(expected) failed\n" + "\n" + - "Locator: locator('span')\n" + + "Locator: locator(\"span\")\n" + "Expected: 0\n" + "Received: 1\n" + "Timeout: 1000ms")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"toHaveCount\" locator('span') with timeout 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"hasCount\" locator(\"span\") with timeout 1000ms")); } @PlaywrightTest @DisplayName("EX-187 fail zero 2") - @Fixme("java: the assertion error has another format: 'Locator expected not to have count\nExpected: 1\nReceived: 1\n\nCall log:\n- Assert \"hasCount\" locator(\"span\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void failZero2(Page page) { page.setContent("
"); Locator locator = page.locator("span"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).not().hasCount(1, new LocatorAssertions.HasCountOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).not.toHaveCount(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).not().hasCount(expected) failed\n" + "\n" + - "Locator: locator('span')\n" + + "Locator: locator(\"span\")\n" + "Expected: not 1\n" + "Received: 1\n" + "Timeout: 1000ms")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"not toHaveCount\" locator('span') with timeout 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"not hasCount\" locator(\"span\") with timeout 1000ms")); } } @@ -145,7 +143,6 @@ void pass(Page page) { @PlaywrightTest @DisplayName("EX-189 fail") - @Fixme("java: the assertion error has another format: 'Locator expected to have JavaScript property 'foo'\nExpected: {a=1, b=string, c=Wed Jul 28 13:26:32 PDT 2021}\nReceived: {a=1, b=string, c=Wed Jul 28 13:26:32 PDT 2021}\n\nCall log:\n- Assert \"hasJSProperty\" locator(\"div\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void fail(Page page) { page.setContent("
"); page.evalOnSelector("div", "e => e.foo = { a: 1, b: 'string', c: new Date(1627503992000) }"); @@ -166,20 +163,19 @@ void passString(Page page) { @PlaywrightTest @DisplayName("EX-191 fail string") - @Fixme("java: the assertion error has another format: 'Locator expected to have JavaScript property 'foo'\nExpected: error\nReceived: string\n\nCall log:\n- Assert \"hasJSProperty\" locator(\"div\") with timeout 200ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void failString(Page page) { page.setContent("
"); page.evalOnSelector("div", "e => e.foo = 'string'"); Locator locator = page.locator("div"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).hasJSProperty("foo", "error", new LocatorAssertions.HasJSPropertyOptions().setTimeout(200))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toHaveJSProperty(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).hasJSProperty(expected) failed\n" + "\n" + - "Locator: locator('div')\n" + + "Locator: locator(\"div\")\n" + "Expected: \"error\"\n" + "Received: \"string\"\n" + "Timeout: 200ms")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"toHaveJSProperty\" locator('div') with timeout 200ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"hasJSProperty\" locator(\"div\") with timeout 200ms")); } @PlaywrightTest @@ -193,20 +189,19 @@ void passNumber(Page page) { @PlaywrightTest @DisplayName("EX-193 fail number") - @Fixme("java: the assertion error has another format: 'Locator expected to have JavaScript property 'foo'\nExpected: 1\nReceived: 2021\n\nCall log:\n- Assert \"hasJSProperty\" locator(\"div\") with timeout 200ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void failNumber(Page page) { page.setContent("
"); page.evalOnSelector("div", "e => e.foo = 2021"); Locator locator = page.locator("div"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).hasJSProperty("foo", 1, new LocatorAssertions.HasJSPropertyOptions().setTimeout(200))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toHaveJSProperty(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).hasJSProperty(expected) failed\n" + "\n" + - "Locator: locator('div')\n" + + "Locator: locator(\"div\")\n" + "Expected: 1\n" + "Received: 2021\n" + "Timeout: 200ms")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"toHaveJSProperty\" locator('div') with timeout 200ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"hasJSProperty\" locator(\"div\") with timeout 200ms")); } @PlaywrightTest @@ -220,20 +215,19 @@ void passBoolean(Page page) { @PlaywrightTest @DisplayName("EX-195 fail boolean") - @Fixme("java: the assertion error has another format: 'Locator expected to have JavaScript property 'foo'\nExpected: true\nReceived: false\n\nCall log:\n- Assert \"hasJSProperty\" locator(\"div\") with timeout 200ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void failBoolean(Page page) { page.setContent("
"); page.evalOnSelector("div", "e => e.foo = false"); Locator locator = page.locator("div"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).hasJSProperty("foo", true, new LocatorAssertions.HasJSPropertyOptions().setTimeout(200))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toHaveJSProperty(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).hasJSProperty(expected) failed\n" + "\n" + - "Locator: locator('div')\n" + + "Locator: locator(\"div\")\n" + "Expected: true\n" + "Received: false\n" + "Timeout: 200ms")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"toHaveJSProperty\" locator('div') with timeout 200ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"hasJSProperty\" locator(\"div\") with timeout 200ms")); } @PlaywrightTest @@ -247,20 +241,19 @@ void passBoolean2(Page page) { @PlaywrightTest @DisplayName("EX-197 fail boolean 2") - @Fixme("java: the assertion error has another format: 'Locator expected to have JavaScript property 'foo'\nExpected: true\nReceived: false\n\nCall log:\n- Assert \"hasJSProperty\" locator(\"div\") with timeout 200ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void failBoolean2(Page page) { page.setContent("
"); page.evalOnSelector("div", "e => e.foo = false"); Locator locator = page.locator("div"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).hasJSProperty("foo", true, new LocatorAssertions.HasJSPropertyOptions().setTimeout(200))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toHaveJSProperty(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).hasJSProperty(expected) failed\n" + "\n" + - "Locator: locator('div')\n" + + "Locator: locator(\"div\")\n" + "Expected: true\n" + "Received: false\n" + "Timeout: 200ms")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"toHaveJSProperty\" locator('div') with timeout 200ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"hasJSProperty\" locator(\"div\") with timeout 200ms")); } @PlaywrightTest @@ -296,7 +289,6 @@ void passNested(Page page) { @PlaywrightTest @DisplayName("EX-201 fail nested") - @Fixme("java: the assertion error has another format: 'Locator expected to have JavaScript property 'foo.bar'\nExpected: {a=1, b=string, c=Wed Jul 28 13:26:32 PDT 2021}\nReceived: null\n\nCall log:\n- Assert \"hasJSProperty\" locator(\"div\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void failNested(Page page) { page.setContent("
"); page.evalOnSelector("div", "e => e.foo = { nested: { a: 1, b: 'string', c: new Date(1627503992000) } }"); @@ -331,21 +323,20 @@ void passWithSVGs(Page page) { @PlaywrightTest @DisplayName("EX-204 fail") - @Fixme("java: the assertion error has another format: 'Locator expected to have class\nExpected: foo bar baz\nReceived: bar baz\n\nCall log:\n- Assert \"hasClass\" locator(\"div\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void fail(Page page) { page.setContent("
"); Locator locator = page.locator("div"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).hasClass("foo bar baz", new LocatorAssertions.HasClassOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toHaveClass(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).hasClass(expected) failed\n" + "\n" + - "Locator: locator('div')\n" + + "Locator: locator(\"div\")\n" + "Expected: \"foo bar baz\"\n" + "Received: \"bar baz\"\n" + "Timeout: 1000ms\n" + "\n" + "Call log:\n")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"toHaveClass\" locator('div') with timeout 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"hasClass\" locator(\"div\") with timeout 1000ms")); } // EX-205 pass with array: not ported, see upstream_not_ported.txt. @@ -366,36 +357,34 @@ void passWithSVGs(Page page) { @PlaywrightTest @DisplayName("EX-209 fail") - @Fixme("java: the assertion error has another format: 'Locator expected to contain class\nExpected: does-not-exist\nReceived: bar baz\n\nCall log:\n- Assert \"containsClass\" locator(\"div\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void fail(Page page) { page.setContent("
"); Locator locator = page.locator("div"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).containsClass("does-not-exist", new LocatorAssertions.ContainsClassOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toContainClass(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).containsClass(expected) failed\n" + "\n" + - "Locator: locator('div')\n" + + "Locator: locator(\"div\")\n" + "Expected: \"does-not-exist\"\n" + "Received: \"bar baz\"\n" + "Timeout: 1000ms\n" + "\n" + "Call log:\n")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"toContainClass\" locator('div') with timeout 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"containsClass\" locator(\"div\") with timeout 1000ms")); } // EX-210 pass with array: not ported, see upstream_not_ported.txt. @PlaywrightTest @DisplayName("EX-211 fail with array") - @Fixme("java: the assertion error has another format: 'Locator expected to contain classes\nExpected: [foo, bar, baz]\nReceived: [foo, bar, bar]\n\nCall log:\n- Assert \"containsClass\" locator(\"div\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void failWithArray(Page page) { page.setContent("
"); Locator locator = page.locator("div"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).containsClass(Arrays.asList("foo", "bar", "baz"), new LocatorAssertions.ContainsClassOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toContainClass(expected) failed")); + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).containsClass(expected) failed")); assertTrue(stripAnsi(error.getMessage()).contains("Timeout: 1000ms")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"toContainClass\" locator('div') with timeout 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"containsClass\" locator(\"div\") with timeout 1000ms")); } } @@ -410,19 +399,18 @@ void pass(Page page) { @PlaywrightTest @DisplayName("EX-213 fail") - @Fixme("java: the assertion error has another format: 'Page title expected to be\nExpected: Hello\nReceived: Bye\n\nCall log:\n- Assert \"hasTitle\" with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void fail(Page page) { page.setContent("Bye"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page).hasTitle("Hello", new PageAssertions.HasTitleOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(page).toHaveTitle(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(page).hasTitle(expected) failed\n" + "\n" + "Expected: \"Hello\"\n" + "Received: \"Bye\"\n" + "Timeout: 1000ms\n" + "\n" + "Call log:\n")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"toHaveTitle\" with timeout 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"hasTitle\" with timeout 1000ms")); } } @@ -437,12 +425,11 @@ void pass(Page page) { @PlaywrightTest @DisplayName("EX-215 fail string") - @Fixme("java: the assertion error has another format: 'Page URL expected to be\nExpected: wrong\nReceived: data:text/html,
A
\n\nCall log:\n- Assert \"hasURL\" with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void failString(Page page) { page.navigate("data:text/html,
A
"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page).hasURL("wrong", new PageAssertions.HasURLOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(page).toHaveURL(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(page).hasURL(expected) failed\n" + "\n" + "Expected: \"wrong\"\n" + "Received: \"data:text/html,
A
\"\n" + @@ -483,35 +470,34 @@ void pass(Page page) { @PlaywrightTest @DisplayName("EX-224 should not match missing attribute") - @Fixme("java: the assertion error has another format: 'Locator expected to have attribute 'disabled'\nExpected:\nReceived: null\n\nCall log:\n- Assert \"hasAttribute\" locator(\"#node\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void shouldNotMatchMissingAttribute(Page page) { page.setContent("
Text content
"); Locator locator = page.locator("#node"); { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).hasAttribute("disabled", "", new LocatorAssertions.HasAttributeOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toHaveAttribute(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).hasAttribute(expected) failed\n" + "\n" + - "Locator: locator('#node')\n" + + "Locator: locator(\"#node\")\n" + "Expected: \"\"\n" + "Received: serializes to the same string\n" + "Timeout: 1000ms\n" + "\n" + "Call log:\n")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"toHaveAttribute\" locator('#node') with timeout 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"hasAttribute\" locator(\"#node\") with timeout 1000ms")); } { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).hasAttribute("disabled", Pattern.compile(".*"), new LocatorAssertions.HasAttributeOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toHaveAttribute(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).hasAttribute(expected) failed\n" + "\n" + - "Locator: locator('#node')\n" + + "Locator: locator(\"#node\")\n" + "Expected pattern: /.*/\n" + "Received string: \"\"\n" + "Timeout: 1000ms\n" + "\n" + "Call log:\n")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"toHaveAttribute\" locator('#node') with timeout 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"hasAttribute\" locator(\"#node\") with timeout 1000ms")); } assertThat(locator).not().hasAttribute("disabled", ""); assertThat(locator).not().hasAttribute("disabled", Pattern.compile(".*")); @@ -519,7 +505,6 @@ void shouldNotMatchMissingAttribute(Page page) { @PlaywrightTest @DisplayName("EX-225 should match boolean attribute") - @Fixme("java: the assertion error has another format: 'Locator expected not to have attribute 'checked'\nExpected:\nReceived:\n\nCall log:\n- Assert \"hasAttribute\" locator(\"#node\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void shouldMatchBooleanAttribute(Page page) { page.setContent("
Text content
"); Locator locator = page.locator("#node"); @@ -528,26 +513,26 @@ void shouldMatchBooleanAttribute(Page page) { { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).not().hasAttribute("checked", "", new LocatorAssertions.HasAttributeOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).not.toHaveAttribute(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).not().hasAttribute(expected) failed\n" + "\n" + - "Locator: locator('#node')\n" + + "Locator: locator(\"#node\")\n" + "Expected: not \"\"\n" + "Received: \"\"\n" + "Timeout: 1000ms\n" + "\n" + "Call log:\n")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"not toHaveAttribute\" locator('#node') with timeout 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"not hasAttribute\" locator(\"#node\") with timeout 1000ms")); } { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).not().hasAttribute("checked", Pattern.compile(".*"), new LocatorAssertions.HasAttributeOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).not.toHaveAttribute(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).not().hasAttribute(expected) failed\n" + "\n" + - "Locator: locator('#node')\n" + + "Locator: locator(\"#node\")\n" + "Expected pattern: not /.*/\n" + "Received string: \"\"\n" + "Timeout: 1000ms")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"not toHaveAttribute\" locator('#node') with timeout 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"not hasAttribute\" locator(\"#node\") with timeout 1000ms")); } } @@ -663,12 +648,11 @@ void shouldReportIntersectionEvenIfFullyCoveredByOtherElement(Page page) { @PlaywrightTest @DisplayName("EX-237 toHaveCount should not produce logs twice") - @Fixme("java: the assertion error has another format: 'Locator expected to have count\nExpected: 2\nReceived: 1\n\nCall log:\n- Assert \"hasCount\" locator(\"option\") with timeout 2000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void toHaveCountShouldNotProduceLogsTwice(Page page) { page.setContent(""); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("option")).hasCount(2, new LocatorAssertions.HasCountOptions().setTimeout(2000))); - String waitingForMessage = "waiting for locator('option')"; + String waitingForMessage = "waiting for locator(\"option\")"; assertTrue(error.getMessage().contains(waitingForMessage)); assertTrue(error.getMessage().contains("locator resolved to 1 element")); assertTrue(error.getMessage().contains("unexpected value \"1\"")); @@ -677,12 +661,11 @@ void toHaveCountShouldNotProduceLogsTwice(Page page) { @PlaywrightTest @DisplayName("EX-238 toHaveText should not produce logs twice") - @Fixme("java: the assertion error has another format: 'Locator expected to have text\nExpected: world\nReceived: hello\n\nCall log:\n- Assert \"hasText\" locator(\"div\") with timeout 2000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void toHaveTextShouldNotProduceLogsTwice(Page page) { page.setContent("
hello
"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("div")).hasText("world", new LocatorAssertions.HasTextOptions().setTimeout(2000))); - String waitingForMessage = "waiting for locator('div')"; + String waitingForMessage = "waiting for locator(\"div\")"; assertTrue(error.getMessage().contains(waitingForMessage)); assertTrue(error.getMessage().contains("locator resolved to
hello
")); assertTrue(error.getMessage().contains("unexpected value \"hello\"")); @@ -691,12 +674,11 @@ void toHaveTextShouldNotProduceLogsTwice(Page page) { @PlaywrightTest @DisplayName("EX-239 toHaveText that does not match should not produce logs twice") - @Fixme("java: the assertion error has another format: 'Locator expected to have text\nError: element(s) not found\nExpected: world\nReceived: - text: hello\n\nCall log:\n- Assert \"hasText\" locator(\"span\") with timeout 2000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void toHaveTextThatDoesNotMatchShouldNotProduceLogsTwice(Page page) { page.setContent("
hello
"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("span")).hasText("world", new LocatorAssertions.HasTextOptions().setTimeout(2000))); - String waitingForMessage = "waiting for locator('span')"; + String waitingForMessage = "waiting for locator(\"span\")"; assertTrue(error.getMessage().contains(waitingForMessage)); assertFalse(error.getMessage().contains("locator resolved to")); assertFalse(error.getMessage().replace(waitingForMessage, "").contains(waitingForMessage)); @@ -704,30 +686,28 @@ void toHaveTextThatDoesNotMatchShouldNotProduceLogsTwice(Page page) { @PlaywrightTest @DisplayName("EX-240 strict mode violation error format") - @Fixme("java: the assertion error has another format: 'Locator expected to have text\nError: strict mode violation: locator(\"div\") resolved to 2 elements:\n1)
a
aka getByText(\"a\")\n2)
b
aka getByText(\"b\")\nExpected: foo\n\nCall log:\n- Assert \"hasText\" locator(\"div\") with timeout 5000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void strictModeViolationErrorFormat(Page page) { page.setContent("
a
b
"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("div")).hasText("foo")); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toHaveText(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).hasText(expected) failed\n" + "\n" + - "Locator: locator('div')\n" + + "Locator: locator(\"div\")\n" + "Expected: \"foo\"\n" + - "Error: strict mode violation: locator('div') resolved to 2 elements:\n" + - " 1)
a
aka getByText('a')\n" + - " 2)
b
aka getByText('b')\n" + + "Error: strict mode violation: locator(\"div\") resolved to 2 elements:\n" + + " 1)
a
aka getByText(\"a\")\n" + + " 2)
b
aka getByText(\"b\")\n" + "\n" + "Call log:\n")); } @PlaywrightTest @DisplayName("EX-241 invalid selector error format") - @Fixme("java: the assertion error has another format: 'Locator expected to be visible\nError: Unexpected token \"#\" while parsing css selector \"##\". Did you mean to CSS.escape it?\n\nCall log:\n- Assert \"isVisible\" ## with timeout 5000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void invalidSelectorErrorFormat(Page page) { page.setContent("
a
b
"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("##")).isVisible()); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toBeVisible() failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).isVisible() failed\n" + "\n" + "Locator: ##\n" + "Expected: visible\n" + diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectTimeout.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectTimeout.java index 76c9f7ad6..ed9753b3c 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectTimeout.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectTimeout.java @@ -35,14 +35,13 @@ public class TestExpectTimeout { @PlaywrightTest @DisplayName("EX-244 should print element not found") - @Fixme("java: the assertion error has another format: no 'expect(locator).toHaveText(expected) failed' header, no 'Locator:' and 'Expected:' lines") void shouldPrintElementNotFound(Page page) { page.setContent("
Text content
"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("no-such-thing")).hasText("hey", new LocatorAssertions.HasTextOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toHaveText(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).hasText(expected) failed\n" + "\n" + - "Locator: locator('no-such-thing')\n" + + "Locator: locator(\"no-such-thing\")\n" + "Expected: \"hey\"\n" + "Timeout: 1000ms\n" + "Error: element(s) not found\n" + @@ -52,14 +51,13 @@ void shouldPrintElementNotFound(Page page) { @PlaywrightTest @DisplayName("EX-245 should print timed out error message when value does not match") - @Fixme("java: the assertion error has another format: no 'expect(locator).toHaveText(expected) failed' header, no 'Locator:' and 'Expected:' lines") void shouldPrintTimedOutErrorMessageWhenValueDoesNotMatch(Page page) { page.setContent("
Text content
"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("div")).hasText("hey", new LocatorAssertions.HasTextOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toHaveText(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).hasText(expected) failed\n" + "\n" + - "Locator: locator('div')\n" + + "Locator: locator(\"div\")\n" + "Expected: \"hey\"\n" + "Received: \"Text content\"\n" + "Timeout: 1000ms\n" + @@ -69,14 +67,13 @@ void shouldPrintTimedOutErrorMessageWhenValueDoesNotMatch(Page page) { @PlaywrightTest @DisplayName("EX-246 should print timed out error message with impossible timeout") - @Fixme("java: the assertion error has another format: no 'expect(locator).toHaveText(expected) failed' header, no 'Locator:' and 'Expected:' lines") void shouldPrintTimedOutErrorMessageWithImpossibleTimeout(Page page) { page.setContent("
Text content
"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("no-such-thing")).hasText("hey", new LocatorAssertions.HasTextOptions().setTimeout(1))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toHaveText(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).hasText(expected) failed\n" + "\n" + - "Locator: locator('no-such-thing')\n" + + "Locator: locator(\"no-such-thing\")\n" + "Expected: \"hey\"\n" + "Timeout: 1ms\n" + "Error: element(s) not found\n" + @@ -86,14 +83,13 @@ void shouldPrintTimedOutErrorMessageWithImpossibleTimeout(Page page) { @PlaywrightTest @DisplayName("EX-247 should print timed out error message when value does not match with impossible timeout") - @Fixme("java: the assertion error has another format: no 'expect(locator).toHaveText(expected) failed' header, no 'Locator:' and 'Expected:' lines") void shouldPrintTimedOutErrorMessageWhenValueDoesNotMatchWithImpossibleTimeout(Page page) { page.setContent("
Text content
"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("div")).hasText("hey", new LocatorAssertions.HasTextOptions().setTimeout(1))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toHaveText(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).hasText(expected) failed\n" + "\n" + - "Locator: locator('div')\n" + + "Locator: locator(\"div\")\n" + "Expected: \"hey\"\n" + "Received: \"Text content\"\n" + "Timeout: 1ms\n" + @@ -113,21 +109,20 @@ void shouldHaveTimeoutErrorName(Page page) { @PlaywrightTest @DisplayName("EX-251 should timeout during first locator handler check") - @Fixme("java: the assertion error has another format: no 'expect(locator).toHaveText(expected) failed' header, no 'Locator:' and 'Expected:' lines") void shouldTimeoutDuringFirstLocatorHandlerCheck(Page page, TestServer server) { page.addLocatorHandler(page.locator("div"), locator -> {}); page.setContent("
hello
bye"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("span")).hasText("bye", new LocatorAssertions.HasTextOptions().setTimeout(3000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toHaveText(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).hasText(expected) failed\n" + "\n" + - "Locator: locator('span')\n" + + "Locator: locator(\"span\")\n" + "Expected: \"bye\"\n" + "Received: \"\"\n" + "Timeout: 3000ms\n" + "\n" + "Call log:\n")); - assertTrue(error.getMessage().contains("locator handler has finished, waiting for locator('div') to be hidden")); + assertTrue(error.getMessage().contains("locator handler has finished, waiting for locator(\"div\") to be hidden")); assertTrue(error.getMessage().contains("locator resolved to visible
hello
")); } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveText.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveText.java index 03c11da8a..d7932fb98 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveText.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveText.java @@ -55,15 +55,14 @@ void pass(Page page) { @PlaywrightTest @DisplayName("EX-275 fail") - @Fixme("java: the assertion error has another format: 'Locator expected to have text matching regex\nExpected: Text 2\nReceived: Text content\n\nCall log:\n- Assert \"hasText\" locator(\"#node\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void fail(Page page) { page.setContent("
Text content
"); Locator locator = page.locator("#node"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).hasText(Pattern.compile("Text 2"), new LocatorAssertions.HasTextOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toHaveText(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).hasText(expected) failed\n" + "\n" + - "Locator: locator('#node')\n" + + "Locator: locator(\"#node\")\n" + "Expected pattern: /Text 2/\n" + "Received string: \"Text content\"\n" + "Timeout: 1000ms\n" + @@ -87,7 +86,6 @@ void pass(Page page) { @PlaywrightTest @DisplayName("EX-277 fail") - @Fixme("java: the assertion error has another format: 'Locator expected to contain regex\nExpected: ex2\nReceived: Text content\n\nCall log:\n- Assert \"containsText\" locator(\"#node\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void fail(Page page) { page.setContent("
Text content
"); Locator locator = page.locator("#node"); @@ -110,15 +108,14 @@ void pass(Page page) { @PlaywrightTest @DisplayName("EX-279 fail") - @Fixme("java: the assertion error has another format: 'Locator expected to contain text\nExpected: foo\nReceived: Text content\n\nCall log:\n- Assert \"containsText\" locator(\"#node\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void fail(Page page) { page.setContent("
Text content
"); Locator locator = page.locator("#node"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).containsText("foo", new LocatorAssertions.ContainsTextOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).toContainText(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).containsText(expected) failed\n" + "\n" + - "Locator: locator('#node')\n" + + "Locator: locator(\"#node\")\n" + "Expected substring: \"foo\"\n" + "Received string: \"Text content\"\n" + "Timeout: 1000ms\n" + @@ -162,7 +159,6 @@ void passContain(Page page) { @PlaywrightTest @DisplayName("EX-282 fail") - @Fixme("java: the assertion error has another format: 'Locator expected to have text\nExpected: Text\nReceived: Text content\n\nCall log:\n- Assert \"hasText\" locator(\"#node\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void fail(Page page) { page.setContent("
Text content
"); Locator locator = page.locator("#node"); @@ -217,7 +213,6 @@ void inShadowDom(Page page) { @PlaywrightTest @DisplayName("EX-286 fail with impossible timeout") - @Fixme("java: the assertion error has another format: 'Locator expected to have text\nExpected: Text\nReceived: Text content\n\nCall log:\n- Assert \"hasText\" locator(\"#node\") with timeout 1ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void failWithImpossibleTimeout(Page page) { page.setContent("
Text content
"); AssertionFailedError error = assertThrows(AssertionFailedError.class, @@ -228,7 +223,6 @@ void failWithImpossibleTimeout(Page page) { @PlaywrightTest @DisplayName("EX-287 do not show \"element(s) not found\" when the real failure is a string mismatch") - @Fixme("java: the assertion error has another format: 'Locator expected to have text\nExpected: Something\nReceived: Final value\n\nCall log:\n- Assert \"hasText\" locator(\"#field\") with timeout 3000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void doNotShowElementSNotFoundWhenTheRealFailureIsAStringMismatch(Page page) { assumeFalse("frozen".equals(System.getenv("PW_CLOCK")), "The element is attached after 1 second."); page.setContent("\n" + @@ -264,7 +258,6 @@ void pass(Page page) { @PlaywrightTest @DisplayName("EX-289 fail") - @Fixme("java: the assertion error has another format: 'Locator expected not to have text\nExpected: Text content\nReceived: Text content\n\nCall log:\n- Assert \"hasText\" locator(\"#node\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void fail(Page page) { page.setContent("
Text content
"); Locator locator = page.locator("#node"); @@ -276,14 +269,13 @@ void fail(Page page) { @PlaywrightTest @DisplayName("EX-290 should work when selector does not match") - @Fixme("java: the assertion error has another format: 'Locator expected not to have text\nError: element(s) not found\nExpected: hello\nReceived: - text: hello\n\nCall log:\n- Assert \"hasText\" locator(\"span\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void shouldWorkWhenSelectorDoesNotMatch(Page page) { page.setContent("
hello
"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.locator("span")).not().hasText("hello", new LocatorAssertions.HasTextOptions().setTimeout(1000))); assertTrue(stripAnsi(error.getMessage()).contains("Expected: not \"hello\"")); assertTrue(stripAnsi(error.getMessage()).contains("Error: element(s) not found")); - assertTrue(stripAnsi(error.getMessage()).contains("waiting for locator('span')")); + assertTrue(stripAnsi(error.getMessage()).contains("waiting for locator(\"span\")")); } } @@ -334,15 +326,14 @@ void passOnEmpty(Page page) { @PlaywrightTest @DisplayName("EX-296 fail on not+empty") - @Fixme("java: the assertion error has another format: 'Locator expected not to have text\nExpected: []\nReceived: []\n\nCall log:\n- Assert \"hasText\" locator(\"p\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void failOnNotEmpty(Page page) { page.setContent("
"); Locator locator = page.locator("p"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).not().hasText(new String[]{}, new LocatorAssertions.HasTextOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(locator).not.toHaveText(expected)")); + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).not().hasText(expected)")); assertTrue(stripAnsi(error.getMessage()).contains("Timeout: 1000ms")); - assertTrue(stripAnsi(error.getMessage()).contains("- Expect \"not toHaveText\" locator('p') with timeout 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"not hasText\" locator(\"p\") with timeout 1000ms")); } @PlaywrightTest @@ -379,7 +370,6 @@ class ToContainTextWithArray { @PlaywrightTest @DisplayName("EX-301 fail") - @Fixme("java: the assertion error has another format: 'Locator expected to contain text\nExpected: [Text 2]\nReceived: [Text 1, Text 3]\n\nCall log:\n- Assert \"containsText\" locator(\"div\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void fail(Page page) { page.setContent("
Text 1
Text 3
"); Locator locator = page.locator("div"); diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveValue.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveValue.java index 02e34262a..0d5953e0f 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveValue.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveValue.java @@ -106,7 +106,6 @@ void followsLabels(Page page) { @PlaywrightTest @DisplayName("EX-308 exact match with text failure") - @Fixme("java: the assertion error has another format: 'Locator expected to have values\nExpected: [R, G]\nReceived: [RR, GG]\n\nCall log:\n- Assert \"hasValues\" locator(\"select\") with timeout 1000ms ...' (no 'expect(locator)... failed' header, no 'Locator:' line, unquoted values, double quoted locators)") void exactMatchWithTextFailure(Page page) { page.setContent("\n" + " \n" + diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorAnyFrame.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorAnyFrame.java index 97c661b0f..34048daf6 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorAnyFrame.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorAnyFrame.java @@ -200,7 +200,6 @@ void shouldWaitForAFrameToAppearWithToHaveCount(Page page, TestServer server) { @PlaywrightTest @DisplayName("LO-010 should fail toHaveCount when elements match in multiple frames") - @Fixme("java: the assertion message has no 'Locator: frameLocator().locator(...)' line, only the call log: Assert \"hasCount\" frameLocator().locator(\"span\")") void shouldFailToHaveCountWhenElementsMatchInMultipleFrames(Page page, TestServer server) { routePage(page, "empty.html", ""); routePage(page, "a.html", "one"); @@ -209,7 +208,7 @@ void shouldFailToHaveCountWhenElementsMatchInMultipleFrames(Page page, TestServe waitForAllFrames(page, 3, "span"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.frameLocator().locator("span")).hasCount(2, new LocatorAssertions.HasCountOptions().setTimeout(3000))); assertTrue(error.getMessage().contains("frameLocator() matched elements in multiple frames")); - assertTrue(error.getMessage().contains("Locator: frameLocator().locator('span')")); + assertTrue(error.getMessage().contains("Locator: frameLocator().locator(\"span\")")); } @PlaywrightTest @@ -232,7 +231,6 @@ void shouldSupportToHaveTextWithAnArray(Page page, TestServer server) { @PlaywrightTest @DisplayName("LO-013 should fail toHaveText when elements match in multiple frames") - @Fixme("java: the assertion message has no 'Locator: frameLocator().locator(...)' line, only the call log: Assert \"hasCount\" frameLocator().locator(\"span\")") void shouldFailToHaveTextWhenElementsMatchInMultipleFrames(Page page, TestServer server) { routePage(page, "empty.html", ""); routePage(page, "a.html", "
one
"); @@ -241,7 +239,7 @@ void shouldFailToHaveTextWhenElementsMatchInMultipleFrames(Page page, TestServer waitForAllFrames(page, 3, "div"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.frameLocator().locator("div")).hasText("one", new LocatorAssertions.HasTextOptions().setTimeout(3000))); assertTrue(error.getMessage().contains("frameLocator() matched elements in multiple frames")); - assertTrue(error.getMessage().contains("Locator: frameLocator().locator('div')")); + assertTrue(error.getMessage().contains("Locator: frameLocator().locator(\"div\")")); } @PlaywrightTest @@ -258,7 +256,6 @@ void shouldFailToHaveTextWithAnArrayWhenElementsMatchInMultipleFrames(Page page, @PlaywrightTest @DisplayName("LO-015 should fail toHaveText upon strict mode violation inside a single frame") - @Fixme("java: the assertion message has no 'Locator: frameLocator().locator(...)' line, only the call log: Assert \"hasCount\" frameLocator().locator(\"span\")") void shouldFailToHaveTextUponStrictModeViolationInsideASingleFrame(Page page, TestServer server) { routePage(page, "empty.html", ""); routePage(page, "a.html", "
one
two
"); @@ -266,7 +263,7 @@ void shouldFailToHaveTextUponStrictModeViolationInsideASingleFrame(Page page, Te waitForAllFrames(page, 2, "div"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page.frameLocator().locator("div")).hasText("one", new LocatorAssertions.HasTextOptions().setTimeout(3000))); assertTrue(error.getMessage().contains("strict mode violation")); - assertTrue(error.getMessage().contains("Locator: frameLocator().locator('div')")); + assertTrue(error.getMessage().contains("Locator: frameLocator().locator(\"div\")")); } @PlaywrightTest diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestToMatchAriaSnapshot.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestToMatchAriaSnapshot.java index 7a3c78437..4edb8d147 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestToMatchAriaSnapshot.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestToMatchAriaSnapshot.java @@ -74,13 +74,12 @@ void shouldMatchPageWithNot(Page page) { @PlaywrightTest @DisplayName("AR-110 should fail page with timeout") - @Fixme("java: the assertion error message starts with \"Page expected to match Aria snapshot\" (for a locator \"Locator expected to match Aria snapshot\"), not \"expect(page).toMatchAriaSnapshot(expected) failed\" and has no \"Timeout: Nms\" line") void shouldFailPageWithTimeout(Page page) { page.setContent("

title

"); AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - heading \"wrong\"\n" + " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(2000))); - assertTrue(stripAnsi(e.getMessage()).contains("expect(page).toMatchAriaSnapshot(expected) failed")); + assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); assertTrue(stripAnsi(e.getMessage()).contains("Timeout: 2000ms")); assertFalse(stripAnsi(e.getMessage()).contains("Locator")); } @@ -217,7 +216,6 @@ void detailsVisibility(Page page) { @PlaywrightTest @DisplayName("AR-119 checked attribute") - @Fixme("java: the assertion error message starts with \"Page expected to match Aria snapshot\" (for a locator \"Locator expected to match Aria snapshot\"), not \"expect(page).toMatchAriaSnapshot(expected) failed\" and has no \"Timeout: Nms\" line") void checkedAttribute(Page page) { page.setContent("\n" + " \n" + @@ -239,7 +237,7 @@ void checkedAttribute(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - checkbox [checked=false]\n" + " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); - assertTrue(stripAnsi(e.getMessage()).contains("expect(page).toMatchAriaSnapshot(expected) failed")); + assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); assertTrue(stripAnsi(e.getMessage()).contains("Timeout: 1000ms")); } @@ -247,7 +245,7 @@ void checkedAttribute(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - checkbox [checked=mixed]\n" + " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); - assertTrue(stripAnsi(e.getMessage()).contains("expect(page).toMatchAriaSnapshot(expected) failed")); + assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); assertTrue(stripAnsi(e.getMessage()).contains("Timeout: 1000ms")); } @@ -261,7 +259,6 @@ void checkedAttribute(Page page) { @PlaywrightTest @DisplayName("AR-120 disabled attribute") - @Fixme("java: the assertion error message starts with \"Page expected to match Aria snapshot\" (for a locator \"Locator expected to match Aria snapshot\"), not \"expect(page).toMatchAriaSnapshot(expected) failed\" and has no \"Timeout: Nms\" line") void disabledAttribute(Page page) { page.setContent("\n" + " \n" + @@ -283,7 +280,7 @@ void disabledAttribute(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - button [disabled=false]\n" + " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); - assertTrue(stripAnsi(e.getMessage()).contains("expect(page).toMatchAriaSnapshot(expected) failed")); + assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); assertTrue(stripAnsi(e.getMessage()).contains("Timeout: 1000ms")); } @@ -297,7 +294,6 @@ void disabledAttribute(Page page) { @PlaywrightTest @DisplayName("AR-121 expanded attribute") - @Fixme("java: the assertion error message starts with \"Page expected to match Aria snapshot\" (for a locator \"Locator expected to match Aria snapshot\"), not \"expect(page).toMatchAriaSnapshot(expected) failed\" and has no \"Timeout: Nms\" line") void expandedAttribute(Page page) { page.setContent("\n" + " \n" + @@ -319,7 +315,7 @@ void expandedAttribute(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - button [expanded=false]\n" + " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); - assertTrue(stripAnsi(e.getMessage()).contains("expect(page).toMatchAriaSnapshot(expected) failed")); + assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); assertTrue(stripAnsi(e.getMessage()).contains("Timeout: 1000ms")); } @@ -333,7 +329,6 @@ void expandedAttribute(Page page) { @PlaywrightTest @DisplayName("AR-122 level attribute") - @Fixme("java: the assertion error message starts with \"Page expected to match Aria snapshot\" (for a locator \"Locator expected to match Aria snapshot\"), not \"expect(page).toMatchAriaSnapshot(expected) failed\" and has no \"Timeout: Nms\" line") void levelAttribute(Page page) { page.setContent("\n" + "

Section Title

\n" + @@ -351,7 +346,7 @@ void levelAttribute(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - heading [level=3]\n" + " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); - assertTrue(stripAnsi(e.getMessage()).contains("expect(page).toMatchAriaSnapshot(expected) failed")); + assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); assertTrue(stripAnsi(e.getMessage()).contains("Timeout: 1000ms")); } @@ -365,7 +360,6 @@ void levelAttribute(Page page) { @PlaywrightTest @DisplayName("AR-123 pressed attribute") - @Fixme("java: the assertion error message starts with \"Page expected to match Aria snapshot\" (for a locator \"Locator expected to match Aria snapshot\"), not \"expect(page).toMatchAriaSnapshot(expected) failed\" and has no \"Timeout: Nms\" line") void pressedAttribute(Page page) { page.setContent("\n" + " \n" + @@ -387,7 +381,7 @@ void pressedAttribute(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - button [pressed=false]\n" + " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); - assertTrue(stripAnsi(e.getMessage()).contains("expect(page).toMatchAriaSnapshot(expected) failed")); + assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); assertTrue(stripAnsi(e.getMessage()).contains("Timeout: 1000ms")); } @@ -404,7 +398,7 @@ void pressedAttribute(Page page) { AssertionFailedError e = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - button [pressed=true]\n" + " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); - assertTrue(stripAnsi(e.getMessage()).contains("expect(page).toMatchAriaSnapshot(expected) failed")); + assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); assertTrue(stripAnsi(e.getMessage()).contains("Timeout: 1000ms")); } @@ -418,7 +412,6 @@ void pressedAttribute(Page page) { @PlaywrightTest @DisplayName("AR-124 selected attribute") - @Fixme("java: the assertion error message starts with \"Page expected to match Aria snapshot\" (for a locator \"Locator expected to match Aria snapshot\"), not \"expect(page).toMatchAriaSnapshot(expected) failed\" and has no \"- Expected - N / + Received + M\" diff, only the Expected: and Received: dumps") void selectedAttribute(Page page) { page.setContent("\n" + " \n" + @@ -458,7 +451,7 @@ void selectedAttribute(Page page) { " - row [selected=false]\n" + " - row [selected=false]\n" + " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); - assertTrue(stripAnsi(e.getMessage()).contains("expect(page).toMatchAriaSnapshot(expected) failed\n" + + assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed\n" + "\n" + "Timeout: 1000ms\n" + "- Expected - 2\n" + @@ -549,7 +542,6 @@ void integrationTest2(Page page) { @PlaywrightTest @DisplayName("AR-127 expected formatter") - @Fixme("java: the assertion error message starts with \"Page expected to match Aria snapshot\" (for a locator \"Locator expected to match Aria snapshot\"), not \"expect(page).toMatchAriaSnapshot(expected) failed\" and has no \"- Expected - N / + Received + M\" diff, only the Expected: and Received: dumps") void expectedFormatter(Page page) { page.setContent("\n" + "
\n" + @@ -566,7 +558,7 @@ void expectedFormatter(Page page) { // Note that error message should not contain any regular expressions, // unlike the baseline generated by --update-snapshots. - assertTrue(stripAnsi(error.getMessage()).contains("expect(page).toMatchAriaSnapshot(expected) failed\n" + + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed\n" + "\n" + "Timeout: 1ms\n" + "- Expected - 2\n" + @@ -674,7 +666,6 @@ void shouldUnpackEscapedNames(Page page) { @PlaywrightTest @DisplayName("AR-129 should report error in YAML") - @Fixme("java: the error message is \"Page expected to match Aria snapshot\\nError: Aria snapshot must be a YAML sequence, elements starting with \\\" -\\\"\\nExpected: ...\" with the call log \"Assert \\\"matchesAriaSnapshot\\\" with timeout 5000ms\", not \"expect(page).toMatchAriaSnapshot(expected) failed\\n\\nExpected: ...\" with the call log \"Expect \\\"toMatchAriaSnapshot\\\" with timeout 10000ms\"") void shouldReportErrorInYAML(Page page) { page.setContent("

title

"); @@ -682,20 +673,20 @@ void shouldReportErrorInYAML(Page page) { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " heading \"title\"\n" + " ")); - assertEquals("expect(page).toMatchAriaSnapshot(expected) failed\n" + + assertEquals("assertThat(page).matchesAriaSnapshot(expected) failed\n" + "\n" + "Expected: \"heading \\\"title\\\"\"\n" + "Error: Aria snapshot must be a YAML sequence, elements starting with \" -\"\n" + "\n" + "Call log:\n" + - " - Expect \"toMatchAriaSnapshot\" with timeout 10000ms\n", stripAnsi(error.getMessage())); + " - Assert \"matchesAriaSnapshot\" with timeout 5000ms\n", stripAnsi(error.getMessage())); } { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - heading: a:\n" + " ")); - assertEquals("expect(page).toMatchAriaSnapshot(expected) failed\n" + + assertEquals("assertThat(page).matchesAriaSnapshot(expected) failed\n" + "\n" + "Expected: \"- heading: a:\"\n" + "Error: Nested mappings are not allowed in compact mappings at line 1, column 12:\n" + @@ -704,13 +695,12 @@ void shouldReportErrorInYAML(Page page) { " ^\n" + "\n" + "Call log:\n" + - " - Expect \"toMatchAriaSnapshot\" with timeout 10000ms\n", stripAnsi(error.getMessage())); + " - Assert \"matchesAriaSnapshot\" with timeout 5000ms\n", stripAnsi(error.getMessage())); } } @PlaywrightTest @DisplayName("AR-130 should report error in YAML keys") - @Fixme("java: the error message is \"Page expected to match Aria snapshot\\nError: Unterminated string:\\n...\" with the call log \"Assert \\\"matchesAriaSnapshot\\\" with timeout 5000ms\", not \"expect(page).toMatchAriaSnapshot(expected) failed\\n\\nExpected: ...\" with the call log \"Expect \\\"toMatchAriaSnapshot\\\" with timeout 10000ms\"") void shouldReportErrorInYAMLKeys(Page page) { page.setContent("

title

"); @@ -718,7 +708,7 @@ void shouldReportErrorInYAMLKeys(Page page) { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - heading \"title\n" + " ")); - assertEquals("expect(page).toMatchAriaSnapshot(expected) failed\n" + + assertEquals("assertThat(page).matchesAriaSnapshot(expected) failed\n" + "\n" + "Expected: \"- heading \\\"title\"\n" + "Error: Unterminated string:\n" + @@ -727,14 +717,14 @@ void shouldReportErrorInYAMLKeys(Page page) { " ^\n" + "\n" + "Call log:\n" + - " - Expect \"toMatchAriaSnapshot\" with timeout 10000ms\n", stripAnsi(error.getMessage())); + " - Assert \"matchesAriaSnapshot\" with timeout 5000ms\n", stripAnsi(error.getMessage())); } { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - heading /title\n" + " ")); - assertEquals("expect(page).toMatchAriaSnapshot(expected) failed\n" + + assertEquals("assertThat(page).matchesAriaSnapshot(expected) failed\n" + "\n" + "Expected: \"- heading /title\"\n" + "Error: Unterminated regex:\n" + @@ -743,14 +733,14 @@ void shouldReportErrorInYAMLKeys(Page page) { " ^\n" + "\n" + "Call log:\n" + - " - Expect \"toMatchAriaSnapshot\" with timeout 10000ms\n", stripAnsi(error.getMessage())); + " - Assert \"matchesAriaSnapshot\" with timeout 5000ms\n", stripAnsi(error.getMessage())); } { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - heading [level=a]\n" + " ")); - assertEquals("expect(page).toMatchAriaSnapshot(expected) failed\n" + + assertEquals("assertThat(page).matchesAriaSnapshot(expected) failed\n" + "\n" + "Expected: \"- heading [level=a]\"\n" + "Error: Value of \"level\" attribute must be a number:\n" + @@ -759,14 +749,14 @@ void shouldReportErrorInYAMLKeys(Page page) { " ^\n" + "\n" + "Call log:\n" + - " - Expect \"toMatchAriaSnapshot\" with timeout 10000ms\n", stripAnsi(error.getMessage())); + " - Assert \"matchesAriaSnapshot\" with timeout 5000ms\n", stripAnsi(error.getMessage())); } { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - heading [expanded=FALSE]\n" + " ")); - assertEquals("expect(page).toMatchAriaSnapshot(expected) failed\n" + + assertEquals("assertThat(page).matchesAriaSnapshot(expected) failed\n" + "\n" + "Expected: \"- heading [expanded=FALSE]\"\n" + "Error: Value of \"expanded\" attribute must be a boolean:\n" + @@ -775,14 +765,14 @@ void shouldReportErrorInYAMLKeys(Page page) { " ^\n" + "\n" + "Call log:\n" + - " - Expect \"toMatchAriaSnapshot\" with timeout 10000ms\n", stripAnsi(error.getMessage())); + " - Assert \"matchesAriaSnapshot\" with timeout 5000ms\n", stripAnsi(error.getMessage())); } { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - heading [checked=foo]\n" + " ")); - assertEquals("expect(page).toMatchAriaSnapshot(expected) failed\n" + + assertEquals("assertThat(page).matchesAriaSnapshot(expected) failed\n" + "\n" + "Expected: \"- heading [checked=foo]\"\n" + "Error: Value of \"checked\" attribute must be a boolean or \"mixed\":\n" + @@ -791,14 +781,14 @@ void shouldReportErrorInYAMLKeys(Page page) { " ^\n" + "\n" + "Call log:\n" + - " - Expect \"toMatchAriaSnapshot\" with timeout 10000ms\n", stripAnsi(error.getMessage())); + " - Assert \"matchesAriaSnapshot\" with timeout 5000ms\n", stripAnsi(error.getMessage())); } { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - heading [level=]\n" + " ")); - assertEquals("expect(page).toMatchAriaSnapshot(expected) failed\n" + + assertEquals("assertThat(page).matchesAriaSnapshot(expected) failed\n" + "\n" + "Expected: \"- heading [level=]\"\n" + "Error: Value of \"level\" attribute must be a number:\n" + @@ -807,14 +797,14 @@ void shouldReportErrorInYAMLKeys(Page page) { " ^\n" + "\n" + "Call log:\n" + - " - Expect \"toMatchAriaSnapshot\" with timeout 10000ms\n", stripAnsi(error.getMessage())); + " - Assert \"matchesAriaSnapshot\" with timeout 5000ms\n", stripAnsi(error.getMessage())); } { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - heading [bogus]\n" + " ")); - assertEquals("expect(page).toMatchAriaSnapshot(expected) failed\n" + + assertEquals("assertThat(page).matchesAriaSnapshot(expected) failed\n" + "\n" + "Expected: \"- heading [bogus]\"\n" + "Error: Unsupported attribute [bogus]:\n" + @@ -823,14 +813,14 @@ void shouldReportErrorInYAMLKeys(Page page) { " ^\n" + "\n" + "Call log:\n" + - " - Expect \"toMatchAriaSnapshot\" with timeout 10000ms\n", stripAnsi(error.getMessage())); + " - Assert \"matchesAriaSnapshot\" with timeout 5000ms\n", stripAnsi(error.getMessage())); } { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - heading invalid\n" + " ")); - assertEquals("expect(page).toMatchAriaSnapshot(expected) failed\n" + + assertEquals("assertThat(page).matchesAriaSnapshot(expected) failed\n" + "\n" + "Expected: \"- heading invalid\"\n" + "Error: Unexpected input:\n" + @@ -839,7 +829,7 @@ void shouldReportErrorInYAMLKeys(Page page) { " ^\n" + "\n" + "Call log:\n" + - " - Expect \"toMatchAriaSnapshot\" with timeout 10000ms\n", stripAnsi(error.getMessage())); + " - Assert \"matchesAriaSnapshot\" with timeout 5000ms\n", stripAnsi(error.getMessage())); } } @@ -878,7 +868,6 @@ void shouldParseAttributes(Page page) { @PlaywrightTest @DisplayName("AR-133 should not unshift actual template text") - @Fixme("java: the assertion error message has no \"- Expected - N / + Received + M\" diff with the \"+ - heading ...\" lines, only the Expected: and Received: dumps") void shouldNotUnshiftActualTemplateText(Page page) { page.setContent("\n" + "

title

\n" + @@ -895,7 +884,6 @@ void shouldNotUnshiftActualTemplateText(Page page) { @PlaywrightTest @DisplayName("AR-134 should not match what is not matched") - @Fixme("java: the assertion error message has no \"- Expected - N / + Received + M\" diff with the \"+ - heading ...\" lines, only the Expected: and Received: dumps") void shouldNotMatchWhatIsNotMatched(Page page) { page.setContent("

Text

"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + @@ -923,7 +911,6 @@ void shouldMatchUrl(Page page) { @PlaywrightTest @DisplayName("AR-136 should detect unexpected children: equal") - @Fixme("java: the assertion error message starts with \"Page expected to match Aria snapshot\" (for a locator \"Locator expected to match Aria snapshot\"), not \"expect(page).toMatchAriaSnapshot(expected) failed\" and has no \"- Expected - N / + Received + M\" diff, only the Expected: and Received: dumps") void shouldDetectUnexpectedChildrenEqual(Page page) { page.setContent("\n" + "
    \n" + @@ -946,13 +933,12 @@ void shouldDetectUnexpectedChildrenEqual(Page page) { " - listitem: \"Three\"\n" + " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); - assertTrue(stripAnsi(e.getMessage()).contains("expect(page).toMatchAriaSnapshot(expected) failed")); + assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); assertTrue(stripAnsi(e.getMessage()).contains("+ - listitem: Two")); } @PlaywrightTest @DisplayName("AR-137 should detect unexpected children: deep-equal") - @Fixme("java: the assertion error message starts with \"Page expected to match Aria snapshot\" (for a locator \"Locator expected to match Aria snapshot\"), not \"expect(page).toMatchAriaSnapshot(expected) failed\" and has no \"- Expected - N / + Received + M\" diff, only the Expected: and Received: dumps") void shouldDetectUnexpectedChildrenDeepequal(Page page) { page.setContent("\n" + "
      \n" + @@ -988,13 +974,12 @@ void shouldDetectUnexpectedChildrenDeepequal(Page page) { " - listitem: 1.1\n" + " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); - assertTrue(stripAnsi(e.getMessage()).contains("expect(page).toMatchAriaSnapshot(expected) failed")); + assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); assertTrue(stripAnsi(e.getMessage()).contains("+ - listitem: \"1.2\"")); } @PlaywrightTest @DisplayName("AR-138 should allow restoring contain mode inside deep-equal") - @Fixme("java: the assertion error message starts with \"Page expected to match Aria snapshot\" (for a locator \"Locator expected to match Aria snapshot\"), not \"expect(page).toMatchAriaSnapshot(expected) failed\" and has no \"- Expected - N / + Received + M\" diff, only the Expected: and Received: dumps") void shouldAllowRestoringContainModeInsideDeepequal(Page page) { page.setContent("\n" + "
        \n" + @@ -1015,7 +1000,7 @@ void shouldAllowRestoringContainModeInsideDeepequal(Page page) { " - listitem: 1.1\n" + " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); - assertTrue(stripAnsi(e.getMessage()).contains("expect(page).toMatchAriaSnapshot(expected) failed")); + assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); assertTrue(stripAnsi(e.getMessage()).contains("+ - listitem: \"1.2\"")); assertThat(page).matchesAriaSnapshot("\n" + @@ -1030,7 +1015,6 @@ void shouldAllowRestoringContainModeInsideDeepequal(Page page) { @PlaywrightTest @DisplayName("AR-139 top-level deep-equal") - @Fixme("java: the assertion error message has no \"- Expected - N / + Received + M\" diff with the \"+ - heading ...\" lines, only the Expected: and Received: dumps") void toplevelDeepequal(Page page) { page.setContent("\n" + "
          \n" + @@ -1078,14 +1062,13 @@ void generatedSnapshotIncludesTextChildrenWhenNameIsLongerThanText(Page page) { @PlaywrightTest @DisplayName("AR-141 treat bad regex as a string") - @Fixme("java: the assertion error message starts with \"Page expected to match Aria snapshot\" (for a locator \"Locator expected to match Aria snapshot\"), not \"expect(page).toMatchAriaSnapshot(expected) failed\" and has no \"- Expected - N / + Received + M\" diff, only the Expected: and Received: dumps") void treatBadRegexAsAString(Page page) { page.setContent("Log in"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(page).matchesAriaSnapshot("\n" + " - link \"Log in\":\n" + " - /url: /[a/\n" + " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1))); - assertTrue(stripAnsi(error.getMessage()).contains("expect(page).toMatchAriaSnapshot(expected) failed")); + assertTrue(stripAnsi(error.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); assertTrue(stripAnsi(error.getMessage()).contains("- - /url: /[a/")); assertTrue(stripAnsi(error.getMessage()).contains("+ - /url: /foo")); } From b3f4636e07be1e43fdca3758468d1ca1c7444053 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Mon, 23 Nov 2026 14:00:47 -0800 Subject: [PATCH 3/6] chore: do not port jest and the css parser --- playwright/src/main/AGENTS.md | 8 +- .../playwright/impl/AssertionsBase.java | 6 +- .../playwright/impl/DiffSequences.java | 415 ------ .../microsoft/playwright/impl/FrameImpl.java | 4 +- .../microsoft/playwright/impl/JestDiff.java | 1234 ----------------- .../playwright/impl/JestGetType.java | 68 - .../playwright/impl/JestMatcherUtils.java | 213 --- .../playwright/impl/MatcherHint.java | 32 +- .../playwright/impl/MatcherUtils.java | 219 +++ .../playwright/impl/PrettyFormat.java | 407 ------ .../microsoft/playwright/impl/ToBeTruthy.java | 2 +- .../microsoft/playwright/impl/ToEqual.java | 14 +- .../playwright/impl/ToMatchAriaSnapshot.java | 8 +- .../playwright/impl/ToMatchText.java | 12 +- .../playwright/impl/isomorphic/CssParser.java | 363 ----- .../impl/isomorphic/CssTokenizer.java | 995 ------------- .../playwright/impl/isomorphic/RegExp.java | 8 +- .../impl/isomorphic/SelectorParser.java | 21 +- .../playwright/TestLocatorGenerators.java | 4 +- .../playwright/tests/page/TestExpectMisc.java | 3 +- 20 files changed, 280 insertions(+), 3756 deletions(-) delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/DiffSequences.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/JestDiff.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/JestGetType.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/JestMatcherUtils.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/MatcherUtils.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/PrettyFormat.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssParser.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssTokenizer.java diff --git a/playwright/src/main/AGENTS.md b/playwright/src/main/AGENTS.md index 1c75c1eb2..5f43f363e 100644 --- a/playwright/src/main/AGENTS.md +++ b/playwright/src/main/AGENTS.md @@ -31,10 +31,12 @@ Java code around the place it goes to, and write the new lines the same way. `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 `JestMatcherUtils`, with `JestDiff`, `DiffSequences`, `PrettyFormat` and `JestGetType`: ports of - the jest packages in `.upstream/node_modules/`, without colors. A failure message is the - upstream message with the Java call: `assertThat(locator).not().hasText(expected) failed` for + matcher are `MatcherUtils`: jest is not ported, the values and the diff are printed in the same + layout without matching jest in every case. 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/cssParser.ts` and `cssTokenizer.ts` are not ported: `SelectorParser` keeps the + source of a css part and does not reject an invalid css selector. - A class that implements a public interface is `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, diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/AssertionsBase.java b/playwright/src/main/java/com/microsoft/playwright/impl/AssertionsBase.java index 0f468f986..cbcff7396 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/AssertionsBase.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/AssertionsBase.java @@ -35,7 +35,7 @@ abstract class AssertionsBase { this.isNot = isNot; } - // java: the fields of ExpectMatcherStateInternal that the matchers read, utils is JestMatcherUtils. + // java: the fields of ExpectMatcherStateInternal that the matchers read, utils is MatcherUtils. static class ExpectMatcherState { boolean isNot; String promise; @@ -63,7 +63,7 @@ void callMatcherAsStep(String matcherName, RawMatcherFn matcher) { 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 == JestGetType.UNDEFINED)) + 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)); } @@ -82,7 +82,7 @@ private MatcherResult invokeMatcher(String matcherName, RawMatcherFn matcher, St // java: a helper with no counterpart upstream, the value of an AssertionFailedError. protected static ValueWrapper formatValue(Object value) { - if (value == JestGetType.UNDEFINED) { + if (value == MatcherUtils.UNDEFINED) { return ValueWrapper.create(null); } if (value == null || !value.getClass().isArray()) { diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/DiffSequences.java b/playwright/src/main/java/com/microsoft/playwright/impl/DiffSequences.java deleted file mode 100644 index 2bb01fc9c..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/DiffSequences.java +++ /dev/null @@ -1,415 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Port of @jest/diff-sequences. -// java: the original is MIT licensed, Copyright (c) Meta Platforms, Inc. and affiliates. -package com.microsoft.playwright.impl; - -import com.microsoft.playwright.PlaywrightException; - -class DiffSequences { - // java: the types of the input and output callbacks. - interface IsCommon { - boolean isCommon(int aIndex, int bIndex); - } - - interface FoundSubsequence { - void foundSubsequence(int nCommon, int aCommon, int bCommon); - } - - // java: the type of an item of the callbacks array. - private static class Callbacks { - final FoundSubsequence foundSubsequence; - final IsCommon isCommon; - - Callbacks(FoundSubsequence foundSubsequence, IsCommon isCommon) { - this.foundSubsequence = foundSubsequence; - this.isCommon = isCommon; - } - } - - // java: the type of the division object. - private static class Division { - int aCommonFollowing = NOT_YET_SET; - int aCommonPreceding = NOT_YET_SET; - int aEndPreceding = NOT_YET_SET; - int aStartFollowing = NOT_YET_SET; - int bCommonFollowing = NOT_YET_SET; - int bCommonPreceding = NOT_YET_SET; - int bEndPreceding = NOT_YET_SET; - int bStartFollowing = NOT_YET_SET; - int nChangeFollowing = NOT_YET_SET; - int nChangePreceding = NOT_YET_SET; - int nCommonFollowing = NOT_YET_SET; - int nCommonPreceding = NOT_YET_SET; - } - - private static final String pkg = "@jest/diff-sequences"; - private static final int NOT_YET_SET = 0; - - private static int countCommonItemsF(int aIndex, int aEnd, int bIndex, int bEnd, IsCommon isCommon) { - int nCommon = 0; - while (aIndex < aEnd && bIndex < bEnd && isCommon.isCommon(aIndex, bIndex)) { - aIndex += 1; - bIndex += 1; - nCommon += 1; - } - return nCommon; - } - - private static int countCommonItemsR(int aStart, int aIndex, int bStart, int bIndex, IsCommon isCommon) { - int nCommon = 0; - while (aStart <= aIndex && bStart <= bIndex && isCommon.isCommon(aIndex, bIndex)) { - aIndex -= 1; - bIndex -= 1; - nCommon += 1; - } - return nCommon; - } - - private static int extendPathsF(int d, int aEnd, int bEnd, int bF, IsCommon isCommon, int[] aIndexesF, int iMaxF) { - int iF = 0; - int kF = -d; - int aFirst = aIndexesF[iF]; - int aIndexPrev1 = aFirst; - aIndexesF[iF] += countCommonItemsF(aFirst + 1, aEnd, bF + aFirst - kF + 1, bEnd, isCommon); - - int nF = Math.min(d, iMaxF); - - for (iF += 1, kF += 2; iF <= nF; iF += 1, kF += 2) { - if (iF != d && aIndexPrev1 < aIndexesF[iF]) { - aFirst = aIndexesF[iF]; - } else { - aFirst = aIndexPrev1 + 1; - - if (aEnd <= aFirst) { - return iF - 1; - } - } - - aIndexPrev1 = aIndexesF[iF]; - aIndexesF[iF] = aFirst + countCommonItemsF(aFirst + 1, aEnd, bF + aFirst - kF + 1, bEnd, isCommon); - } - return iMaxF; - } - - private static int extendPathsR(int d, int aStart, int bStart, int bR, IsCommon isCommon, int[] aIndexesR, int iMaxR) { - int iR = 0; - int kR = d; - int aFirst = aIndexesR[iR]; - int aIndexPrev1 = aFirst; - aIndexesR[iR] -= countCommonItemsR(aStart, aFirst - 1, bStart, bR + aFirst - kR - 1, isCommon); - - int nR = Math.min(d, iMaxR); - - for (iR += 1, kR -= 2; iR <= nR; iR += 1, kR -= 2) { - if (iR != d && aIndexesR[iR] < aIndexPrev1) { - aFirst = aIndexesR[iR]; - } else { - aFirst = aIndexPrev1 - 1; - - if (aFirst < aStart) { - return iR - 1; - } - } - - aIndexPrev1 = aIndexesR[iR]; - aIndexesR[iR] = aFirst - countCommonItemsR(aStart, aFirst - 1, bStart, bR + aFirst - kR - 1, isCommon); - } - return iMaxR; - } - - private static boolean extendOverlappablePathsF(int d, int aStart, int aEnd, int bStart, int bEnd, IsCommon isCommon, int[] aIndexesF, int iMaxF, int[] aIndexesR, int iMaxR, Division division) { - int bF = bStart - aStart; - int aLength = aEnd - aStart; - int bLength = bEnd - bStart; - int baDeltaLength = bLength - aLength; - - int kMinOverlapF = -baDeltaLength - (d - 1); - int kMaxOverlapF = -baDeltaLength + (d - 1); - - int aIndexPrev1 = NOT_YET_SET; - - int nF = Math.min(d, iMaxF); - - for (int iF = 0, kF = -d; iF <= nF; iF += 1, kF += 2) { - boolean insert = iF == 0 || iF != d && aIndexPrev1 < aIndexesF[iF]; - int aLastPrev = insert ? aIndexesF[iF] : aIndexPrev1; - int aFirst = insert ? aLastPrev - : aLastPrev + 1; - - int bFirst = bF + aFirst - kF; - int nCommonF = countCommonItemsF(aFirst + 1, aEnd, bFirst + 1, bEnd, isCommon); - int aLast = aFirst + nCommonF; - aIndexPrev1 = aIndexesF[iF]; - aIndexesF[iF] = aLast; - if (kMinOverlapF <= kF && kF <= kMaxOverlapF) { - int iR = (d - 1 - (kF + baDeltaLength)) / 2; - - if (iR <= iMaxR && aIndexesR[iR] - 1 <= aLast) { - int bLastPrev = bF + aLastPrev - (insert ? kF + 1 : kF - 1); - - int nCommonR = countCommonItemsR(aStart, aLastPrev, bStart, bLastPrev, isCommon); - int aIndexPrevFirst = aLastPrev - nCommonR; - int bIndexPrevFirst = bLastPrev - nCommonR; - int aEndPreceding = aIndexPrevFirst + 1; - int bEndPreceding = bIndexPrevFirst + 1; - division.nChangePreceding = d - 1; - if (d - 1 == aEndPreceding + bEndPreceding - aStart - bStart) { - division.aEndPreceding = aStart; - division.bEndPreceding = bStart; - } else { - division.aEndPreceding = aEndPreceding; - division.bEndPreceding = bEndPreceding; - } - division.nCommonPreceding = nCommonR; - if (nCommonR != 0) { - division.aCommonPreceding = aEndPreceding; - division.bCommonPreceding = bEndPreceding; - } - division.nCommonFollowing = nCommonF; - if (nCommonF != 0) { - division.aCommonFollowing = aFirst + 1; - division.bCommonFollowing = bFirst + 1; - } - int aStartFollowing = aLast + 1; - int bStartFollowing = bFirst + nCommonF + 1; - division.nChangeFollowing = d - 1; - if (d - 1 == aEnd + bEnd - aStartFollowing - bStartFollowing) { - division.aStartFollowing = aEnd; - division.bStartFollowing = bEnd; - } else { - division.aStartFollowing = aStartFollowing; - division.bStartFollowing = bStartFollowing; - } - return true; - } - } - } - return false; - } - - private static boolean extendOverlappablePathsR(int d, int aStart, int aEnd, int bStart, int bEnd, IsCommon isCommon, int[] aIndexesF, int iMaxF, int[] aIndexesR, int iMaxR, Division division) { - int bR = bEnd - aEnd; - int aLength = aEnd - aStart; - int bLength = bEnd - bStart; - int baDeltaLength = bLength - aLength; - - int kMinOverlapR = baDeltaLength - d; - int kMaxOverlapR = baDeltaLength + d; - - int aIndexPrev1 = NOT_YET_SET; - - int nR = Math.min(d, iMaxR); - - for (int iR = 0, kR = d; iR <= nR; iR += 1, kR -= 2) { - boolean insert = iR == 0 || iR != d && aIndexesR[iR] < aIndexPrev1; - int aLastPrev = insert ? aIndexesR[iR] : aIndexPrev1; - int aFirst = insert ? aLastPrev - : aLastPrev - 1; - - int bFirst = bR + aFirst - kR; - int nCommonR = countCommonItemsR(aStart, aFirst - 1, bStart, bFirst - 1, isCommon); - int aLast = aFirst - nCommonR; - aIndexPrev1 = aIndexesR[iR]; - aIndexesR[iR] = aLast; - if (kMinOverlapR <= kR && kR <= kMaxOverlapR) { - int iF = (d + (kR - baDeltaLength)) / 2; - - if (iF <= iMaxF && aLast - 1 <= aIndexesF[iF]) { - int bLast = bFirst - nCommonR; - division.nChangePreceding = d; - if (d == aLast + bLast - aStart - bStart) { - division.aEndPreceding = aStart; - division.bEndPreceding = bStart; - } else { - division.aEndPreceding = aLast; - division.bEndPreceding = bLast; - } - division.nCommonPreceding = nCommonR; - if (nCommonR != 0) { - division.aCommonPreceding = aLast; - division.bCommonPreceding = bLast; - } - division.nChangeFollowing = d - 1; - if (d == 1) { - division.nCommonFollowing = 0; - division.aStartFollowing = aEnd; - division.bStartFollowing = bEnd; - } else { - int bLastPrev = bR + aLastPrev - (insert ? kR - 1 : kR + 1); - - int nCommonF = countCommonItemsF(aLastPrev, aEnd, bLastPrev, bEnd, isCommon); - division.nCommonFollowing = nCommonF; - if (nCommonF != 0) { - division.aCommonFollowing = aLastPrev; - division.bCommonFollowing = bLastPrev; - } - int aStartFollowing = aLastPrev + nCommonF; - int bStartFollowing = bLastPrev + nCommonF; - - if (d - 1 == aEnd + bEnd - aStartFollowing - bStartFollowing) { - division.aStartFollowing = aEnd; - division.bStartFollowing = bEnd; - } else { - division.aStartFollowing = aStartFollowing; - division.bStartFollowing = bStartFollowing; - } - } - return true; - } - } - } - return false; - } - - private static void divide(int nChange, int aStart, int aEnd, int bStart, int bEnd, IsCommon isCommon, int[] aIndexesF, int[] aIndexesR, Division division) { - int bF = bStart - aStart; - int bR = bEnd - aEnd; - int aLength = aEnd - aStart; - int bLength = bEnd - bStart; - - int baDeltaLength = bLength - aLength; - - int iMaxF = aLength; - int iMaxR = aLength; - - aIndexesF[0] = aStart - 1; - aIndexesR[0] = aEnd; - - if (baDeltaLength % 2 == 0) { - int dMin = (nChange != 0 ? nChange : baDeltaLength) / 2; - int dMax = (aLength + bLength) / 2; - for (int d = 1; d <= dMax; d += 1) { - iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); - if (d < dMin) { - iMaxR = extendPathsR(d, aStart, bStart, bR, isCommon, aIndexesR, iMaxR); - } else if ( - extendOverlappablePathsR(d, aStart, aEnd, bStart, bEnd, isCommon, aIndexesF, iMaxF, aIndexesR, iMaxR, division)) { - return; - } - } - } else { - int dMin = ((nChange != 0 ? nChange : baDeltaLength) + 1) / 2; - int dMax = (aLength + bLength + 1) / 2; - - int d = 1; - iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); - for (d += 1; d <= dMax; d += 1) { - iMaxR = extendPathsR(d - 1, aStart, bStart, bR, isCommon, aIndexesR, iMaxR); - if (d < dMin) { - iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); - } else if ( - extendOverlappablePathsF(d, aStart, aEnd, bStart, bEnd, isCommon, aIndexesF, iMaxF, aIndexesR, iMaxR, division)) { - return; - } - } - } - - throw new PlaywrightException(pkg + ": no overlap aStart=" + aStart + " aEnd=" + aEnd + " bStart=" + bStart + " bEnd=" + bEnd); - } - - private static void findSubsequences(int nChange, int aStart, int aEnd, int bStart, int bEnd, boolean transposed, Callbacks[] callbacks, int[] aIndexesF, int[] aIndexesR, Division division) { - if (bEnd - bStart < aEnd - aStart) { - transposed = !transposed; - // java: the callbacks array has two slots, the second one is null until it is set. - if (transposed && callbacks[1] == null) { - FoundSubsequence foundSubsequence = callbacks[0].foundSubsequence; - IsCommon isCommon = callbacks[0].isCommon; - callbacks[1] = new Callbacks( - (nCommon, bCommon, aCommon) -> { - foundSubsequence.foundSubsequence(nCommon, aCommon, bCommon); - }, - (bIndex, aIndex) -> isCommon.isCommon(aIndex, bIndex)); - } - int tStart = aStart; - int tEnd = aEnd; - aStart = bStart; - aEnd = bEnd; - bStart = tStart; - bEnd = tEnd; - } - FoundSubsequence foundSubsequence = callbacks[transposed ? 1 : 0].foundSubsequence; - IsCommon isCommon = callbacks[transposed ? 1 : 0].isCommon; - - divide(nChange, aStart, aEnd, bStart, bEnd, isCommon, aIndexesF, aIndexesR, division); - int nChangePreceding = division.nChangePreceding; - int aEndPreceding = division.aEndPreceding; - int bEndPreceding = division.bEndPreceding; - int nCommonPreceding = division.nCommonPreceding; - int aCommonPreceding = division.aCommonPreceding; - int bCommonPreceding = division.bCommonPreceding; - int nCommonFollowing = division.nCommonFollowing; - int aCommonFollowing = division.aCommonFollowing; - int bCommonFollowing = division.bCommonFollowing; - int nChangeFollowing = division.nChangeFollowing; - int aStartFollowing = division.aStartFollowing; - int bStartFollowing = division.bStartFollowing; - - if (aStart < aEndPreceding && bStart < bEndPreceding) { - findSubsequences(nChangePreceding, aStart, aEndPreceding, bStart, bEndPreceding, transposed, callbacks, aIndexesF, aIndexesR, division); - } - - if (nCommonPreceding != 0) { - foundSubsequence.foundSubsequence(nCommonPreceding, aCommonPreceding, bCommonPreceding); - } - if (nCommonFollowing != 0) { - foundSubsequence.foundSubsequence(nCommonFollowing, aCommonFollowing, bCommonFollowing); - } - - if (aStartFollowing < aEnd && bStartFollowing < bEnd) { - findSubsequences(nChangeFollowing, aStartFollowing, aEnd, bStartFollowing, bEnd, transposed, callbacks, aIndexesF, aIndexesR, division); - } - } - - // java: validateLength and validateCallback are not ported, the Java types make these checks. - - static void diffSequence(int aLength, int bLength, IsCommon isCommon, FoundSubsequence foundSubsequence) { - int nCommonF = countCommonItemsF(0, aLength, 0, bLength, isCommon); - if (nCommonF != 0) { - foundSubsequence.foundSubsequence(nCommonF, 0, 0); - } - - if (aLength != nCommonF || bLength != nCommonF) { - int aStart = nCommonF; - int bStart = nCommonF; - - int nCommonR = countCommonItemsR(aStart, aLength - 1, bStart, bLength - 1, isCommon); - - int aEnd = aLength - nCommonR; - int bEnd = bLength - nCommonR; - - int nCommonFR = nCommonF + nCommonR; - if (aLength != nCommonFR && bLength != nCommonFR) { - int nChange = 0; - boolean transposed = false; - Callbacks[] callbacks = new Callbacks[] {new Callbacks(foundSubsequence, isCommon), null}; - - // java: a JavaScript array grows on assignment. The paths use the indexes from zero - // to the length of the shorter sequence, the Java arrays have that size from the start. - int[] aIndexesF = new int[Math.min(aEnd - aStart, bEnd - bStart) + 1]; - int[] aIndexesR = new int[Math.min(aEnd - aStart, bEnd - bStart) + 1]; - - Division division = new Division(); - - findSubsequences(nChange, aStart, aEnd, bStart, bEnd, transposed, callbacks, aIndexesF, aIndexesR, division); - } - if (nCommonR != 0) { - foundSubsequence.foundSubsequence(nCommonR, aEnd, bEnd); - } - } - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java index 05e29d3b2..ba40b4617 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java @@ -943,8 +943,8 @@ FrameExpectResult expect(String expression, FrameExpectOptions options) { FrameExpectResult.ExpectReceived received = null; if (details.received != null) { received = new FrameExpectResult.ExpectReceived(); - // java: an undefined value is JestGetType.UNDEFINED, null is the JavaScript null. - received.value = details.received.value != null && !"undefined".equals(details.received.value.v) ? parseResult(details.received.value) : JestGetType.UNDEFINED; + // 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(); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/JestDiff.java b/playwright/src/main/java/com/microsoft/playwright/impl/JestDiff.java deleted file mode 100644 index 0bb32bf23..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/JestDiff.java +++ /dev/null @@ -1,1234 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Port of jest-diff. -// java: the original is MIT licensed, Copyright (c) Meta Platforms, Inc. and affiliates. -// java: cleanupSemantic.ts is from Diff Match and Patch, Copyright 2018 The diff-match-patch Authors, -// https://github.com/google/diff-match-patch, licensed under the Apache License, Version 2.0. -// java: the upstream files are in one class, in the order of the bundle: cleanupSemantic.ts, -// constants.ts, diffLines.ts, diffStrings.ts, escapeControlCharacters.ts, getAlignedDiffs.ts, -// joinAlignedDiffs.ts, normalizeDiffOptions.ts, printDiffs.ts, index.ts. -package com.microsoft.playwright.impl; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.microsoft.playwright.impl.DiffSequences.diffSequence; -import static com.microsoft.playwright.impl.JestGetType.getType; - -class JestDiff { - // java: no ANSI colors, the color functions return the text as is. - static class Chalk { - static String green(String text) { - return text; - } - - static String red(String text) { - return text; - } - - static String inverse(String text) { - return text; - } - - static String bold(String text) { - return text; - } - - static String dim(String text) { - return text; - } - - static String yellow(String text) { - return text; - } - - static String bgYellow(String text) { - return text; - } - } - - // java: the type of the options object. A null field is an option that is not set. - static class DiffOptions { - String aAnnotation; - Function aColor; - String aIndicator; - String bAnnotation; - Function bColor; - String bIndicator; - Function changeColor; - Function changeLineTrailingSpaceColor; - Function commonColor; - String commonIndicator; - Function commonLineTrailingSpaceColor; - Comparator compareKeys; - Integer contextLines; - String emptyFirstOrLastLinePlaceholder; - Boolean expand; - Boolean includeChangeCounts; - Boolean omitAnnotationLines; - Function patchColor; - } - - // java: the type of the result of countChanges. - private static class ChangeCounts { - int a; - int b; - } - - // java: helpers with no counterpart upstream, the ports of String.prototype.substring and - // String.prototype.charAt. They accept an index that is out of the string, as JavaScript does. - private static String substring(String string, int start) { - return substring(string, start, string.length()); - } - - private static String substring(String string, int start, int end) { - start = Math.max(0, Math.min(start, string.length())); - end = Math.max(0, Math.min(end, string.length())); - return string.substring(Math.min(start, end), Math.max(start, end)); - } - - private static String charAt(String string, int index) { - return index < 0 || index >= string.length() ? "" : string.substring(index, index + 1); - } - - // java: helper with no counterpart upstream, the port of String.prototype.repeat. - private static String repeat(String string, int count) { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < count; i++) { - result.append(string); - } - return result.toString(); - } - - // java: helper with no counterpart upstream, the port of String.prototype.split: it keeps - // the empty strings at the end. - private static List split(String string, String separator) { - return new ArrayList<>(Arrays.asList(string.split(Pattern.quote(separator), -1))); - } - - // java: the whitespace characters of \s in a JavaScript regular expression. \s in Java - // matches the ASCII whitespace only. - static final String WHITESPACE = "[\\t\\n\\x0B\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]"; - - static final int DIFF_DELETE = -1; - static final int DIFF_INSERT = 1; - static final int DIFF_EQUAL = 0; - - // java: the items 0 and 1 of upstream are the fields op and text. - static class Diff { - int op; - String text; - - Diff(int op, String text) { - this.op = op; - this.text = text; - } - } - - private static int diff_commonPrefix(String text1, String text2) { - if (text1.isEmpty() || text2.isEmpty() || text1.charAt(0) != text2.charAt(0)) { - return 0; - } - int pointermin = 0; - int pointermax = Math.min(text1.length(), text2.length()); - int pointermid = pointermax; - int pointerstart = 0; - while (pointermin < pointermid) { - if (substring(text1, pointerstart, pointermid).equals(substring(text2, pointerstart, pointermid))) { - pointermin = pointermid; - pointerstart = pointermin; - } else { - pointermax = pointermid; - } - pointermid = (pointermax - pointermin) / 2 + pointermin; - } - return pointermid; - } - - private static int diff_commonSuffix(String text1, String text2) { - if (text1.isEmpty() || text2.isEmpty() || text1.charAt(text1.length() - 1) != text2.charAt(text2.length() - 1)) { - return 0; - } - int pointermin = 0; - int pointermax = Math.min(text1.length(), text2.length()); - int pointermid = pointermax; - int pointerend = 0; - while (pointermin < pointermid) { - if (substring(text1, text1.length() - pointermid, text1.length() - pointerend).equals(substring(text2, text2.length() - pointermid, text2.length() - pointerend))) { - pointermin = pointermid; - pointerend = pointermin; - } else { - pointermax = pointermid; - } - pointermid = (pointermax - pointermin) / 2 + pointermin; - } - return pointermid; - } - - private static int diff_commonOverlap_(String text1, String text2) { - int text1_length = text1.length(); - int text2_length = text2.length(); - if (text1_length == 0 || text2_length == 0) { - return 0; - } - if (text1_length > text2_length) { - text1 = substring(text1, text1_length - text2_length); - } else if (text1_length < text2_length) { - text2 = substring(text2, 0, text1_length); - } - int text_length = Math.min(text1_length, text2_length); - if (text1.equals(text2)) { - return text_length; - } - - int best = 0; - int length = 1; - while (true) { - String pattern = substring(text1, text_length - length); - int found = text2.indexOf(pattern); - if (found == -1) { - return best; - } - length += found; - if (found == 0 || substring(text1, text_length - length).equals(substring(text2, 0, length))) { - best = length; - length++; - } - } - } - - static void diff_cleanupSemantic(List diffs) { - boolean changes = false; - // java: the stack is a map, because upstream decreases equalitiesLength below zero and - // then writes and reads the property -1 of the JavaScript array. - Map equalities = new HashMap<>(); - int equalitiesLength = 0; - String lastEquality = null; - int pointer = 0; - int length_insertions1 = 0; - int length_deletions1 = 0; - int length_insertions2 = 0; - int length_deletions2 = 0; - while (pointer < diffs.size()) { - if (diffs.get(pointer).op == DIFF_EQUAL) { - equalities.put(equalitiesLength++, pointer); - length_insertions1 = length_insertions2; - length_deletions1 = length_deletions2; - length_insertions2 = 0; - length_deletions2 = 0; - lastEquality = diffs.get(pointer).text; - } else { - if (diffs.get(pointer).op == DIFF_INSERT) { - length_insertions2 += diffs.get(pointer).text.length(); - } else { - length_deletions2 += diffs.get(pointer).text.length(); - } - if (lastEquality != null && !lastEquality.isEmpty() && lastEquality.length() <= Math.max(length_insertions1, length_deletions1) && lastEquality.length() <= Math.max(length_insertions2, length_deletions2)) { - diffs.add(equalities.get(equalitiesLength - 1), new Diff(DIFF_DELETE, lastEquality)); - diffs.get(equalities.get(equalitiesLength - 1) + 1).op = DIFF_INSERT; - equalitiesLength--; - equalitiesLength--; - pointer = equalitiesLength > 0 ? equalities.get(equalitiesLength - 1) : -1; - length_insertions1 = 0; - length_deletions1 = 0; - length_insertions2 = 0; - length_deletions2 = 0; - lastEquality = null; - changes = true; - } - } - pointer++; - } - - if (changes) { - diff_cleanupMerge(diffs); - } - diff_cleanupSemanticLossless(diffs); - - pointer = 1; - while (pointer < diffs.size()) { - if (diffs.get(pointer - 1).op == DIFF_DELETE && diffs.get(pointer).op == DIFF_INSERT) { - String deletion = diffs.get(pointer - 1).text; - String insertion = diffs.get(pointer).text; - int overlap_length1 = diff_commonOverlap_(deletion, insertion); - int overlap_length2 = diff_commonOverlap_(insertion, deletion); - if (overlap_length1 >= overlap_length2) { - if (overlap_length1 >= deletion.length() / 2.0 || overlap_length1 >= insertion.length() / 2.0) { - diffs.add(pointer, new Diff(DIFF_EQUAL, substring(insertion, 0, overlap_length1))); - diffs.get(pointer - 1).text = substring(deletion, 0, deletion.length() - overlap_length1); - diffs.get(pointer + 1).text = substring(insertion, overlap_length1); - pointer++; - } - } else { - if (overlap_length2 >= deletion.length() / 2.0 || overlap_length2 >= insertion.length() / 2.0) { - diffs.add(pointer, new Diff(DIFF_EQUAL, substring(deletion, 0, overlap_length2))); - diffs.get(pointer - 1).op = DIFF_INSERT; - diffs.get(pointer - 1).text = substring(insertion, 0, insertion.length() - overlap_length2); - diffs.get(pointer + 1).op = DIFF_DELETE; - diffs.get(pointer + 1).text = substring(deletion, overlap_length2); - pointer++; - } - } - pointer++; - } - pointer++; - } - } - - // java: diff_cleanupSemanticScore_ is a function inside of diff_cleanupSemanticLossless upstream. - private static int diff_cleanupSemanticScore_(String one, String two) { - if (one.isEmpty() || two.isEmpty()) { - return 6; - } - - String char1 = charAt(one, one.length() - 1); - String char2 = charAt(two, 0); - boolean nonAlphaNumeric1 = nonAlphaNumericRegex_.matcher(char1).find(); - boolean nonAlphaNumeric2 = nonAlphaNumericRegex_.matcher(char2).find(); - boolean whitespace1 = nonAlphaNumeric1 && whitespaceRegex_.matcher(char1).find(); - boolean whitespace2 = nonAlphaNumeric2 && whitespaceRegex_.matcher(char2).find(); - boolean lineBreak1 = whitespace1 && linebreakRegex_.matcher(char1).find(); - boolean lineBreak2 = whitespace2 && linebreakRegex_.matcher(char2).find(); - boolean blankLine1 = lineBreak1 && blanklineEndRegex_.matcher(one).find(); - boolean blankLine2 = lineBreak2 && blanklineStartRegex_.matcher(two).find(); - if (blankLine1 || blankLine2) { - return 5; - } else if (lineBreak1 || lineBreak2) { - return 4; - } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { - return 3; - } else if (whitespace1 || whitespace2) { - return 2; - } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { - return 1; - } - return 0; - } - - private static void diff_cleanupSemanticLossless(List diffs) { - int pointer = 1; - while (pointer < diffs.size() - 1) { - if (diffs.get(pointer - 1).op == DIFF_EQUAL && diffs.get(pointer + 1).op == DIFF_EQUAL) { - String equality1 = diffs.get(pointer - 1).text; - String edit = diffs.get(pointer).text; - String equality2 = diffs.get(pointer + 1).text; - - int commonOffset = diff_commonSuffix(equality1, edit); - if (commonOffset != 0) { - String commonString = substring(edit, edit.length() - commonOffset); - equality1 = substring(equality1, 0, equality1.length() - commonOffset); - edit = commonString + substring(edit, 0, edit.length() - commonOffset); - equality2 = commonString + equality2; - } - - String bestEquality1 = equality1; - String bestEdit = edit; - String bestEquality2 = equality2; - int bestScore = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); - while (charAt(edit, 0).equals(charAt(equality2, 0))) { - equality1 += charAt(edit, 0); - edit = substring(edit, 1) + charAt(equality2, 0); - equality2 = substring(equality2, 1); - int score = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); - if (score >= bestScore) { - bestScore = score; - bestEquality1 = equality1; - bestEdit = edit; - bestEquality2 = equality2; - } - } - if (!diffs.get(pointer - 1).text.equals(bestEquality1)) { - if (!bestEquality1.isEmpty()) { - diffs.get(pointer - 1).text = bestEquality1; - } else { - diffs.remove(pointer - 1); - pointer--; - } - diffs.get(pointer).text = bestEdit; - if (!bestEquality2.isEmpty()) { - diffs.get(pointer + 1).text = bestEquality2; - } else { - diffs.remove(pointer + 1); - pointer--; - } - } - } - pointer++; - } - } - - private static final Pattern nonAlphaNumericRegex_ = Pattern.compile("[^a-zA-Z0-9]"); - private static final Pattern whitespaceRegex_ = Pattern.compile(WHITESPACE); - private static final Pattern linebreakRegex_ = Pattern.compile("[\\r\\n]"); - // java: \z is the end of the string. $ in Java matches before a line terminator at the end too. - private static final Pattern blanklineEndRegex_ = Pattern.compile("\\n\\r?\\n\\z"); - private static final Pattern blanklineStartRegex_ = Pattern.compile("^\\r?\\n\\r?\\n"); - - private static void diff_cleanupMerge(List diffs) { - diffs.add(new Diff(DIFF_EQUAL, "")); - int pointer = 0; - int count_delete = 0; - int count_insert = 0; - String text_delete = ""; - String text_insert = ""; - int commonlength; - while (pointer < diffs.size()) { - switch (diffs.get(pointer).op) { - case DIFF_INSERT: - count_insert++; - text_insert += diffs.get(pointer).text; - pointer++; - break; - case DIFF_DELETE: - count_delete++; - text_delete += diffs.get(pointer).text; - pointer++; - break; - case DIFF_EQUAL: - if (count_delete + count_insert > 1) { - if (count_delete != 0 && count_insert != 0) { - commonlength = diff_commonPrefix(text_insert, text_delete); - if (commonlength != 0) { - if (pointer - count_delete - count_insert > 0 && diffs.get(pointer - count_delete - count_insert - 1).op == DIFF_EQUAL) { - diffs.get(pointer - count_delete - count_insert - 1).text += substring(text_insert, 0, commonlength); - } else { - diffs.add(0, new Diff(DIFF_EQUAL, substring(text_insert, 0, commonlength))); - pointer++; - } - text_insert = substring(text_insert, commonlength); - text_delete = substring(text_delete, commonlength); - } - commonlength = diff_commonSuffix(text_insert, text_delete); - if (commonlength != 0) { - diffs.get(pointer).text = substring(text_insert, text_insert.length() - commonlength) + diffs.get(pointer).text; - text_insert = substring(text_insert, 0, text_insert.length() - commonlength); - text_delete = substring(text_delete, 0, text_delete.length() - commonlength); - } - } - pointer -= count_delete + count_insert; - // java: splice(pointer, n) removes n items. - for (int i = 0; i < count_delete + count_insert; i++) { - diffs.remove(pointer); - } - if (text_delete.length() != 0) { - diffs.add(pointer, new Diff(DIFF_DELETE, text_delete)); - pointer++; - } - if (text_insert.length() != 0) { - diffs.add(pointer, new Diff(DIFF_INSERT, text_insert)); - pointer++; - } - pointer++; - } else if (pointer != 0 && diffs.get(pointer - 1).op == DIFF_EQUAL) { - diffs.get(pointer - 1).text += diffs.get(pointer).text; - diffs.remove(pointer); - } else { - pointer++; - } - count_insert = 0; - count_delete = 0; - text_delete = ""; - text_insert = ""; - break; - } - } - if (diffs.get(diffs.size() - 1).text.equals("")) { - diffs.remove(diffs.size() - 1); - } - - boolean changes = false; - pointer = 1; - while (pointer < diffs.size() - 1) { - if (diffs.get(pointer - 1).op == DIFF_EQUAL && diffs.get(pointer + 1).op == DIFF_EQUAL) { - if (substring(diffs.get(pointer).text, diffs.get(pointer).text.length() - diffs.get(pointer - 1).text.length()).equals(diffs.get(pointer - 1).text)) { - diffs.get(pointer).text = diffs.get(pointer - 1).text + substring(diffs.get(pointer).text, 0, diffs.get(pointer).text.length() - diffs.get(pointer - 1).text.length()); - diffs.get(pointer + 1).text = diffs.get(pointer - 1).text + diffs.get(pointer + 1).text; - diffs.remove(pointer - 1); - changes = true; - } else if (substring(diffs.get(pointer).text, 0, diffs.get(pointer + 1).text.length()).equals(diffs.get(pointer + 1).text)) { - diffs.get(pointer - 1).text += diffs.get(pointer + 1).text; - diffs.get(pointer).text = substring(diffs.get(pointer).text, diffs.get(pointer + 1).text.length()) + diffs.get(pointer + 1).text; - diffs.remove(pointer + 1); - changes = true; - } - } - pointer++; - } - if (changes) { - diff_cleanupMerge(diffs); - } - } - - static final String NO_DIFF_MESSAGE = "Compared values have no visual difference."; - static final String SIMILAR_MESSAGE = "Compared values serialize to the same structure.\n" + "Printing internal object structure without calling `toJSON` instead."; - - private static boolean isEmptyString(List lines) { - return lines.size() == 1 && lines.get(0).length() == 0; - } - - private static ChangeCounts countChanges(List diffs) { - int a = 0; - int b = 0; - for (Diff diff : diffs) { - switch (diff.op) { - case DIFF_DELETE: - a += 1; - break; - case DIFF_INSERT: - b += 1; - break; - } - } - ChangeCounts changeCounts = new ChangeCounts(); - changeCounts.a = a; - changeCounts.b = b; - return changeCounts; - } - - private static String printAnnotation(DiffOptions options, ChangeCounts changeCounts) { - String aAnnotation = options.aAnnotation; - Function aColor = options.aColor; - String aIndicator = options.aIndicator; - String bAnnotation = options.bAnnotation; - Function bColor = options.bColor; - String bIndicator = options.bIndicator; - boolean includeChangeCounts = options.includeChangeCounts; - boolean omitAnnotationLines = options.omitAnnotationLines; - if (omitAnnotationLines) { - return ""; - } - String aRest = ""; - String bRest = ""; - if (includeChangeCounts) { - String aCount = String.valueOf(changeCounts.a); - String bCount = String.valueOf(changeCounts.b); - - int baAnnotationLengthDiff = bAnnotation.length() - aAnnotation.length(); - String aAnnotationPadding = repeat(" ", Math.max(0, baAnnotationLengthDiff)); - String bAnnotationPadding = repeat(" ", Math.max(0, -baAnnotationLengthDiff)); - - int baCountLengthDiff = bCount.length() - aCount.length(); - String aCountPadding = repeat(" ", Math.max(0, baCountLengthDiff)); - String bCountPadding = repeat(" ", Math.max(0, -baCountLengthDiff)); - aRest = aAnnotationPadding + " " + aIndicator + " " + aCountPadding + aCount; - bRest = bAnnotationPadding + " " + bIndicator + " " + bCountPadding + bCount; - } - String a = aIndicator + " " + aAnnotation + aRest; - String b = bIndicator + " " + bAnnotation + bRest; - return aColor.apply(a) + "\n" + bColor.apply(b) + "\n\n"; - } - - static String printDiffLines(List diffs, DiffOptions options) { - return printAnnotation(options, countChanges(diffs)) + (options.expand ? joinAlignedDiffsExpand(diffs, options) : joinAlignedDiffsNoExpand(diffs, options)); - } - - static String diffLinesUnified(List aLines, List bLines, DiffOptions options) { - return printDiffLines(diffLinesRaw(isEmptyString(aLines) ? new ArrayList<>() : map(aLines, JestDiff::escapeControlCharacters), isEmptyString(bLines) ? new ArrayList<>() : map(bLines, JestDiff::escapeControlCharacters)), normalizeDiffOptions(options)); - } - - // java: helper with no counterpart upstream, the port of Array.prototype.map. - private static List map(List lines, Function callback) { - List result = new ArrayList<>(); - for (String line : lines) { - result.add(callback.apply(line)); - } - return result; - } - - static String diffLinesUnified2(List aLinesDisplay, List bLinesDisplay, List aLinesCompare, List bLinesCompare, DiffOptions options) { - if (isEmptyString(aLinesDisplay) && isEmptyString(aLinesCompare)) { - aLinesDisplay = new ArrayList<>(); - aLinesCompare = new ArrayList<>(); - } - if (isEmptyString(bLinesDisplay) && isEmptyString(bLinesCompare)) { - bLinesDisplay = new ArrayList<>(); - bLinesCompare = new ArrayList<>(); - } - if (aLinesDisplay.size() != aLinesCompare.size() || bLinesDisplay.size() != bLinesCompare.size()) { - return diffLinesUnified(aLinesDisplay, bLinesDisplay, options); - } - List diffs = diffLinesRaw(aLinesCompare, bLinesCompare); - - int aIndex = 0; - int bIndex = 0; - for (Diff diff : diffs) { - switch (diff.op) { - case DIFF_DELETE: - diff.text = aLinesDisplay.get(aIndex); - aIndex += 1; - break; - case DIFF_INSERT: - diff.text = bLinesDisplay.get(bIndex); - bIndex += 1; - break; - default: - diff.text = bLinesDisplay.get(bIndex); - aIndex += 1; - bIndex += 1; - } - } - return printDiffLines(diffs, normalizeDiffOptions(options)); - } - - static List diffLinesRaw(List aLines, List bLines) { - int aLength = aLines.size(); - int bLength = bLines.size(); - DiffSequences.IsCommon isCommon = (aIndex, bIndex) -> aLines.get(aIndex).equals(bLines.get(bIndex)); - List diffs = new ArrayList<>(); - // java: a lambda cannot assign a local variable, aIndex and bIndex are arrays of one item. - int[] aIndex = {0}; - int[] bIndex = {0}; - DiffSequences.FoundSubsequence foundSubsequence = (nCommon, aCommon, bCommon) -> { - for (; aIndex[0] != aCommon; aIndex[0] += 1) { - diffs.add(new Diff(DIFF_DELETE, aLines.get(aIndex[0]))); - } - for (; bIndex[0] != bCommon; bIndex[0] += 1) { - diffs.add(new Diff(DIFF_INSERT, bLines.get(bIndex[0]))); - } - for (; nCommon != 0; nCommon -= 1, aIndex[0] += 1, bIndex[0] += 1) { - diffs.add(new Diff(DIFF_EQUAL, bLines.get(bIndex[0]))); - } - }; - diffSequence(aLength, bLength, isCommon, foundSubsequence); - - for (; aIndex[0] != aLength; aIndex[0] += 1) { - diffs.add(new Diff(DIFF_DELETE, aLines.get(aIndex[0]))); - } - for (; bIndex[0] != bLength; bIndex[0] += 1) { - diffs.add(new Diff(DIFF_INSERT, bLines.get(bIndex[0]))); - } - return diffs; - } - - private static List diffStrings(String a, String b) { - DiffSequences.IsCommon isCommon = (aIndex, bIndex) -> a.charAt(aIndex) == b.charAt(bIndex); - // java: a lambda cannot assign a local variable, aIndex and bIndex are arrays of one item. - int[] aIndex = {0}; - int[] bIndex = {0}; - List diffs = new ArrayList<>(); - DiffSequences.FoundSubsequence foundSubsequence = (nCommon, aCommon, bCommon) -> { - if (aIndex[0] != aCommon) { - diffs.add(new Diff(DIFF_DELETE, a.substring(aIndex[0], aCommon))); - } - if (bIndex[0] != bCommon) { - diffs.add(new Diff(DIFF_INSERT, b.substring(bIndex[0], bCommon))); - } - aIndex[0] = aCommon + nCommon; - bIndex[0] = bCommon + nCommon; - diffs.add(new Diff(DIFF_EQUAL, b.substring(bCommon, bIndex[0]))); - }; - diffSequence(a.length(), b.length(), isCommon, foundSubsequence); - - if (aIndex[0] != a.length()) { - diffs.add(new Diff(DIFF_DELETE, a.substring(aIndex[0]))); - } - if (bIndex[0] != b.length()) { - diffs.add(new Diff(DIFF_INSERT, b.substring(bIndex[0]))); - } - return diffs; - } - - private static final Pattern controlCharactersRegex = Pattern.compile("[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F-\\u009F]"); - - static String escapeControlCharacters(String str) { - // java: replaceAll with a callback is a loop over the matches. - Matcher matcher = controlCharactersRegex.matcher(str); - StringBuffer result = new StringBuffer(); - while (matcher.find()) { - String match = matcher.group(); - String replacement; - switch (match) { - case "\b": - replacement = "\\b"; - break; - case "\f": - replacement = "\\f"; - break; - case "\u000B": - replacement = "\\v"; - break; - default: { - int code = match.codePointAt(0); - replacement = "\\x" + (code < 16 ? "0" : "") + Integer.toString(code, 16); - } - } - matcher.appendReplacement(result, Matcher.quoteReplacement(replacement)); - } - matcher.appendTail(result); - return result.toString(); - } - - private static String concatenateRelevantDiffs(int op, List diffs, Function changeColor) { - String reduced = ""; - for (Diff diff : diffs) { - reduced = reduced + (diff.op == DIFF_EQUAL ? diff.text : diff.op == op && diff.text.length() > 0 - ? changeColor.apply(diff.text) : ""); - } - return reduced; - } - - private static class ChangeBuffer { - int op; - List line; - List lines; - Function changeColor; - - ChangeBuffer(int op, Function changeColor) { - this.op = op; - this.line = new ArrayList<>(); - this.lines = new ArrayList<>(); - this.changeColor = changeColor; - } - - void pushSubstring(String substring) { - this.pushDiff(new Diff(this.op, substring)); - } - - void pushLine() { - this.lines.add(this.line.size() == 1 ? this.line.get(0).op == this.op ? this.line.get(0) - : new Diff(this.op, this.line.get(0).text) : new Diff(this.op, concatenateRelevantDiffs(this.op, this.line, this.changeColor)) - ); - this.line.clear(); - } - - boolean isLineEmpty() { - return this.line.size() == 0; - } - - void pushDiff(Diff diff) { - this.line.add(diff); - } - - void align(Diff diff) { - String string = diff.text; - if (string.contains("\n")) { - List substrings = split(string, "\n"); - int iLast = substrings.size() - 1; - for (int i = 0; i < substrings.size(); i++) { - String substring = substrings.get(i); - if (i < iLast) { - this.pushSubstring(substring); - this.pushLine(); - } else if (substring.length() > 0) { - this.pushSubstring(substring); - } - } - } else { - this.pushDiff(diff); - } - } - - void moveLinesTo(List lines) { - if (!this.isLineEmpty()) { - this.pushLine(); - } - lines.addAll(this.lines); - this.lines.clear(); - } - } - - private static class CommonBuffer { - ChangeBuffer deleteBuffer; - ChangeBuffer insertBuffer; - List lines; - - CommonBuffer(ChangeBuffer deleteBuffer, ChangeBuffer insertBuffer) { - this.deleteBuffer = deleteBuffer; - this.insertBuffer = insertBuffer; - this.lines = new ArrayList<>(); - } - - void pushDiffCommonLine(Diff diff) { - this.lines.add(diff); - } - - void pushDiffChangeLines(Diff diff) { - boolean isDiffEmpty = diff.text.length() == 0; - - if (!isDiffEmpty || this.deleteBuffer.isLineEmpty()) { - this.deleteBuffer.pushDiff(diff); - } - if (!isDiffEmpty || this.insertBuffer.isLineEmpty()) { - this.insertBuffer.pushDiff(diff); - } - } - - void flushChangeLines() { - this.deleteBuffer.moveLinesTo(this.lines); - this.insertBuffer.moveLinesTo(this.lines); - } - - void align(Diff diff) { - int op = diff.op; - String string = diff.text; - if (string.contains("\n")) { - List substrings = split(string, "\n"); - int iLast = substrings.size() - 1; - for (int i = 0; i < substrings.size(); i++) { - String substring = substrings.get(i); - if (i == 0) { - Diff subdiff = new Diff(op, substring); - if (this.deleteBuffer.isLineEmpty() && this.insertBuffer.isLineEmpty()) { - this.flushChangeLines(); - this.pushDiffCommonLine(subdiff); - } else { - this.pushDiffChangeLines(subdiff); - this.flushChangeLines(); - } - } else if (i < iLast) { - this.pushDiffCommonLine(new Diff(op, substring)); - } else if (substring.length() > 0) { - this.pushDiffChangeLines(new Diff(op, substring)); - } - } - } else { - this.pushDiffChangeLines(diff); - } - } - - List getLines() { - this.flushChangeLines(); - return this.lines; - } - } - - private static List getAlignedDiffs(List diffs, Function changeColor) { - ChangeBuffer deleteBuffer = new ChangeBuffer(DIFF_DELETE, changeColor); - ChangeBuffer insertBuffer = new ChangeBuffer(DIFF_INSERT, changeColor); - CommonBuffer commonBuffer = new CommonBuffer(deleteBuffer, insertBuffer); - for (Diff diff : diffs) { - switch (diff.op) { - case DIFF_DELETE: - deleteBuffer.align(diff); - break; - case DIFF_INSERT: - insertBuffer.align(diff); - break; - default: - commonBuffer.align(diff); - } - } - return commonBuffer.getLines(); - } - - // java: \z is the end of the string. $ in Java matches before a line terminator at the end too. - private static final Pattern trailingSpacesRegex = Pattern.compile(WHITESPACE + "+\\z"); - - private static String formatTrailingSpaces(String line, Function trailingSpaceFormatter) { - // java: replace with a callback is the replacement of the first match. - Matcher matcher = trailingSpacesRegex.matcher(line); - if (!matcher.find()) { - return line; - } - return line.substring(0, matcher.start()) + trailingSpaceFormatter.apply(matcher.group()) + line.substring(matcher.end()); - } - - private static String printDiffLine(String line, boolean isFirstOrLast, Function color, String indicator, Function trailingSpaceFormatter, String emptyFirstOrLastLinePlaceholder) { - return line.length() == 0 ? indicator.equals(" ") ? isFirstOrLast && emptyFirstOrLastLinePlaceholder.length() > 0 ? color.apply(indicator + " " + emptyFirstOrLastLinePlaceholder) : "" : color.apply(indicator) : color.apply(indicator + " " + formatTrailingSpaces(line, trailingSpaceFormatter)); - } - - private static String printDeleteLine(String line, boolean isFirstOrLast, DiffOptions options) { - return printDiffLine(line, isFirstOrLast, options.aColor, options.aIndicator, options.changeLineTrailingSpaceColor, options.emptyFirstOrLastLinePlaceholder); - } - - private static String printInsertLine(String line, boolean isFirstOrLast, DiffOptions options) { - return printDiffLine(line, isFirstOrLast, options.bColor, options.bIndicator, options.changeLineTrailingSpaceColor, options.emptyFirstOrLastLinePlaceholder); - } - - private static String printCommonLine(String line, boolean isFirstOrLast, DiffOptions options) { - return printDiffLine(line, isFirstOrLast, options.commonColor, options.commonIndicator, options.commonLineTrailingSpaceColor, options.emptyFirstOrLastLinePlaceholder); - } - - private static String createPatchMark(int aStart, int aEnd, int bStart, int bEnd, DiffOptions options) { - return options.patchColor.apply("@@ -" + (aStart + 1) + "," + (aEnd - aStart) + " +" + (bStart + 1) + "," + (bEnd - bStart) + " @@"); - } - - private static String joinAlignedDiffsNoExpand(List diffs, DiffOptions options) { - int iLength = diffs.size(); - int nContextLines = options.contextLines; - int nContextLines2 = nContextLines + nContextLines; - - int jLength = iLength; - boolean hasExcessAtStartOrEnd = false; - int nExcessesBetweenChanges = 0; - int i = 0; - while (i != iLength) { - int iStart = i; - while (i != iLength && diffs.get(i).op == DIFF_EQUAL) { - i += 1; - } - if (iStart != i) { - if (iStart == 0) { - if (i > nContextLines) { - jLength -= i - nContextLines; - hasExcessAtStartOrEnd = true; - } - } else if (i == iLength) { - int n = i - iStart; - if (n > nContextLines) { - jLength -= n - nContextLines; - hasExcessAtStartOrEnd = true; - } - } else { - int n = i - iStart; - if (n > nContextLines2) { - jLength -= n - nContextLines2; - nExcessesBetweenChanges += 1; - } - } - } - while (i != iLength && diffs.get(i).op != DIFF_EQUAL) { - i += 1; - } - } - boolean hasPatch = nExcessesBetweenChanges != 0 || hasExcessAtStartOrEnd; - if (nExcessesBetweenChanges != 0) { - jLength += nExcessesBetweenChanges + 1; - } else if (hasExcessAtStartOrEnd) { - jLength += 1; - } - int jLast = jLength - 1; - List lines = new ArrayList<>(); - int jPatchMark = 0; - if (hasPatch) { - lines.add(""); - } - - // java: a lambda cannot assign a local variable, aEnd and bEnd are arrays of one item. - int aStart = 0; - int bStart = 0; - int[] aEnd = {0}; - int[] bEnd = {0}; - Consumer pushCommonLine = line -> { - int j = lines.size(); - lines.add(printCommonLine(line, j == 0 || j == jLast, options)); - aEnd[0] += 1; - bEnd[0] += 1; - }; - Consumer pushDeleteLine = line -> { - int j = lines.size(); - lines.add(printDeleteLine(line, j == 0 || j == jLast, options)); - aEnd[0] += 1; - }; - Consumer pushInsertLine = line -> { - int j = lines.size(); - lines.add(printInsertLine(line, j == 0 || j == jLast, options)); - bEnd[0] += 1; - }; - - i = 0; - while (i != iLength) { - int iStart = i; - while (i != iLength && diffs.get(i).op == DIFF_EQUAL) { - i += 1; - } - if (iStart != i) { - if (iStart == 0) { - if (i > nContextLines) { - iStart = i - nContextLines; - aStart = iStart; - bStart = iStart; - aEnd[0] = aStart; - bEnd[0] = bStart; - } - for (int iCommon = iStart; iCommon != i; iCommon += 1) { - pushCommonLine.accept(diffs.get(iCommon).text); - } - } else if (i == iLength) { - int iEnd = i - iStart > nContextLines ? iStart + nContextLines : i; - for (int iCommon = iStart; iCommon != iEnd; iCommon += 1) { - pushCommonLine.accept(diffs.get(iCommon).text); - } - } else { - int nCommon = i - iStart; - if (nCommon > nContextLines2) { - int iEnd = iStart + nContextLines; - for (int iCommon = iStart; iCommon != iEnd; iCommon += 1) { - pushCommonLine.accept(diffs.get(iCommon).text); - } - lines.set(jPatchMark, createPatchMark(aStart, aEnd[0], bStart, bEnd[0], options)); - jPatchMark = lines.size(); - lines.add(""); - - int nOmit = nCommon - nContextLines2; - aStart = aEnd[0] + nOmit; - bStart = bEnd[0] + nOmit; - aEnd[0] = aStart; - bEnd[0] = bStart; - for (int iCommon = i - nContextLines; iCommon != i; iCommon += 1) { - pushCommonLine.accept(diffs.get(iCommon).text); - } - } else { - for (int iCommon = iStart; iCommon != i; iCommon += 1) { - pushCommonLine.accept(diffs.get(iCommon).text); - } - } - } - } - while (i != iLength && diffs.get(i).op == DIFF_DELETE) { - pushDeleteLine.accept(diffs.get(i).text); - i += 1; - } - while (i != iLength && diffs.get(i).op == DIFF_INSERT) { - pushInsertLine.accept(diffs.get(i).text); - i += 1; - } - } - if (hasPatch) { - lines.set(jPatchMark, createPatchMark(aStart, aEnd[0], bStart, bEnd[0], options)); - } - return String.join("\n", lines); - } - - private static String joinAlignedDiffsExpand(List diffs, DiffOptions options) { - List lines = new ArrayList<>(); - for (int i = 0; i < diffs.size(); i++) { - Diff diff = diffs.get(i); - String line = diff.text; - boolean isFirstOrLast = i == 0 || i == diffs.size() - 1; - switch (diff.op) { - case DIFF_DELETE: - lines.add(printDeleteLine(line, isFirstOrLast, options)); - break; - case DIFF_INSERT: - lines.add(printInsertLine(line, isFirstOrLast, options)); - break; - default: - lines.add(printCommonLine(line, isFirstOrLast, options)); - } - } - return String.join("\n", lines); - } - - static String noColor(String string) { - return string; - } - - private static final int DIFF_CONTEXT_DEFAULT = 5; - private static final DiffOptions OPTIONS_DEFAULT = new DiffOptions(); - static { - OPTIONS_DEFAULT.aAnnotation = "Expected"; - OPTIONS_DEFAULT.aColor = Chalk::green; - OPTIONS_DEFAULT.aIndicator = "-"; - OPTIONS_DEFAULT.bAnnotation = "Received"; - OPTIONS_DEFAULT.bColor = Chalk::red; - OPTIONS_DEFAULT.bIndicator = "+"; - OPTIONS_DEFAULT.changeColor = Chalk::inverse; - OPTIONS_DEFAULT.changeLineTrailingSpaceColor = JestDiff::noColor; - OPTIONS_DEFAULT.commonColor = Chalk::dim; - OPTIONS_DEFAULT.commonIndicator = " "; - OPTIONS_DEFAULT.commonLineTrailingSpaceColor = JestDiff::noColor; - OPTIONS_DEFAULT.compareKeys = null; - OPTIONS_DEFAULT.contextLines = DIFF_CONTEXT_DEFAULT; - OPTIONS_DEFAULT.emptyFirstOrLastLinePlaceholder = ""; - OPTIONS_DEFAULT.expand = true; - OPTIONS_DEFAULT.includeChangeCounts = false; - OPTIONS_DEFAULT.omitAnnotationLines = false; - OPTIONS_DEFAULT.patchColor = Chalk::yellow; - } - - private static Comparator getCompareKeys(Comparator compareKeys) { - return compareKeys != null ? compareKeys : OPTIONS_DEFAULT.compareKeys; - } - - private static int getContextLines(Integer contextLines) { - return contextLines != null && contextLines >= 0 ? contextLines : DIFF_CONTEXT_DEFAULT; - } - - static DiffOptions normalizeDiffOptions(DiffOptions options) { - if (options == null) { - options = new DiffOptions(); - } - // java: the object spread is one assignment per field. - DiffOptions result = new DiffOptions(); - result.aAnnotation = options.aAnnotation != null ? options.aAnnotation : OPTIONS_DEFAULT.aAnnotation; - result.aColor = options.aColor != null ? options.aColor : OPTIONS_DEFAULT.aColor; - result.aIndicator = options.aIndicator != null ? options.aIndicator : OPTIONS_DEFAULT.aIndicator; - result.bAnnotation = options.bAnnotation != null ? options.bAnnotation : OPTIONS_DEFAULT.bAnnotation; - result.bColor = options.bColor != null ? options.bColor : OPTIONS_DEFAULT.bColor; - result.bIndicator = options.bIndicator != null ? options.bIndicator : OPTIONS_DEFAULT.bIndicator; - result.changeColor = options.changeColor != null ? options.changeColor : OPTIONS_DEFAULT.changeColor; - result.changeLineTrailingSpaceColor = options.changeLineTrailingSpaceColor != null ? options.changeLineTrailingSpaceColor : OPTIONS_DEFAULT.changeLineTrailingSpaceColor; - result.commonColor = options.commonColor != null ? options.commonColor : OPTIONS_DEFAULT.commonColor; - result.commonIndicator = options.commonIndicator != null ? options.commonIndicator : OPTIONS_DEFAULT.commonIndicator; - result.commonLineTrailingSpaceColor = options.commonLineTrailingSpaceColor != null ? options.commonLineTrailingSpaceColor : OPTIONS_DEFAULT.commonLineTrailingSpaceColor; - result.emptyFirstOrLastLinePlaceholder = options.emptyFirstOrLastLinePlaceholder != null ? options.emptyFirstOrLastLinePlaceholder : OPTIONS_DEFAULT.emptyFirstOrLastLinePlaceholder; - result.expand = options.expand != null ? options.expand : OPTIONS_DEFAULT.expand; - result.includeChangeCounts = options.includeChangeCounts != null ? options.includeChangeCounts : OPTIONS_DEFAULT.includeChangeCounts; - result.omitAnnotationLines = options.omitAnnotationLines != null ? options.omitAnnotationLines : OPTIONS_DEFAULT.omitAnnotationLines; - result.patchColor = options.patchColor != null ? options.patchColor : OPTIONS_DEFAULT.patchColor; - result.compareKeys = getCompareKeys(options.compareKeys); - result.contextLines = getContextLines(options.contextLines); - return result; - } - - private static boolean hasCommonDiff(List diffs, boolean isMultiline) { - if (isMultiline) { - int iLast = diffs.size() - 1; - for (int i = 0; i < diffs.size(); i++) { - Diff diff = diffs.get(i); - if (diff.op == DIFF_EQUAL && (i != iLast || !diff.text.equals("\n"))) { - return true; - } - } - return false; - } - for (Diff diff : diffs) { - if (diff.op == DIFF_EQUAL) { - return true; - } - } - return false; - } - - static String diffStringsUnified(String a, String b, DiffOptions options) { - if (!a.equals(b) && a.length() > 0 && b.length() > 0) { - boolean isMultiline = a.contains("\n") || b.contains("\n"); - - List diffs = diffStringsRaw(isMultiline ? a + "\n" : a, isMultiline ? b + "\n" : b, true - ); - if (hasCommonDiff(diffs, isMultiline)) { - DiffOptions optionsNormalized = normalizeDiffOptions(options); - List lines = getAlignedDiffs(diffs, optionsNormalized.changeColor); - return printDiffLines(lines, optionsNormalized); - } - } - - return diffLinesUnified(split(a, "\n"), split(b, "\n"), options); - } - - static List diffStringsRaw(String a, String b, boolean cleanup) { - List diffs = diffStrings(a, b); - if (cleanup) { - diff_cleanupSemantic(diffs); - } - return diffs; - } - - private static String getCommonMessage(String message, DiffOptions options) { - Function commonColor = normalizeDiffOptions(options).commonColor; - return commonColor.apply(message); - } - - // java: there are no plugins. - private static final PrettyFormat.Options FORMAT_OPTIONS = new PrettyFormat.Options(); - private static final PrettyFormat.Options FALLBACK_FORMAT_OPTIONS = new PrettyFormat.Options(); - static { - FALLBACK_FORMAT_OPTIONS.callToJSON = false; - FALLBACK_FORMAT_OPTIONS.maxDepth = 10; - } - - // java: helper with no counterpart upstream, the port of Object.is. - private static boolean objectIs(Object a, Object b) { - if (a instanceof Number && b instanceof Number) { - return Double.compare(((Number) a).doubleValue(), ((Number) b).doubleValue()) == 0; - } - if (a instanceof String || a instanceof Boolean) { - return a.equals(b); - } - return a == b; - } - - static String diff(Object a, Object b, DiffOptions options) { - if (objectIs(a, b)) { - return getCommonMessage(NO_DIFF_MESSAGE, options); - } - String aType = getType(a); - String expectedType = aType; - // java: there are no asymmetric matchers, omitDifference is always false. - if (!expectedType.equals(getType(b))) { - return " Comparing two different types of values." + " Expected " + Chalk.green(expectedType) + " but " + "received " + Chalk.red(getType(b)) + "."; - } - switch (aType) { - case "string": - return diffLinesUnified(split(escapeControlCharacters((String) a), "\n"), split(escapeControlCharacters((String) b), "\n"), options); - case "boolean": - case "number": - return comparePrimitive(a, b, options); - // java: the types map and set have no Java values, sortMap and sortSet are not ported. - default: - return compareObjects(a, b, options); - } - } - - private static String comparePrimitive(Object a, Object b, DiffOptions options) { - String aFormat = PrettyFormat.format(a, FORMAT_OPTIONS); - String bFormat = PrettyFormat.format(b, FORMAT_OPTIONS); - return aFormat.equals(bFormat) ? getCommonMessage(NO_DIFF_MESSAGE, options) : diffLinesUnified(split(aFormat, "\n"), split(bFormat, "\n"), options); - } - - private static String compareObjects(Object a, Object b, DiffOptions options) { - String difference = null; - boolean hasThrown = false; - try { - PrettyFormat.Options formatOptions = getFormatOptions(FORMAT_OPTIONS, options); - difference = getObjectsDifference(a, b, formatOptions, options); - } catch (RuntimeException e) { - hasThrown = true; - } - String noDiffMessage = getCommonMessage(NO_DIFF_MESSAGE, options); - if (difference == null || difference.equals(noDiffMessage)) { - PrettyFormat.Options formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options); - difference = getObjectsDifference(a, b, formatOptions, options); - if (!difference.equals(noDiffMessage) && !hasThrown) { - difference = getCommonMessage(SIMILAR_MESSAGE, options) + "\n\n" + difference; - } - } - return difference; - } - - private static PrettyFormat.Options getFormatOptions(PrettyFormat.Options formatOptions, DiffOptions options) { - Comparator compareKeys = normalizeDiffOptions(options).compareKeys; - // java: the object spread is one assignment per field. - PrettyFormat.Options result = new PrettyFormat.Options(); - result.callToJSON = formatOptions.callToJSON; - result.indent = formatOptions.indent; - result.maxDepth = formatOptions.maxDepth; - result.maxWidth = formatOptions.maxWidth; - result.min = formatOptions.min; - result.compareKeys = compareKeys; - return result; - } - - private static String getObjectsDifference(Object a, Object b, PrettyFormat.Options formatOptions, DiffOptions options) { - // java: the object spread is one assignment per field. - PrettyFormat.Options formatOptionsZeroIndent = new PrettyFormat.Options(); - formatOptionsZeroIndent.callToJSON = formatOptions.callToJSON; - formatOptionsZeroIndent.compareKeys = formatOptions.compareKeys; - formatOptionsZeroIndent.maxDepth = formatOptions.maxDepth; - formatOptionsZeroIndent.maxWidth = formatOptions.maxWidth; - formatOptionsZeroIndent.min = formatOptions.min; - formatOptionsZeroIndent.indent = 0; - String aCompare = PrettyFormat.format(a, formatOptionsZeroIndent); - String bCompare = PrettyFormat.format(b, formatOptionsZeroIndent); - if (aCompare.equals(bCompare)) { - return getCommonMessage(NO_DIFF_MESSAGE, options); - } else { - String aDisplay = PrettyFormat.format(a, formatOptions); - String bDisplay = PrettyFormat.format(b, formatOptions); - return diffLinesUnified2(split(aDisplay, "\n"), split(bDisplay, "\n"), split(aCompare, "\n"), split(bCompare, "\n"), options); - } - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/JestGetType.java b/playwright/src/main/java/com/microsoft/playwright/impl/JestGetType.java deleted file mode 100644 index 1d2e2695a..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/JestGetType.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Port of @jest/get-type. -// java: the original is MIT licensed, Copyright (c) Meta Platforms, Inc. and affiliates. -package com.microsoft.playwright.impl; - -import java.util.Date; -import java.util.List; -import java.util.regex.Pattern; - -class JestGetType { - // java: a Java value has one of these JavaScript types: null is null, a List or an array is - // an array, a Boolean is a boolean, a Number is a number, a String is a string, a Pattern is - // a regexp, a Date is a date. All other values, a Map too, are objects. The other types have no Java values. - // java: the undefined value is UNDEFINED: Frame.expect returns it for a received value that is undefined. - static final Object UNDEFINED = new Object() { - @Override - public String toString() { - return "undefined"; - } - }; - - static String getType(Object value) { - if (value == UNDEFINED) { - return "undefined"; - } else if (value == null) { - return "null"; - } else if (isArray(value)) { - return "array"; - } else if (value instanceof Boolean) { - return "boolean"; - } else if (value instanceof Number) { - return "number"; - } else if (value instanceof String) { - return "string"; - } else { - if (value instanceof Pattern) { - return "regexp"; - } else if (value instanceof Date) { - return "date"; - } - return "object"; - } - } - - static boolean isPrimitive(Object value) { - return value == null || value == UNDEFINED || value instanceof Boolean || value instanceof Number || value instanceof String; - } - - // java: helper with no counterpart upstream, the port of Array.isArray. - static boolean isArray(Object value) { - return value instanceof List || value != null && value.getClass().isArray(); - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/JestMatcherUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/JestMatcherUtils.java deleted file mode 100644 index 7f770b59d..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/JestMatcherUtils.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Port of jest-matcher-utils. -// java: the original is MIT licensed, Copyright (c) Meta Platforms, Inc. and affiliates. -package com.microsoft.playwright.impl; - -import java.util.List; -import java.util.function.Function; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.microsoft.playwright.impl.JestDiff.DIFF_DELETE; -import static com.microsoft.playwright.impl.JestDiff.DIFF_EQUAL; -import static com.microsoft.playwright.impl.JestDiff.DIFF_INSERT; -import static com.microsoft.playwright.impl.JestDiff.diffStringsRaw; -import static com.microsoft.playwright.impl.JestDiff.diffStringsUnified; -import static com.microsoft.playwright.impl.JestGetType.getType; -import static com.microsoft.playwright.impl.JestGetType.isPrimitive; - -// java: the ensure functions, matcherHint, matcherErrorMessage, pluralize, highlightTrailingWhitespace, -// diff and shouldPrintDiff are not ported, the assertions do not call them. -class JestMatcherUtils { - // java: no ANSI colors, the color functions return the text as is. - static String EXPECTED_COLOR(String text) { - return JestDiff.Chalk.green(text); - } - - static String RECEIVED_COLOR(String text) { - return JestDiff.Chalk.red(text); - } - - static String INVERTED_COLOR(String text) { - return JestDiff.Chalk.inverse(text); - } - - static String BOLD_WEIGHT(String text) { - return JestDiff.Chalk.bold(text); - } - - static String DIM_COLOR(String text) { - return JestDiff.Chalk.dim(text); - } - - private static final Pattern MULTILINE_REGEXP = Pattern.compile("\\n"); - private static final String SPACE_SYMBOL = "·"; - - static String stringify(Object object) { - return stringify(object, 10, 10); - } - - static String stringify(Object object, int maxDepth, int maxWidth) { - int MAX_LENGTH = 10_000; - String result; - try { - PrettyFormat.Options options = new PrettyFormat.Options(); - options.maxDepth = maxDepth; - options.maxWidth = maxWidth; - options.min = true; - result = PrettyFormat.format(object, options); - } catch (RuntimeException e) { - PrettyFormat.Options options = new PrettyFormat.Options(); - options.callToJSON = false; - options.maxDepth = maxDepth; - options.maxWidth = maxWidth; - options.min = true; - result = PrettyFormat.format(object, options); - } - if (result.length() >= MAX_LENGTH && maxDepth > 1) { - return stringify(object, maxDepth / 2, maxWidth); - } else if (result.length() >= MAX_LENGTH && maxWidth > 1) { - return stringify(object, maxDepth, maxWidth / 2); - } else { - return result; - } - } - - // java: $ with the m flag in JavaScript is the position before \n, \r, 
, 
 or the - // end of the string. $ with MULTILINE in Java does not match between \r and \n, and it - // matches before \u0085. - private static final Pattern trailingSpacesRegex = Pattern.compile(JestDiff.WHITESPACE + "+(?=[\\n\\r\\u2028\\u2029]|\\z)"); - - private static String replaceTrailingSpaces(String text) { - // java: replaceAll with a callback is a loop over the matches. - Matcher matcher = trailingSpacesRegex.matcher(text); - StringBuffer result = new StringBuffer(); - while (matcher.find()) { - String spaces = matcher.group(); - matcher.appendReplacement(result, Matcher.quoteReplacement(repeat(SPACE_SYMBOL, spaces.length()))); - } - matcher.appendTail(result); - return result.toString(); - } - - // java: helper with no counterpart upstream, the port of String.prototype.repeat. - private static String repeat(String string, int count) { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < count; i++) { - result.append(string); - } - return result.toString(); - } - - static String printReceived(Object object) { - return RECEIVED_COLOR(replaceTrailingSpaces(stringify(object))); - } - - static String printExpected(Object value) { - return EXPECTED_COLOR(replaceTrailingSpaces(stringify(value))); - } - - static String printWithType(String name, Object value, Function print) { - String type = getType(value); - String hasType = !type.equals("null") && !type.equals("undefined") ? name + " has type: " + type + "\n" : ""; - String hasValue = name + " has value: " + print.apply(value); - return hasType + hasValue; - } - - private static String getCommonAndChangedSubstrings(List diffs, int op, boolean hasCommonDiff) { - String reduced = ""; - for (JestDiff.Diff diff : diffs) { - reduced = reduced + (diff.op == DIFF_EQUAL ? diff.text : diff.op == op ? hasCommonDiff ? INVERTED_COLOR(diff.text) : diff.text : ""); - } - return reduced; - } - - private static boolean isLineDiffable(Object expected, Object received) { - String expectedType = getType(expected); - String receivedType = getType(received); - if (!expectedType.equals(receivedType)) { - return false; - } - if (isPrimitive(expected)) { - return expected instanceof String && received instanceof String && ((String) expected).length() > 0 && ((String) received).length() > 0 && (MULTILINE_REGEXP.matcher((String) expected).find() || MULTILINE_REGEXP.matcher((String) received).find()); - } - if (expectedType.equals("date") || expectedType.equals("function") || expectedType.equals("regexp")) { - return false; - } - // java: the value model has no Error values and no asymmetric matchers, these two - // checks are not ported. - return true; - } - - private static final int MAX_DIFF_STRING_LENGTH = 20_000; - - static String printDiffOrStringify(Object expected, Object received, String expectedLabel, String receivedLabel, boolean expand) { - if (expected instanceof String && received instanceof String && ((String) expected).length() > 0 && ((String) received).length() > 0 && ((String) expected).length() <= MAX_DIFF_STRING_LENGTH && ((String) received).length() <= MAX_DIFF_STRING_LENGTH && !expected.equals(received)) { - if (((String) expected).contains("\n") || ((String) received).contains("\n")) { - JestDiff.DiffOptions options = new JestDiff.DiffOptions(); - options.aAnnotation = expectedLabel; - options.bAnnotation = receivedLabel; - options.changeLineTrailingSpaceColor = JestDiff.Chalk::bgYellow; - options.commonLineTrailingSpaceColor = JestDiff.Chalk::bgYellow; - options.emptyFirstOrLastLinePlaceholder = "↵"; - options.expand = expand; - options.includeChangeCounts = true; - return diffStringsUnified((String) expected, (String) received, options); - } - List diffs = diffStringsRaw((String) expected, (String) received, true); - boolean hasCommonDiff = false; - for (JestDiff.Diff diff : diffs) { - if (diff.op == DIFF_EQUAL) { - hasCommonDiff = true; - } - } - Function printLabel = getLabelPrinter(expectedLabel, receivedLabel); - String expectedLine = printLabel.apply(expectedLabel) + printExpected(getCommonAndChangedSubstrings(diffs, DIFF_DELETE, hasCommonDiff)); - String receivedLine = printLabel.apply(receivedLabel) + printReceived(getCommonAndChangedSubstrings(diffs, DIFF_INSERT, hasCommonDiff)); - return expectedLine + "\n" + receivedLine; - } - if (isLineDiffable(expected, received)) { - // java: there are no asymmetric matchers, replaceMatchedToAsymmetricMatcher returns - // the values as they are and is not ported. - Object replacedExpected = expected; - Object replacedReceived = received; - JestDiff.DiffOptions options = new JestDiff.DiffOptions(); - options.aAnnotation = expectedLabel; - options.bAnnotation = receivedLabel; - options.expand = expand; - options.includeChangeCounts = true; - String difference = JestDiff.diff(replacedExpected, replacedReceived, options); - if (difference != null && difference.contains("- " + expectedLabel) && difference.contains("+ " + receivedLabel)) { - return difference; - } - } - Function printLabel = getLabelPrinter(expectedLabel, receivedLabel); - String expectedLine = printLabel.apply(expectedLabel) + printExpected(expected); - String receivedLine = printLabel.apply(receivedLabel) + (stringify(expected).equals(stringify(received)) ? "serializes to the same string" : printReceived(received)); - return expectedLine + "\n" + receivedLine; - } - - static Function getLabelPrinter(String... strings) { - int maxLength = 0; - for (String string : strings) { - maxLength = Math.max(string.length(), maxLength); - } - int finalMaxLength = maxLength; - return string -> string + ": " + repeat(" ", finalMaxLength - string.length()); - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/MatcherHint.java b/playwright/src/main/java/com/microsoft/playwright/impl/MatcherHint.java index 1cea82b96..e0c340f43 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/MatcherHint.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/MatcherHint.java @@ -21,11 +21,8 @@ import java.util.function.Supplier; import java.util.regex.Matcher; -import static com.microsoft.playwright.impl.JestMatcherUtils.DIM_COLOR; -import static com.microsoft.playwright.impl.JestMatcherUtils.EXPECTED_COLOR; -import static com.microsoft.playwright.impl.JestMatcherUtils.INVERTED_COLOR; -import static com.microsoft.playwright.impl.JestMatcherUtils.RECEIVED_COLOR; -import static com.microsoft.playwright.impl.JestMatcherUtils.printReceived; +import static com.microsoft.playwright.impl.MatcherUtils.printReceived; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.numberToString; class MatcherHint { // java: no attachments, suggestedRebaseline, softError and shouldNotRetryTest, they belong to the test runner. @@ -44,19 +41,18 @@ static class MatcherResult { // java: no expectTypes, the receiver of a matcher is typed. - // java: InternalMatcherUtils is JestMatcherUtils, its methods are static. + // java: InternalMatcherUtils is MatcherUtils, its methods are static; there are no colors. private static String printSubstring(String val) { return val.replaceAll("\"|\\\\", "\\\\$0"); } static String printReceivedStringContainExpectedSubstring(String received, int start, int length) { - return RECEIVED_COLOR( - "\"" + + return "\"" + printSubstring(slice(received, 0, start)) + - INVERTED_COLOR(printSubstring(slice(received, start, start + length))) + + printSubstring(slice(received, start, start + length)) + printSubstring(slice(received, start + length, received.length())) + - "\""); + "\""; } // java: result is the Matcher after a successful find(), or null. @@ -88,10 +84,10 @@ static class MatcherMessageDetails { static String formatMatcherMessage(MatcherMessageDetails details) { String receiver = details.receiver != null ? details.receiver : (details.locator != null && !details.locator.isEmpty() ? "locator" : "page"); // java: the call is the Java one: assertThat(locator).not().hasText(expected). - String message = DIM_COLOR("assertThat(") + RECEIVED_COLOR(receiver) - + DIM_COLOR(")" + (details.promise != null && !details.promise.isEmpty() ? "." + details.promise : "") + (details.isNot ? ".not()" : "") + ".") + String message = "assertThat(" + receiver + + ")" + (details.promise != null && !details.promise.isEmpty() ? "." + details.promise : "") + (details.isNot ? ".not()" : "") + "." + details.matcherName - + DIM_COLOR("(") + EXPECTED_COLOR(details.expectation) + DIM_COLOR(")") + + "(" + details.expectation + ")" + " failed\n\n"; String[] diffLines = details.printedDiff == null ? null : details.printedDiff.split("\n", -1); @@ -110,7 +106,7 @@ static String formatMatcherMessage(MatcherMessageDetails details) { if (!isEmpty(details.printedReceived)) message += details.printedReceived + "\n"; if (details.timedOut != null && details.timedOut && details.timeout != null && details.timeout != 0) - message += "Timeout: " + (align ? " " : "") + formatNumber(details.timeout) + "ms\n"; + message += "Timeout: " + (align ? " " : "") + numberToString(details.timeout) + "ms\n"; if (!isEmpty(details.printedDiff)) message += details.printedDiff + "\n"; if (!isEmpty(details.errorMessage)) { @@ -125,10 +121,10 @@ static String formatMatcherMessage(MatcherMessageDetails details) { static String callLogText(List log) { if (log == null || !log.stream().anyMatch(l -> !isEmpty(l))) return ""; - return "\nCall log:\n" + DIM_COLOR(String.join("\n", log)) + "\n"; + return "\nCall log:\n" + (String.join("\n", log)) + "\n"; } - // java: helpers with no counterpart upstream: String.prototype.slice, the truthiness of a string and the text of a number. + // java: helpers with no counterpart upstream: String.prototype.slice, and the truthiness of a string. private static String slice(String string, int start, int end) { int length = string.length(); int from = start < 0 ? Math.max(length + start, 0) : Math.min(start, length); @@ -139,8 +135,4 @@ private static String slice(String string, int start, int end) { private static boolean isEmpty(String string) { return string == null || string.isEmpty(); } - - static String formatNumber(double number) { - return number == Math.rint(number) && Math.abs(number) < 1e15 ? String.valueOf((long) number) : String.valueOf(number); - } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/MatcherUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/MatcherUtils.java new file mode 100644 index 000000000..99374102d --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/MatcherUtils.java @@ -0,0 +1,219 @@ +/* + * 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 java.lang.reflect.Array; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.regex.Pattern; + +import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.numberToString; + +// java: the utils of a matcher. Upstream they are jest-matcher-utils, which is not ported: these methods print the +// Java values in the same format, without colors, and the diff is a plain line diff. +class MatcherUtils { + // java: the undefined value: Frame.expect returns it for a received value that is undefined. + static final Object UNDEFINED = new Object() { + @Override + public String toString() { + return "undefined"; + } + }; + + private static final int MAX_DIFF_LINES = 2000; + + static String printExpected(Object value) { + return stringify(value); + } + + static String printReceived(Object value) { + return stringify(value); + } + + static String stringify(Object value) { + if (isArray(value)) { + List items = new ArrayList<>(); + for (Object item : toList(value)) + items.add(stringify(item)); + return "[" + String.join(", ", items) + "]"; + } + if (value instanceof Map) { + List entries = new ArrayList<>(); + for (Map.Entry entry : sortedEntries((Map) value).entrySet()) + entries.add(quote(entry.getKey()) + ": " + stringify(entry.getValue())); + return "{" + String.join(", ", entries) + "}"; + } + return formatBasicValue(value); + } + + static String printDiffOrStringify(Object expected, Object received, String expectedLabel, String receivedLabel) { + List expectedLines = null; + List receivedLines = null; + if (expected instanceof String && received instanceof String) { + String expectedString = (String) expected; + String receivedString = (String) received; + if (!expectedString.isEmpty() && !receivedString.isEmpty() && (expectedString.contains("\n") || receivedString.contains("\n"))) { + expectedLines = split(expectedString); + receivedLines = split(receivedString); + } + } else if (isArray(expected) && isArray(received) || expected instanceof Map && received instanceof Map) { + expectedLines = format(expected); + receivedLines = format(received); + } + if (expectedLines != null && !expectedLines.equals(receivedLines) && expectedLines.size() <= MAX_DIFF_LINES && receivedLines.size() <= MAX_DIFF_LINES) + return diffLines(expectedLines, receivedLines, expectedLabel, receivedLabel); + int width = Math.max(expectedLabel.length(), receivedLabel.length()); + String expectedLine = pad(expectedLabel + ":", width + 2) + printExpected(expected); + String receivedLine = pad(receivedLabel + ":", width + 2) + (stringify(expected).equals(stringify(received)) ? "serializes to the same string" : printReceived(received)); + return expectedLine + "\n" + receivedLine; + } + + private static String diffLines(List a, List b, String aLabel, String bLabel) { + int[][] lcs = new int[a.size() + 1][b.size() + 1]; + for (int i = a.size() - 1; i >= 0; i--) { + for (int j = b.size() - 1; j >= 0; j--) + lcs[i][j] = a.get(i).equals(b.get(j)) ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]); + } + List lines = new ArrayList<>(); + int removed = 0; + int added = 0; + int i = 0; + int j = 0; + while (i < a.size() || j < b.size()) { + if (i < a.size() && j < b.size() && a.get(i).equals(b.get(j))) { + lines.add(a.get(i).isEmpty() ? "" : " " + a.get(i)); + i++; + j++; + } else if (i < a.size() && (j == b.size() || lcs[i + 1][j] >= lcs[i][j + 1])) { + lines.add(a.get(i).isEmpty() ? "-" : "- " + a.get(i)); + removed++; + i++; + } else { + lines.add(b.get(j).isEmpty() ? "+" : "+ " + b.get(j)); + added++; + j++; + } + } + int labelWidth = Math.max(aLabel.length(), bLabel.length()); + int countWidth = Math.max(String.valueOf(removed).length(), String.valueOf(added).length()); + return "- " + pad(aLabel, labelWidth) + " - " + padStart(String.valueOf(removed), countWidth) + "\n" + + "+ " + pad(bLabel, labelWidth) + " + " + padStart(String.valueOf(added), countWidth) + "\n\n" + + String.join("\n", lines); + } + + private static List format(Object value) { + List lines = new ArrayList<>(); + format(value, "", "", lines); + String last = lines.get(lines.size() - 1); + lines.set(lines.size() - 1, last.substring(0, last.length() - 1)); + return lines; + } + + private static void format(Object value, String indent, String key, List lines) { + if (isArray(value)) { + List items = toList(value); + if (items.isEmpty()) { + lines.add(indent + key + "Array [],"); + return; + } + lines.add(indent + key + "Array ["); + for (Object item : items) + format(item, indent + " ", "", lines); + lines.add(indent + "],"); + return; + } + if (value instanceof Map) { + Map entries = sortedEntries((Map) value); + if (entries.isEmpty()) { + lines.add(indent + key + "Object {},"); + return; + } + lines.add(indent + key + "Object {"); + for (Map.Entry entry : entries.entrySet()) + format(entry.getValue(), indent + " ", quote(entry.getKey()) + ": ", lines); + lines.add(indent + "},"); + return; + } + lines.add(indent + key + formatBasicValue(value) + ","); + } + + private static Map sortedEntries(Map map) { + Map entries = new TreeMap<>(); + for (Map.Entry entry : map.entrySet()) + entries.put(String.valueOf(entry.getKey()), entry.getValue()); + return entries; + } + + private static String formatBasicValue(Object value) { + if (value == null) + return "null"; + if (value instanceof Number) + return numberToString(((Number) value).doubleValue()); + if (value instanceof String) + return quote((String) value); + if (value instanceof Pattern) + return "/" + ((Pattern) value).pattern() + "/" + toJsRegexFlags((Pattern) value); + if (value instanceof Date) + return DateTimeFormatter.ISO_INSTANT.format(((Date) value).toInstant().truncatedTo(ChronoUnit.MILLIS)).replaceFirst("(:\\d\\d)Z$", "$1.000Z"); + return String.valueOf(value); + } + + private static String quote(String value) { + return "\"" + value.replaceAll("\"|\\\\", "\\\\$0") + "\""; + } + + private static boolean isArray(Object value) { + return value instanceof List || value != null && value.getClass().isArray(); + } + + @SuppressWarnings("unchecked") + private static List toList(Object value) { + if (value instanceof List) + return (List) value; + List result = new ArrayList<>(); + for (int i = 0; i < Array.getLength(value); i++) + result.add(Array.get(value, i)); + return result; + } + + private static List split(String value) { + List result = new ArrayList<>(); + for (String line : value.split("\n", -1)) + result.add(line); + return result; + } + + private static String pad(String value, int width) { + StringBuilder result = new StringBuilder(value); + while (result.length() < width) + result.append(' '); + return result.toString(); + } + + private static String padStart(String value, int width) { + StringBuilder result = new StringBuilder(value); + while (result.length() < width) + result.insert(0, ' '); + return result.toString(); + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PrettyFormat.java b/playwright/src/main/java/com/microsoft/playwright/impl/PrettyFormat.java deleted file mode 100644 index 7ad797872..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PrettyFormat.java +++ /dev/null @@ -1,407 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Port of pretty-format. -// java: the original is MIT licensed, Copyright (c) Meta Platforms, Inc. and affiliates. -package com.microsoft.playwright.impl; - -import com.microsoft.playwright.PlaywrightException; - -import java.lang.reflect.Array; -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; -import java.time.format.DateTimeFormatter; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -import static com.microsoft.playwright.impl.JestGetType.isArray; -import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; - -// java: only the code that formats the Java values is ported: null, Boolean, Number, String, -// Pattern, List and arrays, Map. The plugins, callToJSON, the colors and the other JavaScript -// types are not ported. -class PrettyFormat { - // java: the type of the options object. A null field is an option that is not set. - static class Options { - Boolean callToJSON; - Comparator compareKeys; - Integer indent; - Integer maxDepth; - Integer maxWidth; - Boolean min; - } - - // java: the type of the config object. - static class Config { - boolean callToJSON; - Comparator compareKeys; - boolean escapeRegex; - boolean escapeString; - String indent; - int maxDepth; - int maxWidth; - boolean min; - boolean printBasicPrototype; - boolean printFunctionName; - String spacingInner; - String spacingOuter; - } - - // java: compareKeys is undefined or a function here. The null value of upstream, which - // keeps the order of the keys, is not ported. - private static List getKeysOfEnumerableProperties(Map object, Comparator compareKeys) { - // java: a key that is not a String is converted with String.valueOf, as a JavaScript - // object converts its keys. - List rawKeys = new ArrayList<>(); - for (Object key : object.keySet()) { - rawKeys.add(String.valueOf(key)); - } - // java: the default order of Array.prototype.sort is the order of the UTF-16 code units, - // which is the order of String.compareTo. - Collections.sort(rawKeys, compareKeys); - List keys = new ArrayList(rawKeys); - return keys; - } - - static String printListItems(List list, Config config, String indentation, int depth, List refs) { - String result = ""; - int length = list.size(); - if (length > 0) { - result += config.spacingOuter; - String indentationNext = indentation + config.indent; - for (int i = 0; i < length; i++) { - result += indentationNext; - if (i == config.maxWidth) { - result += "…"; - break; - } - result += printer(list.get(i), config, indentationNext, depth, refs, false); - if (i < length - 1) { - result += "," + config.spacingInner; - } else if (!config.min) { - result += ","; - } - } - result += config.spacingOuter + indentation; - } - return result; - } - - static String printObjectProperties(Map val, Config config, String indentation, int depth, List refs) { - String result = ""; - List keys = getKeysOfEnumerableProperties(val, config.compareKeys); - if (keys.size() > 0) { - result += config.spacingOuter; - String indentationNext = indentation + config.indent; - for (int i = 0; i < keys.size(); i++) { - Object key = keys.get(i); - String name = printer(key, config, indentationNext, depth, refs, false); - String value = printer(get(val, key), config, indentationNext, depth, refs, false); - result += indentationNext + name + ": " + value; - if (i < keys.size() - 1) { - result += "," + config.spacingInner; - } else if (!config.min) { - result += ","; - } - } - result += config.spacingOuter + indentation; - } - return result; - } - - // java: helper with no counterpart upstream, the port of val[key] for the converted keys. - private static Object get(Map val, Object key) { - if (val.containsKey(key)) { - return val.get(key); - } - for (Map.Entry entry : val.entrySet()) { - if (key.equals(String.valueOf(entry.getKey()))) { - return entry.getValue(); - } - } - return null; - } - - private static String printNumber(double val) { - return Double.compare(val, -0.0) == 0 ? "-0" : numberToString(val); - } - - // java: helper with no counterpart upstream, the port of String(val) for a number: the - // Number::toString algorithm of ECMAScript. Double.toString has another format, and before - // JDK 19 it does not always give the shortest digits. - private static String numberToString(double m) { - if (Double.isNaN(m)) { - return "NaN"; - } - if (m == 0) { - return "0"; - } - if (m < 0) { - return "-" + numberToString(-m); - } - if (Double.isInfinite(m)) { - return "Infinity"; - } - BigDecimal exact = new BigDecimal(m); - BigDecimal shortest = null; - for (int precision = 1; shortest == null; precision++) { - BigDecimal down = exact.round(new MathContext(precision, RoundingMode.DOWN)); - BigDecimal up = exact.round(new MathContext(precision, RoundingMode.UP)); - boolean isDown = down.doubleValue() == m; - boolean isUp = up.doubleValue() == m; - if (isDown && isUp) { - int order = exact.subtract(down).compareTo(up.subtract(exact)); - if (order == 0) { - shortest = down.unscaledValue().testBit(0) ? up : down; - } else { - shortest = order < 0 ? down : up; - } - } else if (isDown) { - shortest = down; - } else if (isUp) { - shortest = up; - } - } - shortest = shortest.stripTrailingZeros(); - String s = shortest.unscaledValue().toString(); - int k = s.length(); - int n = k - shortest.scale(); - if (k <= n && n <= 21) { - return s + repeat("0", n - k); - } - if (0 < n && n <= 21) { - return s.substring(0, n) + "." + s.substring(n); - } - if (-6 < n && n <= 0) { - return "0." + repeat("0", -n) + s; - } - String exponent = (n - 1 < 0 ? "-" : "+") + Math.abs(n - 1); - if (k == 1) { - return s + "e" + exponent; - } - return s.substring(0, 1) + "." + s.substring(1) + "e" + exponent; - } - - // java: helper with no counterpart upstream, the port of String.prototype.repeat. - private static String repeat(String string, int count) { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < count; i++) { - result.append(string); - } - return result.toString(); - } - - // java: helper with no counterpart upstream, the port of RegExp.prototype.toString. The - // source is escaped as JavaScript escapes it: an empty source, a slash that is not in a - // character class and the line terminators. The syntax of the Java pattern stays as it is. - private static String regExpToString(Pattern val) { - String pattern = val.pattern(); - StringBuilder source = new StringBuilder(); - boolean inCharClass = false; - boolean previousCharWasBackslash = false; - for (int i = 0; i < pattern.length(); i++) { - char c = pattern.charAt(i); - String escaped = null; - if (c == '\n') { - escaped = "\\n"; - } else if (c == '\r') { - escaped = "\\r"; - } else if (c == '
') { - escaped = "\\u2028"; - } else if (c == '
') { - escaped = "\\u2029"; - } - if (previousCharWasBackslash) { - if (escaped != null) { - source.setLength(source.length() - 1); - source.append(escaped); - } else { - source.append(c); - } - previousCharWasBackslash = false; - continue; - } - if (escaped != null) { - source.append(escaped); - } else if (c == '/' && !inCharClass) { - source.append("\\/"); - } else { - if (c == '[') { - inCharClass = true; - } else if (c == ']') { - inCharClass = false; - } else if (c == '\\') { - previousCharWasBackslash = true; - } - source.append(c); - } - } - if (source.length() == 0) { - source.append("(?:)"); - } - // java: toJsRegexFlags gives the flags in the order "ism", JavaScript prints them in - // the alphabetical order. - char[] flags = toJsRegexFlags(val).toCharArray(); - Arrays.sort(flags); - return "/" + source + "/" + new String(flags); - } - - private static String printBasicValue(Object val, boolean printFunctionName, boolean escapeRegex, boolean escapeString) { - if (Boolean.TRUE.equals(val) || Boolean.FALSE.equals(val)) { - return "" + val; - } - if (val == JestGetType.UNDEFINED) { - return "undefined"; - } - if (val == null) { - return "null"; - } - if (val instanceof Number) { - // java: each Number is a JavaScript number, a double. - return printNumber(((Number) val).doubleValue()); - } - if (val instanceof String) { - if (escapeString) { - return "\"" + ((String) val).replaceAll("\"|\\\\", "\\\\$0") + "\""; - } - return "\"" + val + "\""; - } - if (val instanceof Date) { - // java: a java.util.Date is never invalid, so there is no "Date { NaN }". - return DateTimeFormatter.ISO_INSTANT.format(((Date) val).toInstant().truncatedTo(ChronoUnit.MILLIS)).replaceFirst("(:\\d\\d)Z$", "$1.000Z"); - } - if (val instanceof Pattern) { - if (escapeRegex) { - return regExpToString((Pattern) val).replaceAll("[$()*+.?\\[\\\\\\]^{|}]", "\\\\$0"); - } - return regExpToString((Pattern) val); - } - return null; - } - - private static String printComplexValue(Object val, Config config, String indentation, int depth, List refs, boolean hasCalledToJSON) { - // java: includes compares the objects by identity. - for (Object ref : refs) { - if (ref == val) { - return "[Circular]"; - } - } - refs = new ArrayList<>(refs); - refs.add(val); - boolean hitMaxDepth = ++depth > config.maxDepth; - boolean min = config.min; - if (isArray(val)) { - return hitMaxDepth ? "[Array]" : (min ? "" : !config.printBasicPrototype ? "" : "Array ") + "[" + printListItems(toList(val), config, indentation, depth, refs) + "]"; - } - if (!(val instanceof Map)) { - // java: a value that is not in the value model has no enumerable properties to print. - return String.valueOf(val); - } - - return hitMaxDepth ? "[Object]" : (min ? "" : !config.printBasicPrototype ? "" : "Object ") + "{" + printObjectProperties((Map) val, config, indentation, depth, refs) + "}"; - } - - // java: helper with no counterpart upstream, the items of a List or of an array. - private static List toList(Object val) { - if (val instanceof List) { - return (List) val; - } - List list = new ArrayList<>(); - for (int i = 0; i < Array.getLength(val); i++) { - list.add(Array.get(val, i)); - } - return list; - } - - private static String printer(Object val, Config config, String indentation, int depth, List refs, boolean hasCalledToJSON) { - String basicResult = printBasicValue(val, config.printFunctionName, config.escapeRegex, config.escapeString); - if (basicResult != null) { - return basicResult; - } - return printComplexValue(val, config, indentation, depth, refs, hasCalledToJSON); - } - - static final Options DEFAULT_OPTIONS = new Options(); - static { - DEFAULT_OPTIONS.callToJSON = true; - DEFAULT_OPTIONS.compareKeys = null; - DEFAULT_OPTIONS.indent = 2; - // java: an int has no infinity. - DEFAULT_OPTIONS.maxDepth = Integer.MAX_VALUE; - DEFAULT_OPTIONS.maxWidth = Integer.MAX_VALUE; - DEFAULT_OPTIONS.min = false; - } - - private static void validateOptions(Options options) { - if (options.min != null && options.min && options.indent != null && options.indent != 0) { - throw new PlaywrightException("pretty-format: Options \"min\" and \"indent\" cannot be used together."); - } - } - - // java: Options has no printFunctionName, escapeRegex and escapeString, the three getters - // return the default values. - private static boolean getPrintFunctionName(Options options) { - return true; - } - - private static boolean getEscapeRegex(Options options) { - return false; - } - - private static boolean getEscapeString(Options options) { - return true; - } - - private static Config getConfig(Options options) { - Config config = new Config(); - config.callToJSON = options != null && options.callToJSON != null ? options.callToJSON : DEFAULT_OPTIONS.callToJSON; - config.compareKeys = options != null && options.compareKeys != null ? options.compareKeys : DEFAULT_OPTIONS.compareKeys; - config.escapeRegex = getEscapeRegex(options); - config.escapeString = getEscapeString(options); - config.indent = options != null && options.min != null && options.min ? "" : createIndent(options != null && options.indent != null ? options.indent : DEFAULT_OPTIONS.indent); - config.maxDepth = options != null && options.maxDepth != null ? options.maxDepth : DEFAULT_OPTIONS.maxDepth; - config.maxWidth = options != null && options.maxWidth != null ? options.maxWidth : DEFAULT_OPTIONS.maxWidth; - config.min = options != null && options.min != null ? options.min : DEFAULT_OPTIONS.min; - config.printBasicPrototype = true; - config.printFunctionName = getPrintFunctionName(options); - config.spacingInner = options != null && options.min != null && options.min ? " " : "\n"; - config.spacingOuter = options != null && options.min != null && options.min ? "" : "\n"; - return config; - } - - private static String createIndent(int indent) { - return repeat(" ", indent); - } - - static String format(Object val, Options options) { - if (options != null) { - validateOptions(options); - } - String basicResult = printBasicValue(val, getPrintFunctionName(options), getEscapeRegex(options), getEscapeString(options)); - if (basicResult != null) { - return basicResult; - } - return printComplexValue(val, getConfig(options), "", 0, new ArrayList<>(), false); - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ToBeTruthy.java b/playwright/src/main/java/com/microsoft/playwright/impl/ToBeTruthy.java index 5caa2e171..e86837f97 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ToBeTruthy.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ToBeTruthy.java @@ -45,7 +45,7 @@ static MatcherResult toBeTruthy( Boolean timedOut = queryResult.timedOut; FrameExpectResult.ExpectReceived received = queryResult.received; String errorMessage = queryResult.errorMessage; - Object receivedValue = received == null ? JestGetType.UNDEFINED : received.value; + Object receivedValue = received == null ? MatcherUtils.UNDEFINED : received.value; if (pass == !state.isNot) { MatcherResult result = new MatcherResult(); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ToEqual.java b/playwright/src/main/java/com/microsoft/playwright/impl/ToEqual.java index 051d4778a..6c4af4d43 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ToEqual.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ToEqual.java @@ -27,9 +27,9 @@ import java.util.List; import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.JestMatcherUtils.printDiffOrStringify; -import static com.microsoft.playwright.impl.JestMatcherUtils.printExpected; -import static com.microsoft.playwright.impl.JestMatcherUtils.printReceived; +import static com.microsoft.playwright.impl.MatcherUtils.printDiffOrStringify; +import static com.microsoft.playwright.impl.MatcherUtils.printExpected; +import static com.microsoft.playwright.impl.MatcherUtils.printReceived; import static com.microsoft.playwright.impl.MatcherHint.formatMatcherMessage; class ToEqual { @@ -53,7 +53,7 @@ static MatcherResult toEqual( List log = queryResult.log; Boolean timedOut = queryResult.timedOut; String errorMessage = queryResult.errorMessage; - Object receivedValue = received == null ? JestGetType.UNDEFINED : received.value; + Object receivedValue = received == null ? MatcherUtils.UNDEFINED : received.value; if (pass == !state.isNot) { MatcherResult result = new MatcherResult(); @@ -91,15 +91,13 @@ static MatcherResult toEqual( normalizedExpected, receivedValue, EXPECTED_LABEL, - RECEIVED_LABEL, - false); + RECEIVED_LABEL); } else { printedDiff = printDiffOrStringify( expected, receivedValue, EXPECTED_LABEL, - RECEIVED_LABEL, - false); + RECEIVED_LABEL); } String finalPrintedExpected = printedExpected; String finalPrintedReceived = printedReceived; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchAriaSnapshot.java b/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchAriaSnapshot.java index 8e470c7db..440d033b6 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchAriaSnapshot.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchAriaSnapshot.java @@ -25,8 +25,8 @@ import java.util.List; import java.util.Map; -import static com.microsoft.playwright.impl.JestMatcherUtils.printDiffOrStringify; -import static com.microsoft.playwright.impl.JestMatcherUtils.printExpected; +import static com.microsoft.playwright.impl.MatcherUtils.printDiffOrStringify; +import static com.microsoft.playwright.impl.MatcherUtils.printExpected; import static com.microsoft.playwright.impl.MatcherHint.formatMatcherMessage; import static com.microsoft.playwright.impl.MatcherHint.printReceivedStringContainExpectedSubstring; @@ -64,7 +64,7 @@ static MatcherResult toMatchAriaSnapshot( Boolean timedOut = queryResult.timedOut; String errorMessage = queryResult.errorMessage; // java: MatcherReceived is the parsed object, a Map with raw and regex. - Map typedReceived = received == null || received.value == JestGetType.UNDEFINED ? null : (Map) received.value; + Map typedReceived = received == null || received.value == MatcherUtils.UNDEFINED ? null : (Map) received.value; String finalExpected = expected; MatcherResult result = new MatcherResult(); @@ -80,7 +80,7 @@ static MatcherResult toMatchAriaSnapshot( printedExpected = "Expected: not " + printExpected(finalExpected); printedReceived = "Received: " + receivedString; } else { - printedDiff = printDiffOrStringify(finalExpected, typedReceived.get("raw"), "Expected", "Received", false); + printedDiff = printDiffOrStringify(finalExpected, typedReceived.get("raw"), "Expected", "Received"); } MatcherMessageDetails details = new MatcherMessageDetails(); details.isNot = state.isNot; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchText.java b/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchText.java index 3f6a8d338..d1dffedbd 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchText.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchText.java @@ -27,10 +27,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.JestMatcherUtils.EXPECTED_COLOR; -import static com.microsoft.playwright.impl.JestMatcherUtils.printDiffOrStringify; -import static com.microsoft.playwright.impl.JestMatcherUtils.printExpected; -import static com.microsoft.playwright.impl.JestMatcherUtils.printWithType; +import static com.microsoft.playwright.impl.MatcherUtils.printDiffOrStringify; +import static com.microsoft.playwright.impl.MatcherUtils.printExpected; import static com.microsoft.playwright.impl.MatcherHint.formatMatcherMessage; import static com.microsoft.playwright.impl.MatcherHint.printReceivedStringContainExpectedResult; import static com.microsoft.playwright.impl.MatcherHint.printReceivedStringContainExpectedSubstring; @@ -53,7 +51,7 @@ static MatcherResult toMatchText( !(expected instanceof String) && !(expected instanceof Pattern) ) { - String errorMessage = "Error: " + EXPECTED_COLOR("expected") + " value must be a string or regular expression\n" + printWithType("Expected", expected, JestMatcherUtils::printExpected); + String errorMessage = "Error: expected value must be a string or regular expression\n" + "Expected has value: " + printExpected(expected); MatcherMessageDetails details = new MatcherMessageDetails(); details.promise = state.promise; details.isNot = state.isNot; @@ -85,7 +83,7 @@ static MatcherResult toMatchText( String expectedSuffix = expected instanceof String ? (matchSubstring ? " substring" : "") : " pattern"; String receivedSuffix = expected instanceof String ? (matchSubstring ? " string" : "") : " string"; // java: a received value that is not a string keeps its text. - String receivedValue = received == null || received.value == null || received.value == JestGetType.UNDEFINED ? null : String.valueOf(received.value); + String receivedValue = received == null || received.value == null || received.value == MatcherUtils.UNDEFINED ? null : String.valueOf(received.value); String receivedString = receivedValue == null ? "" : receivedValue; String printedReceived = null; String printedExpected = null; @@ -109,7 +107,7 @@ static MatcherResult toMatchText( if (errorMessage != null) printedExpected = "Expected" + expectedSuffix + ": " + printExpected(expected); else - printedDiff = printDiffOrStringify(expected, receivedString, "Expected" + expectedSuffix, "Received" + receivedSuffix, false); + printedDiff = printDiffOrStringify(expected, receivedString, "Expected" + expectedSuffix, "Received" + receivedSuffix); } String finalPrintedExpected = printedExpected; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssParser.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssParser.java deleted file mode 100644 index 1afaefe59..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssParser.java +++ /dev/null @@ -1,363 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Port of isomorphic/cssParser.ts. -package com.microsoft.playwright.impl.isomorphic; - -import com.microsoft.playwright.PlaywrightException; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; - -// java: the types of the file are nested classes. A CSSFunctionArgument is an Object holding a CSSComplexSelector, -// a Double or a String. serializeSelector is not ported, the locator generators do not use it. -public final class CssParser { - private CssParser() { - } - - public static class InvalidSelectorError extends PlaywrightException { - public InvalidSelectorError(String message) { - super(message); - } - } - - public static boolean isInvalidSelectorError(Throwable error) { - return error instanceof InvalidSelectorError; - } - - public static class CSSFunction { - public String name; - public List args; - - CSSFunction(String name, List args) { - this.name = name; - this.args = args; - } - } - - public static class CSSSimpleSelector { - public String css; - public List functions; - - CSSSimpleSelector(String css, List functions) { - this.css = css; - this.functions = functions; - } - } - - // java: the type of an item of CSSComplexSelector.simples. - public static class CSSSimple { - public CSSSimpleSelector selector; - public String combinator; - - CSSSimple(CSSSimpleSelector selector, String combinator) { - this.selector = selector; - this.combinator = combinator; - } - } - - public static class CSSComplexSelector { - public List simples = new ArrayList<>(); - } - - // java: the object that parseCSS() returns. - public static class ParsedCSS { - public List selector; - public List names; - } - - public static ParsedCSS parseCSS(String selector, Set customNames) { - List tokens; - try { - tokens = CssTokenizer.tokenize(selector); - // java: the item before the first one of an empty list is undefined upstream. - if (tokens.isEmpty() || !(tokens.get(tokens.size() - 1) instanceof CssTokenizer.EOFToken)) - tokens.add(new CssTokenizer.EOFToken()); - } catch (RuntimeException e) { - // java: the message of an exception is final, so a new exception with the new message wraps the caught one. - String newMessage = e.getMessage() + " while parsing css selector \"" + selector + "\". Did you mean to CSS.escape it?"; - throw new PlaywrightException(newMessage, e); - } - CssTokenizer.CSSTokenInterface unsupportedToken = null; - for (CssTokenizer.CSSTokenInterface token : tokens) { - if ((token instanceof CssTokenizer.AtKeywordToken) || - (token instanceof CssTokenizer.BadStringToken) || - (token instanceof CssTokenizer.BadURLToken) || - (token instanceof CssTokenizer.ColumnToken) || - (token instanceof CssTokenizer.CDOToken) || - (token instanceof CssTokenizer.CDCToken) || - (token instanceof CssTokenizer.SemicolonToken) || - (token instanceof CssTokenizer.OpenCurlyToken) || - (token instanceof CssTokenizer.CloseCurlyToken) || - (token instanceof CssTokenizer.URLToken) || - (token instanceof CssTokenizer.PercentageToken)) { - unsupportedToken = token; - break; - } - } - if (unsupportedToken != null) - throw new InvalidSelectorError("Unsupported token \"" + unsupportedToken.toSource() + "\" while parsing css selector \"" + selector + "\". Did you mean to CSS.escape it?"); - - Parser parser = new Parser(selector, customNames, tokens); - List result = parser.consumeFunctionArguments(); - if (!parser.isEOF()) - throw parser.unexpected(); - List complexSelectors = new ArrayList<>(); - for (Object arg : result) { - if (!(arg instanceof CSSComplexSelector)) - throw new InvalidSelectorError("Error while parsing css selector \"" + selector + "\". Did you mean to CSS.escape it?"); - complexSelectors.add((CSSComplexSelector) arg); - } - ParsedCSS parsed = new ParsedCSS(); - parsed.selector = complexSelectors; - parsed.names = new ArrayList<>(parser.names); - return parsed; - } - - // java: the local variables and the nested functions of parseCSS() are the fields and the methods of this class. - private static class Parser { - private final String selector; - private final Set customNames; - private final List tokens; - private int pos = 0; - private final Set names = new LinkedHashSet<>(); - - Parser(String selector, Set customNames, List tokens) { - this.selector = selector; - this.customNames = customNames; - this.tokens = tokens; - } - - InvalidSelectorError unexpected() { - return new InvalidSelectorError("Unexpected token \"" + tokens.get(pos).toSource() + "\" while parsing css selector \"" + selector + "\". Did you mean to CSS.escape it?"); - } - - void skipWhitespace() { - while (tokens.get(pos) instanceof CssTokenizer.WhitespaceToken) - pos++; - } - - boolean isIdent() { - return isIdent(pos); - } - - boolean isIdent(int p) { - return tokens.get(p) instanceof CssTokenizer.IdentToken; - } - - boolean isString() { - return isString(pos); - } - - boolean isString(int p) { - return tokens.get(p) instanceof CssTokenizer.StringToken; - } - - boolean isNumber() { - return isNumber(pos); - } - - boolean isNumber(int p) { - return tokens.get(p) instanceof CssTokenizer.NumberToken; - } - - boolean isComma() { - return isComma(pos); - } - - boolean isComma(int p) { - return tokens.get(p) instanceof CssTokenizer.CommaToken; - } - - boolean isOpenParen() { - return isOpenParen(pos); - } - - boolean isOpenParen(int p) { - return tokens.get(p) instanceof CssTokenizer.OpenParenToken; - } - - boolean isCloseParen() { - return isCloseParen(pos); - } - - boolean isCloseParen(int p) { - return tokens.get(p) instanceof CssTokenizer.CloseParenToken; - } - - boolean isFunction() { - return isFunction(pos); - } - - boolean isFunction(int p) { - return tokens.get(p) instanceof CssTokenizer.FunctionToken; - } - - boolean isStar() { - return isStar(pos); - } - - boolean isStar(int p) { - return (tokens.get(p) instanceof CssTokenizer.DelimToken) && "*".equals(tokens.get(p).value()); - } - - boolean isEOF() { - return isEOF(pos); - } - - boolean isEOF(int p) { - return tokens.get(p) instanceof CssTokenizer.EOFToken; - } - - boolean isClauseCombinator() { - return isClauseCombinator(pos); - } - - boolean isClauseCombinator(int p) { - return (tokens.get(p) instanceof CssTokenizer.DelimToken) && (Arrays.asList(">", "+", "~").contains((String) tokens.get(p).value())); - } - - boolean isSelectorClauseEnd() { - return isSelectorClauseEnd(pos); - } - - boolean isSelectorClauseEnd(int p) { - return isComma(p) || isCloseParen(p) || isEOF(p) || isClauseCombinator(p) || (tokens.get(p) instanceof CssTokenizer.WhitespaceToken); - } - - List consumeFunctionArguments() { - List result = new ArrayList<>(); - result.add(consumeArgument()); - while (true) { - skipWhitespace(); - if (!isComma()) - break; - pos++; - result.add(consumeArgument()); - } - return result; - } - - Object consumeArgument() { - skipWhitespace(); - if (isNumber()) - return tokens.get(pos++).value(); - if (isString()) - return tokens.get(pos++).value(); - return consumeComplexSelector(); - } - - CSSComplexSelector consumeComplexSelector() { - CSSComplexSelector result = new CSSComplexSelector(); - skipWhitespace(); - if (isClauseCombinator()) { - List functions = new ArrayList<>(); - functions.add(new CSSFunction("scope", new ArrayList<>())); - result.simples.add(new CSSSimple(new CSSSimpleSelector(null, functions), "")); - } else { - result.simples.add(new CSSSimple(consumeSimpleSelector(), "")); - } - while (true) { - skipWhitespace(); - if (isClauseCombinator()) { - result.simples.get(result.simples.size() - 1).combinator = (String) tokens.get(pos++).value(); - skipWhitespace(); - } else if (isSelectorClauseEnd()) { - break; - } - result.simples.add(new CSSSimple(consumeSimpleSelector(), "")); - } - return result; - } - - CSSSimpleSelector consumeSimpleSelector() { - String rawCSSString = ""; - List functions = new ArrayList<>(); - - while (!isSelectorClauseEnd()) { - if (isIdent() || isStar()) { - rawCSSString += tokens.get(pos++).toSource(); - } else if (tokens.get(pos) instanceof CssTokenizer.HashToken) { - rawCSSString += tokens.get(pos++).toSource(); - } else if ((tokens.get(pos) instanceof CssTokenizer.DelimToken) && ".".equals(tokens.get(pos).value())) { - pos++; - if (isIdent()) - rawCSSString += "." + tokens.get(pos++).toSource(); - else - throw unexpected(); - } else if (tokens.get(pos) instanceof CssTokenizer.ColonToken) { - pos++; - if (isIdent()) { - if (!customNames.contains(((String) tokens.get(pos).value()).toLowerCase(Locale.ROOT))) { - rawCSSString += ":" + tokens.get(pos++).toSource(); - } else { - String name = ((String) tokens.get(pos++).value()).toLowerCase(Locale.ROOT); - functions.add(new CSSFunction(name, new ArrayList<>())); - names.add(name); - } - } else if (isFunction()) { - String name = ((String) tokens.get(pos++).value()).toLowerCase(Locale.ROOT); - if (!customNames.contains(name)) { - rawCSSString += ":" + name + "(" + consumeBuiltinFunctionArguments() + ")"; - } else { - functions.add(new CSSFunction(name, consumeFunctionArguments())); - names.add(name); - } - skipWhitespace(); - if (!isCloseParen()) - throw unexpected(); - pos++; - } else { - throw unexpected(); - } - } else if (tokens.get(pos) instanceof CssTokenizer.OpenSquareToken) { - rawCSSString += "["; - pos++; - while (!(tokens.get(pos) instanceof CssTokenizer.CloseSquareToken) && !isEOF()) - rawCSSString += tokens.get(pos++).toSource(); - if (!(tokens.get(pos) instanceof CssTokenizer.CloseSquareToken)) - throw unexpected(); - rawCSSString += "]"; - pos++; - } else { - throw unexpected(); - } - } - if (rawCSSString.isEmpty() && functions.isEmpty()) - throw unexpected(); - return new CSSSimpleSelector(rawCSSString.isEmpty() ? null : rawCSSString, functions); - } - - String consumeBuiltinFunctionArguments() { - String s = ""; - int balance = 1; - while (!isEOF()) { - if (isOpenParen() || isFunction()) - balance++; - if (isCloseParen()) - balance--; - if (balance == 0) - break; - s += tokens.get(pos++).toSource(); - } - return s; - } - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssTokenizer.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssTokenizer.java deleted file mode 100644 index 5d1d01d2e..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/CssTokenizer.java +++ /dev/null @@ -1,995 +0,0 @@ -/* - * The code in this file is licensed under the CC0 license. - * http://creativecommons.org/publicdomain/zero/1.0/ - * It is free to use for any purpose. No attribution, permission, or reproduction of this license is required. - */ - -// Port of isomorphic/cssTokenizer.ts. -package com.microsoft.playwright.impl.isomorphic; - -import com.microsoft.playwright.PlaywrightException; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -// java: the token classes are nested classes of this class. A code point is an int, -1 where upstream reads NaN. -// A number value is a Double. toJSON is not ported. -public final class CssTokenizer { - private CssTokenizer() { - } - - // java: the value property is a method. - public interface CSSTokenInterface { - String toSource(); - Object value(); - } - - private static boolean between(int num, int first, int last) { return num >= first && num <= last; } - private static boolean digit(int code) { return between(code, 0x30, 0x39); } - private static boolean hexdigit(int code) { return digit(code) || between(code, 0x41, 0x46) || between(code, 0x61, 0x66); } - private static boolean uppercaseletter(int code) { return between(code, 0x41, 0x5a); } - private static boolean lowercaseletter(int code) { return between(code, 0x61, 0x7a); } - private static boolean letter(int code) { return uppercaseletter(code) || lowercaseletter(code); } - private static boolean nonascii(int code) { return code >= 0x80; } - private static boolean namestartchar(int code) { return letter(code) || nonascii(code) || code == 0x5f; } - private static boolean namechar(int code) { return namestartchar(code) || digit(code) || code == 0x2d; } - private static boolean nonprintable(int code) { return between(code, 0, 8) || code == 0xb || between(code, 0xe, 0x1f) || code == 0x7f; } - private static boolean newline(int code) { return code == 0xa; } - private static boolean whitespace(int code) { return newline(code) || code == 9 || code == 0x20; } - - private static final int maximumallowedcodepoint = 0x10ffff; - - public static class InvalidCharacterError extends PlaywrightException { - public InvalidCharacterError(String message) { - super(message); - } - } - - private static List preprocess(String str) { - List codepoints = new ArrayList<>(); - for (int i = 0; i < str.length(); i++) { - int code = charCodeAt(str, i); - if (code == 0xd && charCodeAt(str, i + 1) == 0xa) { - code = 0xa; i++; - } - if (code == 0xd || code == 0xc) - code = 0xa; - if (code == 0x0) - code = 0xfffd; - if (between(code, 0xd800, 0xdbff) && between(charCodeAt(str, i + 1), 0xdc00, 0xdfff)) { - int lead = code - 0xd800; - int trail = charCodeAt(str, i + 1) - 0xdc00; - code = (1 << 16) + lead * (1 << 10) + trail; - i++; - } - codepoints.add(code); - } - return codepoints; - } - - private static String stringFromCode(int code) { - if (code <= 0xffff) - return String.valueOf((char) code); - code -= 1 << 16; - int lead = code / (1 << 10) + 0xd800; - int trail = code % (1 << 10) + 0xdc00; - return String.valueOf((char) lead) + String.valueOf((char) trail); - } - - public static List tokenize(String str1) { - return new Tokenizer(str1).tokenize(); - } - - // java: the local variables and the closures of tokenize() are the fields and the methods of this class. - private static class Tokenizer { - private final List str; - private int i = -1; - private final List tokens = new ArrayList<>(); - private int code; - - private int line = 0; - private int column = 0; - private int lastLineLength = 0; - // java: locStart is two fields. - private int locStartLine = line; - private int locStartColumn = column; - - Tokenizer(String str1) { - str = preprocess(str1); - } - - private void incrLineno() { - line += 1; - lastLineLength = column; - column = 0; - } - - private int codepoint(int i) { - if (i >= str.size()) - return -1; - - return str.get(i); - } - - private int next() { - return next(1); - } - - private int next(int num) { - if (num > 3) - throw new PlaywrightException("Spec Error: no more than three codepoints of lookahead."); - return codepoint(i + num); - } - - private boolean consume() { - return consume(1); - } - - private boolean consume(int num) { - i += num; - code = codepoint(i); - if (newline(code)) - incrLineno(); - else - column += num; - return true; - } - - private boolean reconsume() { - i -= 1; - if (newline(code)) { - line -= 1; - column = lastLineLength; - } else { - column -= 1; - } - locStartLine = line; - locStartColumn = column; - return true; - } - - private boolean eof() { - return eof(code); - } - - private boolean eof(int codepoint) { - return codepoint == -1; - } - - private void donothing() { - } - - private void parseerror() { - } - - private CSSTokenInterface consumeAToken() { - consumeComments(); - consume(); - if (whitespace(code)) { - while (whitespace(next())) - consume(); - return new WhitespaceToken(); - } else if (code == 0x22) {return consumeAStringToken();} else if (code == 0x23) { - if (namechar(next()) || areAValidEscape(next(1), next(2))) { - HashToken token = new HashToken(""); - if (wouldStartAnIdentifier(next(1), next(2), next(3))) - token.type = "id"; - token.value = consumeAName(); - return token; - } else { - return new DelimToken(code); - } - } else if (code == 0x24) { - if (next() == 0x3d) { - consume(); - return new SuffixMatchToken(); - } else { - return new DelimToken(code); - } - } else if (code == 0x27) {return consumeAStringToken();} else if (code == 0x28) {return new OpenParenToken();} else if (code == 0x29) {return new CloseParenToken();} else if (code == 0x2a) { - if (next() == 0x3d) { - consume(); - return new SubstringMatchToken(); - } else { - return new DelimToken(code); - } - } else if (code == 0x2b) { - if (startsWithANumber()) { - reconsume(); - return consumeANumericToken(); - } else { - return new DelimToken(code); - } - } else if (code == 0x2c) {return new CommaToken();} else if (code == 0x2d) { - if (startsWithANumber()) { - reconsume(); - return consumeANumericToken(); - } else if (next(1) == 0x2d && next(2) == 0x3e) { - consume(2); - return new CDCToken(); - } else if (startsWithAnIdentifier()) { - reconsume(); - return consumeAnIdentlikeToken(); - } else { - return new DelimToken(code); - } - } else if (code == 0x2e) { - if (startsWithANumber()) { - reconsume(); - return consumeANumericToken(); - } else { - return new DelimToken(code); - } - } else if (code == 0x3a) {return new ColonToken();} else if (code == 0x3b) {return new SemicolonToken();} else if (code == 0x3c) { - if (next(1) == 0x21 && next(2) == 0x2d && next(3) == 0x2d) { - consume(3); - return new CDOToken(); - } else { - return new DelimToken(code); - } - } else if (code == 0x40) { - if (wouldStartAnIdentifier(next(1), next(2), next(3))) - return new AtKeywordToken(consumeAName()); - else - return new DelimToken(code); - - } else if (code == 0x5b) {return new OpenSquareToken();} else if (code == 0x5c) { - if (startsWithAValidEscape()) { - reconsume(); - return consumeAnIdentlikeToken(); - } else { - parseerror(); - return new DelimToken(code); - } - } else if (code == 0x5d) {return new CloseSquareToken();} else if (code == 0x5e) { - if (next() == 0x3d) { - consume(); - return new PrefixMatchToken(); - } else { - return new DelimToken(code); - } - } else if (code == 0x7b) {return new OpenCurlyToken();} else if (code == 0x7c) { - if (next() == 0x3d) { - consume(); - return new DashMatchToken(); - } else if (next() == 0x7c) { - consume(); - return new ColumnToken(); - } else { - return new DelimToken(code); - } - } else if (code == 0x7d) {return new CloseCurlyToken();} else if (code == 0x7e) { - if (next() == 0x3d) { - consume(); - return new IncludeMatchToken(); - } else { - return new DelimToken(code); - } - } else if (digit(code)) { - reconsume(); - return consumeANumericToken(); - } else if (namestartchar(code)) { - reconsume(); - return consumeAnIdentlikeToken(); - } else if (eof()) {return new EOFToken();} else {return new DelimToken(code);} - } - - private void consumeComments() { - while (next(1) == 0x2f && next(2) == 0x2a) { - consume(2); - while (true) { - consume(); - if (code == 0x2a && next() == 0x2f) { - consume(); - break; - } else if (eof()) { - parseerror(); - return; - } - } - } - } - - private CSSTokenInterface consumeANumericToken() { - ConsumedNumber num = consumeANumber(); - if (wouldStartAnIdentifier(next(1), next(2), next(3))) { - DimensionToken token = new DimensionToken(); - token.value = num.value; - token.repr = num.repr; - token.type = num.type; - token.unit = consumeAName(); - return token; - } else if (next() == 0x25) { - consume(); - PercentageToken token = new PercentageToken(); - token.value = num.value; - token.repr = num.repr; - return token; - } else { - NumberToken token = new NumberToken(); - token.value = num.value; - token.repr = num.repr; - token.type = num.type; - return token; - } - } - - private CSSTokenInterface consumeAnIdentlikeToken() { - String str = consumeAName(); - if (str.toLowerCase(Locale.ROOT).equals("url") && next() == 0x28) { - consume(); - while (whitespace(next(1)) && whitespace(next(2))) - consume(); - if (next() == 0x22 || next() == 0x27) - return new FunctionToken(str); - else if (whitespace(next()) && (next(2) == 0x22 || next(2) == 0x27)) - return new FunctionToken(str); - else - return consumeAURLToken(); - - } else if (next() == 0x28) { - consume(); - return new FunctionToken(str); - } else { - return new IdentToken(str); - } - } - - private CSSParserToken consumeAStringToken() { - return consumeAStringToken(code); - } - - private CSSParserToken consumeAStringToken(int endingCodePoint) { - String string = ""; - while (consume()) { - if (code == endingCodePoint || eof()) { - return new StringToken(string); - } else if (newline(code)) { - parseerror(); - reconsume(); - return new BadStringToken(); - } else if (code == 0x5c) { - if (eof(next())) - donothing(); - else if (newline(next())) - consume(); - else - string += stringFromCode(consumeEscape()); - - } else { - string += stringFromCode(code); - } - } - throw new PlaywrightException("Internal error"); - } - - private CSSTokenInterface consumeAURLToken() { - URLToken token = new URLToken(""); - while (whitespace(next())) - consume(); - if (eof(next())) - return token; - while (consume()) { - if (code == 0x29 || eof()) { - return token; - } else if (whitespace(code)) { - while (whitespace(next())) - consume(); - if (next() == 0x29 || eof(next())) { - consume(); - return token; - } else { - consumeTheRemnantsOfABadURL(); - return new BadURLToken(); - } - } else if (code == 0x22 || code == 0x27 || code == 0x28 || nonprintable(code)) { - parseerror(); - consumeTheRemnantsOfABadURL(); - return new BadURLToken(); - } else if (code == 0x5c) { - if (startsWithAValidEscape()) { - token.value = token.value + stringFromCode(consumeEscape()); - } else { - parseerror(); - consumeTheRemnantsOfABadURL(); - return new BadURLToken(); - } - } else { - token.value = token.value + stringFromCode(code); - } - } - throw new PlaywrightException("Internal error"); - } - - private int consumeEscape() { - consume(); - if (hexdigit(code)) { - List digits = new ArrayList<>(); - digits.add(code); - for (int total = 0; total < 5; total++) { - if (hexdigit(next())) { - consume(); - digits.add(code); - } else { - break; - } - } - if (whitespace(next())) - consume(); - StringBuilder joined = new StringBuilder(); - for (int x : digits) - joined.append((char) x); - int value = Integer.parseInt(joined.toString(), 16); - if (value > maximumallowedcodepoint) - value = 0xfffd; - return value; - } else if (eof()) { - return 0xfffd; - } else { - return code; - } - } - - private boolean areAValidEscape(int c1, int c2) { - if (c1 != 0x5c) - return false; - if (newline(c2)) - return false; - return true; - } - - private boolean startsWithAValidEscape() { - return areAValidEscape(code, next()); - } - - private boolean wouldStartAnIdentifier(int c1, int c2, int c3) { - if (c1 == 0x2d) - return namestartchar(c2) || c2 == 0x2d || areAValidEscape(c2, c3); - else if (namestartchar(c1)) - return true; - else if (c1 == 0x5c) - return areAValidEscape(c1, c2); - else - return false; - - } - - private boolean startsWithAnIdentifier() { - return wouldStartAnIdentifier(code, next(1), next(2)); - } - - private boolean wouldStartANumber(int c1, int c2, int c3) { - if (c1 == 0x2b || c1 == 0x2d) { - if (digit(c2)) - return true; - if (c2 == 0x2e && digit(c3)) - return true; - return false; - } else if (c1 == 0x2e) { - if (digit(c2)) - return true; - return false; - } else if (digit(c1)) { - return true; - } else { - return false; - } - } - - private boolean startsWithANumber() { - return wouldStartANumber(code, next(1), next(2)); - } - - private String consumeAName() { - String result = ""; - while (consume()) { - if (namechar(code)) { - result += stringFromCode(code); - } else if (startsWithAValidEscape()) { - result += stringFromCode(consumeEscape()); - } else { - reconsume(); - return result; - } - } - throw new PlaywrightException("Internal parse error"); - } - - private ConsumedNumber consumeANumber() { - String repr = ""; - String type = "integer"; - if (next() == 0x2b || next() == 0x2d) { - consume(); - repr += stringFromCode(code); - } - while (digit(next())) { - consume(); - repr += stringFromCode(code); - } - if (next(1) == 0x2e && digit(next(2))) { - consume(); - repr += stringFromCode(code); - consume(); - repr += stringFromCode(code); - type = "number"; - while (digit(next())) { - consume(); - repr += stringFromCode(code); - } - } - int c1 = next(1); - int c2 = next(2); - int c3 = next(3); - if ((c1 == 0x45 || c1 == 0x65) && digit(c2)) { - consume(); - repr += stringFromCode(code); - consume(); - repr += stringFromCode(code); - type = "number"; - while (digit(next())) { - consume(); - repr += stringFromCode(code); - } - } else if ((c1 == 0x45 || c1 == 0x65) && (c2 == 0x2b || c2 == 0x2d) && digit(c3)) { - consume(); - repr += stringFromCode(code); - consume(); - repr += stringFromCode(code); - consume(); - repr += stringFromCode(code); - type = "number"; - while (digit(next())) { - consume(); - repr += stringFromCode(code); - } - } - double value = convertAStringToANumber(repr); - ConsumedNumber result = new ConsumedNumber(); - result.type = type; - result.value = value; - result.repr = repr; - return result; - } - - // java: the repr is a decimal literal with a digit after the dot, which Double.parseDouble reads like the unary plus. - private double convertAStringToANumber(String string) { - return Double.parseDouble(string); - } - - private void consumeTheRemnantsOfABadURL() { - while (consume()) { - if (code == 0x29 || eof()) { - return; - } else if (startsWithAValidEscape()) { - consumeEscape(); - donothing(); - } else { - donothing(); - } - } - } - - List tokenize() { - int iterationCount = 0; - while (!eof(next())) { - tokens.add(consumeAToken()); - iterationCount++; - if (iterationCount > str.size() * 2) - throw new PlaywrightException("I'm infinite-looping!"); - } - return tokens; - } - } - - // java: the object that consumeANumber() returns. - private static class ConsumedNumber { - String type; - double value; - String repr; - } - - // java: a subclass sets tokenType and value in an initializer block or in its constructor. - public static class CSSParserToken implements CSSTokenInterface { - String tokenType = ""; - Object value; - @Override - public String toString() { return tokenType; } - @Override - public String toSource() { return "" + this; } - @Override - public Object value() { return value; } - } - - public static class BadStringToken extends CSSParserToken { - { tokenType = "BADSTRING"; } - } - - public static class BadURLToken extends CSSParserToken { - { tokenType = "BADURL"; } - } - - public static class WhitespaceToken extends CSSParserToken { - { tokenType = "WHITESPACE"; } - @Override - public String toString() { return "WS"; } - @Override - public String toSource() { return " "; } - } - - public static class CDOToken extends CSSParserToken { - { tokenType = "CDO"; } - @Override - public String toSource() { return ""; } - } - - public static class ColonToken extends CSSParserToken { - { tokenType = ":"; } - } - - public static class SemicolonToken extends CSSParserToken { - { tokenType = ";"; } - } - - public static class CommaToken extends CSSParserToken { - { tokenType = ","; } - } - - public static class GroupingToken extends CSSParserToken { - { value = ""; } - String mirror = ""; - } - - public static class OpenCurlyToken extends GroupingToken { - { tokenType = "{"; } - public OpenCurlyToken() { - super(); - this.value = "{"; - this.mirror = "}"; - } - } - - public static class CloseCurlyToken extends GroupingToken { - { tokenType = "}"; } - public CloseCurlyToken() { - super(); - this.value = "}"; - this.mirror = "{"; - } - } - - public static class OpenSquareToken extends GroupingToken { - { tokenType = "["; } - public OpenSquareToken() { - super(); - this.value = "["; - this.mirror = "]"; - } - } - - public static class CloseSquareToken extends GroupingToken { - { tokenType = "]"; } - public CloseSquareToken() { - super(); - this.value = "]"; - this.mirror = "["; - } - } - - public static class OpenParenToken extends GroupingToken { - { tokenType = "("; } - public OpenParenToken() { - super(); - this.value = "("; - this.mirror = ")"; - } - } - - public static class CloseParenToken extends GroupingToken { - { tokenType = ")"; } - public CloseParenToken() { - super(); - this.value = ")"; - this.mirror = "("; - } - } - - public static class IncludeMatchToken extends CSSParserToken { - { tokenType = "~="; } - } - - public static class DashMatchToken extends CSSParserToken { - { tokenType = "|="; } - } - - public static class PrefixMatchToken extends CSSParserToken { - { tokenType = "^="; } - } - - public static class SuffixMatchToken extends CSSParserToken { - { tokenType = "$="; } - } - - public static class SubstringMatchToken extends CSSParserToken { - { tokenType = "*="; } - } - - public static class ColumnToken extends CSSParserToken { - { tokenType = "||"; } - } - - public static class EOFToken extends CSSParserToken { - { tokenType = "EOF"; } - @Override - public String toSource() { return ""; } - } - - public static class DelimToken extends CSSParserToken { - { tokenType = "DELIM"; } - - public DelimToken(int code) { - super(); - this.value = stringFromCode(code); - } - - @Override - public String toString() { return "DELIM(" + this.value + ")"; } - - @Override - public String toSource() { - if (this.value.equals("\\")) - return "\\\n"; - else - return (String) this.value; - } - } - - public abstract static class StringValuedToken extends CSSParserToken { - { value = ""; } - public boolean ASCIIMatch(String str) { - return ((String) this.value).toLowerCase(Locale.ROOT).equals(str.toLowerCase(Locale.ROOT)); - } - } - - public static class IdentToken extends StringValuedToken { - public IdentToken(String val) { - super(); - this.value = val; - } - - { tokenType = "IDENT"; } - @Override - public String toString() { return "IDENT(" + this.value + ")"; } - @Override - public String toSource() { - return escapeIdent((String) this.value); - } - } - - public static class FunctionToken extends StringValuedToken { - { tokenType = "FUNCTION"; } - String mirror; - public FunctionToken(String val) { - super(); - this.value = val; - this.mirror = ")"; - } - - @Override - public String toString() { return "FUNCTION(" + this.value + ")"; } - - @Override - public String toSource() { - return escapeIdent((String) this.value) + "("; - } - } - - public static class AtKeywordToken extends StringValuedToken { - { tokenType = "AT-KEYWORD"; } - public AtKeywordToken(String val) { - super(); - this.value = val; - } - @Override - public String toString() { return "AT(" + this.value + ")"; } - @Override - public String toSource() { - return "@" + escapeIdent((String) this.value); - } - } - - public static class HashToken extends StringValuedToken { - { tokenType = "HASH"; } - String type; - public HashToken(String val) { - super(); - this.value = val; - this.type = "unrestricted"; - } - - @Override - public String toString() { return "HASH(" + this.value + ")"; } - - @Override - public String toSource() { - if (this.type.equals("id")) - return "#" + escapeIdent((String) this.value); - else - return "#" + escapeHash((String) this.value); - - } - } - - public static class StringToken extends StringValuedToken { - { tokenType = "STRING"; } - public StringToken(String val) { - super(); - this.value = val; - } - - @Override - public String toString() { - return "\"" + escapeString((String) this.value) + "\""; - } - } - - public static class URLToken extends StringValuedToken { - { tokenType = "URL"; } - public URLToken(String val) { - super(); - this.value = val; - } - @Override - public String toString() { return "URL(" + this.value + ")"; } - @Override - public String toSource() { - return "url(\"" + escapeString((String) this.value) + "\")"; - } - } - - public static class NumberToken extends CSSParserToken { - { tokenType = "NUMBER"; } - String type; - String repr; - - public NumberToken() { - super(); - this.type = "integer"; - this.repr = ""; - } - - @Override - public String toString() { - if (this.type.equals("integer")) - return "INT(" + this.value + ")"; - return "NUMBER(" + this.value + ")"; - } - @Override - public String toSource() { return this.repr; } - } - - - public static class PercentageToken extends CSSParserToken { - { tokenType = "PERCENTAGE"; } - String repr; - public PercentageToken() { - super(); - this.repr = ""; - } - @Override - public String toString() { return "PERCENTAGE(" + this.value + ")"; } - @Override - public String toSource() { return this.repr + "%"; } - } - - public static class DimensionToken extends CSSParserToken { - { tokenType = "DIMENSION"; } - String type; - String repr; - String unit; - - public DimensionToken() { - super(); - this.type = "integer"; - this.repr = ""; - this.unit = ""; - } - - @Override - public String toString() { return "DIM(" + this.value + "," + this.unit + ")"; } - @Override - public String toSource() { - String source = this.repr; - String unit = escapeIdent(this.unit); - if (unit.substring(0, 1).toLowerCase(Locale.ROOT).equals("e") && (charCodeAt(unit, 1) == '-' || between(charCodeAt(unit, 1), 0x30, 0x39))) { - unit = "\\65 " + unit.substring(1, unit.length()); - } - return source + unit; - } - } - - private static String escapeIdent(String string) { - String result = ""; - int firstcode = charCodeAt(string, 0); - for (int i = 0; i < string.length(); i++) { - int code = charCodeAt(string, i); - if (code == 0x0) - throw new InvalidCharacterError("Invalid character: the input contains U+0000."); - - if ( - between(code, 0x1, 0x1f) || code == 0x7f || - (i == 0 && between(code, 0x30, 0x39)) || - (i == 1 && between(code, 0x30, 0x39) && firstcode == 0x2d) - ) - result += "\\" + Integer.toString(code, 16) + " "; - else if ( - code >= 0x80 || - code == 0x2d || - code == 0x5f || - between(code, 0x30, 0x39) || - between(code, 0x41, 0x5a) || - between(code, 0x61, 0x7a) - ) - result += string.charAt(i); - else - result += "\\" + string.charAt(i); - - } - return result; - } - - private static String escapeHash(String string) { - String result = ""; - for (int i = 0; i < string.length(); i++) { - int code = charCodeAt(string, i); - if (code == 0x0) - throw new InvalidCharacterError("Invalid character: the input contains U+0000."); - - if ( - code >= 0x80 || - code == 0x2d || - code == 0x5f || - between(code, 0x30, 0x39) || - between(code, 0x41, 0x5a) || - between(code, 0x61, 0x7a) - ) - result += string.charAt(i); - else - result += "\\" + Integer.toString(code, 16) + " "; - - } - return result; - } - - private static String escapeString(String string) { - String result = ""; - for (int i = 0; i < string.length(); i++) { - int code = charCodeAt(string, i); - - if (code == 0x0) - throw new InvalidCharacterError("Invalid character: the input contains U+0000."); - - if (between(code, 0x1, 0x1f) || code == 0x7f) - result += "\\" + Integer.toString(code, 16) + " "; - else if (code == 0x22 || code == 0x5c) - result += "\\" + string.charAt(i); - else - result += string.charAt(i); - - } - return result; - } - - // java: helpers with no counterpart upstream. - - // java: String.prototype.charCodeAt, -1 where it returns NaN. - private static int charCodeAt(String string, int index) { - return index < string.length() ? string.charAt(index) : -1; - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/RegExp.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/RegExp.java index 2ebc11a2e..6fb130b38 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/RegExp.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/RegExp.java @@ -57,9 +57,9 @@ private static String escapeSource(String pattern) { result.append("\\n"); else if (escaped == '\r') result.append("\\r"); - else if (escaped == '
') + else if (escaped == '\u2028') result.append("\\u2028"); - else if (escaped == '
') + else if (escaped == '\u2029') result.append("\\u2029"); else result.append(c).append(escaped); @@ -75,9 +75,9 @@ else if (c == '\n') result.append("\\n"); else if (c == '\r') result.append("\\r"); - else if (c == '
') + else if (c == '\u2028') result.append("\\u2028"); - else if (c == '
') + else if (c == '\u2029') result.append("\\u2029"); else result.append(c); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/SelectorParser.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/SelectorParser.java index af62ab7c5..9dc7be84e 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/SelectorParser.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/SelectorParser.java @@ -19,7 +19,7 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; -import com.microsoft.playwright.impl.isomorphic.CssParser.InvalidSelectorError; +import com.microsoft.playwright.PlaywrightException; import java.util.ArrayList; import java.util.Arrays; @@ -29,7 +29,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.isomorphic.CssParser.parseCSS; import static com.microsoft.playwright.impl.isomorphic.StringUtils.JS_WHITESPACE; import static com.microsoft.playwright.impl.isomorphic.StringUtils.jsTrim; import static com.microsoft.playwright.impl.isomorphic.StringUtils.jsonParse; @@ -37,11 +36,19 @@ import static com.microsoft.playwright.impl.isomorphic.StringUtils.toNumber; // java: the types of the file are nested classes. kAnyFrameSelector, splitSelectorByFrame and visitAllSelectorParts -// are not ported, the locator generators do not use them. +// are not ported, the locator generators do not use them. There is no port of cssParser.ts and cssTokenizer.ts: +// the body of a css part is its source, and a css selector that upstream rejects is not rejected here. public final class SelectorParser { private SelectorParser() { } + // java: InvalidSelectorError of cssParser.ts. + public static class InvalidSelectorError extends PlaywrightException { + public InvalidSelectorError(String message) { + super(message); + } + } + public static class NestedSelectorBody { public ParsedSelector parsed; public Double distance; @@ -50,7 +57,7 @@ public static class NestedSelectorBody { private static final Set kNestedSelectorNames = new HashSet<>(Arrays.asList("internal:has", "internal:has-not", "internal:and", "internal:or", "internal:chain", "left-of", "right-of", "above", "below", "near")); private static final Set kNestedSelectorNamesWithDistance = new HashSet<>(Arrays.asList("left-of", "right-of", "above", "below", "near")); - // java: the body is an Object holding a String, a List or a NestedSelectorBody. + // java: the body is an Object holding a String or a NestedSelectorBody. public static class ParsedSelectorPart { public String name; public Object body; @@ -88,7 +95,7 @@ private static class ParsedSelectorStrings { Integer capture; } - public static final Set customCSSNames = new HashSet<>(Arrays.asList("not", "is", "where", "has", "scope", "light", "visible", "text", "text-matches", "text-is", "has-text", "above", "below", "right-of", "left-of", "near", "nth-match")); + // java: no customCSSNames, parseCSS reads them. public static ParsedSelector parseSelector(String selector) { ParsedSelectorStrings parsedStrings = parseSelectorString(selector); @@ -97,10 +104,10 @@ public static ParsedSelector parseSelector(String selector) { if (part.name.equals("css") || part.name.equals("css:light")) { if (part.name.equals("css:light")) part.body = ":light(" + part.body + ")"; - CssParser.ParsedCSS parsedCSS = parseCSS(part.body, customCSSNames); + // java: no parseCSS, the body is the source. parts.add(new ParsedSelectorPart( "css", - parsedCSS.selector, + part.body, part.body )); continue; diff --git a/playwright/src/test/java/com/microsoft/playwright/TestLocatorGenerators.java b/playwright/src/test/java/com/microsoft/playwright/TestLocatorGenerators.java index 53514c167..78e8b5f3f 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestLocatorGenerators.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestLocatorGenerators.java @@ -276,7 +276,9 @@ void reverseEngineerRegexFlags() { void asLocatorDescriptionInvalidInput() { assertEquals("desc", asLocatorDescription("java", "body >> internal:describe=\"desc\"")); assertEquals("locator(\"body\")", asLocatorDescription("java", "body >> internal:describe=12")); - assertEquals("following-sibling::*[1]", asLocatorDescription("java", "following-sibling::*[1]")); + assertEquals("div >> internal:has=bad", asLocatorDescription("java", "div >> internal:has=bad")); + // The client does not parse css, so an invalid css selector is not rejected. + assertEquals("locator(\"following-sibling::*[1]\")", asLocatorDescription("java", "following-sibling::*[1]")); assertEquals("locator(\"body\").locator(\"div\")", asLocatorDescription("java", "body >> internal:describe=\"desc\" >> div")); } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java index e6c85a4e0..c572893de 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java @@ -709,7 +709,8 @@ void invalidSelectorErrorFormat(Page page) { () -> assertThat(page.locator("##")).isVisible()); assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).isVisible() failed\n" + "\n" + - "Locator: ##\n" + + // Java: the client does not parse css, so the locator is not printed as the raw selector. + "Locator: locator(\"##\")\n" + "Expected: visible\n" + "Error: Unexpected token \"#\" while parsing css selector \"##\". Did you mean to CSS.escape it?\n" + "\n" + From e54762b43b0bf113a238105b79377249ef0f608a Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Mon, 23 Nov 2026 14:05:22 -0800 Subject: [PATCH 4/6] chore: print the locator with the driver, do not port the locator generators --- playwright/src/main/AGENTS.md | 4 +- .../microsoft/playwright/impl/LocalUtils.java | 8 + .../playwright/impl/LocatorImpl.java | 27 +- .../playwright/impl/MatcherHint.java | 2 +- .../playwright/impl/MatcherUtils.java | 11 +- .../impl/isomorphic/LocatorGenerators.java | 559 ------------------ .../playwright/impl/isomorphic/RegExp.java | 92 --- .../impl/isomorphic/SelectorParser.java | 536 ----------------- .../impl/isomorphic/StringUtils.java | 52 +- .../playwright/TestLocatorGenerators.java | 290 --------- .../playwright/tests/page/TestExpectMisc.java | 3 +- 11 files changed, 44 insertions(+), 1540 deletions(-) delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorGenerators.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/RegExp.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/SelectorParser.java delete mode 100644 playwright/src/test/java/com/microsoft/playwright/TestLocatorGenerators.java diff --git a/playwright/src/main/AGENTS.md b/playwright/src/main/AGENTS.md index 5f43f363e..7b0232d38 100644 --- a/playwright/src/main/AGENTS.md +++ b/playwright/src/main/AGENTS.md @@ -35,8 +35,8 @@ Java code around the place it goes to, and write the new lines the same way. layout without matching jest in every case. 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/cssParser.ts` and `cssTokenizer.ts` are not ported: `SelectorParser` keeps the - source of a css part and does not reject an invalid css selector. +- `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 `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, diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LocalUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/LocalUtils.java index 87be2ac77..619f1f4aa 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocalUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocalUtils.java @@ -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(); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java index 310ab068c..c3b519ddd 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java @@ -34,8 +34,6 @@ import java.util.regex.Pattern; import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; -import static com.microsoft.playwright.impl.isomorphic.LocatorGenerators.asLocatorDescription; -import static com.microsoft.playwright.impl.isomorphic.LocatorGenerators.locatorCustomDescription; import static com.microsoft.playwright.impl.isomorphic.LocatorUtils.*; import static com.microsoft.playwright.impl.Serialization.gson; import static com.microsoft.playwright.impl.Serialization.serializeArgument; @@ -357,10 +355,19 @@ public Locator describe(String description) { return new LocatorImpl(frame, selector + " >> internal:describe=" + gson().toJson(description)); } + // java: there is no port of the selector parser; this matches the trailing internal:describe part + // that upstream locatorCustomDescription() reads. @Override public String description() { - String description = locatorCustomDescription(selector); - return description == null || description.isEmpty() ? null : description; + Matcher matcher = Pattern.compile(" >> internal:describe=(\"(?:[^\"\\\\]|\\\\.)*\")$").matcher(selector); + if (!matcher.find()) + return null; + try { + String description = gson().fromJson(matcher.group(1), String.class); + return description == null || description.isEmpty() ? null : description; + } catch (RuntimeException e) { + return null; + } } @Override @@ -699,10 +706,18 @@ FrameExpectResult expect(String expression, FrameExpectOptions options) { // java: no _inspect, it serves inspect.custom. - // java: the language is java, not javascript: the Java client prints Java locator code. + // java: there is no port of the locator generators: the driver prints the Java locator code. When it cannot + // be asked (the connection is closed), the text is the description or Locator@. @Override public String toString() { - return asLocatorDescription("java", selector); + try { + return frame.connection.localUtils().asLocatorDescription(selector); + } catch (PlaywrightException e) { + String description = description(); + if (description != null) + return description; + return "Locator@" + selector; + } } // java: the module-level _testIdAttributeName is SelectorsImpl.testIdAttributeName of the Playwright instance, diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/MatcherHint.java b/playwright/src/main/java/com/microsoft/playwright/impl/MatcherHint.java index e0c340f43..6108bcfb6 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/MatcherHint.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/MatcherHint.java @@ -21,8 +21,8 @@ import java.util.function.Supplier; import java.util.regex.Matcher; +import static com.microsoft.playwright.impl.MatcherUtils.numberToString; import static com.microsoft.playwright.impl.MatcherUtils.printReceived; -import static com.microsoft.playwright.impl.isomorphic.StringUtils.numberToString; class MatcherHint { // java: no attachments, suggestedRebaseline, softError and shouldNotRetryTest, they belong to the test runner. diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/MatcherUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/MatcherUtils.java index 99374102d..a78c651b0 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/MatcherUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/MatcherUtils.java @@ -27,7 +27,6 @@ import java.util.regex.Pattern; import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; -import static com.microsoft.playwright.impl.isomorphic.StringUtils.numberToString; // java: the utils of a matcher. Upstream they are jest-matcher-utils, which is not ported: these methods print the // Java values in the same format, without colors, and the diff is a plain line diff. @@ -178,6 +177,16 @@ private static String formatBasicValue(Object value) { return String.valueOf(value); } + static String numberToString(double value) { + if (Double.isNaN(value)) + return "NaN"; + if (Double.isInfinite(value)) + return value > 0 ? "Infinity" : "-Infinity"; + if (value == Math.rint(value) && Math.abs(value) < 1e15) + return String.valueOf((long) value); + return Double.toString(value); + } + private static String quote(String value) { return "\"" + value.replaceAll("\"|\\\\", "\\\\$0") + "\""; } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorGenerators.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorGenerators.java deleted file mode 100644 index a010a770a..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorGenerators.java +++ /dev/null @@ -1,559 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Port of isomorphic/locatorGenerators.ts. -package com.microsoft.playwright.impl.isomorphic; - -import com.google.gson.JsonElement; -import com.microsoft.playwright.PlaywrightException; -import com.microsoft.playwright.impl.isomorphic.SelectorParser.AttributeSelector; -import com.microsoft.playwright.impl.isomorphic.SelectorParser.AttributeSelectorPart; -import com.microsoft.playwright.impl.isomorphic.SelectorParser.NestedSelectorBody; -import com.microsoft.playwright.impl.isomorphic.SelectorParser.ParsedSelector; -import com.microsoft.playwright.impl.isomorphic.SelectorParser.ParsedSelectorPart; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.function.Supplier; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.microsoft.playwright.impl.isomorphic.SelectorParser.parseAttributeSelector; -import static com.microsoft.playwright.impl.isomorphic.SelectorParser.parseSelector; -import static com.microsoft.playwright.impl.isomorphic.SelectorParser.stringifySelector; -import static com.microsoft.playwright.impl.isomorphic.SelectorParser.valueToString; -import static com.microsoft.playwright.impl.isomorphic.StringUtils.escapeWithQuotes; -import static com.microsoft.playwright.impl.isomorphic.StringUtils.jsonParse; -import static com.microsoft.playwright.impl.isomorphic.StringUtils.normalizeEscapedRegexQuotes; -import static com.microsoft.playwright.impl.isomorphic.StringUtils.toNumber; -import static com.microsoft.playwright.impl.isomorphic.StringUtils.toSnakeCase; -import static com.microsoft.playwright.impl.isomorphic.StringUtils.toTitleCase; - -// java: only the JavaLocatorFactory is ported, the JavaScript, Python, CSharp and Jsonl factories are not: the client -// prints Java code. Language, LocatorType and LocatorBase are a String. A string | RegExp is an Object holding -// a String or a RegExp. There is no preferredQuote parameter, only the JavaScript factory reads it. -public final class LocatorGenerators { - private LocatorGenerators() { - } - - // java: the type of an item of LocatorOptions.attrs. The value is a String, a Boolean, a Double, a RegExp or null. - static class LocatorOptionsAttr { - String name; - Object value; - - LocatorOptionsAttr(String name, Object value) { - this.name = name; - this.value = value; - } - } - - static class LocatorOptions { - List attrs; - Boolean exact; - Object name; - Object description; - Object hasText; - Object hasNotText; - } - - public interface LocatorFactory { - String generateLocator(String base, String kind, Object body, LocatorOptions options); - String chainLocators(List locators); - // java: the overload for the optional options parameter. - default String generateLocator(String base, String kind, Object body) { - return generateLocator(base, kind, body, null); - } - } - - public static String asLocatorDescription(String lang, String selector) { - try { - ParsedSelector parsed = parseSelector(selector); - String customDescription = parseCustomDescription(parsed); - if (customDescription != null && !customDescription.isEmpty()) - return customDescription; - return innerAsLocators(generators.get(lang).get(), parsed, false, 1).get(0); - } catch (RuntimeException e) { - return selector; - } - } - - public static String locatorCustomDescription(String selector) { - try { - ParsedSelector parsed = parseSelector(selector); - return parseCustomDescription(parsed); - } catch (RuntimeException e) { - return null; - } - } - - private static String parseCustomDescription(ParsedSelector parsed) { - ParsedSelectorPart lastPart = parsed.parts.get(parsed.parts.size() - 1); - if (lastPart.name.equals("internal:describe")) { - JsonElement description = jsonParse((String) lastPart.body); - if (description.isJsonPrimitive() && description.getAsJsonPrimitive().isString()) - return description.getAsString(); - } - return null; - } - - public static String asLocator(String lang, String selector) { - return asLocator(lang, selector, false); - } - - public static String asLocator(String lang, String selector, boolean isFrameLocator) { - return asLocators(lang, selector, isFrameLocator, 1).get(0); - } - - public static List asLocators(String lang, String selector) { - return asLocators(lang, selector, false, 20); - } - - public static List asLocators(String lang, String selector, boolean isFrameLocator, int maxOutputSize) { - try { - return innerAsLocators(generators.get(lang).get(), parseSelector(selector), isFrameLocator, maxOutputSize); - } catch (RuntimeException e) { - return new ArrayList<>(Collections.singletonList(selector)); - } - } - - private static List innerAsLocators(LocatorFactory factory, ParsedSelector parsed, boolean isFrameLocator, int maxOutputSize) { - List parts = new ArrayList<>(parsed.parts); - List> tokens = new ArrayList<>(); - String nextBase = isFrameLocator ? "frame-locator" : "page"; - for (int index = 0; index < parts.size(); index++) { - ParsedSelectorPart part = parts.get(index); - String base = nextBase; - nextBase = "locator"; - - if (part.name.equals("internal:describe")) - continue; - if (part.name.equals("nth")) { - if ("0".equals(part.body)) - tokens.add(listOf(factory.generateLocator(base, "first", ""), factory.generateLocator(base, "nth", "0"))); - else if ("-1".equals(part.body)) - tokens.add(listOf(factory.generateLocator(base, "last", ""), factory.generateLocator(base, "nth", "-1"))); - else - tokens.add(listOf(factory.generateLocator(base, "nth", (String) part.body))); - continue; - } - if (part.name.equals("visible")) { - List tokenList = new ArrayList<>(); - if ("true".equals(part.body)) - tokenList.add(factory.generateLocator(base, "visible", "")); - tokenList.add(factory.generateLocator(base, "filter-visible", (String) part.body)); - tokenList.add(factory.generateLocator(base, "default", "visible=" + part.body)); - tokens.add(tokenList); - continue; - } - if (part.name.equals("internal:text")) { - DetectedExact detected = detectExact((String) part.body); - LocatorOptions options = new LocatorOptions(); - options.exact = detected.exact; - tokens.add(listOf(factory.generateLocator(base, "text", detected.text, options))); - continue; - } - if (part.name.equals("internal:has-text")) { - DetectedExact detected = detectExact((String) part.body); - if (!(detected.exact != null && detected.exact)) { - LocatorOptions options = new LocatorOptions(); - options.exact = detected.exact; - tokens.add(listOf(factory.generateLocator(base, "has-text", detected.text, options))); - continue; - } - } - if (part.name.equals("internal:has-not-text")) { - DetectedExact detected = detectExact((String) part.body); - if (!(detected.exact != null && detected.exact)) { - LocatorOptions options = new LocatorOptions(); - options.exact = detected.exact; - tokens.add(listOf(factory.generateLocator(base, "has-not-text", detected.text, options))); - continue; - } - } - if (part.name.equals("internal:has")) { - List inners = innerAsLocators(factory, ((NestedSelectorBody) part.body).parsed, false, maxOutputSize); - List mapped = new ArrayList<>(); - for (String inner : inners) - mapped.add(factory.generateLocator(base, "has", inner)); - tokens.add(mapped); - continue; - } - if (part.name.equals("internal:has-not")) { - List inners = innerAsLocators(factory, ((NestedSelectorBody) part.body).parsed, false, maxOutputSize); - List mapped = new ArrayList<>(); - for (String inner : inners) - mapped.add(factory.generateLocator(base, "hasNot", inner)); - tokens.add(mapped); - continue; - } - if (part.name.equals("internal:and")) { - List inners = innerAsLocators(factory, ((NestedSelectorBody) part.body).parsed, false, maxOutputSize); - List mapped = new ArrayList<>(); - for (String inner : inners) - mapped.add(factory.generateLocator(base, "and", inner)); - tokens.add(mapped); - continue; - } - if (part.name.equals("internal:or")) { - List inners = innerAsLocators(factory, ((NestedSelectorBody) part.body).parsed, false, maxOutputSize); - List mapped = new ArrayList<>(); - for (String inner : inners) - mapped.add(factory.generateLocator(base, "or", inner)); - tokens.add(mapped); - continue; - } - if (part.name.equals("internal:chain")) { - List inners = innerAsLocators(factory, ((NestedSelectorBody) part.body).parsed, false, maxOutputSize); - List mapped = new ArrayList<>(); - for (String inner : inners) - mapped.add(factory.generateLocator(base, "chain", inner)); - tokens.add(mapped); - continue; - } - if (part.name.equals("internal:label")) { - DetectedExact detected = detectExact((String) part.body); - LocatorOptions options = new LocatorOptions(); - options.exact = detected.exact; - tokens.add(listOf(factory.generateLocator(base, "label", detected.text, options))); - continue; - } - if (part.name.equals("internal:role")) { - AttributeSelector attrSelector = parseAttributeSelector((String) part.body, true); - LocatorOptions options = new LocatorOptions(); - options.attrs = new ArrayList<>(); - for (AttributeSelectorPart attr : attrSelector.attributes) { - if (attr.name.equals("name") || attr.name.equals("description")) { - if (attr.value instanceof String) { - if (options.exact != null && options.exact != attr.caseSensitive) - throw new PlaywrightException("Conflicting exactness in internal:role selector: " + stringifySelector(new ParsedSelector(listOf(part)))); - options.exact = attr.caseSensitive; - } - if (attr.name.equals("name")) - options.name = attr.value; - else - options.description = attr.value; - } else { - if (attr.name.equals("level") && attr.value instanceof String) - attr.value = toNumber((String) attr.value); - options.attrs.add(new LocatorOptionsAttr(attr.name.equals("include-hidden") ? "includeHidden" : attr.name, attr.value)); - } - } - tokens.add(listOf(factory.generateLocator(base, "role", attrSelector.name, options))); - continue; - } - if (part.name.equals("internal:testid")) { - AttributeSelector attrSelector = parseAttributeSelector((String) part.body, true); - Object value = attrSelector.attributes.get(0).value; - tokens.add(listOf(factory.generateLocator(base, "test-id", value))); - continue; - } - if (part.name.equals("internal:attr")) { - AttributeSelector attrSelector = parseAttributeSelector((String) part.body, true); - String name = attrSelector.attributes.get(0).name; - Object text = attrSelector.attributes.get(0).value; - boolean exact = attrSelector.attributes.get(0).caseSensitive; - LocatorOptions options = new LocatorOptions(); - options.exact = exact; - if (name.equals("placeholder")) { - tokens.add(listOf(factory.generateLocator(base, "placeholder", text, options))); - continue; - } - if (name.equals("alt")) { - tokens.add(listOf(factory.generateLocator(base, "alt", text, options))); - continue; - } - if (name.equals("title")) { - tokens.add(listOf(factory.generateLocator(base, "title", text, options))); - continue; - } - } - if (part.name.equals("internal:control") && "any-frame".equals(part.body)) { - tokens.add(listOf(factory.generateLocator(base, "any-frame", ""))); - nextBase = "frame-locator"; - continue; - } - if (part.name.equals("internal:control") && "enter-frame".equals(part.body)) { - List lastTokens = tokens.get(tokens.size() - 1); - ParsedSelectorPart lastPart = parts.get(index - 1); - - List transformed = new ArrayList<>(); - for (String token : lastTokens) - transformed.add(factory.chainLocators(listOf(token, factory.generateLocator(base, "frame", "")))); - if (Arrays.asList("xpath", "css").contains(lastPart.name)) { - transformed.add(factory.generateLocator(base, "frame-locator", stringifySelector(new ParsedSelector(listOf(lastPart))))); - transformed.add(factory.generateLocator(base, "frame-locator", stringifySelector(new ParsedSelector(listOf(lastPart)), true))); - } - - lastTokens.clear(); - lastTokens.addAll(transformed); - nextBase = "frame-locator"; - continue; - } - - ParsedSelectorPart nextPart = index + 1 < parts.size() ? parts.get(index + 1) : null; - - String selectorPart = stringifySelector(new ParsedSelector(listOf(part))); - String locatorPart = factory.generateLocator(base, "default", selectorPart); - - if (nextPart != null && Arrays.asList("internal:has-text", "internal:has-not-text").contains(nextPart.name)) { - DetectedExact detected = detectExact((String) nextPart.body); - if (!(detected.exact != null && detected.exact)) { - LocatorOptions nextOptions = new LocatorOptions(); - nextOptions.exact = detected.exact; - String nextLocatorPart = factory.generateLocator("locator", nextPart.name.equals("internal:has-text") ? "has-text" : "has-not-text", detected.text, nextOptions); - LocatorOptions options = new LocatorOptions(); - if (nextPart.name.equals("internal:has-text")) - options.hasText = detected.text; - else - options.hasNotText = detected.text; - String combinedPart = factory.generateLocator(base, "default", selectorPart, options); - tokens.add(listOf(factory.chainLocators(listOf(locatorPart, nextLocatorPart)), combinedPart)); - index++; - continue; - } - } - - String locatorPartWithEngine = null; - if (Arrays.asList("xpath", "css").contains(part.name)) { - String selectorPartWithEngine = stringifySelector(new ParsedSelector(listOf(part)), true); - locatorPartWithEngine = factory.generateLocator(base, "default", selectorPartWithEngine); - } - - List tokenList = new ArrayList<>(); - for (String token : Arrays.asList(locatorPart, locatorPartWithEngine)) { - if (token != null && !token.isEmpty()) - tokenList.add(token); - } - tokens.add(tokenList); - } - - return combineTokens(factory, tokens, maxOutputSize); - } - - private static List combineTokens(LocatorFactory factory, List> tokens, int maxOutputSize) { - List currentTokens = new ArrayList<>(); - for (int i = 0; i < tokens.size(); i++) - currentTokens.add(""); - List result = new ArrayList<>(); - - visit(factory, tokens, maxOutputSize, currentTokens, result, 0); - return result; - } - - // java: the visit closure of combineTokens() is a method, the variables it captures are parameters. - private static boolean visit(LocatorFactory factory, List> tokens, int maxOutputSize, List currentTokens, List result, int index) { - if (index == tokens.size()) { - result.add(factory.chainLocators(currentTokens)); - return result.size() < maxOutputSize; - } - for (String taken : tokens.get(index)) { - currentTokens.set(index, taken); - if (!visit(factory, tokens, maxOutputSize, currentTokens, result, index + 1)) - return false; - } - return true; - } - - // java: the object that detectExact() returns. - private static class DetectedExact { - Boolean exact; - Object text; - - DetectedExact(Boolean exact, Object text) { - this.exact = exact; - this.text = text; - } - } - - // java: the dot of a JS RegExp does not match the line terminators, and its $ only matches at the end. - private static DetectedExact detectExact(String text) { - boolean exact = false; - Matcher match = Pattern.compile("/([^\\n\\r\\u2028\\u2029]*)/([dgimsuvy]*)").matcher(text); - if (match.matches()) - return new DetectedExact(null, new RegExp(match.group(1), match.group(2))); - if (text.endsWith("\"")) { - text = jsonParse(text).getAsString(); - exact = true; - } else if (text.endsWith("\"s")) { - text = jsonParse(text.substring(0, text.length() - 1)).getAsString(); - exact = true; - } else if (text.endsWith("\"i")) { - text = jsonParse(text.substring(0, text.length() - 1)).getAsString(); - exact = false; - } - return new DetectedExact(exact, text); - } - - // java: a body that is not a String or a RegExp (a boolean, a number or null attribute value) fails the cast to - // String, so asLocator() returns the selector; upstream quotes a part of JSON.stringify(body), "ru" for true. - public static class JavaLocatorFactory implements LocatorFactory { - @Override - public String generateLocator(String base, String kind, Object body, LocatorOptions options) { - if (options == null) - options = new LocatorOptions(); - String clazz = null; - switch (base) { - case "page": clazz = "Page"; break; - case "frame-locator": clazz = "FrameLocator"; break; - case "locator": clazz = "Locator"; break; - } - switch (kind) { - case "default": - if (options.hasText != null) - return "locator(" + this.quote((String) body) + ", new " + clazz + ".LocatorOptions().setHasText(" + this.toHasText(options.hasText) + "))"; - if (options.hasNotText != null) - return "locator(" + this.quote((String) body) + ", new " + clazz + ".LocatorOptions().setHasNotText(" + this.toHasText(options.hasNotText) + "))"; - return "locator(" + this.quote((String) body) + ")"; - case "frame-locator": - return "frameLocator(" + this.quote((String) body) + ")"; - case "frame": - return "contentFrame()"; - case "any-frame": - return "frameLocator()"; - case "nth": - return "nth(" + body + ")"; - case "first": - return "first()"; - case "last": - return "last()"; - case "visible": - return "visible()"; - case "filter-visible": - return "filter(new " + clazz + ".FilterOptions().setVisible(" + ("true".equals(body) ? "true" : "false") + "))"; - case "role": - List attrs = new ArrayList<>(); - if (isRegExp(options.name)) - attrs.add(".setName(" + this.regexToString((RegExp) options.name) + ")"); - else if (options.name instanceof String) - attrs.add(".setName(" + this.quote((String) options.name) + ")"); - if (isRegExp(options.description)) - attrs.add(".setDescription(" + this.regexToString((RegExp) options.description) + ")"); - else if (options.description instanceof String) - attrs.add(".setDescription(" + this.quote((String) options.description) + ")"); - if (options.exact != null && options.exact && (options.name instanceof String || options.description instanceof String)) - attrs.add(".setExact(true)"); - for (LocatorOptionsAttr attr : options.attrs) - attrs.add(".set" + toTitleCase(attr.name) + "(" + (attr.value instanceof String ? this.quote((String) attr.value) : valueToString(attr.value)) + ")"); - String attrString = !attrs.isEmpty() ? ", new " + clazz + ".GetByRoleOptions()" + String.join("", attrs) : ""; - return "getByRole(AriaRole." + toSnakeCase((String) body).toUpperCase(Locale.ROOT) + attrString + ")"; - case "has-text": - return "filter(new " + clazz + ".FilterOptions().setHasText(" + this.toHasText(body) + "))"; - case "has-not-text": - return "filter(new " + clazz + ".FilterOptions().setHasNotText(" + this.toHasText(body) + "))"; - case "has": - return "filter(new " + clazz + ".FilterOptions().setHas(" + body + "))"; - case "hasNot": - return "filter(new " + clazz + ".FilterOptions().setHasNot(" + body + "))"; - case "and": - return "and(" + body + ")"; - case "or": - return "or(" + body + ")"; - case "chain": - return "locator(" + body + ")"; - case "test-id": - return "getByTestId(" + this.toTestIdValue(body) + ")"; - case "text": - return this.toCallWithExact(clazz, "getByText", body, options.exact != null && options.exact); - case "alt": - return this.toCallWithExact(clazz, "getByAltText", body, options.exact != null && options.exact); - case "placeholder": - return this.toCallWithExact(clazz, "getByPlaceholder", body, options.exact != null && options.exact); - case "label": - return this.toCallWithExact(clazz, "getByLabel", body, options.exact != null && options.exact); - case "title": - return this.toCallWithExact(clazz, "getByTitle", body, options.exact != null && options.exact); - default: - throw new PlaywrightException("Unknown selector kind " + kind); - } - } - - @Override - public String chainLocators(List locators) { - return String.join(".", locators); - } - - private String regexToString(RegExp body) { - String suffix = regexFlagsSuffix(body, "Pattern", regexFlagNames.get("java")); - return "Pattern.compile(" + this.quote(normalizeEscapedRegexQuotes(body.source)) + suffix + ")"; - } - - private String toCallWithExact(String clazz, String method, Object body, boolean exact) { - if (isRegExp(body)) - return method + "(" + this.regexToString((RegExp) body) + ")"; - if (exact) - return method + "(" + this.quote((String) body) + ", new " + clazz + "." + toTitleCase(method) + "Options().setExact(true))"; - return method + "(" + this.quote((String) body) + ")"; - } - - private String toHasText(Object body) { - if (isRegExp(body)) - return this.regexToString((RegExp) body); - return this.quote((String) body); - } - - private String toTestIdValue(Object value) { - if (isRegExp(value)) - return this.regexToString((RegExp) value); - return this.quote((String) value); - } - - private String quote(String text) { - return escapeWithQuotes(text, "\""); - } - } - - // java: only the java generator. - private static final Map> generators = new LinkedHashMap<>(); - static { - generators.put("java", JavaLocatorFactory::new); - } - - // java: only the java flag names. - public static final Map> regexFlagNames = new LinkedHashMap<>(); - static { - Map java = new LinkedHashMap<>(); - java.put("i", "CASE_INSENSITIVE"); - java.put("m", "MULTILINE"); - java.put("s", "DOTALL"); - regexFlagNames.put("java", java); - } - - private static String regexFlagsSuffix(RegExp body, String flagsEnum, Map names) { - List flags = new ArrayList<>(); - for (char flag : body.flags.toCharArray()) { - if (names.containsKey(String.valueOf(flag))) - flags.add(flagsEnum + "." + names.get(String.valueOf(flag))); - } - return !flags.isEmpty() ? ", " + String.join(" | ", flags) : ""; - } - - private static boolean isRegExp(Object obj) { - return obj instanceof RegExp; - } - - // java: helpers with no counterpart upstream. - - // java: an array literal, as a list that can be changed. - @SafeVarargs - private static List listOf(T... items) { - return new ArrayList<>(Arrays.asList(items)); - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/RegExp.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/RegExp.java deleted file mode 100644 index 6fb130b38..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/RegExp.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// java: no counterpart upstream. A JS RegExp of a selector, as its source and flags. It is never compiled: -// a Java Pattern does not accept every JS regular expression, and the generators only print it. -package com.microsoft.playwright.impl.isomorphic; - -import com.microsoft.playwright.PlaywrightException; - -public final class RegExp { - public final String source; - public final String flags; - - // java: the constructor of a JS RegExp throws on an invalid flag or a repeated one, and on an invalid source; - // the source is not checked here. - public RegExp(String source, String flags) { - StringBuilder canonicalFlags = new StringBuilder(); - for (char flag : "dgimsuvy".toCharArray()) { - int index = flags.indexOf(flag); - if (index == -1) - continue; - if (flags.indexOf(flag, index + 1) != -1) - throw new PlaywrightException("Invalid flags supplied to RegExp constructor '" + flags + "'"); - canonicalFlags.append(flag); - } - if (canonicalFlags.length() != flags.length() || (flags.contains("u") && flags.contains("v"))) - throw new PlaywrightException("Invalid flags supplied to RegExp constructor '" + flags + "'"); - this.source = escapeSource(source); - this.flags = canonicalFlags.toString(); - } - - // java: RegExp.prototype.source escapes a slash outside of a character class and the line terminators, - // and is (?:) for an empty pattern. - private static String escapeSource(String pattern) { - if (pattern.isEmpty()) - return "(?:)"; - StringBuilder result = new StringBuilder(); - boolean inClass = false; - for (int i = 0; i < pattern.length(); i++) { - char c = pattern.charAt(i); - if (c == '\\' && i + 1 < pattern.length()) { - char escaped = pattern.charAt(++i); - if (escaped == '\n') - result.append("\\n"); - else if (escaped == '\r') - result.append("\\r"); - else if (escaped == '\u2028') - result.append("\\u2028"); - else if (escaped == '\u2029') - result.append("\\u2029"); - else - result.append(c).append(escaped); - continue; - } - if (c == '[') - inClass = true; - else if (c == ']') - inClass = false; - if (c == '/' && !inClass) - result.append("\\/"); - else if (c == '\n') - result.append("\\n"); - else if (c == '\r') - result.append("\\r"); - else if (c == '\u2028') - result.append("\\u2028"); - else if (c == '\u2029') - result.append("\\u2029"); - else - result.append(c); - } - return result.toString(); - } - - @Override - public String toString() { - return "/" + source + "/" + flags; - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/SelectorParser.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/SelectorParser.java deleted file mode 100644 index 9dc7be84e..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/SelectorParser.java +++ /dev/null @@ -1,536 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Port of isomorphic/selectorParser.ts. -package com.microsoft.playwright.impl.isomorphic; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.microsoft.playwright.PlaywrightException; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.microsoft.playwright.impl.isomorphic.StringUtils.JS_WHITESPACE; -import static com.microsoft.playwright.impl.isomorphic.StringUtils.jsTrim; -import static com.microsoft.playwright.impl.isomorphic.StringUtils.jsonParse; -import static com.microsoft.playwright.impl.isomorphic.StringUtils.numberToString; -import static com.microsoft.playwright.impl.isomorphic.StringUtils.toNumber; - -// java: the types of the file are nested classes. kAnyFrameSelector, splitSelectorByFrame and visitAllSelectorParts -// are not ported, the locator generators do not use them. There is no port of cssParser.ts and cssTokenizer.ts: -// the body of a css part is its source, and a css selector that upstream rejects is not rejected here. -public final class SelectorParser { - private SelectorParser() { - } - - // java: InvalidSelectorError of cssParser.ts. - public static class InvalidSelectorError extends PlaywrightException { - public InvalidSelectorError(String message) { - super(message); - } - } - - public static class NestedSelectorBody { - public ParsedSelector parsed; - public Double distance; - } - - private static final Set kNestedSelectorNames = new HashSet<>(Arrays.asList("internal:has", "internal:has-not", "internal:and", "internal:or", "internal:chain", "left-of", "right-of", "above", "below", "near")); - private static final Set kNestedSelectorNamesWithDistance = new HashSet<>(Arrays.asList("left-of", "right-of", "above", "below", "near")); - - // java: the body is an Object holding a String or a NestedSelectorBody. - public static class ParsedSelectorPart { - public String name; - public Object body; - public String source; - - ParsedSelectorPart(String name, Object body, String source) { - this.name = name; - this.body = body; - this.source = source; - } - } - - public static class ParsedSelector { - public List parts; - public Integer capture; - - ParsedSelector(List parts) { - this.parts = parts; - } - } - - // java: the type of an item of ParsedSelectorStrings.parts. - private static class ParsedSelectorStringPart { - String name; - String body; - - ParsedSelectorStringPart(String name, String body) { - this.name = name; - this.body = body; - } - } - - private static class ParsedSelectorStrings { - List parts = new ArrayList<>(); - Integer capture; - } - - // java: no customCSSNames, parseCSS reads them. - - public static ParsedSelector parseSelector(String selector) { - ParsedSelectorStrings parsedStrings = parseSelectorString(selector); - List parts = new ArrayList<>(); - for (ParsedSelectorStringPart part : parsedStrings.parts) { - if (part.name.equals("css") || part.name.equals("css:light")) { - if (part.name.equals("css:light")) - part.body = ":light(" + part.body + ")"; - // java: no parseCSS, the body is the source. - parts.add(new ParsedSelectorPart( - "css", - part.body, - part.body - )); - continue; - } - if (kNestedSelectorNames.contains(part.name)) { - String innerSelector; - Double distance = null; - try { - JsonElement unescaped = jsonParse("[" + part.body + "]"); - if (!unescaped.isJsonArray() || unescaped.getAsJsonArray().size() < 1 || unescaped.getAsJsonArray().size() > 2 || !isJsonString(unescaped.getAsJsonArray().get(0))) - throw new InvalidSelectorError("Malformed selector: " + part.name + "=" + part.body); - JsonArray array = unescaped.getAsJsonArray(); - innerSelector = array.get(0).getAsString(); - if (array.size() == 2) { - if (!(array.get(1).isJsonPrimitive() && array.get(1).getAsJsonPrimitive().isNumber()) || !kNestedSelectorNamesWithDistance.contains(part.name)) - throw new InvalidSelectorError("Malformed selector: " + part.name + "=" + part.body); - distance = array.get(1).getAsDouble(); - } - } catch (RuntimeException e) { - throw new InvalidSelectorError("Malformed selector: " + part.name + "=" + part.body); - } - NestedSelectorBody nestedBody = new NestedSelectorBody(); - nestedBody.parsed = parseSelector(innerSelector); - nestedBody.distance = distance; - ParsedSelectorPart nested = new ParsedSelectorPart(part.name, nestedBody, part.body); - ParsedSelectorPart lastFrame = null; - for (int i = nestedBody.parsed.parts.size() - 1; i >= 0; i--) { - ParsedSelectorPart p = nestedBody.parsed.parts.get(i); - if (p.name.equals("internal:control") && "enter-frame".equals(p.body)) { - lastFrame = p; - break; - } - } - int lastFrameIndex = lastFrame != null ? nestedBody.parsed.parts.indexOf(lastFrame) : -1; - List outerParts = !parts.isEmpty() && parts.get(0).name.equals("internal:control") && "any-frame".equals(parts.get(0).body) ? slice(parts, 1, parts.size()) : parts; - if (lastFrameIndex != -1 && selectorPartsEqual(slice(nestedBody.parsed.parts, 0, lastFrameIndex + 1), slice(outerParts, 0, lastFrameIndex + 1))) { - nestedBody.parsed.parts.subList(0, lastFrameIndex + 1).clear(); - if (nestedBody.parsed.capture != null) { - if (nestedBody.parsed.capture <= lastFrameIndex) - throw new InvalidSelectorError("Can not capture the selector before diving into the frame. Only use * after the last frame has been selected"); - nestedBody.parsed.capture -= lastFrameIndex + 1; - } - } - parts.add(nested); - continue; - } - parts.add(new ParsedSelectorPart(part.name, part.body, part.body)); - } - if (kNestedSelectorNames.contains(parts.get(0).name)) - throw new InvalidSelectorError("\"" + parts.get(0).name + "\" selector cannot be first"); - ParsedSelector result = new ParsedSelector(parts); - result.capture = parsedStrings.capture; - return result; - } - - private static boolean selectorPartsEqual(List list1, List list2) { - return stringifySelector(new ParsedSelector(list1)).equals(stringifySelector(new ParsedSelector(list2))); - } - - public static String stringifySelector(String selector) { - return selector; - } - - public static String stringifySelector(ParsedSelector selector) { - return stringifySelector(selector, false); - } - - public static String stringifySelector(ParsedSelector selector, boolean forceEngineName) { - List result = new ArrayList<>(); - for (int i = 0; i < selector.parts.size(); i++) { - ParsedSelectorPart p = selector.parts.get(i); - boolean isCapture = selector.capture != null && i == selector.capture; - boolean includeEngine = true; - if (!forceEngineName && !isCapture) { - if (p.name.equals("css")) - includeEngine = false; - else if (p.name.equals("xpath") && (p.source.startsWith("//") || p.source.startsWith(".."))) - includeEngine = false; - } - String prefix = includeEngine ? p.name + "=" : ""; - result.add((isCapture ? "*" : "") + prefix + p.source); - } - return String.join(" >> ", result); - } - - private static ParsedSelectorStrings parseSelectorString(String selector) { - return new SelectorStringParser(selector).parse(); - } - - // java: the local variables and the closures of parseSelectorString() are the fields and the methods of this class. - private static class SelectorStringParser { - private final String selector; - private int index = 0; - private String quote; - private int start = 0; - private final ParsedSelectorStrings result = new ParsedSelectorStrings(); - - SelectorStringParser(String selector) { - this.selector = selector; - } - - private void append() { - String part = jsTrim(selector.substring(start, index)); - int eqIndex = part.indexOf('='); - String name; - String body; - if (eqIndex != -1 && jsTrim(part.substring(0, eqIndex)).matches("[a-zA-Z_0-9\\-+:*]+")) { - name = jsTrim(part.substring(0, eqIndex)); - body = part.substring(eqIndex + 1); - } else if (part.length() > 1 && part.charAt(0) == '"' && part.charAt(part.length() - 1) == '"') { - name = "text"; - body = part; - } else if (part.length() > 1 && part.charAt(0) == '\'' && part.charAt(part.length() - 1) == '\'') { - name = "text"; - body = part; - } else if (Pattern.compile("^\\(*//").matcher(part).find() || part.startsWith("..")) { - name = "xpath"; - body = part; - } else { - name = "css"; - body = part; - } - boolean capture = false; - if (name.charAt(0) == '*') { - capture = true; - name = name.substring(1); - } - result.parts.add(new ParsedSelectorStringPart(name, body)); - if (capture) { - if (result.capture != null) - throw new InvalidSelectorError("Only one of the selectors can capture using * modifier"); - result.capture = result.parts.size() - 1; - } - } - - // java: the dot of a JS RegExp does not match the line terminators, and its $ only matches at the end. - private boolean shouldIgnoreTextSelectorQuote() { - String prefix = selector.substring(start, index); - Matcher match = Pattern.compile(JS_WHITESPACE + "*text" + JS_WHITESPACE + "*=([^\\n\\r\\u2028\\u2029]*)").matcher(prefix); - return match.matches() && !match.group(1).isEmpty(); - } - - ParsedSelectorStrings parse() { - if (!selector.contains(">>")) { - index = selector.length(); - append(); - return result; - } - - while (index < selector.length()) { - String c = selector.substring(index, index + 1); - if (c.equals("\\") && index + 1 < selector.length()) { - index += 2; - } else if (c.equals(quote)) { - quote = null; - index++; - } else if (quote == null && (c.equals("\"") || c.equals("'") || c.equals("`")) && !shouldIgnoreTextSelectorQuote()) { - quote = c; - index++; - } else if (quote == null && c.equals(">") && index + 1 < selector.length() && selector.charAt(index + 1) == '>') { - append(); - index += 2; - start = index; - } else { - index++; - } - } - append(); - return result; - } - } - - // java: the value is an Object holding a String, a Boolean, a Double, a RegExp or null. - public static class AttributeSelectorPart { - public String name; - public List jsonPath; - public String op; - public Object value; - public boolean caseSensitive; - - AttributeSelectorPart(String name, List jsonPath, String op, Object value, boolean caseSensitive) { - this.name = name; - this.jsonPath = jsonPath; - this.op = op; - this.value = value; - this.caseSensitive = caseSensitive; - } - } - - public static class AttributeSelector { - public String name = ""; - public List attributes = new ArrayList<>(); - } - - - public static AttributeSelector parseAttributeSelector(String selector, boolean allowUnquotedStrings) { - return new AttributeSelectorParser(selector, allowUnquotedStrings).parse(); - } - - // java: the local variables and the nested functions of parseAttributeSelector() are the fields and the methods of - // this class. A character is a String of one char, empty at the end of the selector. - private static class AttributeSelectorParser { - private final String selector; - private final boolean allowUnquotedStrings; - private int wp = 0; - private boolean EOL; - - AttributeSelectorParser(String selector, boolean allowUnquotedStrings) { - this.selector = selector; - this.allowUnquotedStrings = allowUnquotedStrings; - EOL = selector.length() == 0; - } - - private String next() { - return wp < selector.length() ? selector.substring(wp, wp + 1) : ""; - } - - private String eat1() { - String result = next(); - ++wp; - EOL = wp >= selector.length(); - return result; - } - - private void syntaxError(String stage) { - if (EOL) - throw new InvalidSelectorError("Unexpected end of selector while parsing selector `" + selector + "`"); - throw new InvalidSelectorError("Error while parsing selector `" + selector + "` - unexpected symbol \"" + next() + "\" at position " + wp + (stage != null ? " during " + stage : "")); - } - - private void skipSpaces() { - while (!EOL && next().matches(JS_WHITESPACE)) - eat1(); - } - - // java: an empty string is not a name char; upstream compares it with the range bounds, which gives false. - private boolean isCSSNameChar(String ch) { - if (ch.isEmpty()) - return false; - char c = ch.charAt(0); - return (c >= '\u0080') - || (c >= '0' && c <= '9') - || (c >= 'A' && c <= 'Z') - || (c >= 'a' && c <= 'z') - || (c >= '0' && c <= '9') - || c == '_' - || c == '-'; - } - - private String readIdentifier() { - String result = ""; - skipSpaces(); - while (!EOL && isCSSNameChar(next())) - result += eat1(); - return result; - } - - private String readQuotedString(String quote) { - String result = eat1(); - if (!result.equals(quote)) - syntaxError("parsing quoted string"); - while (!EOL && !next().equals(quote)) { - if (next().equals("\\")) - eat1(); - result += eat1(); - } - if (!next().equals(quote)) - syntaxError("parsing quoted string"); - result += eat1(); - return result; - } - - private RegExp readRegularExpression() { - if (!eat1().equals("/")) - syntaxError("parsing regular expression"); - String source = ""; - boolean inClass = false; - while (!EOL) { - if (next().equals("\\")) { - source += eat1(); - if (EOL) - syntaxError("parsing regular expression"); - } else if (inClass && next().equals("]")) { - inClass = false; - } else if (!inClass && next().equals("[")) { - inClass = true; - } else if (!inClass && next().equals("/")) { - break; - } - source += eat1(); - } - if (!eat1().equals("/")) - syntaxError("parsing regular expression"); - String flags = ""; - while (!EOL && next().matches("[dgimsuvy]")) - flags += eat1(); - try { - return new RegExp(source, flags); - } catch (RuntimeException e) { - throw new InvalidSelectorError("Error while parsing selector `" + selector + "`: " + e.getMessage()); - } - } - - private String readAttributeToken() { - String token = ""; - skipSpaces(); - if (next().equals("'") || next().equals("\"")) { - String quoted = readQuotedString(next()); - token = quoted.substring(1, quoted.length() - 1); - } else { - token = readIdentifier(); - } - if (token.isEmpty()) - syntaxError("parsing property path"); - return token; - } - - private String readOperator() { - skipSpaces(); - String op = ""; - if (!EOL) - op += eat1(); - if (!EOL && (!op.equals("="))) - op += eat1(); - if (!Arrays.asList("=", "*=", "^=", "$=", "|=", "~=").contains(op)) - syntaxError("parsing operator"); - return op; - } - - private AttributeSelectorPart readAttribute() { - eat1(); - - List jsonPath = new ArrayList<>(); - jsonPath.add(readAttributeToken()); - skipSpaces(); - while (next().equals(".")) { - eat1(); - jsonPath.add(readAttributeToken()); - skipSpaces(); - } - if (next().equals("]")) { - eat1(); - return new AttributeSelectorPart(String.join(".", jsonPath), jsonPath, "", null, false); - } - - String operator = readOperator(); - - Object value = null; - boolean caseSensitive = true; - skipSpaces(); - if (next().equals("/")) { - if (!operator.equals("=")) - throw new InvalidSelectorError("Error while parsing selector `" + selector + "` - cannot use " + operator + " in attribute with regular expression"); - value = readRegularExpression(); - } else if (next().equals("'") || next().equals("\"")) { - String quoted = readQuotedString(next()); - value = quoted.substring(1, quoted.length() - 1); - skipSpaces(); - if (next().equals("i") || next().equals("I")) { - caseSensitive = false; - eat1(); - } else if (next().equals("s") || next().equals("S")) { - caseSensitive = true; - eat1(); - } - } else { - String unquoted = ""; - while (!EOL && (isCSSNameChar(next()) || next().equals("+") || next().equals("."))) - unquoted += eat1(); - value = unquoted; - if (unquoted.equals("true")) { - value = true; - } else if (unquoted.equals("false")) { - value = false; - } else { - if (!allowUnquotedStrings) { - value = toNumber(unquoted); - if (Double.isNaN((Double) value)) - syntaxError("parsing attribute value"); - } - } - } - skipSpaces(); - if (!next().equals("]")) - syntaxError("parsing attribute value"); - - eat1(); - if (!operator.equals("=") && !(value instanceof String)) - throw new InvalidSelectorError("Error while parsing selector `" + selector + "` - cannot use " + operator + " in attribute with non-string matching value - " + valueToString(value)); - return new AttributeSelectorPart(String.join(".", jsonPath), jsonPath, operator, value, caseSensitive); - } - - AttributeSelector parse() { - AttributeSelector result = new AttributeSelector(); - result.name = readIdentifier(); - skipSpaces(); - while (next().equals("[")) { - result.attributes.add(readAttribute()); - skipSpaces(); - } - if (!EOL) - syntaxError(null); - if (result.name.isEmpty() && result.attributes.isEmpty()) - throw new InvalidSelectorError("Error while parsing selector `" + selector + "` - selector cannot be empty"); - return result; - } - } - - // java: helpers with no counterpart upstream. - - private static boolean isJsonString(JsonElement element) { - return element.isJsonPrimitive() && element.getAsJsonPrimitive().isString(); - } - - // java: Array.prototype.slice, which clamps the indexes to the length. - private static List slice(List list, int start, int end) { - return new ArrayList<>(list.subList(Math.min(start, list.size()), Math.min(end, list.size()))); - } - - // java: String(value) of an attribute value. - static String valueToString(Object value) { - if (value instanceof Double) - return numberToString((Double) value); - return String.valueOf(value); - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java index 0e3ec729e..cde6ffca1 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java @@ -19,15 +19,8 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonParseException; -import com.google.gson.Strictness; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonToken; import com.microsoft.playwright.PlaywrightException; -import java.io.IOException; -import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -321,56 +314,13 @@ public static String jsonStringify(String value) { return gson.toJson(value); } - // java: JSON.parse; throws on malformed JSON. - public static JsonElement jsonParse(String text) { - try { - JsonReader reader = new JsonReader(new StringReader(text)); - reader.setStrictness(Strictness.STRICT); - JsonElement result = gson.getAdapter(JsonElement.class).read(reader); - if (reader.peek() != JsonToken.END_DOCUMENT) - throw new PlaywrightException("Unexpected non-whitespace character after JSON"); - return result; - } catch (IOException | IllegalStateException | JsonParseException e) { - throw new PlaywrightException("Malformed JSON: " + text, e); - } - } - - // java: String.prototype.trim, which removes the \s characters of a JS RegExp. - public static String jsTrim(String text) { - return text.replaceAll("^" + JS_WHITESPACE + "+|" + JS_WHITESPACE + "+$", ""); - } - - // java: the unary plus on a string. A hexadecimal literal and a decimal literal are converted, anything else is NaN. - public static double toNumber(String text) { - String trimmed = jsTrim(text); - if (trimmed.isEmpty()) - return 0; - if (trimmed.matches("0[xX][0-9a-fA-F]+")) - return new java.math.BigInteger(trimmed.substring(2), 16).doubleValue(); - if (trimmed.matches("[+-]?(Infinity|(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?)")) - return Double.parseDouble(trimmed); - return Double.NaN; - } - - // java: String(value) of a JS number. A whole number prints without a fraction; other numbers print as - // Double.toString() does, which differs from JS in the exponent form. - public static String numberToString(double value) { - if (Double.isNaN(value)) - return "NaN"; - if (Double.isInfinite(value)) - return value > 0 ? "Infinity" : "-Infinity"; - if (value == Math.rint(value) && Math.abs(value) < 1e15) - return String.valueOf((long) value); - return Double.toString(value); - } - // java: String(re) of a JS RegExp. private static String toJsRegExp(Pattern pattern) { return "/" + pattern.pattern() + "/" + toJsRegexFlags(pattern); } // java: the \s character class of a JS RegExp. - static final String JS_WHITESPACE = "[\\t\\n\\u000B\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]"; + private static final String JS_WHITESPACE = "[\\t\\n\\u000B\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]"; // java: String.prototype.replace with a global RegExp and a function that looks the match up in escaped. private static String replaceEach(String s, Pattern pattern) { diff --git a/playwright/src/test/java/com/microsoft/playwright/TestLocatorGenerators.java b/playwright/src/test/java/com/microsoft/playwright/TestLocatorGenerators.java deleted file mode 100644 index 78e8b5f3f..000000000 --- a/playwright/src/test/java/com/microsoft/playwright/TestLocatorGenerators.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.playwright; - -import com.microsoft.playwright.fixtures.PlaywrightTest; -import com.microsoft.playwright.options.AriaRole; - -import java.util.regex.Pattern; - -import static com.microsoft.playwright.impl.isomorphic.LocatorGenerators.asLocator; -import static com.microsoft.playwright.impl.isomorphic.LocatorGenerators.asLocatorDescription; -import static com.microsoft.playwright.impl.isomorphic.LocatorGenerators.asLocators; -import static java.util.Arrays.asList; -import static org.junit.jupiter.api.Assertions.assertEquals; - -// The java expectations of upstream tests/library/locator-generator.spec.ts. -public class TestLocatorGenerators { - private static String generate(Locator locator) { - return locator.toString(); - } - - @PlaywrightTest - void reverseEngineerLocators(Page page) { - assertEquals("getByTestId(\"Hello\")", generate(page.getByTestId("Hello"))); - assertEquals("getByTestId(\"He\\\"llo\")", generate(page.getByTestId("He\"llo"))); - assertEquals("getByTestId(Pattern.compile(\"He\\\"llo\"))", generate(page.getByTestId(Pattern.compile("He\"llo")))); - assertEquals("getByTestId(Pattern.compile(\"He\\\\\\\\\\\"llo\"))", generate(page.getByTestId(Pattern.compile("He\\\\\"llo")))); - assertEquals("getByText(\"Hello\", new Page.GetByTextOptions().setExact(true))", generate(page.getByText("Hello", new Page.GetByTextOptions().setExact(true)))); - assertEquals("getByText(\"Hello\")", generate(page.getByText("Hello"))); - assertEquals("getByText(Pattern.compile(\"Hello\"))", generate(page.getByText(Pattern.compile("Hello")))); - assertEquals("getByLabel(\"Name\")", generate(page.getByLabel("Name"))); - assertEquals("getByLabel(\"Last Name\", new Page.GetByLabelOptions().setExact(true))", generate(page.getByLabel("Last Name", new Page.GetByLabelOptions().setExact(true)))); - assertEquals("getByLabel(Pattern.compile(\"Last\\\\s+name\", Pattern.CASE_INSENSITIVE))", generate(page.getByLabel(Pattern.compile("Last\\s+name", Pattern.CASE_INSENSITIVE)))); - // Only JavaScript can express these flags, other languages drop them. - for (String flags : asList("u", "s", "y", "d", "v", "gm")) { - for (String[] engineAndMethod : asList(new String[] {"text", "getByText"}, new String[] {"label", "getByLabel"})) { - String selector = "internal:" + engineAndMethod[0] + "=/Hello/" + flags; - String suffix = ""; - if (flags.contains("s")) - suffix = ", Pattern.DOTALL"; - if (flags.contains("m")) - suffix = ", Pattern.MULTILINE"; - assertEquals(engineAndMethod[1] + "(Pattern.compile(\"Hello\"" + suffix + "))", asLocator("java", selector), selector); - } - } - - assertEquals("getByPlaceholder(\"hello\")", generate(page.getByPlaceholder("hello"))); - assertEquals("getByPlaceholder(\"Hello\", new Page.GetByPlaceholderOptions().setExact(true))", generate(page.getByPlaceholder("Hello", new Page.GetByPlaceholderOptions().setExact(true)))); - assertEquals("getByPlaceholder(Pattern.compile(\"wor\", Pattern.CASE_INSENSITIVE))", generate(page.getByPlaceholder(Pattern.compile("wor", Pattern.CASE_INSENSITIVE)))); - - assertEquals("getByAltText(\"hello\")", generate(page.getByAltText("hello"))); - assertEquals("getByAltText(\"Hello\", new Page.GetByAltTextOptions().setExact(true))", generate(page.getByAltText("Hello", new Page.GetByAltTextOptions().setExact(true)))); - assertEquals("getByAltText(Pattern.compile(\"wor\", Pattern.CASE_INSENSITIVE))", generate(page.getByAltText(Pattern.compile("wor", Pattern.CASE_INSENSITIVE)))); - - assertEquals("getByTitle(\"hello\")", generate(page.getByTitle("hello"))); - assertEquals("getByTitle(\"Hello\", new Page.GetByTitleOptions().setExact(true))", generate(page.getByTitle("Hello", new Page.GetByTitleOptions().setExact(true)))); - assertEquals("getByTitle(Pattern.compile(\"wor\", Pattern.CASE_INSENSITIVE))", generate(page.getByTitle(Pattern.compile("wor", Pattern.CASE_INSENSITIVE)))); - assertEquals("getByPlaceholder(\"hello my\\nwo\\\"rld\")", generate(page.getByPlaceholder("hello my\nwo\"rld"))); - assertEquals("getByAltText(\"hello my\\nwo\\\"rld\")", generate(page.getByAltText("hello my\nwo\"rld"))); - assertEquals("getByTitle(\"hello my\\nwo\\\"rld\")", generate(page.getByTitle("hello my\nwo\"rld"))); - } - - @PlaywrightTest - void reverseEngineerGetByRole(Page page) { - assertEquals("getByRole(AriaRole.BUTTON)", generate(page.getByRole(AriaRole.BUTTON))); - assertEquals("getByRole(AriaRole.HEADING)", generate(page.getByRole(AriaRole.HEADING, new Page.GetByRoleOptions()))); - assertEquals("getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Hello\"))", generate(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Hello")))); - assertEquals("getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(Pattern.compile(\"Hello\")))", generate(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(Pattern.compile("Hello"))))); - assertEquals("getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"He\\\"llo\").setExact(true))", generate(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("He\"llo").setExact(true)))); - assertEquals("getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setChecked(true).setLevel(3).setPressed(false))", generate(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setChecked(true).setPressed(false).setLevel(3)))); - assertEquals("getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setName(\"Upload\").setDescription(\"doc.pdf\"))", generate(page.getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setName("Upload").setDescription("doc.pdf")))); - assertEquals("getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setDescription(\"doc.pdf\"))", generate(page.getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setDescription("doc.pdf")))); - assertEquals("getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setDescription(Pattern.compile(\"doc\\\\.pdf\")))", generate(page.getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setDescription(Pattern.compile("doc\\.pdf"))))); - assertEquals("getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setName(\"Upload\").setDescription(\"doc.pdf\").setExact(true))", generate(page.getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setName("Upload").setDescription("doc.pdf").setExact(true)))); - } - - @PlaywrightTest - void refusesToTranslateInternalRoleWithConflictingNameDescriptionExactness() { - // https://github.com/microsoft/playwright/issues/41032 - String conflicting = "internal:role=row[name=\"abc\"i][description=\"d\"s]"; - String conflictingReversed = "internal:role=row[name=\"abc\"s][description=\"d\"i]"; - assertEquals(conflicting, asLocator("java", conflicting)); - assertEquals(conflictingReversed, asLocator("java", conflictingReversed)); - } - - @PlaywrightTest - void reverseEngineerInternalRoleWithRegexAndStringNameDescription() { - assertEquals("getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setName(Pattern.compile(\"Upload\")).setDescription(\"doc.pdf\"))", - asLocator("java", "internal:role=alert[name=/Upload/][description=\"doc.pdf\"i]")); - assertEquals("getByRole(AriaRole.ALERT, new Page.GetByRoleOptions().setName(\"Upload\").setDescription(Pattern.compile(\"doc\\\\.pdf\")))", - asLocator("java", "internal:role=alert[name=\"Upload\"i][description=/doc\\.pdf/]")); - } - - @PlaywrightTest - void reverseEngineerIgnoreCaseLocators(Page page) { - assertEquals("getByText(\"hello my\\nwo\\\"rld\")", generate(page.getByText("hello my\nwo\"rld"))); - assertEquals("getByText(\"hello my wo\\\"rld\")", generate(page.getByText("hello my wo\"rld"))); - assertEquals("getByLabel(\"hello my\\nwo\\\"rld\")", generate(page.getByLabel("hello my\nwo\"rld"))); - } - - @PlaywrightTest - void reverseEngineerOrderedLocators(Page page) { - assertEquals("locator(\"div\").nth(3).first().last()", generate(page.locator("div").nth(3).first().last())); - } - - @PlaywrightTest - void reverseEngineerLocatorsWithRegex(Page page) { - assertEquals("getByText(Pattern.compile(\"he\\\\/\\\\sl\\\\nlo\"))", generate(page.getByText(Pattern.compile("he\\/\\sl\\nlo")))); - assertEquals("getByPlaceholder(Pattern.compile(\"he\\\\/\\\\sl\\\\nlo\"))", generate(page.getByPlaceholder(Pattern.compile("he\\/\\sl\\nlo")))); - assertEquals("getByText(Pattern.compile(\"hel\\\"lo\"))", generate(page.getByText(Pattern.compile("hel\"lo")))); - assertEquals("getByPlaceholder(Pattern.compile(\"hel\\\"lo\"))", generate(page.getByPlaceholder(Pattern.compile("hel\"lo")))); - } - - @PlaywrightTest - void reverseEngineerHasText(Page page) { - assertEquals("getByText(\"Hello\").filter(new Locator.FilterOptions().setHasText(\"wo\\\"rld\\n\"))", - generate(page.getByText("Hello").filter(new Locator.FilterOptions().setHasText("wo\"rld\n")))); - assertEquals("getByText(\"Hello\").filter(new Locator.FilterOptions().setHasText(Pattern.compile(\"wo\\\\/\\\\srld\\\\n\")))", - generate(page.getByText("Hello").filter(new Locator.FilterOptions().setHasText(Pattern.compile("wo\\/\\srld\\n"))))); - assertEquals("getByText(\"Hello\").filter(new Locator.FilterOptions().setHasText(Pattern.compile(\"wor\\\"ld\")))", - generate(page.getByText("Hello").filter(new Locator.FilterOptions().setHasText(Pattern.compile("wor\"ld"))))); - } - - @PlaywrightTest - void reverseEngineerHasNotText(Page page) { - assertEquals("getByText(\"Hello\").filter(new Locator.FilterOptions().setHasNotText(\"wo\\\"rld\\n\"))", - generate(page.getByText("Hello").filter(new Locator.FilterOptions().setHasNotText("wo\"rld\n")))); - } - - @PlaywrightTest - void reverseEngineerVisible(Page page) { - assertEquals("getByText(\"Hello\").visible().locator(\"div\")", generate(page.getByText("Hello").visible().locator("div"))); - assertEquals("getByText(\"Hello\").filter(new Locator.FilterOptions().setVisible(false)).locator(\"div\")", - generate(page.getByText("Hello").filter(new Locator.FilterOptions().setVisible(false)).locator("div"))); - } - - @PlaywrightTest - void reverseEngineerHas(Page page) { - assertEquals("getByText(\"Hello\").filter(new Locator.FilterOptions().setHas(locator(\"div\").getByText(\"bye\")))", - generate(page.getByText("Hello").filter(new Locator.FilterOptions().setHas(page.locator("div").getByText("bye"))))); - - Locator locator = page - .locator("section") - .filter(new Locator.FilterOptions().setHas(page.locator("div").filter(new Locator.FilterOptions().setHas(page.locator("span"))))) - .filter(new Locator.FilterOptions().setHasText("foo")) - .filter(new Locator.FilterOptions().setHas(page.locator("a"))); - assertEquals("locator(\"section\").filter(new Locator.FilterOptions().setHas(locator(\"div\").filter(new Locator.FilterOptions().setHas(locator(\"span\"))))).filter(new Locator.FilterOptions().setHasText(\"foo\")).filter(new Locator.FilterOptions().setHas(locator(\"a\")))", - generate(locator)); - } - - @PlaywrightTest - void reverseEngineerHasNot(Page page) { - assertEquals("getByText(\"Hello\").filter(new Locator.FilterOptions().setHasNot(locator(\"div\").getByText(\"bye\")))", - generate(page.getByText("Hello").filter(new Locator.FilterOptions().setHasNot(page.locator("div").getByText("bye"))))); - - Locator locator = page - .locator("section") - .filter(new Locator.FilterOptions().setHas(page.locator("div").filter(new Locator.FilterOptions().setHasNot(page.locator("span"))))) - .filter(new Locator.FilterOptions().setHasText("foo")) - .filter(new Locator.FilterOptions().setHasNot(page.locator("a"))); - assertEquals("locator(\"section\").filter(new Locator.FilterOptions().setHas(locator(\"div\").filter(new Locator.FilterOptions().setHasNot(locator(\"span\"))))).filter(new Locator.FilterOptions().setHasText(\"foo\")).filter(new Locator.FilterOptions().setHasNot(locator(\"a\")))", - generate(locator)); - } - - @PlaywrightTest - void reverseEngineerHasAndHasText(Page page) { - Locator locator = page.locator("section").filter(new Locator.FilterOptions().setHasText("foo").setHas(page.locator("div"))).locator("a"); - assertEquals("locator(\"section\").filter(new Locator.FilterOptions().setHasText(\"foo\")).filter(new Locator.FilterOptions().setHas(locator(\"div\"))).locator(\"a\")", - generate(locator)); - } - - @PlaywrightTest - void reverseEngineerFrameLocator(Page page) { - Locator locator = page - .frameLocator("iframe") - .getByText("foo", new FrameLocator.GetByTextOptions().setExact(true)) - .frameLocator("frame").first() - .frameLocator("iframe") - .locator("span"); - assertEquals("locator(\"iframe\").contentFrame().getByText(\"foo\", new FrameLocator.GetByTextOptions().setExact(true)).locator(\"frame\").first().contentFrame().locator(\"iframe\").contentFrame().locator(\"span\")", - generate(locator)); - - // Note that frame locators with ">>" are not restored back due to ambiguity. - assertEquals("locator(\"div\").locator(\"iframe\").contentFrame().locator(\"span\")", generate(page.frameLocator("div >> iframe").locator("span"))); - - assertEquals(asList("getByTitle(\"iframe title\").contentFrame()"), asLocators("java", "internal:attr=[title=\"iframe title\"i] >> internal:control=enter-frame")); - } - - @PlaywrightTest - void reverseEngineerFrameLocatorWithoutASelector(Page page) { - assertEquals("frameLocator().getByText(\"foo\").locator(\"span\")", generate(page.frameLocator().getByText("foo").locator("span"))); - assertEquals("frameLocator()", asLocator("java", "internal:control=any-frame")); - } - - @PlaywrightTest - void generateMultipleLocators(Page page) { - String selector = "div >> internal:has-text=\"foo\"i >> nth=0 >> internal:has=\"span >> internal:has-not-text=\\\"bar\\\"i >> nth=-1\""; - Locator locator = page.locator("div", new Page.LocatorOptions().setHasText("foo")).nth(0).filter(new Locator.FilterOptions().setHas(page.locator("span", new Page.LocatorOptions().setHasNotText("bar")).nth(-1))); - assertEquals(asLocator("java", selector), generate(locator)); - assertEquals(asList( - "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).last()))", - "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).nth(-1)))", - "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).last()))", - "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).nth(-1)))", - "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).last()))", - "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).nth(-1)))", - "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).last()))", - "locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).nth(-1)))", - "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).last()))", - "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).nth(-1)))", - "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).last()))", - "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).first().filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).nth(-1)))", - "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).last()))", - "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\").filter(new Locator.FilterOptions().setHasNotText(\"bar\")).nth(-1)))", - "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).last()))", - "locator(\"div\", new Page.LocatorOptions().setHasText(\"foo\")).nth(0).filter(new Locator.FilterOptions().setHas(locator(\"span\", new Page.LocatorOptions().setHasNotText(\"bar\")).nth(-1)))" - ), asLocators("java", selector)); - } - - @PlaywrightTest - void reverseEngineerInternalHasTextLocators() { - assertEquals("locator(\"div\").filter(new Locator.FilterOptions().setHasText(\"Goodbye world\")).locator(\"span\")", asLocator("java", "div >> internal:has-text=\"Goodbye world\"i >> span")); - assertEquals("locator(\"div\").locator(\"internal:has-text=\\\"foo\\\"s\")", asLocator("java", "div >> internal:has-text=\"foo\"s")); - assertEquals("locator(\"div\").locator(\"internal:has-not-text=\\\"foo\\\"s\")", asLocator("java", "div >> internal:has-not-text=\"foo\"s")); - } - - @PlaywrightTest - void asLocatorInternalAnd() { - assertEquals("locator(\"div\").and(locator(\"span\").locator(\"article\"))", asLocator("java", "div >> internal:and=\"span >> article\"")); - } - - @PlaywrightTest - void asLocatorInternalOr() { - assertEquals("locator(\"div\").or(locator(\"span\").locator(\"article\"))", asLocator("java", "div >> internal:or=\"span >> article\"")); - } - - @PlaywrightTest - void asLocatorInternalChain() { - assertEquals("locator(\"div\").locator(locator(\"span\").locator(\"article\"))", asLocator("java", "div >> internal:chain=\"span >> article\"")); - } - - @PlaywrightTest - void reverseEngineerNestedLocators(Page page) { - assertEquals("getByRole(AriaRole.ROW).locator(getByRole(AriaRole.CELL).nth(2))", generate(page.getByRole(AriaRole.ROW).locator(page.getByRole(AriaRole.CELL).nth(2)))); - assertEquals("locator(\"div\").and(getByText(\"foo\")).or(locator(\"span\").locator(locator(\"a\"))).first()", - generate(page.locator("div").and(page.getByText("foo")).or(page.locator("span").locator(page.locator("a"))).first())); - } - - @PlaywrightTest - void asLocatorXpath() { - String selector = "//*[contains(normalizer-text(), 'foo']"; - assertEquals("locator(\"//*[contains(normalizer-text(), 'foo']\")", asLocator("java", selector)); - } - - @PlaywrightTest - void reverseEngineerRegexFlags() { - assertEquals("getByText(Pattern.compile(\"a.b\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL))", asLocator("java", "internal:text=/a.b/ims")); - assertEquals("getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(Pattern.compile(\"a.b\", Pattern.DOTALL)))", asLocator("java", "internal:role=button[name=/a.b/s]")); - } - - @PlaywrightTest - void asLocatorDescriptionInvalidInput() { - assertEquals("desc", asLocatorDescription("java", "body >> internal:describe=\"desc\"")); - assertEquals("locator(\"body\")", asLocatorDescription("java", "body >> internal:describe=12")); - assertEquals("div >> internal:has=bad", asLocatorDescription("java", "div >> internal:has=bad")); - // The client does not parse css, so an invalid css selector is not rejected. - assertEquals("locator(\"following-sibling::*[1]\")", asLocatorDescription("java", "following-sibling::*[1]")); - assertEquals("locator(\"body\").locator(\"div\")", asLocatorDescription("java", "body >> internal:describe=\"desc\" >> div")); - } - - @PlaywrightTest - void toStringShouldPrintTheDescription(Page page) { - assertEquals("Submit button", page.locator("#submit").describe("Submit button").toString()); - assertEquals("getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Submit\"))", page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Submit")).toString()); - } -} diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java index c572893de..e6c85a4e0 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java @@ -709,8 +709,7 @@ void invalidSelectorErrorFormat(Page page) { () -> assertThat(page.locator("##")).isVisible()); assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).isVisible() failed\n" + "\n" + - // Java: the client does not parse css, so the locator is not printed as the raw selector. - "Locator: locator(\"##\")\n" + + "Locator: ##\n" + "Expected: visible\n" + "Error: Unexpected token \"#\" while parsing css selector \"##\". Did you mean to CSS.escape it?\n" + "\n" + From a85fd407531944150cd95a39a7d5b83d87c5fdec Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Mon, 23 Nov 2026 14:27:26 -0800 Subject: [PATCH 5/6] test: isolate the default assertion timeout tests, cover Locator.toString() without a connection --- .../TestAssertionsDefaultTimeout.java | 60 +++++++++++++++++++ .../playwright/TestLocatorAssertions.java | 32 ---------- .../playwright/TestLocatorConvenience.java | 17 ++++++ 3 files changed, 77 insertions(+), 32 deletions(-) create mode 100644 playwright/src/test/java/com/microsoft/playwright/TestAssertionsDefaultTimeout.java diff --git a/playwright/src/test/java/com/microsoft/playwright/TestAssertionsDefaultTimeout.java b/playwright/src/test/java/com/microsoft/playwright/TestAssertionsDefaultTimeout.java new file mode 100644 index 000000000..4b219554d --- /dev/null +++ b/playwright/src/test/java/com/microsoft/playwright/TestAssertionsDefaultTimeout.java @@ -0,0 +1,60 @@ +/* + * 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.assertions.PlaywrightAssertions; +import com.microsoft.playwright.fixtures.PlaywrightTest; +import org.junit.jupiter.api.parallel.Isolated; +import org.opentest4j.AssertionFailedError; + +import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +// The default assertion timeout is global, so these tests do not run in parallel with any other test. +@Isolated +public class TestAssertionsDefaultTimeout { + @PlaywrightTest + void defaultTimeoutHasTextFail(Page page) { + page.setContent("
          "); + Locator locator = page.locator("div"); + PlaywrightAssertions.setDefaultAssertionTimeout(1000); + AssertionFailedError exception = assertThrows(AssertionFailedError.class, () -> assertThat(locator).hasText("foo")); + assertTrue(exception.getMessage().contains("Assert \"hasText\" locator(\"div\") with timeout 1000ms"), exception.getMessage()); + // Restore default. + PlaywrightAssertions.setDefaultAssertionTimeout(5_000); + } + + @PlaywrightTest + void defaultTimeoutHasTextPass(Page page) { + page.setContent("
          foo
          "); + Locator locator = page.locator("div"); + PlaywrightAssertions.setDefaultAssertionTimeout(1000); + assertThat(locator).hasText("foo"); + // Restore default. + PlaywrightAssertions.setDefaultAssertionTimeout(5_000); + } + + @PlaywrightTest + void defaultTimeoutZeroHasTextPass(Page page) { + page.setContent("
          foo
          "); + Locator locator = page.locator("div"); + PlaywrightAssertions.setDefaultAssertionTimeout(0); + assertThat(locator).hasText("foo"); + // Restore default. + PlaywrightAssertions.setDefaultAssertionTimeout(5_000); + } +} diff --git a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java index 94704bb7e..838876e31 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java @@ -18,7 +18,6 @@ import com.microsoft.playwright.assertions.LocatorAssertions; import com.microsoft.playwright.assertions.LocatorAssertions.ContainsClassOptions; -import com.microsoft.playwright.assertions.PlaywrightAssertions; import com.microsoft.playwright.fixtures.PlaywrightTest; import org.opentest4j.AssertionFailedError; @@ -1058,37 +1057,6 @@ void locatorCountShouldWorkWithDeletedMapInMainWorld(Page page) { assertThat(page.locator("#searchResultTableDiv .x-grid3-row")).hasCount(0); } - @PlaywrightTest - void defaultTimeoutHasTextFail(Page page) { - page.setContent("
          "); - Locator locator = page.locator("div"); - PlaywrightAssertions.setDefaultAssertionTimeout(1000); - AssertionFailedError exception = assertThrows(AssertionFailedError.class, () -> assertThat(locator).hasText("foo")); - assertTrue(exception.getMessage().contains("Assert \"hasText\" locator(\"div\") with timeout 1000ms"), exception.getMessage()); - // Restore default. - PlaywrightAssertions.setDefaultAssertionTimeout(5_000); - } - - @PlaywrightTest - void defaultTimeoutHasTextPass(Page page) { - page.setContent("
          foo
          "); - Locator locator = page.locator("div"); - PlaywrightAssertions.setDefaultAssertionTimeout(1000); - assertThat(locator).hasText("foo"); - // Restore default. - PlaywrightAssertions.setDefaultAssertionTimeout(5_000); - } - - @PlaywrightTest - void defaultTimeoutZeroHasTextPass(Page page) { - page.setContent("
          foo
          "); - Locator locator = page.locator("div"); - PlaywrightAssertions.setDefaultAssertionTimeout(0); - assertThat(locator).hasText("foo"); - // Restore default. - PlaywrightAssertions.setDefaultAssertionTimeout(5_000); - } - @PlaywrightTest void containsClassPass(Page page) { page.setContent("
          "); diff --git a/playwright/src/test/java/com/microsoft/playwright/TestLocatorConvenience.java b/playwright/src/test/java/com/microsoft/playwright/TestLocatorConvenience.java index c52e4a5a1..dd77ae5c9 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestLocatorConvenience.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestLocatorConvenience.java @@ -16,6 +16,8 @@ package com.microsoft.playwright; +import com.microsoft.playwright.fixtures.BrowserName; +import com.microsoft.playwright.fixtures.Env; import com.microsoft.playwright.fixtures.PlaywrightTest; import static java.util.Arrays.asList; @@ -235,4 +237,19 @@ void toStringShouldPreferDescription(Page page) { Locator locator = page.locator("div").describe("my div"); assertEquals("my div", locator.toString()); } + + @PlaywrightTest + void toStringShouldNotThrowWhenTheConnectionIsClosed(BrowserName browserName) { + Locator locator; + Locator described; + try (Playwright playwright = Playwright.create(); + Browser browser = browserName.browserType(playwright).launch(Env.launchOptions()); + Page page = browser.newPage()) { + locator = page.locator("div"); + described = page.locator("div").describe("my div"); + assertEquals("locator(\"div\")", locator.toString()); + } + assertEquals("Locator@div", locator.toString()); + assertEquals("my div", described.toString()); + } } From 33ae14a969a7912af6aa5c46313b2159ee920330 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Mon, 23 Nov 2026 16:18:11 -0800 Subject: [PATCH 6/6] chore: print the expected and the received value instead of a diff --- playwright/src/main/AGENTS.md | 4 +- .../playwright/impl/MatcherUtils.java | 113 ++---------------- .../microsoft/playwright/impl/ToEqual.java | 10 +- .../playwright/impl/ToMatchAriaSnapshot.java | 6 +- .../playwright/impl/ToMatchText.java | 9 +- playwright/src/test/AGENTS.md | 2 + .../playwright/TestLocatorAssertions.java | 2 +- .../playwright/tests/page/TestExpectMisc.java | 4 +- .../tests/page/TestExpectToHaveText.java | 2 +- .../tests/page/TestExpectToHaveValue.java | 6 +- .../tests/page/TestToMatchAriaSnapshot.java | 68 +++++------ 11 files changed, 68 insertions(+), 158 deletions(-) diff --git a/playwright/src/main/AGENTS.md b/playwright/src/main/AGENTS.md index 7b0232d38..8fb20f46c 100644 --- a/playwright/src/main/AGENTS.md +++ b/playwright/src/main/AGENTS.md @@ -31,8 +31,8 @@ Java code around the place it goes to, and write the new lines the same way. `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 and the diff are printed in the same - layout without matching jest in every case. A failure message has the upstream layout with the + 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()` diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/MatcherUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/MatcherUtils.java index a78c651b0..9abae2996 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/MatcherUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/MatcherUtils.java @@ -29,7 +29,7 @@ import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; // java: the utils of a matcher. Upstream they are jest-matcher-utils, which is not ported: these methods print the -// Java values in the same format, without colors, and the diff is a plain line diff. +// Java values in the same format, without colors, and there is no diff. class MatcherUtils { // java: the undefined value: Frame.expect returns it for a received value that is undefined. static final Object UNDEFINED = new Object() { @@ -39,8 +39,6 @@ public String toString() { } }; - private static final int MAX_DIFF_LINES = 2000; - static String printExpected(Object value) { return stringify(value); } @@ -65,95 +63,15 @@ static String stringify(Object value) { return formatBasicValue(value); } - static String printDiffOrStringify(Object expected, Object received, String expectedLabel, String receivedLabel) { - List expectedLines = null; - List receivedLines = null; - if (expected instanceof String && received instanceof String) { - String expectedString = (String) expected; - String receivedString = (String) received; - if (!expectedString.isEmpty() && !receivedString.isEmpty() && (expectedString.contains("\n") || receivedString.contains("\n"))) { - expectedLines = split(expectedString); - receivedLines = split(receivedString); - } - } else if (isArray(expected) && isArray(received) || expected instanceof Map && received instanceof Map) { - expectedLines = format(expected); - receivedLines = format(received); - } - if (expectedLines != null && !expectedLines.equals(receivedLines) && expectedLines.size() <= MAX_DIFF_LINES && receivedLines.size() <= MAX_DIFF_LINES) - return diffLines(expectedLines, receivedLines, expectedLabel, receivedLabel); + // java: where upstream prints a diff (printDiffOrStringify of jest), both values are printed in full. + static String[] printExpectedAndReceived(Object expected, Object received, String expectedLabel, String receivedLabel) { int width = Math.max(expectedLabel.length(), receivedLabel.length()); - String expectedLine = pad(expectedLabel + ":", width + 2) + printExpected(expected); - String receivedLine = pad(receivedLabel + ":", width + 2) + (stringify(expected).equals(stringify(received)) ? "serializes to the same string" : printReceived(received)); - return expectedLine + "\n" + receivedLine; - } - - private static String diffLines(List a, List b, String aLabel, String bLabel) { - int[][] lcs = new int[a.size() + 1][b.size() + 1]; - for (int i = a.size() - 1; i >= 0; i--) { - for (int j = b.size() - 1; j >= 0; j--) - lcs[i][j] = a.get(i).equals(b.get(j)) ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]); - } - List lines = new ArrayList<>(); - int removed = 0; - int added = 0; - int i = 0; - int j = 0; - while (i < a.size() || j < b.size()) { - if (i < a.size() && j < b.size() && a.get(i).equals(b.get(j))) { - lines.add(a.get(i).isEmpty() ? "" : " " + a.get(i)); - i++; - j++; - } else if (i < a.size() && (j == b.size() || lcs[i + 1][j] >= lcs[i][j + 1])) { - lines.add(a.get(i).isEmpty() ? "-" : "- " + a.get(i)); - removed++; - i++; - } else { - lines.add(b.get(j).isEmpty() ? "+" : "+ " + b.get(j)); - added++; - j++; - } - } - int labelWidth = Math.max(aLabel.length(), bLabel.length()); - int countWidth = Math.max(String.valueOf(removed).length(), String.valueOf(added).length()); - return "- " + pad(aLabel, labelWidth) + " - " + padStart(String.valueOf(removed), countWidth) + "\n" - + "+ " + pad(bLabel, labelWidth) + " + " + padStart(String.valueOf(added), countWidth) + "\n\n" - + String.join("\n", lines); - } - - private static List format(Object value) { - List lines = new ArrayList<>(); - format(value, "", "", lines); - String last = lines.get(lines.size() - 1); - lines.set(lines.size() - 1, last.substring(0, last.length() - 1)); - return lines; - } - - private static void format(Object value, String indent, String key, List lines) { - if (isArray(value)) { - List items = toList(value); - if (items.isEmpty()) { - lines.add(indent + key + "Array [],"); - return; - } - lines.add(indent + key + "Array ["); - for (Object item : items) - format(item, indent + " ", "", lines); - lines.add(indent + "],"); - return; - } - if (value instanceof Map) { - Map entries = sortedEntries((Map) value); - if (entries.isEmpty()) { - lines.add(indent + key + "Object {},"); - return; - } - lines.add(indent + key + "Object {"); - for (Map.Entry entry : entries.entrySet()) - format(entry.getValue(), indent + " ", quote(entry.getKey()) + ": ", lines); - lines.add(indent + "},"); - return; - } - lines.add(indent + key + formatBasicValue(value) + ","); + String printedExpected = printExpected(expected); + String printedReceived = printReceived(received); + return new String[] { + pad(expectedLabel + ":", width + 2) + printedExpected, + pad(receivedLabel + ":", width + 2) + (printedExpected.equals(printedReceived) ? "serializes to the same string" : printedReceived) + }; } private static Map sortedEntries(Map map) { @@ -205,13 +123,6 @@ private static List toList(Object value) { return result; } - private static List split(String value) { - List result = new ArrayList<>(); - for (String line : value.split("\n", -1)) - result.add(line); - return result; - } - private static String pad(String value, int width) { StringBuilder result = new StringBuilder(value); while (result.length() < width) @@ -219,10 +130,4 @@ private static String pad(String value, int width) { return result.toString(); } - private static String padStart(String value, int width) { - StringBuilder result = new StringBuilder(value); - while (result.length() < width) - result.insert(0, ' '); - return result.toString(); - } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ToEqual.java b/playwright/src/main/java/com/microsoft/playwright/impl/ToEqual.java index 6c4af4d43..8a6e5b9fd 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ToEqual.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ToEqual.java @@ -27,7 +27,7 @@ import java.util.List; import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.MatcherUtils.printDiffOrStringify; +import static com.microsoft.playwright.impl.MatcherUtils.printExpectedAndReceived; import static com.microsoft.playwright.impl.MatcherUtils.printExpected; import static com.microsoft.playwright.impl.MatcherUtils.printReceived; import static com.microsoft.playwright.impl.MatcherHint.formatMatcherMessage; @@ -87,17 +87,21 @@ static MatcherResult toEqual( normalizedExpected.add(exp); } - printedDiff = printDiffOrStringify( + String[] printed = printExpectedAndReceived( normalizedExpected, receivedValue, EXPECTED_LABEL, RECEIVED_LABEL); + printedExpected = printed[0]; + printedReceived = printed[1]; } else { - printedDiff = printDiffOrStringify( + String[] printed = printExpectedAndReceived( expected, receivedValue, EXPECTED_LABEL, RECEIVED_LABEL); + printedExpected = printed[0]; + printedReceived = printed[1]; } String finalPrintedExpected = printedExpected; String finalPrintedReceived = printedReceived; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchAriaSnapshot.java b/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchAriaSnapshot.java index 440d033b6..36bee245b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchAriaSnapshot.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchAriaSnapshot.java @@ -25,7 +25,7 @@ import java.util.List; import java.util.Map; -import static com.microsoft.playwright.impl.MatcherUtils.printDiffOrStringify; +import static com.microsoft.playwright.impl.MatcherUtils.printExpectedAndReceived; import static com.microsoft.playwright.impl.MatcherUtils.printExpected; import static com.microsoft.playwright.impl.MatcherHint.formatMatcherMessage; import static com.microsoft.playwright.impl.MatcherHint.printReceivedStringContainExpectedSubstring; @@ -80,7 +80,9 @@ static MatcherResult toMatchAriaSnapshot( printedExpected = "Expected: not " + printExpected(finalExpected); printedReceived = "Received: " + receivedString; } else { - printedDiff = printDiffOrStringify(finalExpected, typedReceived.get("raw"), "Expected", "Received"); + String[] printed = printExpectedAndReceived(finalExpected, typedReceived.get("raw"), "Expected", "Received"); + printedExpected = printed[0]; + printedReceived = printed[1]; } MatcherMessageDetails details = new MatcherMessageDetails(); details.isNot = state.isNot; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchText.java b/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchText.java index d1dffedbd..31f1c157c 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchText.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ToMatchText.java @@ -27,7 +27,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.MatcherUtils.printDiffOrStringify; +import static com.microsoft.playwright.impl.MatcherUtils.printExpectedAndReceived; import static com.microsoft.playwright.impl.MatcherUtils.printExpected; import static com.microsoft.playwright.impl.MatcherHint.formatMatcherMessage; import static com.microsoft.playwright.impl.MatcherHint.printReceivedStringContainExpectedResult; @@ -106,8 +106,11 @@ static MatcherResult toMatchText( } else { if (errorMessage != null) printedExpected = "Expected" + expectedSuffix + ": " + printExpected(expected); - else - printedDiff = printDiffOrStringify(expected, receivedString, "Expected" + expectedSuffix, "Received" + receivedSuffix); + else { + String[] printed = printExpectedAndReceived(expected, receivedString, "Expected" + expectedSuffix, "Received" + receivedSuffix); + printedExpected = printed[0]; + printedReceived = printed[1]; + } } String finalPrintedExpected = printedExpected; diff --git a/playwright/src/test/AGENTS.md b/playwright/src/test/AGENTS.md index f4bcf55c0..c482b265e 100644 --- a/playwright/src/test/AGENTS.md +++ b/playwright/src/test/AGENTS.md @@ -158,6 +158,8 @@ handler of the request has returned, as in the Node.js server, so a response sto log is `Assert "not hasText"`. A locator in that text is Java code: `locator('div')` is `locator("div")`. The upstream test config sets the expect timeout to 10000ms, the Java default is 5000ms: `with timeout 10000ms` of a matcher without a timeout is `with timeout 5000ms`. + The Java client prints no diff: where upstream pins `- expected` and `+ received` diff lines, the Java + test pins the same content in the `Expected:` and `Received:` values. - `await expect(promise).rejects.toThrow('text')` and `const error = await promise.catch(e => e); expect(error.message).toContain('text')` are `PlaywrightException error = assertThrows(PlaywrightException.class, () -> ...)` then diff --git a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java index 838876e31..f2e85eae0 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestLocatorAssertions.java @@ -222,7 +222,7 @@ void hasTextWTextArrayFail(Page page) { assertEquals("[Text 1, Text 3, Extra]", e.getExpected().getStringRepresentation()); assertEquals("[Text 1, Text 3]", e.getActual().getStringRepresentation()); assertTrue(e.getMessage().contains("assertThat(locator).hasText(expected) failed"), e.getMessage()); - assertTrue(e.getMessage().contains("- \"Extra\","), e.getMessage()); + assertTrue(e.getMessage().contains("Expected: [\"Text 1\", \"Text 3\", \"Extra\"]"), e.getMessage()); } @PlaywrightTest diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java index e6c85a4e0..4b5412799 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectMisc.java @@ -149,7 +149,7 @@ void fail(Page page) { Locator locator = page.locator("div"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).hasJSProperty("foo", mapOf("a", 1, "b", "string", "c", new Date(1627503992001L)), new LocatorAssertions.HasJSPropertyOptions().setTimeout(1000))); - assertTrue(error.getMessage().contains("- \"c\"")); + assertTrue(error.getMessage().contains("\"c\": 2021-07-28T20:26:32.001Z}")); } @PlaywrightTest @@ -383,7 +383,7 @@ void failWithArray(Page page) { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).containsClass(Arrays.asList("foo", "bar", "baz"), new LocatorAssertions.ContainsClassOptions().setTimeout(1000))); assertTrue(stripAnsi(error.getMessage()).contains("assertThat(locator).containsClass(expected) failed")); - assertTrue(stripAnsi(error.getMessage()).contains("Timeout: 1000ms")); + assertTrue(stripAnsi(error.getMessage()).contains("Timeout: 1000ms")); assertTrue(stripAnsi(error.getMessage()).contains("- Assert \"containsClass\" locator(\"div\") with timeout 1000ms")); } } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveText.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveText.java index d7932fb98..25a85878e 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveText.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveText.java @@ -375,7 +375,7 @@ void fail(Page page) { Locator locator = page.locator("div"); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).containsText(new String[]{"Text 2"}, new LocatorAssertions.ContainsTextOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("- \"Text 2\"")); + assertTrue(stripAnsi(error.getMessage()).contains("Expected: [\"Text 2\"]")); } } } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveValue.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveValue.java index 0d5953e0f..8b312f2a8 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveValue.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestExpectToHaveValue.java @@ -117,8 +117,8 @@ void exactMatchWithTextFailure(Page page) { locator.selectOption(new String[]{"RR", "GG"}); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).hasValues(new String[]{"R", "G"}, new LocatorAssertions.HasValuesOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("- \"R\"")); - assertTrue(stripAnsi(error.getMessage()).contains("+ \"RR\"")); + assertTrue(stripAnsi(error.getMessage()).contains("Expected: [\"R\", \"G\"]")); + assertTrue(stripAnsi(error.getMessage()).contains("Received: [\"RR\", \"GG\"]")); } @PlaywrightTest @@ -150,7 +150,7 @@ void failsWhenItemsNotSelected(Page page) { locator.selectOption(new String[]{"B"}); AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertThat(locator).hasValues(new Pattern[]{Pattern.compile("R"), Pattern.compile("G")}, new LocatorAssertions.HasValuesOptions().setTimeout(1000))); - assertTrue(stripAnsi(error.getMessage()).contains("+ \"B\"")); + assertTrue(stripAnsi(error.getMessage()).contains("Received: [\"B\"]")); } @PlaywrightTest diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestToMatchAriaSnapshot.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestToMatchAriaSnapshot.java index 4edb8d147..d59311faf 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestToMatchAriaSnapshot.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestToMatchAriaSnapshot.java @@ -453,18 +453,15 @@ void selectedAttribute(Page page) { " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed\n" + "\n" + - "Timeout: 1000ms\n" + - "- Expected - 2\n" + - "+ Received + 6\n" + - "\n" + - "- - row [selected=false]\n" + - "- - row [selected=false]\n" + - "+ - table:\n" + - "+ - rowgroup:\n" + - "+ - row \"Row\" [selected]:\n" + - "+ - cell \"Row\"\n" + - "+ - row \"Row 2\":\n" + - "+ - cell \"Row 2\"\n" + + "Expected: \"- row [selected=false]\n" + + "- row [selected=false]\"\n" + + "Received: \"- table:\n" + + " - rowgroup:\n" + + " - row \\\"Row\\\" [selected]:\n" + + " - cell \\\"Row\\\"\n" + + " - row \\\"Row 2\\\":\n" + + " - cell \\\"Row 2\\\"\"\n" + + "Timeout: 1000ms\n" + "\n" + "Call log:\n")); } @@ -560,16 +557,13 @@ void expectedFormatter(Page page) { // unlike the baseline generated by --update-snapshots. assertTrue(stripAnsi(error.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed\n" + "\n" + - "Timeout: 1ms\n" + - "- Expected - 2\n" + - "+ Received + 4\n" + - "\n" + - "- - heading \"todos\"\n" + - "- - textbox \"Wrong text\"\n" + - "+ - banner:\n" + - "+ - heading \"todos\" [level=1]\n" + - "+ - textbox \"What needs to be done?\"\n" + - "+ - button \"Time 15:30\"\n" + + "Expected: \"- heading \\\"todos\\\"\n" + + "- textbox \\\"Wrong text\\\"\"\n" + + "Received: \"- banner:\n" + + " - heading \\\"todos\\\" [level=1]\n" + + " - textbox \\\"What needs to be done?\\\"\n" + + " - button \\\"Time 15:30\\\"\"\n" + + "Timeout: 1ms\n" + "\n" + "Call log:\n")); } @@ -891,9 +885,9 @@ void shouldNotMatchWhatIsNotMatched(Page page) { " - button \"bogus\"\n" + " ")); assertTrue(stripAnsi(error.getMessage()).contains("\n" + - "- - paragraph:\n" + - "- - button \"bogus\"\n" + - "+ - paragraph: Text")); + "Expected: \"- paragraph:\n" + + " - button \\\"bogus\\\"\"\n" + + "Received: \"- paragraph: Text\"")); } @PlaywrightTest @@ -934,7 +928,7 @@ void shouldDetectUnexpectedChildrenEqual(Page page) { " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); - assertTrue(stripAnsi(e.getMessage()).contains("+ - listitem: Two")); + assertTrue(stripAnsi(e.getMessage()).contains("\n - listitem: Two")); } @PlaywrightTest @@ -975,7 +969,7 @@ void shouldDetectUnexpectedChildrenDeepequal(Page page) { " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); - assertTrue(stripAnsi(e.getMessage()).contains("+ - listitem: \"1.2\"")); + assertTrue(stripAnsi(e.getMessage()).contains("\n - listitem: \\\"1.2\\\"")); } @PlaywrightTest @@ -1001,7 +995,7 @@ void shouldAllowRestoringContainModeInsideDeepequal(Page page) { " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); assertTrue(stripAnsi(e.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); - assertTrue(stripAnsi(e.getMessage()).contains("+ - listitem: \"1.2\"")); + assertTrue(stripAnsi(e.getMessage()).contains("\n - listitem: \\\"1.2\\\"")); assertThat(page).matchesAriaSnapshot("\n" + " - list:\n" + @@ -1033,13 +1027,13 @@ void toplevelDeepequal(Page page) { " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1000))); assertTrue(stripAnsi(error.getMessage()).contains(("\n" + - "- - /children: deep-equal\n" + - "- - list\n" + - "+ - list:\n" + - "+ - listitem:\n" + - "+ - list:\n" + - "+ - listitem: \"1.1\"\n" + - "+ - listitem: \"1.2\"\n" + + "Expected: \"- /children: deep-equal\n" + + "- list\"\n" + + "Received: \"- list:\n" + + " - listitem:\n" + + " - list:\n" + + " - listitem: \\\"1.1\\\"\n" + + " - listitem: \\\"1.2\\\"\"\n" + " ").trim())); } @@ -1069,8 +1063,8 @@ void treatBadRegexAsAString(Page page) { " - /url: /[a/\n" + " ", new PageAssertions.MatchesAriaSnapshotOptions().setTimeout(1))); assertTrue(stripAnsi(error.getMessage()).contains("assertThat(page).matchesAriaSnapshot(expected) failed")); - assertTrue(stripAnsi(error.getMessage()).contains("- - /url: /[a/")); - assertTrue(stripAnsi(error.getMessage()).contains("+ - /url: /foo")); + assertTrue(stripAnsi(error.getMessage()).contains("\n - /url: /[a/\"")); + assertTrue(stripAnsi(error.getMessage()).contains("\n - /url: /foo\"")); } @PlaywrightTest