diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/common/exceptions/ClassChainSyntaxException.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/common/exceptions/ClassChainSyntaxException.java new file mode 100644 index 0000000..324509a --- /dev/null +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/common/exceptions/ClassChainSyntaxException.java @@ -0,0 +1,54 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * 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 io.appium.uiautomator2.common.exceptions; + +import androidx.annotation.Nullable; + +/** + * Thrown when a class chain query cannot be parsed. The position is a 0-based character offset. + */ +public class ClassChainSyntaxException extends InvalidSelectorException { + private final String query; + private final String reason; + private final int position; + + public ClassChainSyntaxException(String query, String reason, int position) { + this(query, reason, position, null); + } + + public ClassChainSyntaxException(String query, String reason, int position, + @Nullable Throwable cause) { + super(String.format("Cannot parse class chain query '%s'. %s at position %d", + query, reason, position), cause); + this.query = query; + this.reason = reason; + this.position = position; + } + + public String getQuery() { + return query; + } + + public String getReason() { + return reason; + } + + public int getPosition() { + return position; + } +} diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java new file mode 100644 index 0000000..eecd8b5 --- /dev/null +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ChainStep.java @@ -0,0 +1,154 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * 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 io.appium.uiautomator2.utils.classchain; + +import androidx.annotation.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import io.appium.uiautomator2.utils.predicate.PredicateNode; + +/** + * One immutable step of a class chain, e.g. {@code android.widget.TextView[`text == 'A'`][2]}. + */ +public final class ChainStep { + + /** {@code SELF} filters the candidates, {@code DESCENDANT} needs a matching descendant */ + public enum Scope { + SELF('`'), DESCENDANT('$'); + + private final char marker; + + Scope(char marker) { + this.marker = marker; + } + + public char getMarker() { + return marker; + } + } + + public static final class Filter { + private final Scope scope; + private final PredicateNode predicate; + + Filter(Scope scope, PredicateNode predicate) { + this.scope = scope; + this.predicate = predicate; + } + + public Scope getScope() { + return scope; + } + + public PredicateNode getPredicate() { + return predicate; + } + + @Override + public String toString() { + String marker = String.valueOf(scope.getMarker()); + String text = predicate.toString(); + if (predicate instanceof PredicateNode.Logical) { + // the root needs no parentheses, and they would add a nesting level on reparse + text = text.substring(1, text.length() - 1); + } + String escaped = text.replace(marker, marker + marker); + return "[" + marker + escaped + marker + "]"; + } + } + + /** + * Where a step looks, relative to each node of the previous step (or the search root). + * Positions count along the axis: nearest first for {@code PARENT}, {@code ANCESTOR} and + * {@code PRECEDING_SIBLING}, in document order otherwise. + */ + public enum Axis { + CHILD(""), DESCENDANT(""), PARENT(".."), ANCESTOR("^"), + FOLLOWING_SIBLING(">"), PRECEDING_SIBLING("<"), SIBLING("~"); + + private final String symbol; + + Axis(String symbol) { + this.symbol = symbol; + } + + /** The prefix of the step, empty for {@code CHILD} and {@code DESCENDANT} */ + public String getSymbol() { + return symbol; + } + } + + private final Axis axis; + @Nullable + private final String className; + private final List filters; + @Nullable + private final Integer position; + + ChainStep(Axis axis, @Nullable String className, List filters, + @Nullable Integer position) { + this.axis = axis; + this.className = className; + this.filters = Collections.unmodifiableList(new ArrayList<>(filters)); + this.position = position; + } + + public Axis getAxis() { + return axis; + } + + public boolean isDescendant() { + return axis == Axis.DESCENDANT; + } + + /** The exact class name, or null for {@code *} and for the parent axis */ + @Nullable + public String getClassName() { + return className; + } + + /** In source order */ + public List getFilters() { + return filters; + } + + /** 1-based among the matches of class name and filters; negative counts from the end */ + @Nullable + public Integer getPosition() { + return position; + } + + /** The step without the separator before it, which {@link ClassChain} adds */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(axis.getSymbol()); + if (axis != Axis.PARENT) { + sb.append(className == null ? "*" : className); + } + for (Filter filter : filters) { + sb.append(filter); + } + if (position != null) { + sb.append('[').append(position).append(']'); + } + return sb.toString(); + } +} diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChain.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChain.java new file mode 100644 index 0000000..5445574 --- /dev/null +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChain.java @@ -0,0 +1,54 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * 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 io.appium.uiautomator2.utils.classchain; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * A parsed class chain: at least one step. The first step is relative to the search root + * (window roots or the context element). + */ +public final class ClassChain { + private final List steps; + + ClassChain(List steps) { + this.steps = Collections.unmodifiableList(new ArrayList<>(steps)); + } + + public List getSteps() { + return steps; + } + + /** Canonical form, which parses back to the same canonical form */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < steps.size(); i++) { + ChainStep step = steps.get(i); + if (i == 0) { + sb.append(step.isDescendant() ? "**/" : ""); + } else { + sb.append(step.isDescendant() ? "/**/" : "/"); + } + sb.append(step); + } + return sb.toString(); + } +} diff --git a/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java new file mode 100644 index 0000000..180f0a5 --- /dev/null +++ b/packages/uiautomator2-server/app/src/main/java/io/appium/uiautomator2/utils/classchain/ClassChainParser.java @@ -0,0 +1,277 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * 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 io.appium.uiautomator2.utils.classchain; + +import androidx.annotation.Nullable; + +import java.util.ArrayList; +import java.util.List; + +import io.appium.uiautomator2.common.exceptions.ClassChainSyntaxException; +import io.appium.uiautomator2.common.exceptions.PredicateSyntaxException; +import io.appium.uiautomator2.utils.classchain.ChainStep.Axis; +import io.appium.uiautomator2.utils.classchain.ChainStep.Filter; +import io.appium.uiautomator2.utils.classchain.ChainStep.Scope; +import io.appium.uiautomator2.utils.predicate.PredicateParser; + +/** + * Parser of class chain queries like WebDriverAgent's, with {@link PredicateParser} predicates. + * Beyond WDA, a step after {@code /} can start with {@code ..} (parent), {@code ^} (ancestors), + * {@code >} / {@code <} (following / preceding siblings) or {@code ~} (all siblings). + */ +public final class ClassChainParser { + private static final String DESCENDANT_MARKER = "**/"; + + private final String source; + private int pos; + + private ClassChainParser(String source) { + this.source = source; + } + + public static ClassChain parse(String query) { + if (query == null || query.isEmpty()) { + throw new ClassChainSyntaxException(String.valueOf(query), + "The class chain must not be empty", 0); + } + return new ClassChainParser(query).parseChain(); + } + + private ClassChain parseChain() { + List steps = new ArrayList<>(); + boolean descendant = source.startsWith(DESCENDANT_MARKER); + if (descendant) { + pos = DESCENDANT_MARKER.length(); + } + while (true) { + steps.add(parseStep(descendant ? Axis.DESCENDANT : Axis.CHILD)); + if (pos >= source.length()) { + return new ClassChain(steps); + } + pos++; // the '/' that parseStep stopped at + descendant = source.startsWith(DESCENDANT_MARKER, pos); + if (descendant) { + pos += DESCENDANT_MARKER.length(); + } + } + } + + private ChainStep parseStep(Axis plainAxis) { + Axis axis = parseAxis(plainAxis); + String className = axis == Axis.PARENT ? null : parseType(); + List filters = new ArrayList<>(); + Integer position = null; + while (peek() == '[') { + char next = peek(1); + if (next == '`' || next == '$') { + if (position != null) { + throw error("Predicates must be set before the position"); + } + filters.add(parseFilter(next == '`' ? Scope.SELF : Scope.DESCENDANT)); + } else { + if (position != null) { + throw error("The position can be set only once"); + } + if (axis == Axis.PARENT) { + throw error("A parent step '..' has a single candidate, it takes no position"); + } + position = parsePosition(); + } + } + if (pos < source.length() && peek() != '/') { + throw error(String.format("Unexpected '%s'", peek())); + } + return new ChainStep(axis, className, filters, position); + } + + private Axis parseAxis(Axis plainAxis) { + Axis axis; + switch (peek()) { + case '.': + axis = Axis.PARENT; + break; + case '^': + axis = Axis.ANCESTOR; + break; + case '>': + axis = Axis.FOLLOWING_SIBLING; + break; + case '<': + axis = Axis.PRECEDING_SIBLING; + break; + case '~': + axis = Axis.SIBLING; + break; + default: + return plainAxis; + } + if (plainAxis == Axis.DESCENDANT) { + throw error(String.format("'%s' cannot follow the descendant marker '**/'", + axis.getSymbol())); + } + if (axis == Axis.PARENT) { + if (peek(1) != '.') { + throw error("Expected '..' for the parent step"); + } + pos += 2; + if (peek() == '.' || peek() == '*' || isIdentifierStart(codePoint())) { + throw error("A parent step '..' takes no class name, " + + "filter with [`className == ...`] instead"); + } + } else { + pos++; + } + return axis; + } + + @Nullable + private String parseType() { + if (peek() == '*') { + if (peek(1) == '*') { + throw error("Unexpected '**', the descendant marker '**/' must be followed by " + + "a class name or '*'"); + } + pos++; + return null; + } + int start = pos; + while (true) { + if (!isIdentifierStart(codePoint())) { + throw error(pos >= source.length() && pos > start + ? "The class name must not end with '.'" + : "Expected a class name or '*'"); + } + do { + pos += Character.charCount(codePoint()); + } while (isIdentifierPart(codePoint())); + if (peek() != '.') { + return source.substring(start, pos); + } + pos++; + } + } + + private Filter parseFilter(Scope scope) { + char marker = scope.getMarker(); + int open = pos; + pos += 2; // "[" and the marker + int contentStart = pos; + StringBuilder text = new StringBuilder(); + while (true) { + if (pos >= source.length()) { + throw error(String.format("Cannot find the closing '%s' of the predicate", marker), + open); + } + char c = source.charAt(pos); + if (c == marker) { + if (peek(1) == marker) { + text.append(c); + pos += 2; + continue; + } + pos++; + break; + } + text.append(c); + pos++; + } + if (peek() != ']') { + throw error("Expected ']' after the predicate"); + } + pos++; + try { + return new Filter(scope, PredicateParser.parse(text.toString())); + } catch (PredicateSyntaxException e) { + int at = sourceOffset(contentStart, marker, Math.min(e.getPosition(), text.length())); + throw new ClassChainSyntaxException( + source, "Invalid predicate: " + e.getReason(), at, e); + } + } + + /** The query index of the {@code offset}-th predicate character, which skips doubled markers */ + private int sourceOffset(int from, char marker, int offset) { + int index = from; + for (int n = 0; n < offset && index < source.length(); n++) { + boolean doubled = source.charAt(index) == marker + && index + 1 < source.length() && source.charAt(index + 1) == marker; + index += doubled ? 2 : 1; + } + return index; + } + + private int parsePosition() { + pos++; // '[' + int start = pos; + if (peek() == '-') { + pos++; + } + int digitsStart = pos; + while (peek() >= '0' && peek() <= '9') { + pos++; + } + if (pos == digitsStart) { + throw error("Expected a predicate or an integer position after '['", start); + } + int value; + try { + value = Integer.parseInt(source.substring(start, pos)); + } catch (NumberFormatException e) { + throw error("The position is out of the integer range", start); + } + if (value == 0) { + throw error("The position must be a non-zero integer, counted from 1", start); + } + if (peek() != ']') { + throw error("Expected ']' after the position"); + } + pos++; + return value; + } + + /** The code point at the current position, or -1 at the end */ + private int codePoint() { + return pos < source.length() ? source.codePointAt(pos) : -1; + } + + private static boolean isIdentifierStart(int cp) { + return cp > 0 && Character.isJavaIdentifierStart(cp) + && !Character.isIdentifierIgnorable(cp); + } + + private static boolean isIdentifierPart(int cp) { + return cp > 0 && Character.isJavaIdentifierPart(cp) + && !Character.isIdentifierIgnorable(cp); + } + + private char peek() { + return peek(0); + } + + private char peek(int offset) { + int index = pos + offset; + return index < source.length() ? source.charAt(index) : '\0'; + } + + private ClassChainSyntaxException error(String reason) { + return error(reason, pos); + } + + private ClassChainSyntaxException error(String reason, int position) { + return new ClassChainSyntaxException(source, reason, position); + } +} diff --git a/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java b/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java new file mode 100644 index 0000000..d23e852 --- /dev/null +++ b/packages/uiautomator2-server/app/src/test/java/io/appium/uiautomator2/utils/classchain/ClassChainParserTests.java @@ -0,0 +1,433 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * 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 io.appium.uiautomator2.utils.classchain; + +import org.junit.Test; + +import java.util.List; + +import io.appium.uiautomator2.common.exceptions.ClassChainSyntaxException; +import io.appium.uiautomator2.common.exceptions.InvalidSelectorException; +import io.appium.uiautomator2.common.exceptions.PredicateSyntaxException; +import io.appium.uiautomator2.utils.classchain.ChainStep.Axis; +import io.appium.uiautomator2.utils.classchain.ChainStep.Scope; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class ClassChainParserTests { + private static final String BUTTON = "android.widget.Button"; + private static final String VIEW = "android.view.View"; + + private static List steps(String query) { + return ClassChainParser.parse(query).getSteps(); + } + + private static String canonical(String query) { + return ClassChainParser.parse(query).toString(); + } + + private static ClassChainSyntaxException assertInvalid(String query, String reasonPart) { + try { + ClassChainParser.parse(query); + } catch (ClassChainSyntaxException e) { + assertTrue(String.format("'%s' not in '%s'", reasonPart, e.getReason()), + e.getReason().contains(reasonPart)); + return e; + } + fail("Expected a syntax error for: " + query); + return null; + } + + private static void assertStep(ChainStep step, boolean descendant, String className, + Integer position, int filters) { + assertEquals(descendant, step.isDescendant()); + assertEquals(className, step.getClassName()); + assertEquals(position, step.getPosition()); + assertEquals(filters, step.getFilters().size()); + } + + // ---- valid chains (ported from WDA's FBClassChainTests) ---- + + @Test + public void childChain() { + List steps = steps(VIEW + "/" + BUTTON); + assertEquals(2, steps.size()); + assertStep(steps.get(0), false, VIEW, null, 0); + assertStep(steps.get(1), false, BUTTON, null, 0); + } + + @Test + public void starsAndPositions() { + List steps = steps(VIEW + "/" + BUTTON + "[3]/*[4]/*[5]/android.app.Dialog"); + assertEquals(5, steps.size()); + assertStep(steps.get(1), false, BUTTON, 3, 0); + assertStep(steps.get(2), false, null, 4, 0); + assertStep(steps.get(3), false, null, 5, 0); + assertStep(steps.get(4), false, "android.app.Dialog", null, 0); + } + + @Test + public void singleStar() { + List steps = steps("*"); + assertEquals(1, steps.size()); + assertStep(steps.get(0), false, null, null, 0); + } + + @Test + public void leadingDescendantMarker() { + List steps = steps("**/*/*/" + BUTTON); + assertEquals(3, steps.size()); + assertStep(steps.get(0), true, null, null, 0); + assertStep(steps.get(1), false, null, null, 0); + assertStep(steps.get(2), false, BUTTON, null, 0); + } + + @Test + public void descendantMarkersInTheMiddle() { + List steps = steps("**/" + BUTTON + "/**/*"); + assertEquals(2, steps.size()); + assertStep(steps.get(0), true, BUTTON, null, 0); + assertStep(steps.get(1), true, null, null, 0); + steps = steps(VIEW + "/**/" + BUTTON + "/" + VIEW); + assertStep(steps.get(0), false, VIEW, null, 0); + assertStep(steps.get(1), true, BUTTON, null, 0); + assertStep(steps.get(2), false, VIEW, null, 0); + } + + @Test + public void negativePosition() { + List steps = steps(VIEW + "/" + BUTTON + "[-1]"); + assertStep(steps.get(1), false, BUTTON, -1, 0); + } + + @Test + public void predicates() { + List steps = steps(VIEW + "[`text == 'a'`]/" + BUTTON + "[`checked == true`]"); + assertStep(steps.get(0), false, VIEW, null, 1); + assertStep(steps.get(1), false, BUTTON, null, 1); + assertEquals(Scope.SELF, steps.get(0).getFilters().get(0).getScope()); + assertEquals("text == 'a'", steps.get(0).getFilters().get(0).getPredicate().toString()); + } + + @Test + public void descendantAndSelfPredicatesKeepTheirOrder() { + List steps = steps("**/" + VIEW + "[$text == 'a' AND enabled == true$]" + + "[`checked == true`][$clickable == true$][`text == 'b'`][10]"); + assertEquals(1, steps.size()); + ChainStep step = steps.get(0); + assertStep(step, true, VIEW, 10, 4); + assertEquals(Scope.DESCENDANT, step.getFilters().get(0).getScope()); + assertEquals(Scope.SELF, step.getFilters().get(1).getScope()); + assertEquals(Scope.DESCENDANT, step.getFilters().get(2).getScope()); + assertEquals(Scope.SELF, step.getFilters().get(3).getScope()); + } + + @Test + public void predicateEscapes() { + ChainStep step = steps("*[`text == \"к``ири````'лиця\"`][3]").get(0); + assertEquals("text == 'к`ири``\\'лиця'", + step.getFilters().get(0).getPredicate().toString()); + assertEquals(Integer.valueOf(3), step.getPosition()); + ChainStep dollar = steps("*[$text == 'a$$b'$]").get(0); + assertEquals("text == 'a$b'", dollar.getFilters().get(0).getPredicate().toString()); + } + + @Test + public void brackets() { + // brackets and the other marker are plain characters inside a predicate + ChainStep step = steps("*[`text == '[1]$'`][`text == 'a``]``'`][2]").get(0); + assertEquals(2, step.getFilters().size()); + } + + // ---- parent, ancestor and sibling axes ---- + + @Test + public void axes() { + List steps = steps(VIEW + "/../" + VIEW + "/^" + BUTTON + "/>*[2]/<" + VIEW + + "[-1]/~*"); + assertEquals(7, steps.size()); + assertEquals(Axis.CHILD, steps.get(0).getAxis()); + assertEquals(Axis.PARENT, steps.get(1).getAxis()); + assertNull(steps.get(1).getClassName()); + assertEquals(Axis.CHILD, steps.get(2).getAxis()); + assertEquals(Axis.ANCESTOR, steps.get(3).getAxis()); + assertEquals(BUTTON, steps.get(3).getClassName()); + assertEquals(Axis.FOLLOWING_SIBLING, steps.get(4).getAxis()); + assertEquals(Integer.valueOf(2), steps.get(4).getPosition()); + assertEquals(Axis.PRECEDING_SIBLING, steps.get(5).getAxis()); + assertEquals(Integer.valueOf(-1), steps.get(5).getPosition()); + assertEquals(Axis.SIBLING, steps.get(6).getAxis()); + assertNull(steps.get(6).getClassName()); + for (ChainStep step : steps) { + assertFalse(step.isDescendant()); + } + } + + @Test + public void axisAsTheFirstStepAndFollowedByDescendants() { + assertEquals(Axis.PARENT, steps("..").get(0).getAxis()); + assertEquals(Axis.PARENT, steps("../*").get(0).getAxis()); + List steps = steps(BUTTON + "/../**/" + VIEW); + assertEquals(Axis.PARENT, steps.get(1).getAxis()); + assertEquals(Axis.DESCENDANT, steps.get(2).getAxis()); + assertEquals(Axis.FOLLOWING_SIBLING, steps("**/*/>*").get(1).getAxis()); + } + + @Test + public void axisFilters() { + ChainStep parent = steps("*/..[`enabled == true`]").get(1); + assertEquals(1, parent.getFilters().size()); + ChainStep sibling = steps("*/>" + BUTTON + "[$text == 'a'$][`checked == true`][1]").get(1); + assertEquals(2, sibling.getFilters().size()); + assertEquals(Integer.valueOf(1), sibling.getPosition()); + } + + @Test + public void canonicalFormRoundTripsAtThePredicateDepthLimit() { + StringBuilder nots = new StringBuilder(); + for (int i = 0; i < 63; i++) { + nots.append("NOT "); + } + String query = "*[`TRUEPREDICATE AND " + nots + "TRUEPREDICATE`]"; + String canonical = canonical(query); + assertEquals(canonical, canonical(canonical)); + assertEquals("*[`TRUEPREDICATE AND " + nots + "TRUEPREDICATE`]", canonical); + // the root parentheses are only dropped at the root + assertEquals("*[`(text == 'a' OR text == 'b') AND enabled == TRUE`]", + canonical("*[`(text == 'a' OR text == 'b') AND enabled == true`]")); + assertEquals("*[`NOT (text == 'a' OR text == 'b')`]", + canonical("*[`NOT (text == 'a' OR text == 'b')`]")); + } + + @Test + public void axesRoundTrip() { + String[] queries = { + "**/" + BUTTON + "[`text == 'OK'`]/..", "*/../*/../**/" + VIEW, + "a/^b[2]/>*[-1]/*[$text == 'x$$y'$][3]", + }; + for (String query : queries) { + assertEquals(query, canonical(query)); + } + assertEquals("a/..", canonical("a/..")); + } + + @Test + public void invalidAxes() { + assertInvalid("**/..", "cannot follow the descendant marker"); + assertInvalid("a/**/..", "cannot follow the descendant marker"); + assertInvalid("**/>a", "cannot follow the descendant marker"); + assertInvalid("a/**/^b", "cannot follow the descendant marker"); + assertInvalid("a/.", "Expected '..'"); + assertInvalid("a/...", "takes no class name"); + assertInvalid("a/..b", "takes no class name"); + assertInvalid("a/..*", "takes no class name"); + assertInvalid("a/..[1]", "takes no position"); + assertInvalid("a/>", "Expected a class name"); + assertInvalid("a/^", "Expected a class name"); + assertInvalid("a/>>b", "Expected a class name"); + assertInvalid("a/<~b", "Expected a class name"); + assertInvalid("a/>[`text == 'a'`]", "Expected a class name"); + assertInvalid("a/.. ", "Unexpected ' '"); + assertInvalid("a>b", "Unexpected '>'"); + assertInvalid("a/b^", "Unexpected '^'"); + } + + @Test + public void axisErrorPositions() { + assertEquals(2, assertInvalid("a/**/..", "cannot follow").getPosition() - 3); + assertEquals(4, assertInvalid("a/..b", "takes no class name").getPosition()); + assertEquals(4, assertInvalid("a/..[1]", "takes no position").getPosition()); + } + + // ---- class names ---- + + @Test + public void supplementaryPlaneIdentifiers() { + String name = "com.example.\uD835\uDC00View"; // MATHEMATICAL BOLD CAPITAL A + assertEquals(name, steps(name + "/*").get(0).getClassName()); + assertEquals(name.length() + 1, assertInvalid(name + "/ ", "Expected").getPosition()); + } + + @Test + public void classNames() { + assertEquals("android.widget.TextView", + steps("android.widget.TextView").get(0).getClassName()); + assertEquals("Button", steps("Button").get(0).getClassName()); + assertEquals("androidx.recyclerview.widget.RecyclerView$ViewHolder", + steps("androidx.recyclerview.widget.RecyclerView$ViewHolder") + .get(0).getClassName()); + assertEquals("a.b$1", steps("a.b$1").get(0).getClassName()); + assertEquals("com.example.Вид", steps("com.example.Вид").get(0).getClassName()); + } + + @Test + public void dollarInClassNameIsNotAPredicateMarker() { + ChainStep step = steps("a.B$C[$text == 'x'$]").get(0); + assertEquals("a.B$C", step.getClassName()); + assertEquals(Scope.DESCENDANT, step.getFilters().get(0).getScope()); + } + + // ---- canonical form ---- + + @Test + public void canonicalFormRoundTrips() { + String[] queries = { + "*", "**/*", VIEW + "/" + BUTTON + "[2]", "**/" + VIEW + "/**/" + BUTTON + "[-1]", + "**/" + VIEW + "[`text == 'a``b' AND checked == true`][$enabled == true$][3]", + "*[`text == 'a$b'`][$text == 'a$$b'$]", + }; + for (String query : queries) { + String canonical = canonical(query); + assertEquals(canonical, canonical(canonical)); + } + assertEquals("**/*[`text == 'a``b'`]", canonical("**/*[`text == 'a``b'`]")); + assertEquals("*[$text == 'a$$b'$]", canonical("*[$text=='a$$b'$]")); + } + + // ---- invalid chains (ported from WDA's testInvalidChains) ---- + + @Test + public void invalidStructure() { + String[] queries = { + "/" + VIEW, VIEW + "/", VIEW + "//*", VIEW + "*/*", "**", "***", "**/*/**", "/**", + VIEW + "/**", "**[1]/" + VIEW, "**[`text == '1'`]/" + VIEW, "**/**/*", "**/", + "*/", " " + VIEW, VIEW + " ", VIEW + "/ " + BUTTON, "a..b", "a.", ".a", "1a", "a-b", + }; + for (String query : queries) { + assertInvalid(query, ""); + } + } + + @Test + public void invalidPositions() { + String[] queries = { + VIEW + "[0]", VIEW + "[-0]", VIEW + "[1][1]", VIEW + "[ 2 ]", VIEW + "[[2]", + VIEW + "[2]]", VIEW + "[]", VIEW + "[-]", VIEW + "[+1]", VIEW + "[1.5]", + VIEW + "[99999999999]", VIEW + "[1", VIEW + "[0x1]", + }; + for (String query : queries) { + assertInvalid(query, ""); + } + } + + @Test + public void invalidPredicates() { + String[] queries = { + VIEW + "[text = 'a']", VIEW + "[1][`checked == true`]", + VIEW + "[1] [`checked == true`]", VIEW + "[ `checked == true`]", + VIEW + "[`checked == true][`text == 'a'`]", VIEW + "[`checked == true]", + VIEW + "[$checked == true]", VIEW + "[``]", VIEW + "[$$]", + VIEW + "[`text == \"bla```bla\"`]", VIEW + "[$text == \"bla$$$bla\"$]", + VIEW + "[`checked == true` ]", VIEW + "[`checked == true`x]", + VIEW + "[`unknown == 1`]", VIEW + "[`text ==`]", + }; + for (String query : queries) { + assertInvalid(query, ""); + } + } + + @Test + public void emptyQuery() { + assertInvalid("", "must not be empty"); + try { + ClassChainParser.parse(null); + fail(); + } catch (ClassChainSyntaxException e) { + assertTrue(e.getReason().contains("must not be empty")); + } + } + + // ---- error reporting ---- + + @Test + public void errorsAreInvalidSelectorExceptionsWithPositions() { + ClassChainSyntaxException e = assertInvalid(VIEW + "[0]", "non-zero"); + assertTrue(e instanceof InvalidSelectorException); + assertEquals(VIEW.length() + 1, e.getPosition()); + assertEquals(VIEW + "[0]", e.getQuery()); + assertEquals(String.format("Cannot parse class chain query '%s[0]'. %s at position %d", + VIEW, e.getReason(), e.getPosition()), e.getMessage()); + + assertEquals(1, assertInvalid("a/", "Expected a class name").getPosition() - 1); + assertEquals(2, assertInvalid("a/", "Expected a class name").getPosition()); + assertEquals(1, assertInvalid("a/**", "descendant marker").getPosition() - 1); + assertEquals(0, assertInvalid("**", "descendant marker").getPosition()); + assertEquals(1, assertInvalid("a ", "Unexpected ' '").getPosition()); + assertEquals(3, assertInvalid("a.b.", "must not end with '.'").getPosition() - 1); + assertEquals(1, assertInvalid("a[1][2]", "only once").getPosition() - 3); + assertEquals(4, assertInvalid("a[1][`x == 1`]", "before the position").getPosition()); + } + + @Test + public void unterminatedPredicateReportsTheOpeningBracket() { + ClassChainSyntaxException e = assertInvalid("a/b[`text == 'x'", "closing '`'"); + assertEquals(3, e.getPosition()); + e = assertInvalid("a[$text == 'x'", "closing '$'"); + assertEquals(1, e.getPosition()); + } + + @Test + public void predicateErrorsPointAtThePredicateAndKeepTheReason() { + ClassChainSyntaxException e = assertInvalid("a[`bogus == 1`]", "Invalid predicate"); + assertTrue(e.getReason(), e.getReason().contains("bogus")); + assertEquals(3, e.getPosition()); + assertTrue(e.getCause() instanceof PredicateSyntaxException); + e = assertInvalid("a[``]", "must not be empty"); + assertEquals(3, e.getPosition()); + } + + @Test + public void predicateErrorPositionsAccountForEscapedMarkers() { + String query = "*[`text == 'a``b' AND bogus == 1`]"; + assertEquals(query.indexOf("bogus"), assertInvalid(query, "bogus").getPosition()); + query = "*[$text == 'a$$b$$c' AND bogus == 1$]"; + assertEquals(query.indexOf("bogus"), assertInvalid(query, "bogus").getPosition()); + // an error at the end of the predicate points at its closing marker + query = "*[`text == 'a``b' AND`]"; + assertEquals(query.indexOf("`]"), assertInvalid(query, "").getPosition()); + } + + @Test + public void nonDecimalLiteralsAreRejectedInsideChains() { + assertInvalid("*[`inputType == 0x1`]", "not supported"); + } + + @Test + public void stepsAreImmutable() { + List steps = steps("a/b"); + try { + steps.add(steps.get(0)); + fail(); + } catch (UnsupportedOperationException expected) { + // expected + } + assertFalse(steps.get(0).isDescendant()); + assertNull(steps.get(0).getPosition()); + try { + steps.get(0).getFilters().add(null); + fail(); + } catch (UnsupportedOperationException expected) { + // expected + } + } +}