Selenium By API provides a good way to search for element on web page. However, it doesn't support complex search unless you use By.ByXPath. I don't like to use ByXPath, I think it cluttered the code with too many string literals.
I found Locator pattern quite useful in improving the readability of the code so I designed a
Locator interface in Selenium Capsules.
public interface Locator<Where, What> extends Function<Where, What> {
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*
* @see #compose(Function)
*/
default <V> Locator<Where, V> and(Locator<? super What, ? extends V> after) {
Objects.requireNonNull(after);
return (Where t) -> after.apply(apply(t));
}
}
The locator is an extension of function object that became available in Java 8. An example of the Selector and a Locator Factory to return a locator of your choice.
public enum ClassName implements Supplier<By> {
SF_JS_ENABLED("sf-js-enabled"),
UI_DATEPICKER_CALENDAR("ui-datepicker-calendar"),
UI_DATEPICKER_NEXT("ui-datepicker-next"),
UI_DATEPICKER_PREV("ui-datepicker-prev"),
UI_DATEPICKER_MONTH("ui-datepicker-month"),
UI_DATEPICKER_YEAR("ui-datepicker-year"),
UI_DATEPICKER_HEADER("ui-datepicker-header"),
PAGE_TITLE("page-title"),
UI_DATEPICKER_CLOSE("ui-datepicker-close");
private final By by;
private ByClassName(String id) {
this.by = className(id);
}
@Override
public By get() {
return by;
}
@Override
public String toString() {
return by.toString();
}
}
public class Locators<Where extends Searchable<Where>, What>
implements Locator<Where, What> {
public static <Where extends Searchable<Where>> Locators<Where, Element> element(Supplier<By> selector) {
return new ElementLocator<>(selector);
}
public static <Where extends Searchable<Where>> Locators<Where, Stream<Element>> elements(Supplier<By> selector) {
return new ElementsLocator<>(selector);
}
public static <Where extends Searchable<Where>> Locators<Where, Element> tryElement(Supplier<By> selector) {
return new ElementTryLocator<>(selector);
}
public static SelectLocator select(Supplier<By> selector) {
return new SelectLocator(selector);
}
private final Locator<Where, What> locator;
public Locators(Locator<Where, What> locator) {
this.locator = locator;
}
@Override
public What locate(Where where) {
return locator.locate(where);
}
}
public class ElementLocator<Where extends Searchable<Where>>
extends Locators<Where, Element> {
public ElementLocator(Supplier<By> selector) {
super((Where where) -> where.untilFound(selector));
}
}
With this Locator pattern, we can have an Input class for the <input/> tag,
package com.algocrafts.formelements;
import com.algocrafts.algorithm.Retry;
import com.algocrafts.capsules.Element;
import com.algocrafts.capsules.Searchable;
import com.algocrafts.converters.GetText;
import com.algocrafts.locators.Locator;
import org.apache.log4j.Logger;
import java.util.function.Predicate;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.apache.log4j.LogManager.getLogger;
public class Input<T extends Searchable<T>> {
private static final Logger log = getLogger(Input.class);
private final T form;
public Input(T form) {
this.form = form;
}
public void put(final Locator<T, Element> locator, final Object value) {
String string = value.toString();
log.info("setting input[" + locator + "]=[" + string + "]");
final Retry retry = new Retry(5, 1, SECONDS);
try {
retry.attempt(() -> {
locator.apply(form).clear();
locator.apply(form).sendKeys(string);
if (locator.and(GetText.VALUE).apply(form).equals(string)) {
retry.off();
}
return null;
});
} catch (Exception e) {
log.info(String.format("Failed to set text %s to %s", string, locator), e);
}
}
}
In test class, for example,
http://seleniumcapsules.blogspot.com/2013/01/refactor-selenium-example-using-page.html, if there are elements with the same name on a form, it is not possible to use findElementByName method, we need to use alternative API to locate the element, instead of provide other method such as typeByName, typeById and typeByXpath, we can use this type(Locator locator, Object value) to simplify the API, and the test became something like this, using an overloaded type method,
public class LoginPage extends AbstractPage{
public HomePage loginAs(String username, String password) {
put(USER_NAME, username);
put(PASSWORD, password);
button("login").submit();
return new HomePage();
}
}
Where USER_NAME and PASSWORD are enum instances in the above IdLocator
public class AbstractPage {
...
public void put(Locator<AbstractPage, Element> locator, Object value) {
new Input<AbstractPage>(this).put(locator, value);
}
...
}
public class AbstractForm {
...
public void put(Locator<AbstractForm, Element> locator, Object value) {
new Input<AbstractForm>(this).put(locator,value);
}
...
}
The developers of the Selenium may also realize that the By class is not enough to conduct a search on a page, if more complex scenario is required so they came up with another search method,
ByChained, however, this class still doesn't address the issue, if we want to find an element and find all elements on it which meeting certain criteria, Locator solved this problem gracefully.
Locator is a generic interface which is a function of convert A to B, so we can define it operates on any A which can be WebDriver, WebElement, etc and define B as WebElement, List<WebElement> or Stream<WebElement>, where to search from and what to search for are entirely up to you, so the parameter type for the interface is <Where, What> rather than the standard <
as appeared in the Function interface.
Here are some examples of the locators, these two enum instance of CURRENT_YEAR and CURRENT_MONTH return the year and month on the calendar,
public enum CalendarIntegerLocator implements Locator<AbstractPage, Integer> {
/**
* Locate the integer value representing current year on a calendar
*/
CURRENT_YEAR(
Locators.<AbstractPage>element(UI_DATEPICKER_DIV)
.and(element(UI_DATEPICKER_HEADER))
.and(element(UI_DATEPICKER_YEAR))
.and(TEXT)
.and(PARSE_INT)
),
/**
* Locate the integer value representing current month on a calendar
*/
CURRENT_MONTH(
Locators.<AbstractPage>element(UI_DATEPICKER_DIV)
.and(element(UI_DATEPICKER_MONTH))
.and(TEXT)
.and(TO_MONTH)
.and(ORDINAL)
);
private Locator<AbstractPage, Integer> locator;
private CalendarIntegerLocator(Locator<AbstractPage, Integer> locator) {
this.locator = locator;
}
@Override
public Integer locate(AbstractPage page) {
return locator.locate(page);
}
}
Here is a more complex locator which combines mouseover event to locate hidden menu which only displays when you mouse is over its group header,
public class MouseOverLocator implements Locator<AbstractPage, Element> {
private final String menuGroup;
private final String menuItem;
public MouseOverLocator(String menuGroup, String menuItem) {
this.menuGroup = menuGroup;
this.menuItem = menuItem;
}
public Element locate(AbstractPage page) {
return Locators.<AbstractPage>element(MAIN_NAV)
.and(element(SF_JS_ENABLED))
.and(elements(LI))
.and(new FirstMatch<>(DISPLAYED.and(TEXT.and(new IsStringEqual(menuGroup)))))
.and(page.mouseOver())
.and(element(UL))
.and(element(() -> linkText(menuItem)))
.locate(page);
}
@Override
public String toString() {
return "[" + menuGroup + "->" + menuItem + "]";
}
}
First, it locates an element E_A using MAIN_NAV, then locates another element on element E_A using SF_JS_ENABLED, then locates all element iwht <li> tag and find the first element whose text is same as menuGroup, then overOver it and find another element E_B whose tag is <ul> and on element E_B, find the element whose linkText is menuItem. That's how you can find the it, it is quite complex but it is not impossible. This technical is called function composition, it compose a series of simple functions into a complex function and operates the final function on the given subject and returns the final result of the function computation.
Clickable menu = new Menu(homePage, new MouseOverLocator("Features", "Events Management"));
menu.click();
The code above will find the "Events Management" menu and click it. Also, you can have a page return all the menu items and click them one by one,