diff --git a/docs/Page-objects.md b/docs/Page-objects.md index 0ca7ea83c..99ede90f3 100644 --- a/docs/Page-objects.md +++ b/docs/Page-objects.md @@ -763,3 +763,40 @@ It is strongly recommended to implement each subclass of __io.appium.java_clien super(element); } ``` + +## Custom locator annotations + +You can define custom `@FindBy`-style locator annotations by meta-annotating your annotation with `@io.appium.java_client.support.PageFactoryFinder` and providing an `AbstractFindByBuilder` implementation: + +```java +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.TYPE}) +@PageFactoryFinder(DataTestIdBuilder.class) +public @interface DataTestId { + String value() default ""; +} + +public class DataTestIdBuilder extends AbstractFindByBuilder { + @Override + public By buildIt(DataTestId annotation, @Nullable Field field) { + String id = annotation.value().isEmpty() && field != null + ? field.getName() + : annotation.value(); + return By.cssSelector("[data-testid='" + id.replace("'", "\\'") + "']"); + } +} +``` + +### Builder contract + +- The builder class referenced by `@PageFactoryFinder` must provide a zero-argument constructor (it does not have to be `public`; the page factory instantiates it reflectively). +- `buildIt(annotation, field)` receives the decorated `Field` when applied to a field, or `null` when resolving a class-level annotation on a `Widget` class. +- Returning `null` from `buildIt` falls back to default lookup resolution (using `ByIdOrName` based on the field or widget class name). +- Only annotations meta-annotated with `io.appium.java_client.support.PageFactoryFinder` are resolved; legacy `org.openqa.selenium.support.PageFactoryFinder` annotations are ignored. + +### Combining and overriding annotations + +- A `@PageFactoryFinder` annotation supplies the HTML/default locator (`ContentType.HTML_OR_DEFAULT`), so it can be combined on the same field or widget class with mobile native annotations such as `@AndroidFindBy` or `@iOSXCUITFindBy`. +- Combining multiple HTML/default finder annotations (`@FindBy`, `@FindBys`, `@FindAll`, or any `@PageFactoryFinder` annotation) on the same field throws `IllegalArgumentException`. On a `Widget` class, declaring multiple default finder annotations resolves to the first one declared. +- On `Widget` classes, finders declared directly on a subclass override superclass finders (including `@Inherited` custom annotations) instead of conflicting with them. Inherited custom finders from a base widget are used when the subclass declares no finder annotation of its own. + diff --git a/src/main/java/io/appium/java_client/pagefactory/DefaultElementByBuilder.java b/src/main/java/io/appium/java_client/pagefactory/DefaultElementByBuilder.java index 86bd9c225..87cb7b295 100644 --- a/src/main/java/io/appium/java_client/pagefactory/DefaultElementByBuilder.java +++ b/src/main/java/io/appium/java_client/pagefactory/DefaultElementByBuilder.java @@ -23,11 +23,9 @@ import io.appium.java_client.pagefactory.bys.builder.HowToUseSelectors; import io.appium.java_client.support.ByIdOrName; import io.appium.java_client.support.CacheLookup; -import io.appium.java_client.support.FindAll; -import io.appium.java_client.support.FindBy; -import io.appium.java_client.support.FindBys; import io.appium.java_client.support.PageFactory; import io.appium.java_client.support.pagefactory.ByAll; +import io.appium.java_client.support.pagefactory.internal.PageFactoryFinderSupport; import org.jspecify.annotations.Nullable; import org.openqa.selenium.By; @@ -91,16 +89,6 @@ public DefaultElementByBuilder( ); } - private static void checkDisallowedAnnotationPairs(Annotation a1, Annotation a2) - throws IllegalArgumentException { - if (a1 != null && a2 != null) { - throw new IllegalArgumentException( - "If you use a '@" + a1.getClass().getSimpleName() + "' annotation, " - + "you must not also use a '@" + a2.getClass().getSimpleName() - + "' annotation"); - } - } - private static By buildMobileBy(LocatorGroupStrategy locatorGroupStrategy, By[] bys) { if (bys.length == 0) { return null; @@ -114,38 +102,17 @@ private static By buildMobileBy(LocatorGroupStrategy locatorGroupStrategy, By[] @Override protected void assertValidAnnotations() { AnnotatedElement annotatedElement = annotatedElementContainer.getAnnotated(); - FindBy findBy = SeleniumAnnotationsCompat.find(annotatedElement, FindBy.class); - FindBys findBys = SeleniumAnnotationsCompat.find(annotatedElement, FindBys.class); - checkDisallowedAnnotationPairs(findBy, findBys); - FindAll findAll = SeleniumAnnotationsCompat.find(annotatedElement, FindAll.class); - checkDisallowedAnnotationPairs(findBy, findAll); - checkDisallowedAnnotationPairs(findBys, findAll); + if (annotatedElement != null) { + PageFactoryFinderSupport.validateFinderAnnotations(annotatedElement); + } } @Override protected By buildDefaultBy() { AnnotatedElement annotatedElement = annotatedElementContainer.getAnnotated(); - Field field = annotatedElement instanceof Field ? (Field) annotatedElement : null; - By defaultBy = null; - FindBy findBy = SeleniumAnnotationsCompat.find(annotatedElement, FindBy.class); - if (findBy != null) { - defaultBy = new FindBy.FindByBuilder().buildIt(findBy, field); - } - - if (defaultBy == null) { - FindBys findBys = SeleniumAnnotationsCompat.find(annotatedElement, FindBys.class); - if (findBys != null) { - defaultBy = new FindBys.FindByBuilder().buildIt(findBys, field); - } - } - - if (defaultBy == null) { - FindAll findAll = SeleniumAnnotationsCompat.find(annotatedElement, FindAll.class); - if (findAll != null) { - defaultBy = new FindAll.FindByBuilder().buildIt(findAll, field); - } - } - return defaultBy; + return annotatedElement != null + ? PageFactoryFinderSupport.buildBy(annotatedElement, annotatedElement instanceof Field) + : null; } private By[] getBys(Class singleLocator, Class chainedLocator, @@ -310,7 +277,8 @@ protected By buildMobileNativeBy() { @Override public boolean isLookupCached() { AnnotatedElement annotatedElement = annotatedElementContainer.getAnnotated(); - return SeleniumAnnotationsCompat.isPresent(annotatedElement, CacheLookup.class); + return annotatedElement != null + && PageFactoryFinderSupport.isCompatibleAnnotationPresent(annotatedElement, CacheLookup.class); } private By returnMappedBy(By byDefault, By nativeAppBy) { diff --git a/src/main/java/io/appium/java_client/support/FindAll.java b/src/main/java/io/appium/java_client/support/FindAll.java index e7f6ad08d..7034a90e3 100644 --- a/src/main/java/io/appium/java_client/support/FindAll.java +++ b/src/main/java/io/appium/java_client/support/FindAll.java @@ -42,6 +42,7 @@ */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) +@PageFactoryFinder(FindAll.FindByBuilder.class) public @interface FindAll { /** * The locators to search with. diff --git a/src/main/java/io/appium/java_client/support/FindBy.java b/src/main/java/io/appium/java_client/support/FindBy.java index a34b71652..39fd03c95 100644 --- a/src/main/java/io/appium/java_client/support/FindBy.java +++ b/src/main/java/io/appium/java_client/support/FindBy.java @@ -45,6 +45,7 @@ */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) +@PageFactoryFinder(FindBy.FindByBuilder.class) public @interface FindBy { /** * The location strategy to use together with {@link #using()}. diff --git a/src/main/java/io/appium/java_client/support/FindBys.java b/src/main/java/io/appium/java_client/support/FindBys.java index cbfb20660..7abb7a1c3 100644 --- a/src/main/java/io/appium/java_client/support/FindBys.java +++ b/src/main/java/io/appium/java_client/support/FindBys.java @@ -41,6 +41,7 @@ */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) +@PageFactoryFinder(FindBys.FindByBuilder.class) public @interface FindBys { /** * The locators to chain. diff --git a/src/main/java/io/appium/java_client/support/PageFactoryFinder.java b/src/main/java/io/appium/java_client/support/PageFactoryFinder.java new file mode 100644 index 000000000..ce53bb70e --- /dev/null +++ b/src/main/java/io/appium/java_client/support/PageFactoryFinder.java @@ -0,0 +1,34 @@ +/* + * 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.java_client.support; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** Marks a custom locator annotation with its builder class. */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface PageFactoryFinder { + /** + * Specify the builder implementation used to construct a locator from the annotated type. + * + * @return the builder class + */ + Class> value(); +} diff --git a/src/main/java/io/appium/java_client/support/pagefactory/Annotations.java b/src/main/java/io/appium/java_client/support/pagefactory/Annotations.java new file mode 100644 index 000000000..3f1347b94 --- /dev/null +++ b/src/main/java/io/appium/java_client/support/pagefactory/Annotations.java @@ -0,0 +1,88 @@ +/* + * 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.java_client.support.pagefactory; + +import io.appium.java_client.support.ByIdOrName; +import io.appium.java_client.support.CacheLookup; +import io.appium.java_client.support.pagefactory.internal.PageFactoryFinderSupport; +import org.openqa.selenium.By; + +import java.lang.reflect.Field; + +import static java.util.Objects.requireNonNull; + +/** + * Processes locator and cache annotations on a page object field. + * + *

Selenium's protected {@code AbstractAnnotations} hooks ({@code buildByFromFindBy}, + * {@code buildByFromShortFindBy}, {@code buildByFromLongFindBy}, {@code assertValidFindBys}, + * and {@code assertValidFindAll}) are intentionally omitted because finder resolution and + * conflict validation are centralized in {@link PageFactoryFinderSupport} via + * {@link io.appium.java_client.support.PageFactoryFinder} and + * {@link io.appium.java_client.support.AbstractFindByBuilder}. + */ +public class Annotations extends AbstractAnnotations { + private final Field field; + + /** + * Creates an annotation processor for the given field. + * + * @param field the field to inspect + */ + public Annotations(Field field) { + this.field = requireNonNull(field, "Field must not be null"); + } + + @Override + public boolean isLookupCached() { + return PageFactoryFinderSupport.isCompatibleAnnotationPresent(field, CacheLookup.class); + } + + @Override + public By buildBy() { + assertValidAnnotations(); + + By ans = PageFactoryFinderSupport.buildBy(field); + if (ans == null) { + ans = buildByFromDefault(); + } + return ans; + } + + /** + * Gets the annotated field handled by this instance. + * + * @return the field + */ + protected Field getField() { + return field; + } + + /** + * Builds the fallback locator when no locator annotation produces one. + * + * @return a locator using the field name + */ + protected By buildByFromDefault() { + return new ByIdOrName(field.getName()); + } + + /** Verifies that mutually exclusive locator annotations are not combined on the field. */ + protected void assertValidAnnotations() { + PageFactoryFinderSupport.validateFinderAnnotations(field); + } +} diff --git a/src/main/java/io/appium/java_client/support/pagefactory/DefaultFieldDecorator.java b/src/main/java/io/appium/java_client/support/pagefactory/DefaultFieldDecorator.java index 3c0ae5622..d7dc42cad 100644 --- a/src/main/java/io/appium/java_client/support/pagefactory/DefaultFieldDecorator.java +++ b/src/main/java/io/appium/java_client/support/pagefactory/DefaultFieldDecorator.java @@ -16,12 +16,10 @@ package io.appium.java_client.support.pagefactory; -import io.appium.java_client.support.FindAll; -import io.appium.java_client.support.FindBy; -import io.appium.java_client.support.FindBys; import io.appium.java_client.support.PageFactory; import io.appium.java_client.support.pagefactory.internal.LocatingElementHandler; import io.appium.java_client.support.pagefactory.internal.LocatingElementListHandler; +import io.appium.java_client.support.pagefactory.internal.PageFactoryFinderSupport; import org.jspecify.annotations.Nullable; import org.openqa.selenium.WebElement; import org.openqa.selenium.WrapsElement; @@ -39,8 +37,9 @@ /** * Default decorator for use with PageFactory. Will decorate 1) all the WebElement fields and 2) - * {@code List} fields that have {@code @FindBy}, {@code @FindBys}, or {@code @FindAll} - * annotation with a proxy that locates the elements using the passed in ElementLocatorFactory. + * {@code List} fields that have {@code @FindBy}, {@code @FindBys}, {@code @FindAll}, + * or another Appium {@code @PageFactoryFinder} annotation with a proxy that locates the elements + * using the passed in ElementLocatorFactory. * Adapted from Selenium's {@code org.openqa.selenium.support.pagefactory.DefaultFieldDecorator} * (Apache License 2.0). */ @@ -106,13 +105,11 @@ private boolean isDecoratableList(Field field, @Nullable Class pageClass) { return false; } - return hasStandardLocatorAnnotation(field); + return hasLocatorAnnotation(field); } - private static boolean hasStandardLocatorAnnotation(Field field) { - return field.getAnnotation(FindBy.class) != null - || field.getAnnotation(FindBys.class) != null - || field.getAnnotation(FindAll.class) != null; + private static boolean hasLocatorAnnotation(Field field) { + return PageFactoryFinderSupport.hasAppiumLocatorAnnotation(field); } /** diff --git a/src/main/java/io/appium/java_client/support/pagefactory/internal/PageFactoryFinderSupport.java b/src/main/java/io/appium/java_client/support/pagefactory/internal/PageFactoryFinderSupport.java new file mode 100644 index 000000000..3050629c6 --- /dev/null +++ b/src/main/java/io/appium/java_client/support/pagefactory/internal/PageFactoryFinderSupport.java @@ -0,0 +1,197 @@ +/* + * 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.java_client.support.pagefactory.internal; + +import io.appium.java_client.support.AbstractFindByBuilder; +import io.appium.java_client.support.PageFactoryFinder; +import org.jspecify.annotations.Nullable; +import org.openqa.selenium.By; + +import java.lang.annotation.Annotation; +import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; + +/** + * Shared discovery, validation, and builder invocation helpers for Appium + * {@link PageFactoryFinder}-annotated locator annotations. + */ +public final class PageFactoryFinderSupport { + private PageFactoryFinderSupport() { + } + + /** + * Checks whether the field carries at least one Appium {@link PageFactoryFinder} annotation. + * + * @param field the field to inspect + * @return {@code true} if an Appium finder annotation is present on the field + */ + public static boolean hasAppiumLocatorAnnotation(Field field) { + for (Annotation annotation : field.getAnnotations()) { + if (annotation.annotationType().isAnnotationPresent(PageFactoryFinder.class)) { + return true; + } + } + return false; + } + + /** + * Checks whether the given Appium annotation or its Selenium counterpart is present on the element. + * + * @param element the annotated element + * @param type the Appium annotation type + * @return {@code true} if the Appium annotation or Selenium counterpart is present + */ + public static boolean isCompatibleAnnotationPresent(AnnotatedElement element, Class type) { + return SeleniumAnnotationAdapter.isCompatibleAnnotationPresent(element, type); + } + + /** + * Resolves all active Appium {@link PageFactoryFinder} annotations (and un-superseded Selenium + * built-in {@code @FindBy}/{@code @FindBys}/{@code @FindAll}) on the given element. For classes, + * inherited annotations are consulted only when no finder annotation is declared on the class itself. + * + * @param element the field or class to inspect + * @return the resolved finder annotations (with Selenium built-ins adapted to Appium types) + */ + public static List resolveFinderAnnotations(AnnotatedElement element) { + List declared = collectFinderAnnotations(element.getDeclaredAnnotations(), element, true); + if (!declared.isEmpty() || !(element instanceof Class)) { + return declared; + } + return collectFinderAnnotations(element.getAnnotations(), element, false); + } + + /** + * Validates that mutually exclusive {@link PageFactoryFinder} annotations are not combined + * on the given element. + * + * @param element the field or class to validate + * @throws IllegalArgumentException if more than one finder annotation is active on the element + */ + public static void validateFinderAnnotations(AnnotatedElement element) { + validateFinderAnnotations(resolveFinderAnnotations(element)); + } + + /** + * Validates that at most one finder annotation is present in the resolved list. + * + * @param finders the resolved finder annotations + * @throws IllegalArgumentException if more than one finder annotation is present + */ + public static void validateFinderAnnotations(List finders) { + if (finders.size() > 1) { + Annotation first = finders.get(0); + Annotation second = finders.get(1); + throw new IllegalArgumentException( + "If you use a '@" + first.annotationType().getSimpleName() + "' annotation, " + + "you must not also use a '@" + second.annotationType().getSimpleName() + + "' annotation" + ); + } + } + + /** + * Resolves, validates, and builds a {@link By} locator from the finder annotation on {@code element}, + * or returns {@code null} when no finder annotation is present or its builder returns {@code null}. + * + * @param element the field or class to build a locator for + * @return the built {@link By}, or {@code null} + */ + @Nullable + public static By buildBy(AnnotatedElement element) { + return buildBy(element, true); + } + + /** + * Resolves and builds a {@link By} locator from the first finder annotation on {@code element}, + * optionally validating that multiple finder annotations are not combined on {@code element}. + * + * @param element the field or class to build a locator for + * @param validateConflicts whether to throw when multiple finder annotations are active + * @return the built {@link By}, or {@code null} + */ + @Nullable + public static By buildBy(AnnotatedElement element, boolean validateConflicts) { + List finders = resolveFinderAnnotations(element); + if (validateConflicts) { + validateFinderAnnotations(finders); + } + if (finders.isEmpty()) { + return null; + } + Field field = element instanceof Field ? (Field) element : null; + return buildFromFinder(finders.get(0), field); + } + + private static List collectFinderAnnotations( + Annotation[] candidates, + AnnotatedElement element, + boolean declaredOnly + ) { + List finders = new ArrayList<>(); + for (Annotation candidate : candidates) { + if (candidate.annotationType().isAnnotationPresent(PageFactoryFinder.class)) { + finders.add(candidate); + } else { + Annotation adapted = SeleniumAnnotationAdapter.adaptBuiltinSeleniumFinder( + element, candidate, declaredOnly + ); + if (adapted != null) { + finders.add(adapted); + } + } + } + return finders; + } + + @Nullable + @SuppressWarnings("unchecked") + private static By buildFromFinder(Annotation annotation, @Nullable Field field) { + PageFactoryFinder finder = annotation.annotationType().getAnnotation(PageFactoryFinder.class); + if (finder == null) { + return null; + } + Class> builderClass = finder.value(); + AbstractFindByBuilder builder; + try { + Constructor> constructor = builderClass.getDeclaredConstructor(); + constructor.setAccessible(true); + builder = (AbstractFindByBuilder) constructor.newInstance(); + } catch (InvocationTargetException e) { + throw rethrowUnchecked(e.getCause()); + } catch (ReflectiveOperationException e) { + throw new IllegalArgumentException( + "Cannot instantiate PageFactoryFinder builder " + builderClass.getName(), e + ); + } + return builder.buildIt(annotation, field); + } + + private static RuntimeException rethrowUnchecked(@Nullable Throwable cause) { + if (cause instanceof RuntimeException) { + return (RuntimeException) cause; + } + if (cause instanceof Error) { + throw (Error) cause; + } + return new IllegalStateException(cause); + } +} diff --git a/src/main/java/io/appium/java_client/pagefactory/SeleniumAnnotationsCompat.java b/src/main/java/io/appium/java_client/support/pagefactory/internal/SeleniumAnnotationAdapter.java similarity index 51% rename from src/main/java/io/appium/java_client/pagefactory/SeleniumAnnotationsCompat.java rename to src/main/java/io/appium/java_client/support/pagefactory/internal/SeleniumAnnotationAdapter.java index e03c2e148..941c2b00e 100644 --- a/src/main/java/io/appium/java_client/pagefactory/SeleniumAnnotationsCompat.java +++ b/src/main/java/io/appium/java_client/support/pagefactory/internal/SeleniumAnnotationAdapter.java @@ -14,8 +14,11 @@ * limitations under the License. */ -package io.appium.java_client.pagefactory; +package io.appium.java_client.support.pagefactory.internal; +import io.appium.java_client.support.FindAll; +import io.appium.java_client.support.FindBy; +import io.appium.java_client.support.FindBys; import org.jspecify.annotations.Nullable; import java.lang.annotation.Annotation; @@ -27,40 +30,85 @@ import java.util.Arrays; /** - * Lets page objects that still use Selenium's {@code @FindBy}, {@code @FindBys}, {@code @FindAll} - * and {@code @CacheLookup} keep working when selenium-support is on the classpath. - * The Selenium annotations are matched by name and read reflectively, so there is no compile-time - * dependency on Selenium's support package. + * Reflection and dynamic-proxy shims adapting built-in {@code org.openqa.selenium.support} + * page-factory annotations to their Appium counterparts. */ -final class SeleniumAnnotationsCompat { +final class SeleniumAnnotationAdapter { private static final String SELENIUM_SUPPORT_PACKAGE = "org.openqa.selenium.support."; + private static final String SELENIUM_FIND_BY = SELENIUM_SUPPORT_PACKAGE + "FindBy"; + private static final String SELENIUM_FIND_BYS = SELENIUM_SUPPORT_PACKAGE + "FindBys"; + private static final String SELENIUM_FIND_ALL = SELENIUM_SUPPORT_PACKAGE + "FindAll"; - private SeleniumAnnotationsCompat() { + private SeleniumAnnotationAdapter() { } /** - * Finds the given annotation on the element, falling back to its Selenium counterpart. + * Finds the given Appium annotation on the element, falling back to its Selenium counterpart. * * @param element the annotated element * @param type the Appium annotation type * @param the annotation type - * @return the Appium annotation, or a view of the Selenium one, or null if none is present + * @return the Appium annotation, an adapted view of the Selenium counterpart, or {@code null} */ @Nullable - static A find(AnnotatedElement element, Class type) { + static A findCompatibleAnnotation(AnnotatedElement element, Class type) { A annotation = element.getAnnotation(type); if (annotation != null) { return annotation; } return Arrays.stream(element.getAnnotations()) - .filter(a -> isSeleniumCounterpart(a, type)) + .filter(candidate -> isSeleniumCounterpart(candidate, type)) .findFirst() - .map(a -> adapt(a, type)) + .map(candidate -> adapt(candidate, type)) .orElse(null); } - static boolean isPresent(AnnotatedElement element, Class type) { - return find(element, type) != null; + /** + * Checks whether the given Appium annotation or its Selenium counterpart is present on the element. + * + * @param element the annotated element + * @param type the Appium annotation type + * @return {@code true} if the Appium annotation or Selenium counterpart is present + */ + static boolean isCompatibleAnnotationPresent(AnnotatedElement element, Class type) { + return findCompatibleAnnotation(element, type) != null; + } + + /** + * Adapts a built-in Selenium finder annotation to the corresponding Appium annotation unless the + * matching Appium annotation is already present at the same lookup scope. + * + * @param element the annotated element being inspected + * @param candidate the annotation instance encountered on {@code element} + * @param declaredOnly whether precedence checks only declared annotations (for fields) or inherited ones + * @return the adapted Appium annotation, or {@code null} when {@code candidate} is not a Selenium + * built-in finder or is superseded by an Appium annotation + */ + @Nullable + static Annotation adaptBuiltinSeleniumFinder( + AnnotatedElement element, + Annotation candidate, + boolean declaredOnly + ) { + String name = candidate.annotationType().getName(); + if (SELENIUM_FIND_BY.equals(name)) { + return hasAnnotation(element, FindBy.class, declaredOnly) ? null : adapt(candidate, FindBy.class); + } + if (SELENIUM_FIND_BYS.equals(name)) { + return hasAnnotation(element, FindBys.class, declaredOnly) ? null : adapt(candidate, FindBys.class); + } + if (SELENIUM_FIND_ALL.equals(name)) { + return hasAnnotation(element, FindAll.class, declaredOnly) ? null : adapt(candidate, FindAll.class); + } + return null; + } + + private static boolean hasAnnotation( + AnnotatedElement element, + Class type, + boolean declaredOnly + ) { + return (declaredOnly ? element.getDeclaredAnnotation(type) : element.getAnnotation(type)) != null; } private static boolean isSeleniumCounterpart(Annotation annotation, Class type) { @@ -77,7 +125,7 @@ private static A adapt(Annotation source, Class target case "hashCode": return source.hashCode(); case "equals": - return proxy == args[0]; + return args != null && proxy == args[0]; default: return convert(readAttribute(source, method.getName()), method.getReturnType()); } diff --git a/src/test/java/io/appium/java_client/pagefactory_tests/CustomFindByAnnotationTest.java b/src/test/java/io/appium/java_client/pagefactory_tests/CustomFindByAnnotationTest.java new file mode 100644 index 000000000..a10367d70 --- /dev/null +++ b/src/test/java/io/appium/java_client/pagefactory_tests/CustomFindByAnnotationTest.java @@ -0,0 +1,550 @@ +package io.appium.java_client.pagefactory_tests; + +import io.appium.java_client.AppiumBy; +import io.appium.java_client.pagefactory.AndroidFindBy; +import io.appium.java_client.pagefactory.AppiumFieldDecorator; +import io.appium.java_client.pagefactory.Widget; +import io.appium.java_client.pagefactory.bys.ContentMappedBy; +import io.appium.java_client.pagefactory.bys.builder.ByChained; +import io.appium.java_client.pagefactory_tests.widget.tests.AbstractStubWebDriver; +import io.appium.java_client.pagefactory_tests.widget.tests.StubWebElement; +import io.appium.java_client.remote.AppiumWebElement; +import io.appium.java_client.remote.SupportsContextSwitching; +import io.appium.java_client.support.AbstractFindByBuilder; +import io.appium.java_client.support.FindBy; +import io.appium.java_client.support.PageFactoryFinder; +import org.jspecify.annotations.Nullable; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.reflect.Field; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +import static io.appium.java_client.support.PageFactory.initElements; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CustomFindByAnnotationTest { + + private static String buildScrollIntoViewExpression(String resourceId) { + return "new UiScrollable(new UiSelector().scrollable(true))" + + ".scrollIntoView(new UiSelector().resourceId(\"" + resourceId + "\"));"; + } + + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.FIELD, ElementType.TYPE}) + @Repeatable(ScrollingAndroidFindBys.class) + @PageFactoryFinder(ScrollingAndroidFindBy.Builder.class) + @interface ScrollingAndroidFindBy { + String scrollingResourceId(); + + class Builder extends AbstractFindByBuilder { + static Field lastSeenField = AbstractStubWebDriver.class.getDeclaredFields()[0]; + + @Override + public By buildIt(ScrollingAndroidFindBy annotation, @Nullable Field field) { + lastSeenField = field; + return AppiumBy.androidUIAutomator( + buildScrollIntoViewExpression(annotation.scrollingResourceId()) + ); + } + } + } + + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.FIELD, ElementType.TYPE}) + @PageFactoryFinder(ScrollingAndroidFindBys.Builder.class) + @interface ScrollingAndroidFindBys { + ScrollingAndroidFindBy[] value(); + + class Builder extends AbstractFindByBuilder { + @Override + public By buildIt(ScrollingAndroidFindBys annotation, @Nullable Field field) { + ScrollingAndroidFindBy[] items = annotation.value(); + By[] bys = new By[items.length]; + ScrollingAndroidFindBy.Builder singleBuilder = new ScrollingAndroidFindBy.Builder(); + for (int i = 0; i < items.length; i++) { + bys[i] = singleBuilder.buildIt(items[i], field); + } + return new ByChained(bys); + } + } + } + + @Inherited + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.FIELD, ElementType.TYPE}) + @PageFactoryFinder(DataTestIdBuilder.class) + @interface DataTestId { + String value() default ""; + } + + private static final class DataTestIdBuilder extends AbstractFindByBuilder { + @Override + public By buildIt(DataTestId annotation, @Nullable Field field) { + String testId = annotation.value().isEmpty() && field != null + ? field.getName() + : annotation.value(); + return By.cssSelector("[data-testid='" + testId + "']"); + } + } + + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.FIELD, ElementType.TYPE}) + @org.openqa.selenium.support.PageFactoryFinder(LegacyAccessibilityBuilder.class) + @interface LegacyAccessibility { + String value(); + } + + static final class LegacyAccessibilityBuilder + extends org.openqa.selenium.support.AbstractFindByBuilder { + @Override + public By buildIt(LegacyAccessibility annotation, Field field) { + return AppiumBy.accessibilityId(annotation.value()); + } + } + + private static class RecordingStubElement extends StubWebElement { + private final List recordedBys; + + RecordingStubElement(WebDriver driver, By by, List recordedBys) { + super(driver, by); + this.recordedBys = recordedBys; + } + + @Override + public RecordingStubElement findElement(By by) { + if (by instanceof ContentMappedBy) { + return (RecordingStubElement) by.findElement(this); + } + recordedBys.add(by); + return new RecordingStubElement(getWrappedDriver(), by, recordedBys); + } + + @Override + public List findElements(By by) { + if (by instanceof ContentMappedBy) { + return by.findElements(this); + } + recordedBys.add(by); + return List.of( + new RecordingStubElement(getWrappedDriver(), by, recordedBys), + new RecordingStubElement(getWrappedDriver(), by, recordedBys) + ); + } + } + + private static class RecordingAndroidDriver + extends AbstractStubWebDriver.StubAndroidDriver + implements SupportsContextSwitching { + private final List recordedBys = new ArrayList<>(); + private String currentContext = "NATIVE_APP"; + + @Override + public WebDriver context(String name) { + this.currentContext = name; + return this; + } + + @Override + public boolean isBrowser() { + return !"NATIVE_APP".equals(currentContext); + } + + @Override + public String getContext() { + return currentContext; + } + + @Override + public StubWebElement findElement(By by) { + if (by instanceof ContentMappedBy) { + return (StubWebElement) by.findElement(this); + } + recordedBys.add(by); + return new RecordingStubElement(this, by, recordedBys); + } + + @Override + public List findElements(By by) { + if (by instanceof ContentMappedBy) { + return by.findElements(this); + } + recordedBys.add(by); + return List.of( + new RecordingStubElement(this, by, recordedBys), + new RecordingStubElement(this, by, recordedBys) + ); + } + + By captureFirstBy(Runnable action) { + recordedBys.clear(); + action.run(); + return recordedBys.get(0); + } + } + + public static class ChildButtonWidget extends Widget { + @ScrollingAndroidFindBy(scrollingResourceId = "com.test:id/innerAction") + private WebElement innerAction; + + protected ChildButtonWidget(WebElement element) { + super(element); + } + + public void tapInner() { + innerAction.click(); + } + } + + @ScrollingAndroidFindBy(scrollingResourceId = "com.test:id/classAnnotatedCard") + public static class ClassAnnotatedCardWidget extends Widget { + protected ClassAnnotatedCardWidget(WebElement element) { + super(element); + } + + public void tapRoot() { + getWrappedElement().click(); + } + } + + @DataTestId("inherited-card") + public static class InheritedBaseWidget extends Widget { + protected InheritedBaseWidget(WebElement element) { + super(element); + } + + public void tapRoot() { + getWrappedElement().click(); + } + } + + public static class InheritedSubWidget extends InheritedBaseWidget { + protected InheritedSubWidget(WebElement element) { + super(element); + } + } + + @DataTestId("overridden-sub-card") + public static class OverridingSubWidget extends InheritedBaseWidget { + protected OverridingSubWidget(WebElement element) { + super(element); + } + } + + @FindBy(id = "sub-findby") + public static class FindByOverridingSubWidget extends InheritedBaseWidget { + protected FindByOverridingSubWidget(WebElement element) { + super(element); + } + } + + static class CustomFinderPage { + @ScrollingAndroidFindBy(scrollingResourceId = "com.test:id/buttonNotInView") + WebElement scrollingButton; + + @ScrollingAndroidFindBy(scrollingResourceId = "com.test:id/appiumButton") + AppiumWebElement scrollingAppiumButton; + + @ScrollingAndroidFindBy(scrollingResourceId = "com.test:id/listItem") + List scrollingItems; + + @ScrollingAndroidFindBy(scrollingResourceId = "com.test:id/container") + @ScrollingAndroidFindBy(scrollingResourceId = "com.test:id/nestedRow") + WebElement repeatedScrollingRow; + + @ScrollingAndroidFindBy(scrollingResourceId = "com.test:id/byTarget") + By scrollingBy; + + @ScrollingAndroidFindBy(scrollingResourceId = "com.test:id/appiumByTarget") + AppiumBy scrollingAppiumBy; + + @DataTestId + WebElement inferredFieldIdButton; + + @DataTestId("web-checkout") + @AndroidFindBy(id = "com.test:id/native_checkout") + WebElement hybridCheckoutButton; + + @DataTestId("web-checkout-by") + @AndroidFindBy(id = "com.test:id/native_checkout_by") + By hybridCheckoutBy; + + @ScrollingAndroidFindBy(scrollingResourceId = "com.test:id/widgetContainer") + ChildButtonWidget fieldAnnotatedWidget; + + @ScrollingAndroidFindBy(scrollingResourceId = "com.test:id/widgetRow") + List fieldAnnotatedWidgets; + + ClassAnnotatedCardWidget classAnnotatedWidget; + + InheritedSubWidget inheritedWidget; + + OverridingSubWidget overridingWidget; + + FindByOverridingSubWidget findByOverridingWidget; + + @LegacyAccessibility("legacy_submit") + WebElement legacyElement; + + @LegacyAccessibility("legacy_list") + List legacyList; + + @LegacyAccessibility("legacy_widget") + ChildButtonWidget legacyWidget; + + @LegacyAccessibility("legacy_by") + AppiumBy legacyAppiumBy; + + @FindBy(id = "explicit-coexisting") + @LegacyAccessibility("ignored") + WebElement findByWithLegacy; + } + + static class ConflictingCustomAndFindByPage { + @ScrollingAndroidFindBy(scrollingResourceId = "com.test:id/one") + @FindBy(id = "two") + WebElement invalidField; + } + + static class ConflictingTwoCustomFindersPage { + @ScrollingAndroidFindBy(scrollingResourceId = "com.test:id/one") + @DataTestId("two") + By invalidByField; + } + + static class ConflictingCustomAndSeleniumFindByPage { + @ScrollingAndroidFindBy(scrollingResourceId = "com.test:id/one") + @org.openqa.selenium.support.FindBy(id = "two") + WebElement invalidField; + } + + @ScrollingAndroidFindBy(scrollingResourceId = "com.test:id/one") + @FindBy(id = "two") + public static class MultiFinderClassWidget extends Widget { + protected MultiFinderClassWidget(WebElement element) { + super(element); + } + + public void tapRoot() { + getWrappedElement().click(); + } + } + + static class MultiFinderWidgetClassPage { + MultiFinderClassWidget widget; + } + + @Test + void supportsCustomPageFactoryFinderAcrossElementsListsByFieldsAndWidgets() { + RecordingAndroidDriver driver = new RecordingAndroidDriver(); + CustomFinderPage page = new CustomFinderPage(); + initElements(new AppiumFieldDecorator(driver, Duration.ZERO), page); + + By expectedButtonBy = AppiumBy.androidUIAutomator( + buildScrollIntoViewExpression("com.test:id/buttonNotInView") + ); + assertEquals(expectedButtonBy, driver.captureFirstBy(page.scrollingButton::click)); + + assertEquals( + AppiumBy.androidUIAutomator(buildScrollIntoViewExpression("com.test:id/appiumButton")), + driver.captureFirstBy(page.scrollingAppiumButton::click) + ); + + assertEquals(2, page.scrollingItems.size()); + assertEquals( + AppiumBy.androidUIAutomator(buildScrollIntoViewExpression("com.test:id/listItem")), + driver.recordedBys.get(driver.recordedBys.size() - 1) + ); + + By expectedChained = new ByChained(new By[]{ + AppiumBy.androidUIAutomator(buildScrollIntoViewExpression("com.test:id/container")), + AppiumBy.androidUIAutomator(buildScrollIntoViewExpression("com.test:id/nestedRow")) + }); + assertEquals(expectedChained.toString(), driver.captureFirstBy(page.repeatedScrollingRow::click).toString()); + + assertInstanceOf(ContentMappedBy.class, page.scrollingBy); + assertEquals( + AppiumBy.androidUIAutomator(buildScrollIntoViewExpression("com.test:id/byTarget")), + driver.captureFirstBy(() -> driver.findElement(page.scrollingBy)) + ); + assertEquals( + AppiumBy.androidUIAutomator(buildScrollIntoViewExpression("com.test:id/appiumByTarget")), + page.scrollingAppiumBy + ); + + assertEquals( + By.cssSelector("[data-testid='inferredFieldIdButton']"), + driver.captureFirstBy(page.inferredFieldIdButton::click) + ); + + driver.recordedBys.clear(); + page.fieldAnnotatedWidget.tapInner(); + assertEquals( + List.of( + AppiumBy.androidUIAutomator(buildScrollIntoViewExpression("com.test:id/widgetContainer")), + AppiumBy.androidUIAutomator(buildScrollIntoViewExpression("com.test:id/innerAction")) + ), + driver.recordedBys + ); + + assertEquals(2, page.fieldAnnotatedWidgets.size()); + driver.recordedBys.clear(); + page.fieldAnnotatedWidgets.get(0).tapInner(); + assertEquals( + List.of( + AppiumBy.androidUIAutomator(buildScrollIntoViewExpression("com.test:id/widgetRow")), + AppiumBy.androidUIAutomator(buildScrollIntoViewExpression("com.test:id/innerAction")) + ), + driver.recordedBys + ); + } + + static class ClassOnlyWidgetPage { + ClassAnnotatedCardWidget classAnnotatedWidget; + } + + @Test + void supportsClassLevelInheritedAndOverriddenWidgetCustomAnnotations() { + RecordingAndroidDriver driver = new RecordingAndroidDriver(); + + ClassOnlyWidgetPage classPage = new ClassOnlyWidgetPage(); + ScrollingAndroidFindBy.Builder.lastSeenField = CustomFinderPage.class.getDeclaredFields()[0]; + initElements(new AppiumFieldDecorator(driver, Duration.ZERO), classPage); + assertNull(ScrollingAndroidFindBy.Builder.lastSeenField); + + assertEquals( + AppiumBy.androidUIAutomator(buildScrollIntoViewExpression("com.test:id/classAnnotatedCard")), + driver.captureFirstBy(classPage.classAnnotatedWidget::tapRoot) + ); + + CustomFinderPage page = new CustomFinderPage(); + initElements(new AppiumFieldDecorator(driver, Duration.ZERO), page); + assertEquals( + By.cssSelector("[data-testid='inherited-card']"), + driver.captureFirstBy(page.inheritedWidget::tapRoot) + ); + assertEquals( + By.cssSelector("[data-testid='overridden-sub-card']"), + driver.captureFirstBy(page.overridingWidget::tapRoot) + ); + assertEquals( + By.id("sub-findby"), + driver.captureFirstBy(page.findByOverridingWidget::tapRoot) + ); + } + + @Test + void combinesCustomFinderWithMobileNativeAnnotationsAcrossContexts() { + RecordingAndroidDriver driver = new RecordingAndroidDriver(); + CustomFinderPage page = new CustomFinderPage(); + initElements(new AppiumFieldDecorator(driver, Duration.ZERO), page); + + assertEquals( + new ByChained(new By[]{AppiumBy.id("com.test:id/native_checkout")}).toString(), + driver.captureFirstBy(page.hybridCheckoutButton::click).toString() + ); + assertEquals( + new ByChained(new By[]{AppiumBy.id("com.test:id/native_checkout_by")}).toString(), + driver.captureFirstBy(() -> driver.findElement(page.hybridCheckoutBy)).toString() + ); + + driver.context("WEBVIEW_1"); + assertEquals( + By.cssSelector("[data-testid='web-checkout']"), + driver.captureFirstBy(page.hybridCheckoutButton::click) + ); + assertEquals( + By.cssSelector("[data-testid='web-checkout-by']"), + driver.captureFirstBy(() -> driver.findElement(page.hybridCheckoutBy)) + ); + assertEquals( + AppiumBy.androidUIAutomator(buildScrollIntoViewExpression("com.test:id/buttonNotInView")), + driver.captureFirstBy(page.scrollingButton::click) + ); + } + + @Test + void preservesExistingBehaviorForLegacySeleniumPageFactoryFinderAnnotations() { + RecordingAndroidDriver driver = new RecordingAndroidDriver(); + CustomFinderPage page = new CustomFinderPage(); + initElements(new AppiumFieldDecorator(driver, Duration.ZERO), page); + + assertEquals( + By.id("legacyElement"), + driver.captureFirstBy(page.legacyElement::click) + ); + assertEquals(2, page.legacyList.size()); + assertEquals( + By.id("legacyList"), + driver.recordedBys.get(driver.recordedBys.size() - 1) + ); + + driver.recordedBys.clear(); + page.legacyWidget.tapInner(); + assertEquals( + List.of( + By.id("legacyWidget"), + AppiumBy.androidUIAutomator(buildScrollIntoViewExpression("com.test:id/innerAction")) + ), + driver.recordedBys + ); + + assertNull(page.legacyAppiumBy); + assertEquals( + By.id("explicit-coexisting"), + driver.captureFirstBy(page.findByWithLegacy::click) + ); + } + + @Test + void rejectsConflictingCustomAndBuiltinFinderAnnotations() { + RecordingAndroidDriver driver = new RecordingAndroidDriver(); + + IllegalArgumentException e1 = assertThrows( + IllegalArgumentException.class, + () -> initElements(new AppiumFieldDecorator(driver), new ConflictingCustomAndFindByPage()) + ); + assertTrue(e1.getMessage().contains("@ScrollingAndroidFindBy"), e1.getMessage()); + assertTrue(e1.getMessage().contains("@FindBy"), e1.getMessage()); + + IllegalArgumentException e2 = assertThrows( + IllegalArgumentException.class, + () -> initElements(new AppiumFieldDecorator(driver), new ConflictingTwoCustomFindersPage()) + ); + assertTrue(e2.getMessage().contains("@ScrollingAndroidFindBy"), e2.getMessage()); + assertTrue(e2.getMessage().contains("@DataTestId"), e2.getMessage()); + + IllegalArgumentException e3 = assertThrows( + IllegalArgumentException.class, + () -> initElements(new AppiumFieldDecorator(driver), new ConflictingCustomAndSeleniumFindByPage()) + ); + assertTrue(e3.getMessage().contains("@ScrollingAndroidFindBy"), e3.getMessage()); + assertTrue(e3.getMessage().contains("@FindBy"), e3.getMessage()); + } + + @Test + void preservesFirstFinderPrecedenceOnWidgetClassWithMultipleFinders() { + RecordingAndroidDriver driver = new RecordingAndroidDriver(); + MultiFinderWidgetClassPage page = new MultiFinderWidgetClassPage(); + initElements(new AppiumFieldDecorator(driver, Duration.ZERO), page); + + assertEquals( + AppiumBy.androidUIAutomator(buildScrollIntoViewExpression("com.test:id/one")), + driver.captureFirstBy(page.widget::tapRoot) + ); + } +} diff --git a/src/test/java/io/appium/java_client/support/AnnotationsTest.java b/src/test/java/io/appium/java_client/support/AnnotationsTest.java new file mode 100644 index 000000000..3d2da9679 --- /dev/null +++ b/src/test/java/io/appium/java_client/support/AnnotationsTest.java @@ -0,0 +1,276 @@ +package io.appium.java_client.support; + +import io.appium.java_client.support.pagefactory.Annotations; +import io.appium.java_client.support.pagefactory.ByAll; +import io.appium.java_client.support.pagefactory.ByChained; +import io.appium.java_client.support.pagefactory.DefaultFieldDecorator; +import io.appium.java_client.support.pagefactory.ElementLocator; +import org.jspecify.annotations.Nullable; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.reflect.Field; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AnnotationsTest { + + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.FIELD, ElementType.TYPE}) + @PageFactoryFinder(TestIdBuilder.class) + @interface TestId { + String value() default ""; + } + + private static final class TestIdBuilder extends AbstractFindByBuilder { + @Override + public By buildIt(TestId annotation, @Nullable Field field) { + String id = annotation.value().isEmpty() && field != null + ? field.getName() + : annotation.value(); + if ("__null__".equals(id)) { + return null; + } + if ("__invalid__".equals(id)) { + throw new IllegalArgumentException("Invalid test id"); + } + return By.cssSelector("[data-testid='" + id + "']"); + } + } + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.FIELD) + @PageFactoryFinder(NoZeroArgConstructorBuilder.class) + @interface BrokenFinder { + } + + private static final class NoZeroArgConstructorBuilder extends AbstractFindByBuilder { + NoZeroArgConstructorBuilder(String unused) { + } + + @Override + public By buildIt(BrokenFinder annotation, @Nullable Field field) { + return By.id("unreachable"); + } + } + + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.FIELD, ElementType.TYPE}) + @org.openqa.selenium.support.PageFactoryFinder(LegacyRoleBuilder.class) + @interface LegacyRole { + String value(); + } + + static final class LegacyRoleBuilder + extends org.openqa.selenium.support.AbstractFindByBuilder { + @Override + public By buildIt(LegacyRole annotation, Field field) { + return By.cssSelector("[role='" + annotation.value() + "']"); + } + } + + @SuppressWarnings("unused") + private static class SamplePage { + @FindBy(id = "save") + @CacheLookup + WebElement standard; + + @FindBys({@FindBy(id = "form"), @FindBy(name = "email")}) + WebElement chained; + + @FindAll({@FindBy(id = "primary"), @FindBy(id = "secondary")}) + WebElement any; + + @org.openqa.selenium.support.FindBys({ + @org.openqa.selenium.support.FindBy(id = "form"), + @org.openqa.selenium.support.FindBy(name = "email") + }) + WebElement seleniumChained; + + @org.openqa.selenium.support.FindAll({ + @org.openqa.selenium.support.FindBy(id = "primary"), + @org.openqa.selenium.support.FindBy(id = "secondary") + }) + WebElement seleniumAll; + + @TestId("submit-btn") + WebElement customSingle; + + @TestId + List inferredItems; + + @FindBy(id = "appium-list") + List appiumFindByList; + + @TestId("__null__") + WebElement customNullFallback; + + @TestId("__invalid__") + WebElement customInvalid; + + @LegacyRole("listitem") + @org.openqa.selenium.support.CacheLookup + WebElement legacySingleFallback; + + @LegacyRole("listitem") + List legacyOnlyList; + + @org.openqa.selenium.support.FindBy(id = "selenium-list") + List seleniumOnlyList; + + @FindBy(id = "explicit-legacy") + @LegacyRole("ignored") + WebElement findByWithLegacy; + + @FindBy(id = "appium-wins") + @org.openqa.selenium.support.FindBy(id = "selenium-ignored") + WebElement bothBuiltins; + + @TestId("one") + @FindBy(id = "two") + WebElement conflicting; + + @BrokenFinder + WebElement brokenBuilderField; + + List unannotatedList; + + WebElement fallbackByName; + } + + private static Field field(String name) throws NoSuchFieldException { + return SamplePage.class.getDeclaredField(name); + } + + private static ElementLocator locatorFor(Field field) { + By by = new Annotations(field).buildBy(); + return new ElementLocator() { + @Override + public WebElement findElement() { + return Stubs.element(by.toString()); + } + + @Override + public List findElements() { + return List.of(Stubs.element(by.toString())); + } + }; + } + + @Test + void builtinAnnotationsCarryPageFactoryFinderMetadata() { + assertEquals(FindBy.FindByBuilder.class, FindBy.class.getAnnotation(PageFactoryFinder.class).value()); + assertEquals(FindBys.FindByBuilder.class, FindBys.class.getAnnotation(PageFactoryFinder.class).value()); + assertEquals(FindAll.FindByBuilder.class, FindAll.class.getAnnotation(PageFactoryFinder.class).value()); + } + + @Test + void buildsBuiltinCustomLegacyAndFallbackLocators() throws NoSuchFieldException { + Annotations standard = new Annotations(field("standard")); + assertEquals(By.id("save"), standard.buildBy()); + assertTrue(standard.isLookupCached()); + + assertInstanceOf(ByChained.class, new Annotations(field("chained")).buildBy()); + assertInstanceOf(ByAll.class, new Annotations(field("any")).buildBy()); + assertInstanceOf(ByChained.class, new Annotations(field("seleniumChained")).buildBy()); + assertInstanceOf(ByAll.class, new Annotations(field("seleniumAll")).buildBy()); + + assertEquals( + By.cssSelector("[data-testid='submit-btn']"), + new Annotations(field("customSingle")).buildBy() + ); + assertFalse(new Annotations(field("customSingle")).isLookupCached()); + + assertEquals( + By.cssSelector("[data-testid='inferredItems']"), + new Annotations(field("inferredItems")).buildBy() + ); + + assertInstanceOf(ByIdOrName.class, new Annotations(field("fallbackByName")).buildBy()); + assertInstanceOf(ByIdOrName.class, new Annotations(field("customNullFallback")).buildBy()); + + Annotations legacy = new Annotations(field("legacySingleFallback")); + assertInstanceOf(ByIdOrName.class, legacy.buildBy()); + assertTrue(legacy.isLookupCached()); + + assertEquals(By.id("explicit-legacy"), new Annotations(field("findByWithLegacy")).buildBy()); + assertEquals(By.id("appium-wins"), new Annotations(field("bothBuiltins")).buildBy()); + } + + @Test + void decoratesSingleAndListFieldsRespectingAppiumFinderRequirement() { + SamplePage page = new SamplePage(); + DefaultFieldDecorator decorator = new DefaultFieldDecorator(AnnotationsTest::locatorFor); + + for (String name : List.of( + "customSingle", + "inferredItems", + "appiumFindByList", + "legacySingleFallback", + "legacyOnlyList", + "seleniumOnlyList", + "unannotatedList" + )) { + try { + Field f = field(name); + Object decorated = decorator.decorate(SamplePage.class.getClassLoader(), f); + if (decorated != null) { + f.setAccessible(true); + f.set(page, decorated); + } + } catch (ReflectiveOperationException e) { + throw new AssertionError(e); + } + } + + assertNotNull(page.customSingle); + assertEquals(By.cssSelector("[data-testid='submit-btn']").toString(), page.customSingle.getText()); + assertNotNull(page.inferredItems); + assertEquals(1, page.inferredItems.size()); + assertEquals(By.cssSelector("[data-testid='inferredItems']").toString(), page.inferredItems.get(0).getText()); + assertNotNull(page.appiumFindByList); + assertEquals(By.id("appium-list").toString(), page.appiumFindByList.get(0).getText()); + assertNotNull(page.legacySingleFallback); + assertEquals(new ByIdOrName("legacySingleFallback").toString(), page.legacySingleFallback.getText()); + assertNull(page.legacyOnlyList); + assertNull(page.seleniumOnlyList); + assertNull(page.unannotatedList); + } + + @Test + void rejectsConflictingAnnotationsAndInvalidBuilders() throws NoSuchFieldException { + Field conflicting = field("conflicting"); + IllegalArgumentException conflictError = assertThrows( + IllegalArgumentException.class, + () -> new Annotations(conflicting).buildBy() + ); + assertTrue(conflictError.getMessage().contains("@TestId"), conflictError.getMessage()); + assertTrue(conflictError.getMessage().contains("@FindBy"), conflictError.getMessage()); + + Field customInvalid = field("customInvalid"); + IllegalArgumentException builderValidationError = assertThrows( + IllegalArgumentException.class, + () -> new Annotations(customInvalid).buildBy() + ); + assertEquals("Invalid test id", builderValidationError.getMessage()); + + Field broken = field("brokenBuilderField"); + IllegalArgumentException brokenBuilderError = assertThrows( + IllegalArgumentException.class, + () -> new Annotations(broken).buildBy() + ); + assertTrue(brokenBuilderError.getMessage().contains("NoZeroArgConstructorBuilder")); + } +} diff --git a/src/test/java/io/appium/java_client/pagefactory/SeleniumAnnotationsCompatTest.java b/src/test/java/io/appium/java_client/support/pagefactory/internal/SeleniumAnnotationAdapterTest.java similarity index 69% rename from src/test/java/io/appium/java_client/pagefactory/SeleniumAnnotationsCompatTest.java rename to src/test/java/io/appium/java_client/support/pagefactory/internal/SeleniumAnnotationAdapterTest.java index 4b1057fed..fef98fbf5 100644 --- a/src/test/java/io/appium/java_client/pagefactory/SeleniumAnnotationsCompatTest.java +++ b/src/test/java/io/appium/java_client/support/pagefactory/internal/SeleniumAnnotationAdapterTest.java @@ -14,8 +14,9 @@ * limitations under the License. */ -package io.appium.java_client.pagefactory; +package io.appium.java_client.support.pagefactory.internal; +import io.appium.java_client.pagefactory.DefaultElementByBuilder; import io.appium.java_client.support.CacheLookup; import io.appium.java_client.support.FindAll; import io.appium.java_client.support.FindBy; @@ -34,7 +35,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -class SeleniumAnnotationsCompatTest { +class SeleniumAnnotationAdapterTest { @SuppressWarnings("unused") private static class Page { @@ -66,19 +67,29 @@ private static class Page { WebElement none; } + private static final class ExposedDefaultElementByBuilder extends DefaultElementByBuilder { + ExposedDefaultElementByBuilder() { + super(null, null); + } + + By defaultBy() { + return super.buildDefaultBy(); + } + } + private static Field field(String name) throws NoSuchFieldException { return Page.class.getDeclaredField(name); } - private static DefaultElementByBuilder builderFor(String fieldName) throws NoSuchFieldException { - DefaultElementByBuilder builder = new DefaultElementByBuilder(null, null); + private static ExposedDefaultElementByBuilder builderFor(String fieldName) throws NoSuchFieldException { + ExposedDefaultElementByBuilder builder = new ExposedDefaultElementByBuilder(); builder.setAnnotated(field(fieldName)); return builder; } @Test void readsSeleniumFindByAttributes() throws NoSuchFieldException { - FindBy findBy = SeleniumAnnotationsCompat.find(field("seleniumShort"), FindBy.class); + FindBy findBy = SeleniumAnnotationAdapter.findCompatibleAnnotation(field("seleniumShort"), FindBy.class); assertNotNull(findBy); assertEquals("foo", findBy.id()); @@ -89,7 +100,7 @@ void readsSeleniumFindByAttributes() throws NoSuchFieldException { @Test void convertsTheSeleniumHowEnum() throws NoSuchFieldException { - FindBy findBy = SeleniumAnnotationsCompat.find(field("seleniumLong"), FindBy.class); + FindBy findBy = SeleniumAnnotationAdapter.findCompatibleAnnotation(field("seleniumLong"), FindBy.class); assertNotNull(findBy); assertEquals(How.XPATH, findBy.how()); @@ -98,8 +109,8 @@ void convertsTheSeleniumHowEnum() throws NoSuchFieldException { @Test void convertsNestedAnnotationArrays() throws NoSuchFieldException { - FindBys findBys = SeleniumAnnotationsCompat.find(field("seleniumChained"), FindBys.class); - FindAll findAll = SeleniumAnnotationsCompat.find(field("seleniumAll"), FindAll.class); + FindBys findBys = SeleniumAnnotationAdapter.findCompatibleAnnotation(field("seleniumChained"), FindBys.class); + FindAll findAll = SeleniumAnnotationAdapter.findCompatibleAnnotation(field("seleniumAll"), FindAll.class); assertNotNull(findBys); assertNotNull(findAll); @@ -111,13 +122,13 @@ void convertsNestedAnnotationArrays() throws NoSuchFieldException { @Test void detectsTheSeleniumCacheLookupMarker() throws NoSuchFieldException { - assertTrue(SeleniumAnnotationsCompat.isPresent(field("seleniumShort"), CacheLookup.class)); - assertFalse(SeleniumAnnotationsCompat.isPresent(field("seleniumLong"), CacheLookup.class)); + assertTrue(SeleniumAnnotationAdapter.isCompatibleAnnotationPresent(field("seleniumShort"), CacheLookup.class)); + assertFalse(SeleniumAnnotationAdapter.isCompatibleAnnotationPresent(field("seleniumLong"), CacheLookup.class)); } @Test void appiumAnnotationsTakePrecedence() throws NoSuchFieldException { - FindBy findBy = SeleniumAnnotationsCompat.find(field("both"), FindBy.class); + FindBy findBy = SeleniumAnnotationAdapter.findCompatibleAnnotation(field("both"), FindBy.class); assertNotNull(findBy); assertEquals("appium", findBy.id()); @@ -125,24 +136,24 @@ void appiumAnnotationsTakePrecedence() throws NoSuchFieldException { @Test void returnsNullWhenNothingIsPresent() throws NoSuchFieldException { - assertNull(SeleniumAnnotationsCompat.find(field("none"), FindBy.class)); - assertNull(SeleniumAnnotationsCompat.find(field("appiumOnly"), FindAll.class)); + assertNull(SeleniumAnnotationAdapter.findCompatibleAnnotation(field("none"), FindBy.class)); + assertNull(SeleniumAnnotationAdapter.findCompatibleAnnotation(field("appiumOnly"), FindAll.class)); } @Test void defaultElementByBuilderUnderstandsSeleniumAnnotations() throws NoSuchFieldException { - assertEquals(By.id("foo"), builderFor("seleniumShort").buildDefaultBy()); + assertEquals(By.id("foo"), builderFor("seleniumShort").defaultBy()); assertTrue(builderFor("seleniumShort").isLookupCached()); - assertEquals(By.xpath("//a"), builderFor("seleniumLong").buildDefaultBy()); + assertEquals(By.xpath("//a"), builderFor("seleniumLong").defaultBy()); assertEquals("By.chained({By.id: foo,By.className: bar})", - builderFor("seleniumChained").buildDefaultBy().toString()); + builderFor("seleniumChained").defaultBy().toString()); assertEquals("By.all({By.name: foo,By.tagName: bar})", - builderFor("seleniumAll").buildDefaultBy().toString()); + builderFor("seleniumAll").defaultBy().toString()); } @Test void defaultElementByBuilderStillUnderstandsAppiumAnnotations() throws NoSuchFieldException { - assertEquals(By.id("appium"), builderFor("appiumOnly").buildDefaultBy()); + assertEquals(By.id("appium"), builderFor("appiumOnly").defaultBy()); assertTrue(builderFor("appiumOnly").isLookupCached()); assertFalse(builderFor("none").isLookupCached()); }