Run Selenium automation tests on LambdaTest cloud grid
Perform automation testing on 3000+ real desktop and mobile devices online.
package com.orasi.core.interfaces.impl.internal;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.pagefactory.FieldDecorator;
import com.orasi.exception.automation.PageInitialization;
import com.orasi.utils.OrasiDriver;
import com.orasi.utils.TestReporter;
/**
* Element factory for wrapped elements. Similar to {@link org.openqa.selenium.support.PageFactory}
*/
public class ElementFactory {
/**
* See {@link org.openqa.selenium.support.PageFactory#initElements(org.openqa.selenium.WebDriver driver, Class)}
*/
public static <T> T initElements(OrasiDriver driver, Class<T> pageClassToProxy) {
TestReporter.logTrace("Entering ElementFactory#initElements");
TestReporter.logTrace("Creating Page Object");
T page = instantiatePage(driver, pageClassToProxy);
TestReporter.logTrace("Successfully created Page Object");
final OrasiDriver driverRef = driver;
TestReporter.logTrace("Initialize Page Elements");
PageFactory.initElements(new ElementDecorator(new CustomElementLocatorFactory(driverRef)), page);
TestReporter.logTrace("Successfully created Page Elements");
TestReporter.logTrace("Exiting ElementFactory#initElements");
return page;
}
/**
* See {@link org.openqa.selenium.support.PageFactory#initElements(org.openqa.selenium.support.pagefactory.FieldDecorator, Object)}
*/
public static void initElements(OrasiDriver driver, Object page) {
TestReporter.logTrace("Entering ElementFactory#initElements");
final OrasiDriver driverRef = driver;
TestReporter.logTrace("Initialize Page Elements");
PageFactory.initElements(new ElementDecorator(new CustomElementLocatorFactory(driverRef), driverRef), page);
TestReporter.logTrace("Successfully created Page Elements");
TestReporter.logTrace("Exiting ElementFactory#initElements");
}
/**
* see {@link org.openqa.selenium.support.PageFactory#initElements(org.openqa.selenium.support.pagefactory.ElementLocatorFactory, Object)}
*/
public static void initElements(CustomElementLocatorFactory factory, Object page) {
TestReporter.logTrace("Entering ElementFactory#initElements");
final CustomElementLocatorFactory factoryRef = factory;
TestReporter.logTrace("Initialize Page Elements");
PageFactory.initElements(new ElementDecorator(factoryRef), page);
TestReporter.logTrace("Successfully created Page Elements");
TestReporter.logTrace("Exiting ElementFactory#initElements");
}
/**
* see {@link org.openqa.selenium.support.PageFactory#initElements(org.openqa.selenium.support.pagefactory.ElementLocatorFactory, Object)}
*/
public static void initElements(FieldDecorator decorator, Object page) {
TestReporter.logTrace("Entering ElementFactory#initElements");
TestReporter.logTrace("Initialize Page Elements");
PageFactory.initElements(decorator, page);
TestReporter.logTrace("Successfully created Page Elements");
TestReporter.logTrace("Exiting ElementFactory#initElements");
}
/**
* Copy of {@link org.openqa.selenium.support.PageFactory#instantiatePage(org.openqa.selenium.WebDriver, Class)}
*/
private static <T> T instantiatePage(WebDriver driver, Class<T> pageClassToProxy) {
TestReporter.logTrace("Entering ElementFactory#instantiatePage");
try {
try {
TestReporter.logTrace("Create Constructor of Page object");
Constructor<T> constructor = pageClassToProxy.getConstructor(WebDriver.class);
TestReporter.logTrace("Successfully created Constructor");
TestReporter.logTrace("Create new instance of Page object");
T instance = constructor.newInstance(driver);
TestReporter.logTrace("Successfully created new Page instance");
TestReporter.logTrace("Exiting ElementFactory#instantiatePage");
return instance;
} catch (NoSuchMethodException e) {
try{
TestReporter.logTrace("Entering ElementFactory#instantiatePage");
return pageClassToProxy.newInstance();
}catch(InstantiationException ie){
throw new PageInitialization("Failed to create instance of: " + pageClassToProxy.getName(), driver);
}
}
} catch (InstantiationException e) {
throw new PageInitialization("Failed to create instance of: " + pageClassToProxy.getName(), driver);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.support;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.openqa.selenium.support.events.EventFiringWebDriverTest;
import org.openqa.selenium.support.pagefactory.AjaxElementLocatorTest;
import org.openqa.selenium.support.pagefactory.AnnotationsTest;
import org.openqa.selenium.support.pagefactory.ByAllTest;
import org.openqa.selenium.support.pagefactory.ByChainedTest;
import org.openqa.selenium.support.pagefactory.DefaultElementLocatorTest;
import org.openqa.selenium.support.pagefactory.DefaultFieldDecoratorTest;
import org.openqa.selenium.support.pagefactory.internal.LocatingElementHandlerTest;
import org.openqa.selenium.support.pagefactory.internal.LocatingElementListHandlerTest;
import org.openqa.selenium.support.ui.ExpectedConditionsTest;
import org.openqa.selenium.support.ui.FluentWaitTest;
import org.openqa.selenium.support.ui.HowTest;
import org.openqa.selenium.support.ui.LoadableComponentTest;
import org.openqa.selenium.support.ui.QuotesTest;
import org.openqa.selenium.support.ui.SelectTest;
import org.openqa.selenium.support.ui.SlowLoadableComponentTest;
import org.openqa.selenium.support.ui.WebDriverWaitTest;
@RunWith(Suite.class)
@Suite.SuiteClasses({
AjaxElementLocatorTest.class,
AnnotationsTest.class,
ByChainedTest.class,
ByAllTest.class,
ColorTest.class,
DefaultElementLocatorTest.class,
DefaultFieldDecoratorTest.class,
EventFiringWebDriverTest.class,
ExpectedConditionsTest.class,
FluentWaitTest.class,
HowTest.class,
LoadableComponentTest.class,
LocatingElementHandlerTest.class,
LocatingElementListHandlerTest.class,
PageFactoryTest.class,
SelectTest.class,
QuotesTest.class,
SlowLoadableComponentTest.class,
ThreadGuardTest.class,
WebDriverWaitTest.class
})
public class SmallTests {}
public class Element : IWrapsElement
{
public IWebElement WrappedElement { get; set; }
public Element(IWebElement element)
{
this.WrappedElement = element;
}
}
public class Checkbox : Element
{
public Checkbox(IWebElement element) : base(element) { }
public void Check(bool expected)
{
if (this.IsChecked()!= expected)
{
this.WrappedElement.Click();
}
}
public bool IsChecked()
{
return this.WrappedElement.GetAttribute("checked") == "true";
}
}
Checkbox x = new Checkbox(driver.FindElement(By.Id("xyz")));
x.Check(true)
private IWebElement _chkMale{ get; set; }
[FindsBy(How = How.Name, Using = "chkMale")]
private Checkbox ChkMale
{
get { return new Checkbox (_chkMale); }
}
ChkMale.Check(true);
class WEBElment
{
public IWebElement Element;
public WEBElement(/*send whatever you decide, a webelement, a by element, a locator whatever*/)
{
Element = /*make the element from what you sent your self*/
}
public bool IsDisplayed()
{
return Element.Displayed;
}
} // end of class here
public class PermissionsPage extends TableWebElement{
...permissions stuff...
}
import WebElement
public class TableWebElement{
...custom web elements pertaining to my page...
}
public class UserList
{
private UserListPage page;
UserList(WebDriver driver)
{
page = new UserListPage(driver);
}
public void deleteFirstTwoUsers()
{
if (page.userList.size() <2) throw new RuntimeException("Terrible bug!");
page.deleteUserButtons.get(0).click();
page.deleteUserButtons.get(0).click();
}
class UserListPage {
@FindBy(xpath = "//span[@class='All_Users']")
List<BaseElement> userList;
@FindBy(xpath = "//span[@class='All_Users_Delete_Buttons']")
List<BaseElement> deleteUserButtons;
UserListPage(WebDriver driver)
{
PageFactory.initElements(new ExtendedFieldDecorator(driver), this);
}
}
public void deleteFirstTwoUsers()
{
if (page.userList.size() <2) throw new RuntimeException("Terrible bug!");
new UserListPage(driver).deleteUserButtons.get(0).click();
new UserListPage(driver).deleteUserButtons.get(1).click();
}
public class UserList {
private WebDriver driver;
UserList(WebDriver driver)
{
this.driver = driver;
}
UserListPage getPage { return new UserListPage(driver);})
public void deleteFirstTwoUsers()
{
if (getPage.userList.size() <2) throw new RuntimeException("Terrible bug!");
getPage.deleteUserButtons.get(0).click();
getPage.deleteUserButtons.get(0).click();
}
class UserListPage
{
private WebDriver driver;
UserListPage(WebDriver driver)
{
this.driver = driver;
}
List<BaseElement> getUserList() {
return driver.findElements(By.xpath("//span[@class='All_Users']"));
}
public class TableWebElement implements WebElement {
public class WebUI{
private WebDriver driver;
private WebElement permissionTable;
public WebUI(){
driver = new firefoxDriver();
}
public WebDriver getDriver(){
return driver;
}
public WebElement getPermissionTable(){
return permissionTable;
}
public TableWebElement getTable(){
permissionTable = driver.findElement(By.id("studyPermissionsTable"));
return new TableWebElement(this);
}
}
public class TableWebElement{
private WebUI webUI;
public TableWebElement(WebUI wUI){
this.webUI = wUI;
}
public int getTableSize() {
// because I dont know exactly what are you trying to achieve just few hints
// this is how you get to the WebDriver:
WebElement element = webUI.getDriver().findElement(By.id("foo"));
//this is how you get to already found table:
WebElement myTable = webUI.getPermissionTable();
}
}
@Test
public void testTableSize(){
WebUI web = new WebUI();
TableWebElement myTable = web.getTable();
Assert.assertEquals(myTable.getSize(), 25);
}
public class CustomTable {
private WebDriver driver;
private WebElement tableWebElement;
public CustomTable(WebElement table, WebDriver driver) {
this.driver = driver;
tableWebElement = table;
}
public WebElement getTableWebElement() {
return tableWebElement;
}
public List<WebElement> getTableRows() {
String id = tableWebElement.getAttribute("id");
return driver.findElements(By.xpath("//*[@id='" + id + "']/tbody/tr"));
}
public List<WebElement> getTableHeader() {
String id = tableWebElement.getAttribute("id");
return tableWebElement.findElements(By.xpath("//*[@id='" + id + "']/thead/tr/th"));
}
.... more utility functions here
}
public class TestPage {
@FindBy(id = "testTable")
private WebElement myTestTable;
/**
* @return the myTestTable
*/
public CustomTable getBrowserTable() {
return new CustomTable(myTestTable, getDriver());
}
public class Table extends WebComponent {
@FindBy(tagName = "tr")
List<Row> rows;
public Row getRow(int row) {
return rows.get(row - 1);
}
public int getTableSize() {
return rows.size();
}
public static class Row extends WebComponent {
@FindBy(tagName = "td")
List<WebElement> columns;
public WebElement getCell(int column) {
return columns.get(column - 1);
}
}
}
public class PermissionPage {
public PermissionPage(WebDriver driver) {
PageFactory.initElements(new WebDriverExtensionFieldDecorator(driver), this);
}
@FindBy(id = "studyPermissionsTable")
public Table permissionTable;
@FindBy(id = "studyPermissionAddPermission")
public WebElement addPermissionButton;
}
public class PermissionPageTest {
@Test
public void exampleTest() {
WebDriver driver = new FirefoxDriver();
PermissionPage permissionPage = new PermissionPage(driver);
driver.get("http://www.url-to-permission-page.com");
assertEquals(25, permissionPage.permissionTable.getTableSize());
assertEquals("READ", permissionPage.permissionTable.getRow(2).getCell(1).getText());
assertEquals("WRITE", permissionPage.permissionTable.getRow(2).getCell(2).getText());
assertEquals("EXECUTE", permissionPage.permissionTable.getRow(2).getCell(3).getText());
}
}
public class PermissionPage extends WebPage {
@FindBy(id = "studyPermissionsTable")
public Table permissionTable;
@FindBy(id = "studyPermissionAddPermission")
public WebElement addPermissionButton;
@Override
public void open(Object... arguments) {
open("http://www.url-to-permission-page.com");
assertIsOpen();
}
@Override
public void assertIsOpen(Object... arguments) throws AssertionError {
assertIsDisabled(permissionTable);
assertIsDisabled(addPermissionButton);
}
}
import static com.github.webdriverextensions.Bot.*;
@RunWith(WebDriverRunner.class)
public class PermissionPageTest {
PermissionPage permissionPage;
@Test
@Firefox
public void exampleTest() {
open(permissionPage);
assertSizeEquals(25, permissionPage.permissionTable.rows);
assertTextEquals("READ", permissionPage.permissionTable.getRow(2).getCell(1));
assertTextEquals("WRITE", permissionPage.permissionTable.getRow(2).getCell(2));
assertTextEquals("EXECUTE", permissionPage.permissionTable.getRow(2).getCell(3));
}
}
public interface Element extends WebElement, WrapsElement, Locatable {}
public class ElementImpl implements Element {
private final WebElement element;
public ElementImpl(final WebElement element) {
this.element = element;
}
@Override
public void click() {
element.click();
}
@Override
public void sendKeys(CharSequence... keysToSend) {
element.sendKeys(keysToSend);
}
// And so on, delegates all the way down...
}
public class CheckBox extends ElementImpl {
public CheckBox(WebElement element) {
super(element);
}
public void toggle() {
getWrappedElement().click();
}
public void check() {
if (!isChecked()) {
toggle();
}
}
public void uncheck() {
if (isChecked()) {
toggle();
}
}
public boolean isChecked() {
return getWrappedElement().isSelected();
}
}
CheckBox cb = new CheckBox(element);
cb.uncheck();
public class PageObject {
private static final String XPATH_NAME = "...";
public @iOSXCUITFindBy(xpath = XPATH_NAME)
List<MobileElement> mobileElementName;
public By getByXPath(){
return new By.ByXPath(XPATH_NAME);
}
public PageObject() {
PageFactory.initElements(driver, this);
}
}
private String getLocatorFromWebElement(WebElement element) {
return element.toString().split("->")[1].replaceFirst("(?s)(.*)\\]", "$1" + "");
}
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
protected String getLocator(WebElement element) {
try {
Object proxyOrigin = FieldUtils.readField(element, "h", true);
Object locator = FieldUtils.readField(proxyOrigin, "locator", true);
Object findBy = FieldUtils.readField(locator, "by", true);
if (findBy != null) {
return findBy.toString();
}
} catch (IllegalAccessException ignored) {
}
return "[unknown]";
}
private By getByFromElement(WebElement element) {
By by = null;
//[[ChromeDriver: chrome on XP (d85e7e220b2ec51b7faf42210816285e)] -> xpath: //input[@title='Search']]
String[] pathVariables = (element.toString().split("->")[1].replaceFirst("(?s)(.*)\\]", "$1" + "")).split(":");
String selector = pathVariables[0].trim();
String value = pathVariables[1].trim();
switch (selector) {
case "id":
by = By.id(value);
break;
case "className":
by = By.className(value);
break;
case "tagName":
by = By.tagName(value);
break;
case "xpath":
by = By.xpath(value);
break;
case "cssSelector":
by = By.cssSelector(value);
break;
case "linkText":
by = By.linkText(value);
break;
case "name":
by = By.name(value);
break;
case "partialLinkText":
by = By.partialLinkText(value);
break;
default:
throw new IllegalStateException("locator : " + selector + " not found!!!");
}
return by;
}
public class RefreshableWebElement implements WebElement {
public RefreshableWebElement(Driver driver, By by) {
this.driver = driver;
this.by = by;
}
// ...
public WebElement getElement() {
return driver.findElement(by);
}
public void click() {
getElement().click();
}
// other methods here
}
By by = By.id("someId");
WebElement e = driver.findElement(by);
....
DateWidget widget = new DateWidget(driver, "yearId", "monthId", "dayId");
....
public void testYearNumeric() {
widget.setYear("aa");
widget.submit();
//Logic to determine Error message shows up
// ... and day
widget.setDay("bb");
widget.submit();
//Logic to determine Error message shows up
}
package pagefactory.test;
import java.lang.reflect.Field;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.pagefactory.Annotations;
import org.openqa.selenium.support.pagefactory.ElementLocator;
import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
public class DateWidget {
// These constants are used to identify that they should be changed to the actual IDs
private static final String YEAR_ID = "$YEAR_ID$";
private static final String MONTH_ID = "$MONTH_ID$";
private static final String DAY_ID = "$DAY_ID$";
// Elements whose ids will be replaced during run-time
/** Year element */
@FindBy(id = YEAR_ID)
private WebElement year;
/** Month element */
@FindBy(id = MONTH_ID)
private WebElement month;
/** day element */
@FindBy(id = DAY_ID)
private WebElement day;
// The ids of the elements
/** ID of the year element */
private String yearId;
/** ID of the month element */
private String monthId;
/** ID of the day element */
private String dayId;
public DateWidget(WebDriver driver, String yearId, String monthId,
String dayId) {
this.yearId = yearId;
this.monthId = monthId;
this.dayId = dayId;
PageFactory.initElements(new CustomLocatorFactory(driver, 15), this);
}
public String getYear() {
return year.getValue();
}
public void setYear(String year) {
setValue(this.year, year);
}
public String getMonth() {
return month.getValue();
}
public void setMonth(String month) {
setValue(this.month, month);
}
public String getDay() {
return day.getValue();
}
public void setDay(String day) {
setValue(this.day, day);
}
public void submit() {
year.submit();
}
private void setValue(WebElement field, String value) {
field.clear();
field.sendKeys(value);
}
private class CustomLocatorFactory implements ElementLocatorFactory {
private final int timeOutInSeconds;
private WebDriver driver;
public CustomLocatorFactory(WebDriver driver, int timeOutInSeconds) {
this.driver = driver;
this.timeOutInSeconds = timeOutInSeconds;
}
public ElementLocator createLocator(Field field) {
return new CustomElementLocator(driver, field, timeOutInSeconds);
}
}
private class CustomElementLocator implements ElementLocator {
private WebDriver driver;
private int timeOutInSeconds;
private final By by;
public CustomElementLocator(WebDriver driver, Field field,
int timeOutInSeconds) {
this.driver = driver;
this.timeOutInSeconds = timeOutInSeconds;
CustomAnnotations annotations = new CustomAnnotations(field);
this.by = annotations.buildBy();
}
@Override
public WebElement findElement() {
ExpectedCondition<Boolean> e = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
d.findElement(by);
return Boolean.TRUE;
}
};
Wait<WebDriver> w = new WebDriverWait(driver, timeOutInSeconds);
w.until(e);
return driver.findElement(by);
}
}
private class CustomAnnotations extends Annotations {
public CustomAnnotations(Field field) {
super(field);
}
@Override
protected By buildByFromShortFindBy(FindBy findBy) {
if (!"".equals(findBy.id())) {
String id = findBy.id();
if (id.contains(YEAR_ID)) {
id = id.replace(YEAR_ID, yearId);
return By.id(id);
} else if (id.contains(MONTH_ID)) {
id = id.replace(MONTH_ID, monthId);
return By.id(id);
} else if (id.contains(DAY_ID)) {
id = id.replace(DAY_ID, dayId);
return By.id(id);
}
}
return super.buildByFromShortFindBy(findBy);
}
}
}
Accelerate Your Automation Test Cycles With LambdaTest
Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.