All Downloads are FREE. Search and download functionalities are using the official Maven repository.

nl.praegus.fitnesse.slim.util.by.AppiumHeuristicBy Maven / Gradle / Ivy

There is a newer version: 0.0.22
Show newest version
package nl.praegus.fitnesse.slim.util.by;

import io.appium.java_client.MobileBy;
import io.appium.java_client.MobileElement;
import nl.hsac.fitnesse.fixture.util.selenium.by.HeuristicBy;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;

import java.util.List;
import java.util.function.Function;

import static nl.hsac.fitnesse.fixture.util.FirstNonNullHelper.firstNonNull;

public class AppiumHeuristicBy extends HeuristicBy {
    public AppiumHeuristicBy(By firstNested, By... extraNestedBys) {
        super(firstNested, extraNestedBys);
    }

    public AppiumHeuristicBy(Function postProcessor, By firstNested, By... extraNestedBys) {
        super(postProcessor, firstNested, extraNestedBys);
    }

    @Override
    public T findElement(SearchContext context) {
        Function postProcessor = getPostProcessor();
        List byList = getByList();
        return firstNonNull(by -> postProcessor.apply(getMobileWebElement(by, context)), byList);
    }

    private T getMobileWebElement(By by, SearchContext searchContext) {
        T element;
        if (by instanceof MobileBy.ByAccessibilityId) {
            element = findFirstElementOnly(by, searchContext);
        } else {
            element = getWebElement(by, searchContext);
        }
        return element;
    }

    /**
     * Finds the first element matching the supplied criteria, without retrieving all and checking for their visibility.
     * Searching this way should be faster, when a hit is found. When no hit is found an exception is thrown (and swallowed)
     * which is bad Java practice, but not slow compared to Appium performance.
     *
     * @param by            criteria to search
     * @param searchContext context to search in
     * @param            expected subclass of WebElement
     * @return null if no match found, first element returned otherwise.
     */
    public static  X findFirstElementOnly(By by, SearchContext searchContext) {
        X element = null;
        try {
            element = searchContext.findElement(by);
        } catch (NoSuchElementException e) {
            // ignore, we will return null
        }
        return element;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy